Do Docker and VirtualBox play well together on Linux?

Question: I'm currently having issues with a server which randomly freezes. The server is running:

OpenSUSE 42.2, with latest updates
Kernel 4.10.1-2.g561cf31-default (from kernel.opensuse.org)
Docker version 1.12.6, build 78d1802
VirtualBox 5.1.14r112924
The machine has 12 cores & 32GB ram and has hyper threading enabled. (after all services have been started there is ~19GB free RAM left)

For a long time we have been using VirtualBox to create virtual machines with various Linux distributions so we can test our product. Recently we decided to migrate our Linux based VirtualBox machines to Docker. Unfortunately we can't fully migrate to Docker just yet. This is why we have kept a 1 virtual machine running as well. At first, everything was working flawlessly, but once time went by, the machine started freezing randomly. There are no logs and nor indication of what might be causing this. I have ruled out hardware issues - we have enough CPU, RAM and HDD to run all the services we need and the hardware is working fine.
As an experiment, I stopped all of the VirtualBox machines and disabled all VirtualBox related services which were starting at boot and rebooted. So far we haven't had a single freeze.
This leads to my questions - can Docker and VirtualBox run on the same machine without interfering with each other?
Comment: Virtualbox is not a server-grade virtualization platform. I'd recommend looking into KVM, VMware ESXi, or Hyper-V.
Answer: Based on a forum post with the exact same problem I found from 2014, it apperas you shouldn't be running both Docker and VirtualBox at the same time. The exact quote is:

You should not run two virtualizers at the same time. Bad things can happen.

Post can be found here.
P.S. Please feel free to post an answer/comment should the situation change in the future.
Comment: I've got VBox VMs and Docker containers running on multiple hosts.  I've bumped that post to see if it's still true.  If it were true then I believe it would break the isolation model needed for proper virtualisation.
Comment: Thanks for posting on the thread. From what I've learned so far - running Docker and VirtualBox on the same machine at the same time will be problematic at some point. You could have your server up and running without a problem for a few days and then it can randomly freeze (which was what happened to us). However, you can run VirtualBox VMs and install Docker inside the VM. That should work just fine.
Comment: Thanks.  I'm just speaking from experience.  I have VirtualBox VMs and Docker containers running side-by-side in a production environment and the only real issue I've run into is a netfilter bug.  Early on, I did have a freeze but traced it and solve a bug in getty, but the issue was specific to Gentoo guests, and even existed when Virtualbox was not running.  The VMs themselves have been running together in a production environment for 6 months now without a hitch.  Could be different versions or images chosen.  YMMV.


Is it possible to retrieve the audit-log in github.com via the API?

Question: I found nothing in the API docs, only the enterprise version mentions that you can retrieve the audit-logs using the staff-tools.
Any idea? I'd love to periodically check the audit log and send the new entries to our IM channel (ChatOps).
Thanks in advance,
Answer: Update Dec. 2020, 5 years later:

Audit Log Git events and REST API now available

(in limited public beta)

In GitHub Enterprise Cloud, the Audit Log now includes Git events and has a new REST API.
Both are available as a limited public beta.
The new Git events will allow you as an administrator to review activities for users interacting with your Git repositories.
You can view events for git.clone, git.fetch, and git.push.
Additionally, the new REST API provides you with another option to interface with your Audit Log events. During the limited public beta, Git events can only be viewed via the REST API and can be exported.
How can you get access to this limited public beta? To be added to the limited public beta, please contact Sales or Support.

Feb. 2021, still for GHE (GitHub for Enterprise):

GitHub Actions: Workflow run events are now included in the Audit Log

The Audit Log now includes events associated with GitHub Actions workflow runs.
This data provides enterprise customers with a greatly expanded data set for security and compliance audits.
New events will be incorporated into the audit log when:

A workflow run is created, completed, deleted, or re-run
A workflow job is prepared. Importantly, this job will include the list of secrets that were provided to the runner
A self-hosted runner's version is updated

These new events are only available to customers on the Enterprise plan. All events are available in the REST API, and all events except for workflow run created, workflow run completed, and workflow job prepared are available in the UI and exports.
Learn more about Audit Log events

2015:
Not yet possible through the GitHub API.
But at least, it is possible to export it (since May, 5th 2015) in either JSON or CSV format.

See "Exporting the audit log".
Answer: As VonC points out, there is no API (as of October 2017).
Unfortunately the "Export" function in the GitHub audit logs produces JSON or CSV of the audit events but the data is missing the payload with the details.
For example the export would show that an issue_comment.update had been made but the web UI gives a link to the comment itself. The export would show that one user executed org.update_member on another user but the web UI would show what role change was made for that user.
To get the details of each event, at the moment (October 2017), the only way is via the web UI.
Here is a ruby tool which scrapes the web UI, fetching the audit log entries with details.
Comment: That tool looks interesting. +1


How to create a folder after clicking on a button?

Question: I got a requirement like this: In the admin page there should be one create folder button, user can create a new folders as per his wish. How can I achieve this programaticaly.
Till now I created a admin page there one button is also coming, but I am not getting how to proceed further.So please give some suggestions, thanks in advance.
 Below code I have tried.
  $form['create_folder'] = array(
    '#type' => 'submit',
    '#value' => t('Create folder'),
    '#submit' => 'custom_submit',
  );
function custom_submit($form, &$form_state){
  $new_folder = 'public://newfolder/';
  file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);
}

When I click on the submit button I got this warning Warning: Invalid argument supplied for foreach() in form_execute_handlers() (line 1507 of C:\xampp\htdocs\drupaltest\includes\form.inc).
Comment: What do you mean by "proceed further"? That code is correct, it'll create a folder if the web server has permissions to do so
Comment: Thank you for your reply. If don't mind may I know where can check the web server permission related to this?
Comment: The easiest way is probably through the Status Report in Drupal. It'll flag up a problem if the public files folder isn't writeable
Comment: I have edited my question and added the warning message which I am getting when i click on the button.
Comment: Hi, In the Status Report I didn't find anything related to this.
Answer: The #submit property takes an array of function names rather than a single string:
$form['create_folder'] = array(
  '#type' => 'submit',
  '#value' => t('Create folder'),
  '#submit' => array('custom_submit'),
);

Comment: That worked, Thank you. But my requirement was user can name the folder as per there wish. Is this possible? Because in the above code manually I am giving folder name as newfolder. So if that is possible then it would be great..
Answer: This may help:
   $form['folder_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Folder Name'),
    );
    $form['create_folder'] = array(
        '#type' => 'submit',
        '#value' => t('Create folder'),
        '#submit' => array('custom_submit'),
    );

    function custom_submit($form, &$form_state) {
        $new_folder = 'public://' . trim($form_state['values']['folder_name']).'/';
        file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);
    }

Add validation on folder name.


nginx dynamic value from 1 to 1000 in if or map

Question: Is it possible to use dynamic value for a variable in NGINX either using if is evil or Map ?
What i need is return 404 if the $variable is less than 1000 !
Maybe something like :
if ($variable = 1 To 1000 ) {
return 404;
}

Or
if ($variable less than 1000 ) {
return 404;
}

Or maybe using map ?
map $variable $test {

    default                   0;
    "~1 TO 1000"             1;
}

Answer: Using if for doing returns (as long as it happens outside any location directive) is not evil at all.
NGINX does not support if ($variable < 1000) arithmetic comparison, but you can replace that with equivalent regular expression. So:
server {
    ...
    if ($variable ~ "^\d{1,3}(?:\.\d{1,5})?$") {
        return 404;
    }

For explanation of the regular expression used, have a look at here.
Comment: So what is the right config for my case ?
Comment: @anoflsogodi I put an example in my answer.
Comment: What should i change in you example exactly ?
Comment: nothing :) it's a working config that satisfies your requirement "if an argument's value is less than 1000, then return 404", that's what it does!
Comment: What if i want to change 1000 to 800 maybe what should i change ?
Comment: You then have to construct appropriate regex. There are tools for this you may find online like [this one](http://gamon.webfactional.com/regexnumericrangegenerator/)


Sum of principal ideals in a commutative rng

Question: Let's define the principal ideal of an element $a$ of a commutative ring $R$ with or without identity as  $\langle a \rangle = R \cdot a + \mathbb Za$.
It looks like with this definition $\langle a \rangle \cdot \langle b \rangle = \langle a \cdot b \rangle$ in any commutative ring/rng:

$r \cdot (ab) + n(ab) = a \cdot (r \cdot b + nb) = (r \cdot a + na) \cdot b \implies \langle a \cdot b \rangle \subseteq \langle a \rangle \cdot \langle b \rangle$;
$(x \cdot a + na) \cdot (y \cdot b + mb) = (xy + mx + ny) \cdot (ab) + mn(ab) \implies \langle a \rangle \cdot \langle b \rangle \subseteq \langle a \cdot b \rangle$.

I am trying to check the properties for the sum of principal ideals:

$r \cdot (a + b) + n(a + b) = (r \cdot a + na) + (r \cdot b + nb) \implies \langle a + b \rangle \subseteq \langle a \rangle + \langle b \rangle$.

Question:
In which types of rings/rngs $\langle a \rangle + \langle b \rangle \subseteq \langle a + b \rangle$ (and, therefore, $\langle a \rangle + \langle b \rangle = \langle a + b \rangle$)?
Comment: In the case of rings, it's only true for fields: given $x \neq 0$, take $a=1$ and $b = x -1$ to conclude that $x$ is invertible.
Comment: @RobArthan I am trying to apply your logic to $x = 0$: for any principal ideal $(a)$ there is a principal ideal $(-a)$ such that $(a) + (-a) = (a)$, and $(a - a) = (0)$; then $(a) = (a) + (-a) = (a - a) = (0)$; $(a) = (0)$ for any principal ideal $(a)$; therefore, the ring is trivial (zero ring). Is this correct?
Comment: Answering your own question is perfectly acceptable. It's a good question and will likely be useful to others and you deserve the credit for the answer.
Comment: That's much better than the suggestion in my comment. Your argument shows that $(a) + (b) = (a + b)$ holds for all $a$ and $b$ iff $R = \{0\}$. You should write it up as an answer to your question.
Comment: @RobArthan Thank you. I am not sure if I should write the answer since I was asking the question and you provided the hint. Can we just close the question?
Answer: With the help from Rob Arthan:
$\langle a \rangle + \langle b \rangle = \langle a + b \rangle$ for any $a$ and $b$ of a commutative ring/rng $R$ if and only if $R = \{ 0 \}$.
Proof:

If $R = \{ 0 \}$, then $\langle 0 \rangle$ is the only principal ideal of $R$;
$\langle 0 \rangle + \langle 0 \rangle = \langle 0 + 0 \rangle = \langle 0 \rangle$.
Assuming $\langle a \rangle + \langle b \rangle = \langle a + b \rangle$ for any elements $a$ and $b$ of $R$;
Then, for an element $x$: $\langle x \rangle = \langle x \rangle + \langle -x \rangle = \langle x + (-x) \rangle = \langle 0 \rangle$;
$x$ is an element of $\langle x \rangle$, however the only element of $\langle 0 \rangle$ is $0$;
Therefore, $x = 0$ for an arbitrary element $x$ of $R$.


Fator de Cotação

Question: A SQL abaixo me retorna valor das cotações, eu preciso encontrar fator dia da cotação que se resume assim:
SQL
SELECT SIMBOLO,
       CONVERT (VARCHAR(10),DATA,103) as DATA,
       FATOR
FROM GCOTACAO
WHERE SIMBOLO = 'CDI'

Símbolo     Data         Fator    Fator Dia
CDI         01/01/2014   10084    = fator - 1 = 0,0084
CDI         01/02/2014   10163    = Fator (10163 - 10084) - 1
CDI         01/03/2014   10240    = Fator (10240 - 10163) - 1

Agradeço a ajuda de todos.
Answer: Ronnie Von, experimente o seguinte código sql:
SELECT SIMBOLO as [Símbolo],
       convert (char(10), DATA, 103) as Data,
       FATOR as Fator,
       [Fator dia]= (FATOR - coalesce (lag (FATOR) over (order by DATA), 10000)) / 10000.
  from GCOTACAO;

Ele faz uso da função LAG() para obter o valor de FATOR da linha anterior.
Comment: Mestre Jose Diz, era isso mesmo, muito obrigado

Fator de Cotação


Describe the conjugacy classes of UT(3,Zp)

Question: How can all the conjugacy classes of UT(3,Zp) be described, if UT(3,Zp) is a unitriangular matrix group so its members look like $ \left( \begin{array}{ccc} 1 & a_{12} & a_{13} \\ 0 & 1 & a_{23} \\ 0 & 0 & 1 \end{array} \right) $ , $a_{12},a_{13},a_{23} \in \mathbf{Zp}$, $\mathbf{Zp}$ is a сyclic field and p is a prime number?
Comment: Should there be a $1$ in the lower-right entry?
Comment: Also, shouldn't $\Bbb Z_p$ be a *field*, rather than a group?
Comment: Thats right, my mistake
Comment: My mistake; apparently $\Bbb Z_n$ is allowed to simply be a ring rather than a field (that is, even if $n$ isn't prime, this set of matrices forms a group).  However, I assume that the $p$ here means that $p$ is prime.
Answer: Hint: if $a$ has the form
$$
a = \pmatrix{1&a_1&a_3\\&1&a_2\\&&1}
$$
then the elements of the conjugacy class of $a$ are given by
$$
\pmatrix{1&a_1&a_3 + a_2j - a_1 k\\&1&a_2\\&&1}
$$
where $j,k \in \Bbb Z_p$.
If you get stuck again, it will help to know that this group is also referred to as the finite Heisenberg group.


Como salvar dados do app no smartphone?

Question: Para não depender de conexão com a internet, é possível salvar no celular os dados referentes ao app? Por exemplo, ao abrir pela primeira vez selecionar o idioma e nas próximas utilizações do app não ser necessário perguntar o idioma, sim buscar direto do dado que foi salvo.
Comment: Que tipo de dados quer guardar?
Comment: @ramaral seriam dados pequenos, editei a pergunta
Comment: Se não tiver dificuldades com o inglês comece com este [tutorial](http://www.tutorialspoint.com/android/android_shared_preferences.htm). Se tiver alguma dúvida mais concreta faça uma nova pergunta.
Comment: Veja se esta [resposta](http://pt.stackoverflow.com/a/55183/2541) ajuda.
Answer: No desenvolvimento Android existem várias formas de persistir os dados de um aplicativo. Uma delas é o SharedPreferences, que você pode utilizar quando se tem uma pequena coleção de chaves-valores que você gostaria de salvar (conforme a própria documentação do android diz).
Segue as principais maneiras de se utilizar o SharedPreferences:
Criando o SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MinhasPreferencias", MODE_PRIVATE);
Editor editor = pref.edit();

Armazenandoos dados como chave-valor
editor.putBoolean("key_name1", true);           // salvando um boolean - true/false
editor.putInt("key_name2", "int value");        // salvando um integer
editor.putFloat("key_name3", "float value");    // salvando um float
editor.putLong("key_name4", "long value");      // salvando um long
editor.putString("key_name5", "string value");  // salvando uma string

// salva as mudanças no SharedPreferences
editor.apply();

Retornando valores do SharedPreferences
// Se o valor da chave não existir, então retornará o segundo parametro
// Você pode armazenar esse retorno em uma variável
//    Ex: String nome = pref.getString("nome", null);

pref.getBoolean("key_name1", true);         // retornando boolean
pref.getInt("key_name2", 0);             // retornando Integer
pref.getFloat("key_name3", null);           // retornando Float
pref.getLong("key_name4", null);            // retornando Long
pref.getString("key_name5", null);          // retornando String

Deletando valores únicos SharedPreferences
editor.remove("key_name3"); // vai deletar a chave key_name3
editor.remove("key_name4"); // vai deletar a chave key_name4

// salva as mudanças no SharedPreferences
editor.apply();

Deletando todas as informações do SharedPreferences
 editor.clear();
 editor.apply();

Um detalhe: Você pode salvar as alterações utilizando o método apply() e commit(), diferenciando que o apply() é assincrono.

Segue alguns links que possam ser úteis:
Developer.Android - SharedPreferences
Utilizando o SharedPreferences
Resposta baseada nessa outra resposta
Criando arquivos de configurações
Comment: Evite utilizar o editor.commit(), pois ele salva imediatamente. Já o editor.apple() irá gerenciar o salvamento em background, não travando o processamento do app.
Answer: Você pode armazenar em um arquivo xml, como é um padrão para o android, como as activitys, manifest etc.
Comment: Poderia melhorar um pouco a sua resposta, para não ser baseada puramente em um link? Adicionar os tipos de salvamento que existe e como cada um se comporta?
Comment: A minha preocupação é onde salvar e se o usuário vai conseguir apagar esse arquivo, digo se limpar "cache"/"dados dos apps" ele será removido? Vai ter acesso ao arquivo via usb?
Comment: Sim claro, postei rapidamente porque faço isso para armazenar score de jogos.
Comment: Desculpe postar mais um link kkkkk Felipe Avelar, mais tem uma solução, uma pergunta do stack : http://stackoverflow.com/questions/10962344/how-to-save-data-in-an-android-app

Como salvar dados do app no smartphone?


Identifying Non-Analytic Regions for the Function $f(z) = \frac{1}{{z^2 + 5iz - 4}}$

Question: I'm working with the complex function $f(z) = \frac{1}{{z^2 + 5iz - 4}}$, and I'm trying to determine where this function is not analytic. I've been trying to compute its domain of analyticity, but I'm encountering some difficulties.
I'm a bit confused because it seems like there might be two regions where the function becomes indeterminate. However, in my class, I was taught that everything should be understood within a single neighborhood. My professor described the neighborhood as a single inequality that forms a circular region centered at the origin.
Could someone please help me clarify whether there are indeed two separate non-analytic regions for this function, or if it should be comprehended within a single neighborhood? Any insights, methods, or explanations would be greatly appreciated.
If you need any additional information or details about my approach, please let me know. I'm eager to gain a better understanding of this function's behavior.
Thank you in advance for your assistance!
Answer: We can rewrite the function as $f(z) = \frac{1}{(z + 4i)(z + i)}$, and notice that the denominator has two zeros at $z = -4i$ and $z = -i$. These zeros are poles of the function, and so the function will be non-analytic in any neighbourhood containing either of the poles. We would say that the domain of the function's analyticity is the entire complex plane minus these points.
If we are focusing on the origin, which we might be doing because we're interested in something like the radius of convergence of a Taylor series, then we would consider the largest circle we can draw around the origin that doesn't capture either of the poles, and in that case the radius will be 1 since the circle $|z| = 1$ captures the pole at $-i$.


approximate cos(1/10) with three correct decimals around origin with Taylor polynomial

Question: Using the Maclaurin with two derivatives I get the following. Substituting x = 1/10 gives approx 0.9800, but the answers say it should be 0.995.
Comment: The derivatives of $f$ are evaluated at $0$, not at $x$.  The first derivative should be $\sin(0)=0$.  The second should be $-\cos (0)=-1$.  The signs should be $+$ until you apply the signs of the derivative.  Your calculation is still not right because the second term as written should give $-0.1$ and the third should give about $-0.005$.
Comment: Maybe you need an upper bound for the [Taylor series](https://en.wikipedia.org/wiki/Taylor%27s_theorem#Estimates_for_the_remainder) reminder to be $<0.0005$
Answer: A Maclaurin series is a Taylor series expansion of a function about $0$,
$$f(x)=f(0)+f'(0)\cdot x+\frac{f''(0)}{2!}\cdot x^2+\frac{f'''(0)}{3!}\cdot x^3+\frac{f''''(0)}{4!}\cdot x^4+\dots\tag1$$
For $f(x)=\cos(x)$, we get:
$$\cos(x)=1+0-\frac{x^2}{2}+0+\frac{x^4}{24}+\dots=1-\frac{x^2}{2}+\frac{x^4}{24}+\dots\tag2$$
So, when $x=\frac{1}{10}$, we get:
$$\cos\left(\frac{1}{10}\right)=1-\frac{\left(\frac{1}{10}\right)^2}{2}+\frac{\left(\frac{1}{10}\right)^4}{24}+\dots=\frac{238801}{240000}+\dots\tag3$$
And:
$$\frac{238801}{240000}\approx0.995004166666\tag4$$

Note: the error term is given by the terms we did not put into our approximation. The more terms you pick the more accurate it will become.
Comment: @eriksan Look at my edit.
Comment: And now any motivation why we take $3$ terms, not $2$ and not $4$ )) @Jan
Comment: Yes I know, the question is why I get an answer different from the one provided.
Answer: The second term of the Taylor series is $f'(0)(x-0)$.  Because the sine is $0$ at $0$ the term is zero.  The third term is $\frac 1{2!}f''(0)(x-0)^2=-\frac 12(0.1)^2=-0.005$.  Adding this to $1$ gives $0.995$.  The series is alternating, so the error is of the sign of and smaller than the first neglected term.  The next term is $\frac 1{4!}\cdot 1 \cdot 0.1^4 \ll .001$, so our three places are correct.
Comment: Because the third derivative is $-sin(0)=0$, so there is no term with $x^3$
Comment: Why is the "next term" what you wrote, rather than something divided by 3! times 0.1^3?
Answer: In your series, you write $\cos x$ and $\sin x$ when you should be writing $\cos 0 $ and $\sin 0$.  The reason you stop after the 2nd-order term is that this is an alternating series.  The error is bounded by the next term, $(0.1)^4/4!$, so two non-zero terms are sufficient.
Comment: Most calc texts give two different ways to bound the error of a series.  One is the Taylor remainder (which uses the 3rd-order term here.)  The other is the bound for alternating series, when you're lucky.  Since the non-zero terms here form an alternating series, we get to use this much easier bound.
Comment: Thanks. I see that we have a 2nd-order term. I've also read that the error is bounded by the next term, which I understood to be f'''(c)/3!(x-a)^3 (for some c between ax and a) but everyone, including you, tells me it's the next one is (1/10)^4/4!, how come?


calcular horas com javascript

Question: quero calcular o tempo percorrido entre duas horas:

var h1 = 23:14:32;
var h2 = 22:55:27;
var total = h1 - h2;

o retorno que pego é NaN.
Comment: Na verdade isto nem é para executar, esta sintaxe não existe. O que deseja fazer é extramente mais complexo e as pessoas costumam usar bibliotecas para isso, ou fazer gambiarras que funcionam muito mais ou menos, portanto não confiável.
Answer: function formatar_segundos(h,min,s) {
 return (h*3600)+(min*60)+(s);
}

var data = formatar_segundos(23,14,32);
var data2 = formatar_segundos(22,55,27);

var diferenca = data_format(data-data2);
function data_format(s) {
 this.h = Math.floor(s/3600);
 this.min = Math.floor((s - (this.h*3600))/60);
 this.s = s - (Math.floor(s/60)*60);
 return this.h + "h "+ this.min + "min "+this.s + "s";
}

Answer: Ele está retornando propriedade global NaN, que é um valor especial que significa Not-A-Number (não é um número), pois vc esta setando apenas strings nas variáveis.
Use essa função para iniciar e leia documentação da API jquery que pode lhe auxiliar.
:)
Jquery Documentação: https://api.jquery.com/
NaN = https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/NaN
function myFunction() {
  var d = new Date(); //seta o objeto Date
  var n = d.getHours() -2; //subtraí 2 horas da hora atual
  return n;
}
console.log(myFunction()); //exibi "apenas" o valor da hora atual menos 2hrs (sem os minutos)

calcular horas com javascript


Find domain of function whose independent variable is the upper limit of an integral?

Question: I'm trying to answer the following question:
Find the domain of $F(x)$ where $$F(x)=\int_{5}^{x}\frac{1}{1-t^2}dt$$
Are we supposed to use some type of convergence test? I've heard of that for series, but not for integrals. When I search the Net, I only get results for improper integrals. However, this is not an improper integral, right?
Also, if I just evaluate the integral using the formula:
$$\int\frac{1}{1-t^2}dt=\frac{1}{2}\ln\bigg|\frac{t+1}{t-1}\bigg|+C$$
then I get the domain as $x\neq\pm1$, which is wrong. How can you explain that? Thanks!
Comment: The Fundamental Theorem of Calculus requires that the integrand is continuous on the closed interval defined by the limits of integration, in this case it is not continuous on any interval of the form $[x, 5]$ for which $x \le 1$
Comment: The integral is proper iff $x>1.$ For $x=1$ it is improper and divergent (hence also for $x<1$). So the domain is $(1,+\infty).$ (Btw we are not talking about continuity of $F$ and the FTC is off topic.)
Comment: The (proper Riemann) integral is at most defined for bounded functions
Answer: I figured it out. Let me answer my second question first. FTC2 only applies if the integrand is a continuous function on $[a,b]$. But since we have vertical asymptotes at $x=\pm1$, we cannot use $F(b)-F(a)$.
This is, in fact an improper integral. Integrals with an infinite upper or lower limit only make up one type of improper integral. But any integral with an unbounded region is improper. The graph of the integrand looks like this:

So we have three unbounded regions, and we need to test whether they converge or diverge. Let's start by testing the region on the right, by setting $x$ to $1$.
Since vertical asymptotes usually occur in rational functions, as in this example, we can sometimes test for convergence using a combination of a p-series test and comparison test. Let's try it. We need to factor out a negative, giving us: $$F(1)=-\int_{5}^{1}\frac{1}{t^2-1}dt$$
The idea here is to compare with the p-series $\frac{1}{t^2}$. However, since $\frac{1}{t^2-1}$ is larger than $\frac{1}{t^2}$, the comparison test doesn't apply and we have to try something else.
Let's try to evaluate the integral using partial fraction decomposition. After applying PFD, we get: $$F(1)=\frac{1}{2}\int_{5}^{1}\frac{1}{1-t}+\frac{1}{1+t}dt$$
Evaluating the integral gives us: $$\frac{1}{2}[\ln(1+t)-\ln(1-t)]_5^1$$
When we substitute the $1$, we end up with a $\ln(0)$ term, which is undefined. Therefore, the region on the right diverges.
Since the original function is defined with the lower limit of integration at $t=5$, which is to the right of the unbounded regions, and we have a divergence at $t=1$, then the domain is $\large \textbf{x>1}$.


BLOCK_NO_CACHE with Normal page cache enabled

Question: I'm trying to create a block, which shouldn't get cached, even for anonymous users. But there's "Normal" page caching enabled on the website. As I've read in various places, the BLOCK_NO_CACHE setting doesn't really count for anonymous users when page caching is enabled.
As it stands, it's not an option for me to turn off the page caching, as the website receives moderately high traffic.
I've first tried injecting some HTML with hook_footer but this function doesn't get called as well when page caching is enabled.
The block I'm trying to implement is a very simple one, it only has a bit of text and a link, which upon clicking, sets a cookie on the user's browser (with PHP), and returns the user back to the page where they clicked the link on. Upon returning to the page, the block needs to attempt to read the cookie, and if the cookie is set, the block should no longer be displayed.
However with page caching turned on, if AnonymousUser-A clicks the link and no longer sees the block, then AnonymousUser-B comes to the site, they also don't see the block.
Is there a workaround I can use to get around this issue? As you can see from my use of hook_footer, I'm not heavily inclined to implement this as a block. Any solution that will fit the above purpose is welcome.
Comment: Have you come across [`hook_boot()`](http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_boot/6)? It gets run for all pages, even those that are cached
Comment: Thanks, and sorry to be a pain, but could you write me a small example on how to use `hook_boot()` to inject some HTML on the current page?
Comment: You can't use hook_boot to inject HTML on the current page... at least not in a sane way.
Answer: Ajax Blocks or Ajaxify Regions (since you're in D6) allow dynamic blocks within cached pages.
Comment: I'm afraid it's not what I'm looking for, as I'm particularly having issues with anonymous users because BLOCK_NO_CACHE is intended to work for authenticated users, but not for anonymous with full page cache on.
Comment: Trust me when I say that one of the 3 modules above will fix your issue.
Answer: If you want a different example, you can use javascript to read a cookie and hide that blocks div based off of a cookies value. Have the block always be show at the PHP level and use JS to hide it client side.


how to surround a word using System.Text.RegularExpressions.Regex

Question: I've seen this topic:
How to surround text with brackets using regex?
but that's on ruby and I don't know the analog for C#
I tried
text = System.Text.RegularExpressions.Regex.Replace(text, ' '  + SpecialWord + ' ', " \"\0\" ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

but that didn't insert my matched word. So how do I surround my matched word with quotes?
Answer: use $ instead of \ for the backreference. Also, put your special word in parenthesis and reference that sub group, otherwise, you will get the complete matched string:
text = System.Text.RegularExpressions.Regex.Replace(
                         text, "\\b("  + SpecialWord + ")\\b", " \"$1\" ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

Explanation:

\b is a word boundary, i.e. a space, the end of the string, a full stop etc.
$0 will match the whole match, i.e. including the word boundary, whereas $1 matches the first sub group, i.e. the part in the parenthesis.
Comment: I don't think parentheses are necessary if you use `\b` as it's zero-width, so in this case `$0` and `$1` are identical.
Answer: Try using \b to match the word boundary, rather than a space.
You need to use $0 instead of \0 too.
text = Regex.Replace(text, @"\b" + SpecialWord + @"\b", @" ""$0"" ", RegexOptions.IgnoreCase);


Determining whether a change in ranking is statistically significant

Question: I have two populations, A (n=48) and B (n=19). Both took a pre-test, after which B performed an intervention. Both A and B took a post-test which was not the same as the pre-test. It now appears that, while A were originally performing better than B, B is now performing better than A. I want to determine whether this change in performance is significant. I can do this by ranking the scores on each test (using RANK.AVG in Excel, which gives me a rank with an averaged rank for ties) and comparing the difference in the average ranking of each group.
Here's what I found:
Average pre-test rank A: 31.9
Average pre-test rank B: 39.7

Average post-test rank A: 34.8
Average post-test rank B: 32.1

This indicates to me that:
Average rank change A: -2.8
Average rank change B: +7.7

I take this to mean that, possibly due to the intervention, B have gone up in the rankings across the population (on average) while A have dropped. Is there any better way to be investigating this? How can I tell if this change in ranking is significant?
Comment: Could you explain why the pre-test results might have any relevance to the question whether "group B is now performing better than group A"? Your focus on pre-test results suggests you're actually trying to address a different question, which makes your question ambiguous.
Comment: The reason I have a pre-test is to give me a starting benchmark, otherwise I would not be able to tell if B have improved after the intervention, or if they've just been performing better than A all along.
Comment: But that concerns a completely different question than the one you have formulated.
Comment: I am sorry, you will have to help me see how. I want to determine if a change in ranking is significant - how can I do that without a starting point to change from?
Comment: "I want to try and determine if group B is now performing better than group A" is an absolute comparison against how the groups are performing now, regardless of how they might have performed previously.  Perhaps instead of comparing *performances* you wish to compare *changes* in performance?
Comment: Yes, you are correct - I tried to get at this at the end of the question but it is not clear in the opening statement. I will adjust my question.
Answer: You can try Wilcoxon approach to the matter. This is a test for paired samples (pretest and post-test), although you will have to compute is separately for each group. But potentially, you will be able to say that group B improved significantly while group A didn't.


(1995) Bishop's cite on weight decay regularization

Question: On the book "Neural networks for pattern recognition" [Bishop, 1995], in chapter 9 about regularization there is a paragraph that says:

Some heuristic justification for the weight-decay regularizer can be
  given as follows. We know that to produce an over-fitted mapping with
  regions of large curvature requires relatively large values for the
  weights. For small values of the weights the network mapping
  represented by a multi-layer perceptron is approximately linear, since
  the central region of a sigmoidal activation function can be
  approximated by a linear transformation.

Okey so I understand the first part I think. Looking at the image below (taken from Goodfellow.I, deeplearningbook.org), it is clear that for the rightmost figure, the learned function has regions of large curvature, which are explained by high values of the weights of the network.
However, I don't understand what he meant with the second part of the paragraph, namely with the sentence "For small values of the weights the network mapping represented by a multi-layer perceptron is approximately linear, since the central region of a sigmoidal activation function can be approximated by a linear transformation" .
Does he mean that, if the weights are small, then $w_i * feature_i$ will be small and will therefore (assuming sigmoid activation function) lie in the linear region of the sigmoid activation function? Because if that is what he means, then why would we use sigmoid functions? It wouldn't make sense if we are not using the non-lineariy that it provides, right? Or am I missing something?
Thanks!!
Answer:
Does he mean that, if the weights are small, then $w_i$∗$feature_i$ will be small and will therefore (assuming sigmoid activation function) lie in the linear region of the sigmoid activation function?

In short: yes. But, as he states, this is a more or less completely heuristic description. Or one could call it "hand-waving" and convincing.

Because if that is what he means, then why would we use sigmoid functions? It wouldn't make sense if we are not using the non-linearity that it provides, right? Or am I missing something?

The answer to this is more complicated, and a topic still under discussion. I have to admit that I can't recall directly, where I have read a more complete discussion on the choice of activation functions, but most likely it's in the mentioned book itself.
The non-linearity of the activation function is definitely an important part to make ANNs being able to approximate any function. But apart from the theoretical description, there are also practical concerns. If the data and the current state of the ANN during training makes use of the non-linear part "too much", then it can become volatile, inaccurate and slow. I'd have to think a lot more, to make a mathematical argument (or even proof). But this is also a part of the aforementioned discussion (maybe it's in "An Introduction to Statistical Learning" by James, Witten, Hastie and Tibshirani).
So -- no, you're not missing something, if you focus just on the question itself. But there is a bigger picture to it, which make the focus a lot softer.
Comment: I read this in deeplearningbook [Goodfellow. I], when talking about the ReLU function: "Because rectified linear units are nearly linear, they preserve many of the properties that make linear models easy to optimize with gradient based methods." which may be related with what you say.
But do you agree with the thought that if all the weights are pushed towards the linear part of the ReLU, then it loses a bit the sense of using a non-linear function? Or maybe using the non-linearity "a little bit" is enough?
Comment: @sdiabr -- this is a complex question, because it's connected to a lot of different parts. Truly linear approximations can sometimes be trivially solved (single step), in the case of a ANN this is a bit more involved, but technically still straightforward. Unfortunately the error space might be so uneven that you need a lot of elements in the NN, which makes the training complicated again. In a nutshell it is a compromise between complex training and complex description. Bishop has published several papers on this topic, including calculations on "single-step" solutions for network weights.
Comment: when could your sentence "unfortunately the error..." happen? I didn't get that. If using linear activation functions?
Comment: @sdiabr: no, the shape of the error space -- usually called "error surface" --  is a feature of your problem, or rather the data set itself. If you use a linear model, then you don't have this problem, because you are blind to it. Linear models have many nice features, especially when it comes to minimization -- e.g. gradient descent. But they lack in description power; so there is always a trade-off.
Comment: okey I see now, thanks. And this error surface that you mention is defined by the data itself and also the loss function that we choose to optimize right?


Perpendicular distance from the origin to the plane (proof in vector form).

Question: Please note I just need pointing out where my line of reasoning goes wrong.
Given a plane defined by a fixed point $A$ with coordinates $(x_a, y_a, z_a)$ position vector $\boldsymbol{a}$ and a normal vector $\boldsymbol{n}=\begin{pmatrix}a \\ b \\ c\end{pmatrix}$
We have $\boldsymbol{r}.\boldsymbol{n} = \boldsymbol{a}.\boldsymbol{n}$, where $\boldsymbol{r}$ is position vector of a general point in that plane. And the equation of a plane is thus:
$\boldsymbol{r}.\boldsymbol{n} = d$ in vector form
or
$ax+by+cz=d$ in Cartesian form.
Further, I am happy that the perpendicular distance from some point $(x_0, y_0, z_0)$ is given by
$$\frac{|ax_0 + by_0 + cz_0 - d|}{\sqrt{a^2+b^2+c^2}}$$
I also know from various sources (which state it without proof) that if a unit normal vector $\boldsymbol{\hat{n}}=\frac{\boldsymbol{n}}{|\boldsymbol{n}|} = \begin{pmatrix}\frac{a}{\sqrt{a^2+b^2+c^2}} \\ \frac{b}{\sqrt{a^2+b^2+c^2}} \\ \frac{c}{\sqrt{a^2+b^2+c^2}}\end{pmatrix}$ is used in the vector equation of a plane
$$\boldsymbol{r}.\boldsymbol{\hat{n}} = d$$
then $d$ is the perpendicular distance from the origin to the plane.
I am struggling to derive this result for myself.
(1) Using the formula for perpendicular distance of any general point:
$\frac{|a\times 0 + b\times 0 + c\times 0 - d|}{\sqrt{a^2+b^2+c^2}} = \frac{|- d|}{\sqrt{a^2+b^2+c^2}} = \frac{|-(ax_a + bx_a + cz_a)|}{\sqrt{a^2+b^2+c^2}} =  \pm\frac{ax_a + bx_a + cz_a}{\sqrt{a^2+b^2+c^2}}$
(2) Using the vector plane equation:
$\boldsymbol{a}.\boldsymbol{\hat{n}} = \frac{ax_a + bx_a + cz_a}{\sqrt{a^2+b^2+c^2}}$
The only difference is the $\pm$ sign which comes from dropping the modulus. But the modulus is in the formula for a good reason -- to account for cases when the general point $(x_0, y_0, z_0)$ is on either side of the plane.
Is it more correct then to state that in the plane equation $\boldsymbol{r}.\boldsymbol{\hat{n}} = d$, the distance from the origin is $|d|$, rather than $d$?
Answer: Your reasoning goes wrong in this line:

(...) then $d$ is the perpendicular distance from the origin to the plane.

It should be:

(...) then $\color{red}{|}d\color{red}{|}$ is the perpendicular distance from the origin to the plane.

Also you can't drop the modules that way:
$$|something|=\pm something$$
Comment: Embarrasingly for the authors, [this](https://i.imgur.com/a3pQHp1.png) was taken from the new UK [Edexcel math specification texbook](https://www.pearsonschoolsandfecolleges.co.uk/secondary/Mathematics/16plus/EdexcelASandAlevelMathematics2017/ISBN/AS/A%20level%20Further%20Mathematics%20Textbooks/EdexcelASandAlevelMathematicsFurtherPureMathematics1Textbookebook.aspx).
Comment: There is no such thing as lecture book without mistakes ;)


Are there any downsides to using dynamic EQ when mixing?

Question: I've been looking up articles on dynamic EQ and it seems to be mostly positive. I'm wondering if there's any downsides if someone were to go crazy with it like in the following workflow:
Let's say someone has a typical rock song with drums, bass, guitars, vocals and each individual track is already eq'd to their liking (but the track hasn't been compared to any other track in the song).  If they want the kick to come through with minimal masking, they add a sidechain/dynamic eq to all other instruments who produce frequencies in the range of the kick drum. That way they duck out a bit when the kick drum hits.
Then after every track has that, they move on and do the same thing again, but this time with the snare.  Then cymbals. Then  bass guitar. Then guitars, etc etc..
I'm just wondering when too much is too much and artifacts or pumping or other weird things would start to happen.
Comment: But what if some of the "artifacts" are things you want?  Half (or maybe 90%) of stomp-pedals distort or clip the source sound, after all.
Answer: I guess there is no fixed point where 'too much is too much'. This depends on many different factors like

the quality of the the tracks
how each track interfers with the others
what sound you are looking for
etc.

The best way to distinguish such a point is to use your own ears and decide it for every case on your own.
If it sounds good, its good.
A very important point here is to take some time off from your track. If you are mixing your song over a long time periode at a stretch, your ears will adapt to the sound (So what maybe usually would sound weird to you, will sound normal). Listen to some other music which sounds good to you and come back later using these songs as a reference point. It's important to prevent yourself from 'over producing' the song.
I can remember myself mixing some of my recordings the whole night through. It sounded awesome in that moment. When i came back the other day and played the track back, i was wondering what the hell i was doing...
Comment: Thanks. I don't have a specific song I'm mixing in this scenario. I'm just wondering more about what would happen if someone had the time and CPU to do something like this. Would it eventually sound awesome or completely weird. In theory the tracks would no longer interfere with each other (if they ever did) by doing this
Comment: Maybe 10 years ago or so, there was a whole flash-in-the-pan 'genre' of EDM where every kick drum, the entire BT would dive out of the way & take half a beat to come back to full volume. It sounded like $h1t. You can go too far.
Comment: I wonder if that's more a product of attack/release timings or eq. Interesting nonetheless!
Comment: @ekjcfn3902039 I guess this might help to make it sound more clean, but could eventually lead to making it sound 'clinical'. I think it would steal away the 'human' or 'natural' factor of the sound. The same way too much quantization can make a groove sound robotic and stiff.
Comment: @ekjcfn3902039 I think the genre which Tetsujin might be reffereing to is called jump style. Whats going on there is when the kick drum hits, the volume of the baseline is going all the way down and when the kick fades out, the volume of the baseline comes back up. This is called sidechaining. For this particular genre it is used very concise and giving the music some 'drive'. But this technique can also be used (not only on drums or bass) in a sutle way to make some 'room' in the mix for other tracks to stand more out.
Comment: Thanks for the info! I'll google it to see what it sounds like.  I'd imagine one would use dynamic eq to duck out a bit but not completely kill the volume. Guess I never thought about that scenario :)
Comment: That same side-chain ducking wiping out everything in the mix for a fraction of a beat still happens in various genres. It seems popular to them, although I cannot listen to it for very long without feeling very disoriented. Some current Norwegian and Dutch artists use it.


How do we obtain the combined level's HR or OR in a regression model?

Question: I would like to perform a cox PH model. I have identified 4 covariates to investigate the association with survival time.  2 of the covariates are trauma and workplace_injury each taking either Y or N. workplace_injury is not available for all observations, but only for trauma == "Y". Hence, those with trauma == "N" will have missing values for workplace_injury, and as a result, these observations will be removed from the model. Let's name the remaining 2 covariates as A and B to simplify.

So, I have decided to combine the 2 covariates into 1 covariate, as seen in the last column, i.e. trauma_wi.

Using "NonTrauma" as the reference on the model (A+B+trauma_wi), the result is as follows (I cropped out the results for A and B):

My first question:
How do I combine the results (i.e. combine the estimates), such that I can make a comparison between Trauma (Trauma_Y and Trauma_N) and NonTrauma?
My second question:
Would the results be the same if I were to run the model (A+B+trauma), i.e. ignoring the workplace_injury?
Answer: The potential problem with what you seek to do is that, if there is a difference between workplace_injury=="Y" and workplace_injury=="N", as there seems to be, then the value of a regression coefficient that only evaluates trauma as in your second question will depend on the relative prevalence of workplace_injury in your data sample. If outcomes are worse with workplace_injury=="Y" then the overall apparent association with trauma will be progressively worse for data samples weighted toward greater prevalence of workplace_injury=="Y".
There's nothing wrong with that in principle. If your data are representative of an underlying population and your interest is in a population-average estimate for the effect of trauma, that might be what you want. But you have to understand that and make that clear to your audience.
You might consider having separate predictors for trauma and workplace_injury in your model. Logically, if trauma=="N" then also workplace_Injury=="N" so you could code all your trauma=="N" cases that way. That's an accepted way to deal with situations in regression like this, when one predictor only takes non-zero values if another predictor has a non-zero value, as explained in this answer. Then you could use ANOVA to compare the nested models
model1 <- coxph(Surv(time, status)~A+B+trauma+workplace_injury

model2 <- coxph(Surv(time, status)~A+B+trauma

to evaluate the statistical significance and practical importance of workplace_injury, and proceed accordingly. The coefficients that you get from my model1 should correspond to what you have in your 3-level categorical model, with the trauma coefficient in my model1 the same as your regression coefficient for trauma_wiTrauma_N and your regression coefficient for trauma_wiTrauma_Y being the sum of the trauma and workplace_injury coefficients in my model1.* You should be able to get the same results either way, but I at least find it easier to think about the trauma and workplace_injury terms separately, particularly for evaluating the significance and importance of the different workplace_injury values.

*I find it best to do these types of intermediate analyses with the original (additive) coef values, rather than working with their exponentiations into multiplicative hazard ratios. You can then express the final results in terms of hazard ratios once you've added the individual coefficients appropriately.


Web site using using active directory groups slows to a crawl intermittently

Question: I have an asp.net mvc web site on an intranet. Access to the site is determined by groups in active directory. There are 4 different groups each having different access in the site. I have been having occasional problems with the site running slowly.  The site will run fine for several days then suddenly slow to a crawl.  I have both a test site and a production site. When the slowdown occurs both sites are affected equally. I also have a site that test site that has no active directory access and it runs with no problems while these two sites are crawling.  The sites I am having trouble are running under a user account because the application has to reach out to another share on the intranet in order to print and merge pdf files. The sites are running under the same application pool. When the problem occurs, all pages are equally slow even pages with no database activity. When the problem occurs I reset IIS, restart the web sites, and recycle the threads. The only thing that actually resolves the problem is restarting the server. Sometimes it takes a additional restart to get the site back to normal. Here are a few things I have tried. It seems the problem is occurring less often but still occurs.
1. Reduce the numbers of times that I query active directory.
2. Reset IIS when the problem occurs. This has not been helping.
3. Recycle application pools.
4. Restart the sql server service
5. Made sure fully qualified names are used when referring to servers.  This seems to have reduced the problems some. Not sure though. I am using IIS 7 on a windows 2008 server, 64 bit.
<code> user = ConfigurationManager.AppSettings["TravelCardUser.AD_GroupName"];
            approver = ConfigurationManager.AppSettings["TravelCardApprover.AD_GroupName"];
            maintenance = ConfigurationManager.AppSettings["TravelCardMaintenance.AD_GroupName"];
            admin = ConfigurationManager.AppSettings["TravelCardAdmin.AD_GroupName"];
            testuser = ConfigurationManager.AppSettings["TestUser"];

            List<string> adgroups = new List<string>();
            adgroups.Add(admin);
            adgroups.Add(approver);
            adgroups.Add(maintenance);
            adgroups.Add(user);
            this.groups = adgroups;

            List<string> groupmembership = new List<string>();

            foreach (var group in groups)
            {

                if (!String.IsNullOrEmpty(testuser))
                {
                    this.username = testuser;
                }
                else
                {
                    this.username = currentloggedinuser;
                }
                using (var ctx = new PrincipalContext(ContextType.Domain))
                using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, group))

                using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, username))
                {
                    if (groupPrincipal != null)
                    {
                        try
                        {
                            if (userPrincipal.IsMemberOf(groupPrincipal))
                            {
                                groupmembership.Add(group);

                            }
                        }
                        catch (Exception ex)
                        {
                            string theexception = ex.ToString();
                        }
                    }

                }

            }
</code>
Here is my ldap connection string.
<code>  <add name="ADConnectionString_UserRole" connectionString="LDAP://locationX/cn=TravelCardUser,ou=LocationXgroupsGroups,dc=acme,dc=us,dc=com" />
</code>
Comment: Yesterday CPU usage immediatelly became stuck at 100%. In an effort to trouble shoot the issues I have seen many errors in the event log related to team foundation server. The log on "tfsreports" had an expired password. This was fixed the server was restarted. The errors related to TFS have gone away. The server is running very fast now but it has done that in the past only to slow to a crawl without warning. I will just have to wait and see.
Answer: Ther server slows down every 3 or 4 days so I shut down the application pools to my applications and used Sysinternals to monitor process for 3 days.
http://technet.microsoft.com/en-us/sysinternals/bb896653
I am seeing that processes related to sequal server and team foundation server are grabbing resources but not releasing them. By the way I ran my asp.net code through Red Gate Memory Profiler and there are no memory leaks. Now I have to figure out what to do about the problem with memory usage.


Asymptotic equivalence for a matrix inverse depending on a time parameter

Question: Let $A : \mathbb{R} \to M_n(\mathbb{R})$ be a smooth map. We have the following hypothesis
$$A(0) = 0, \qquad A'(0) = I_n, \qquad A''(0) = 0$$
and $A(t)$ is invertible for all $t \not= 0$. I would like to show that
$$A^{-1}(t) \sim \frac{1}{t} I_n \quad \mbox{as} \quad t\rightarrow 0$$

Here is what I began to do : using Taylor's expansion for $t\not= 0$, we have $$A(t) = t I_n + G(t)$$ where $\frac{G(t)}{t^2} \rightarrow 0$ as $t\rightarrow 0$. Therefore, for $t\not= 0$, $$I_n = t A^{-1}(t) + A^{-1}(t)G(t)$$ hence $$A^{-1}(t) = \frac{1}{t}I_n - A^{-1}(t)\bigg(\frac{1}{t}G(t)\bigg)$$ It remains to show that $$A^{-1}(t)\bigg(\frac{1}{t^2}G(t)\bigg) \rightarrow 0 \quad \mbox{as}~~t\rightarrow 0$$ What do you think about it ?
Answer: Let $A=[a_{i,j}]$. By Taylor, for every $i,j$,
$a_{i,j}(t)=a_{i,j}(0)+t{a_{i,j}}'(0)+t^2/2{a_{i,j}}"(0)+O(t^3)=t{a_{i,j}}'(0)+O(t^3)$
Thus $A(t)=tA'(0)+O(t^3)=t(I+O(t^2))$.
Finally, $A^{-1}(t)=1/t(I+O(t^2))^{-1}$; since when $||U||$ tends to $0$, $(I+U)^{-1}=I+O(||U||)$, we deduce that
$A^{-1}(t)=1/t(I+O(t^2))=1/tI+O(t)$.
Comment: It works indeed, thank you very much !
Comment: It appears that the hypothesis $A''(0) = 0$ is not needed.


Replace a substring

Question: I have an input string. I need to replace its prefix (until first dot) with an other string.
The method signature:
    string MyPrefixReplace(string input, string replacer)
Examples:
string res = MyPrefixReplace("12.345.6789", "000")
res = "000.345.6789";

res = MyPrefixReplace("908.345.6789", "1")
res = "1.345.6789";

Is there a way not to extract a sub-string before first dot and make a Replace**?
I.e - I don't want this solution
int i = input.IndexOf(".");
string rep = input.Substring(0,i);
input.Replace(rep,replacer);

Thanks
Comment: What's wrong with `IndexOf` and `Substring`? (apart from the fact that you are taking the wrong part and `Replace` is not needed)
Comment: IndexOf() will give you the position, Substring() will allow you to chop that off
Comment: "I don`t want this solution" - Why?
Answer: You could use String.Split
public string MyPrefixReplace(string source, string value, char delimiter = '.')
{
    var parts = source.Split(delimiter);
    parts[0] = value;
    return String.Join(delimiter.ToString(), parts);
}

Live demo
Answer: Using String.IndexOf and String.Substring ist the most efficient way. In your approach you have used the wrong overload of Substring. String.Replace is pointless anyway since you don't want to replace all occurences of the first part but only the first part.
Therefore you don't have to take  but to skip the the first part and prefix another. This works as desired:
public static string MyPrefixReplace(string input, string replacer, char prefixChar = '.')
{
    int index = input.IndexOf(prefixChar);
    if (index == -1)
        return input;
    return replacer + input.Substring(index);
}

Your input:
string result = MyPrefixReplace("908.345.6789", "1"); // 1.345.6789
result = MyPrefixReplace("12.345.6789", "000");       // 000.345.6789

Comment: +1 it did before the OP was edited (and is still the best way to do it)
Comment: @AlexK.: i haven't seen that OP has edited his question. He uses  the wrong overload of `Substring` and `String.Replace` is pointless. `String.Substring` is the most efficient approach.
Answer: Personally, I'd split the string up to get around this problem, although there's obviously other ways of doing this, this would be my approach:
string Input = "123.456.789"

string[] SplitInput = Input.Split('.');
SplitInput[0] = "321";

string Output = String.Join('.', SplitInput);

Output should be "321.456.789".

Replace a substring


Calculating constant hazards in exponential survival distributions in R using survreg()

Question: In an ecological seed removal experiment, we have seed removal data from 720 seed plates with 25 seeds each. For each plate, we know the number of "surviving" seeds at several times ti until the end of the experiment. This results in right-censored data and a survival object for each plate that looks like this:
> s1<-with(Site_80D1, Surv(Gone,Status))
> s1
 [1]  66  128  128  128  183  183  183  183  183  183  183  183  183  183  247  247
[17] 247  247  367  367  367  367  367  367+ 367+

using survreg(), we estimate a parametric model assuming exponential survival distribution (and thus a constant hazard $h(t)=λ$).
> model1<-survreg(s1 ~ 1, dist="exponential")
> summary(model1)

Call:
survreg(formula = s1 ~ 1, dist = "exponential")
            Value Std. Error    z         p
(Intercept)  5.54      0.209 26.6 2.43e-155

Scale fixed at 1

Exponential distribution
Loglik(model)= -150.3   Loglik(intercept only)= -150.3
Number of Newton-Raphson Iterations: 3
n= 25

assuming that $h(t) = λ = \exp( -\text{Intercept})$, we calculate $λ$ by
> exp(-(summary(model1)$table[,1]))
[1] 0.00394038

The goal is to eventually be able to gather constant hazards for all 720 plates and conduct a LME (since the plates are grouped on 2 different spatial scales) including predictors that might act on the hazard as dependent variable.
My question now is: Am I correct in assuming that $h(t) = λ = \exp( -\text{Intercept})$ returns the constant hazard rate?
Thanks a lot in advance, and bear with me since this is my first time to go to CrossValidated for help on statistics.
Answer: Yes that should be the estimate of the constant hazard rate.
To my understanding, the model is of the form $\log T = \alpha + W$, so $\alpha$ should represent the log of the (population) mean survival time. For an exponential model at least, 1/mean.survival will be the hazard rate, so I believe you're correct. As a result, $\exp(-\hat{\alpha})$ should be the MLE of the constant hazard rate.
Presumably those times are days, in which case that estimate would be the instantaneous hazard rate (on the per-day scale).  [edit: no turns out they're minutes so substitute minute for day everywhere above]
Comment: Yes, $exp(α)$ returns the mean survival time. The times are minutes, so the hazard's unit would be (removal-)events per minute. Thank you very much for taking the time to respond and helping to resolve the doubts I had!
Answer: Yes, you are right that $\lambda$ is exp(-survregObj$coefficients["(Intercept)"]).
When you fit the Weibull model with survreg the output is even more confusing. Suppose you have done survregObj <- survreg(Surv(time, event) ~ 1, dist="weibull"), to fit a single Weibull model to some data with no covariates. The shape parameter of the fitted Weibull model is 1 / survregObj$scale and the scale parameter is exp(survregObj$coefficients["(Intercept)"]).
When I say "shape" and "scale" I am referring to the parameterization that is used by the R functions such as pweibull and Wikipedia (Wikipedia calls this the "standard parameterization"). Obviously survreg uses "shape" and "scale" with completely different meanings.
The parameterization that survreg uses for the Weibull distribution is explained in ?survreg (but only in the Examples section, so I didn't notice it for a long time).
Comment: Please register &/or merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own answer.


Limitar range para exibição do tooltip em gráfico de área com Highcharts

Question: Estou fazendo um gráfico de area com o Highcharts e preciso que o tooltip seja exibido apenas quando eu posicionar o cursor do mouse no ponto da série, e não na linha.
Alguém sabe se há como fazer isso?
Meu exemplo: Aqui
Att
Answer: Estive á procura e não encontrei uma solução direta. Pelos vistos isto não é possivel como "opção", mas dá para fazer.
Lendo estas duas respostas no SOen [(1) (2)] dá para fazer isso usando séries type: 'scatter'. Uma vez que essa série não dá para mostrar a área, precisa de ter o que já tem  e adicionar outra linha type: 'scatter' com os mesmos dados. Precisa ainda de juntar uma função nas opções do tootip:
    tooltip: {
        shared: true,
        formatter: function () {
            if (this.points && this.points.length == 1) {
                return false;
            } else {
                var p = this;
                return 'x: ' + p.x + '
y: ' + p.y;
            }
        }
    },

Exemplo: jsFiddle


Key hash doesn't match while Facebook login

Question: I try to use Facebook Sdk in my project,I got sha1 like this(I use Mac osX)
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

I inserted sha1 in my project,but When i try to login with Facebook,have invalid key hash error .Here is my source
 public void getFacebookLogin()
{
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().logInWithReadPermissions(
            MainActivity.this,
            Arrays.asList("email", "public_profile"));

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    System.out.println("Success");
                    accessToken= loginResult.getAccessToken();
                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject json,
                                        GraphResponse response) {

                                    if (response.getError() != null) {
                                        System.out.println("ERROR");
                                    } else {
                                        System.out.println("Success");
                                        try {
                                            facebookEmail = json.getString("email");
                                            Log.e("Token", "Token: " + accessToken.getToken());
                                            Log.e("UserID", "UserID: " + accessToken.getUserId());
                                            Log.e("facebookEmail", "facebookEmail: " + facebookEmail);
                                            if(!facebookEmail.isEmpty() && accessToken!=null && !accessToken.getToken().isEmpty())
                                                signInWithFacebook(facebookEmail,accessToken.getToken());
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,link,email,first_name,last_name,gender");
                    request.setParameters(parameters);
                    request.executeAsync();

                }

                @Override
                public void onCancel() {
                    Log.d("TAG_CANCEL", "On cancel");
                }

                @Override
                public void onError(FacebookException error) {
                    Log.d("TAG_ERROR", error.toString());
                }
            });
}

What am I doing wrong?App is turn on in developer.facebook.com's panel.When I try to add sha1 in panel I have this alertDialog from Facebook
There was a problem verifying the package mypage on Google Play. Please
check the package name and try again.
If your app isn't listed publicly on Google Play yet you can ignore
this message.

I published my app in playstore but I have only beta testing version
How i can solve my problem?
Thanks
Comment: Make sure your debug keys are in ~/.android/debug.keystore. Also, if you published on Google Play, then you used a production key, not the debug key, so you need to get SHA1 for this key not the debug key
Comment: Thanks your attention .When I put this command in terminal,I got sha1 and inserted it in panel @Mohamed_AbdAllah
Comment: The command will produce output even if you entered wrong location or wrong credentials. You must make sure you provide correct location and credentials
Comment: Also, you need to do this command on the key you used to publish on Google Play (I assume you did not used debug key)
Comment: I also tried like this   keytool -exportcert -alias myalians -keystore ~/Users/myuser/Documents/AndroidProjects/myproject/myprojectkeytools| openssl sha1 -binary | openssl base64 and got sha1 .I'm using both sha1 in panel @ Mohamed_AbdAllah
Comment: Did you enter the correct key store password?
Comment: I put this command in terminal and it got sha1 @Mohamed_AbdAllah
Answer: you are using the sha1 for debug key, regenerate the sha1 from the release key, and submit it on facebook dev website
Comment: I also tried to genarate sha1 with my project's keytools like this :   keytool -exportcert -alias myalians -keystore ~/Users/myuser/Documents/AndroidProjects/myproject/myprojectkeytools| openssl sha1 -binary | openssl base64  @AbuQauod


Evaluating $\lim\limits_{n\rightarrow +\infty }\left ( 2\sqrt[n]{x}-1 \right )^n$ for $x \ge 1$

Question: Given a real number $x\geq 1$. Find the limit
$$\lim_{n\rightarrow +\infty }\left ( 2\sqrt[n]{x}-1 \right )^n$$
Comment: HINT: use series expansion
Answer: The Taylor expansion of $x^{n}$ at $n=0$ is $\displaystyle 1+ n \ln x  + \mathcal{O}(n^{2})$.
So the Laurent expansion of $x^{\frac{1}{n}}$ at $n= \infty$ is $ \displaystyle 1 + \frac{\ln x}{n} + \mathcal{O}\left( \frac{1}{n^{2}}\right)$.
Then $ \displaystyle \lim_{n\to \infty }\left( 2\sqrt[n]{x}-1 \right )^{n} = \lim_{n \to \infty} \left(2 + \frac{2 \log x}{n}  + \mathcal{O} (n^{-2} )-1 \right)^{n}  $
$\displaystyle = \lim_{n \to \infty} \left( 1 + \frac{\log x^{2}}{n} + \mathcal{O}(n^{-2}) \right)^{n} = e^{\log x^{2}} = x^{2}$
Answer: $$\lim_{n\to\infty}(2\cdot\sqrt[n]x-1)^n=\lim_{n\to\infty}\exp\,\left[n\cdot\ln\left(2\cdot\sqrt[n]x-1\right)\right]=\lim_{n\to\infty}\exp\left[\frac{\ln(2\cdot x^\frac1n-1)}{\frac1n}\right]=$$ $$=\lim_{n\to\infty}\exp\Bigg[\frac{2\cdot x^\frac1n\cdot\ln x\left(-\frac1{n^2}\right)\bigg/\left(2\cdot\sqrt[n]x-1\right)}{-\frac1{n^2}}\Bigg]=\lim_{n\to\infty}\exp\left[\frac{2\cdot\sqrt[n]x\cdot\ln x}{2\cdot\sqrt[n]x-1}\right]=$$ $$=\exp\left[\frac{2\cdot1\cdot\ln x}{2\cdot1-1}\right]=\exp\left[2\cdot\ln x\right]=x^2$$
Comment: Please tell my why you have $$\lim_{n\to\infty}\exp\left[\frac{\ln(2\cdot x^\frac1n-1)}{\frac1n}\right]=$$$$\lim_{n\to\infty}\exp\Bigg[\frac{2\cdot x^\frac1n\cdot\ln x\left(-\frac1{n^2}\right)\bigg/\left(2\cdot\sqrt[n]x-1\right)}{-\frac1{n^2}}\Bigg]$$
Comment: L'Hopital's rule.


Manipulating compound inequalities of supremums and upper bounds

Question: $a\in A$, $b\in B$, $\alpha=\sup A$, $\beta=\sup B$, $C=\{a+b:a\in A, b\in B\}$, $\gamma$ is an upperbound for C.
I am trying to show that $\alpha+\beta\le\gamma$ i.e. $\sup C = \sup A + \sup B$.
I have determined that $b\le \beta \le \gamma - a$ and that $a\le \alpha \le \gamma - b$
I combined these inequalities to $a+b \le \alpha + \beta \le 2\gamma - (a+ b)$.
So $2(a+b) \le \alpha + \beta + (a+b) \le 2\gamma$
Clearly $\alpha + \beta + (a+b) \le 2(\alpha + \beta)$, but how do I know that $ 2(\alpha + \beta) \le 2\gamma$? Once I show this I divide by 2 and my proof is done, but I am stuck at this point.
Comment: it is assumed $a \ge 0$ and $b \ge 0$ (not mentioned in question)
Comment: I don't understand how this helps, I am sorry
Answer: Let us fix an arbitrary $b \in B$. Then for every $a \in A$ we have
\begin{equation}
a + b \leq \gamma.
\end{equation}
This is true for every $a \in A$. Thus it is also true for $\alpha$ (to see this, choose a sequence of elements in $A$ which converge to $\alpha$.) That is,
\begin{equation}
\alpha + b \leq \gamma.
\end{equation}
Now, this inequality holds for every $b \in B$ and thus it also holds for $\beta$.


A new way of thinking about $\pi$

Question: I don't know whether I should ask this question or not, but I am asking this:
(Before anything, this is an analysis of closed 2D figures.)
I was analyzing $\pi$ . It seems to be a constant, But being a constant is my curiosity. Can we say that $\pi$ is a property of circle which makes circle a circle. Same as there must be constant for each and every figure possible. So I suggested a new theory of $\pi$ or a new definition of $\pi$, which says -
$Figure_\pi = {L \over D}$
where, L = Length of the curve,
D = Maximum distance possible between any two points
So, $Circle_\pi = {Circumference \over Diameter} \implies Circle_\pi = \pi$
Also, $Square_\pi = {Perimeter \over Diagonal } \implies Square_\pi = {4a \over a\sqrt2} = {2\sqrt2}$
And, $Rectangle_\pi = {2(a+b) \over \sqrt{a^2+b^2}}$
Now I got stuck, as for rectangle I am not getting a constant, but I realized that this is obvious. Two squares or circles are always similar but two rectangles are not necessarily similar, because for two rectangles to be similar, their ratios of lengths and breadths must be constant. So I suggested types of figure on the basis of their variables.
As a circle or a square can be defined by a single variable, I called them single variable figures. For a rectangle, a rhombus, or an ellipse, we must have two variables, so I called them 2 variable figures. For random figure to be similar we must know by some means the length of the curve and maximum distance between any two points, and we will get a constant calling it $Figure_\pi$
My question is this: Am I thinking in the right direction or not, because I am finding different constants for different 2D figures as different variable figures?
Comment: It might interest you to know that [all parabolas are similar](http://mathworld.wolfram.com/UniversalParabolicConstant.html).
Comment: What would be a more interesting way (for me, at least) is to define it as the maximum of $\frac{4*Area}{Perimeter^2}$ over every closed figure where this quantity makes sense.
Comment: On a tangential note, you might be interested in looking up the "shape factor" of various shapes.
Comment: Yes, exactly, and $\pi$ must be one of them.
Comment: Thnks J.M., I didn't know that
Comment: You say this number should be a defining property of a circle, so I have to ask: is there any reason these numbers should be unique (up to scaling)?
Comment: @guy: I am not saying that this number should be unique, but I am saying that a figure must have a constant to define its shape. Two figures can have same constants, but by just knowing that constant you cant guess the figure. As per my assumption, It is a ratio which can be generated by set of numbers.
Answer: For any given shape you can define the ratio between the circumference and the longest chord, which will be a constant regardless of scale.  This is because when you double the size of the shape you double the circumference and double the chord, so the ratio stays the same.  You are correct that there is not a single ratio for all rectangles, but there is one for rectangles of a given proportion.  Your $Rectangle_\pi$ can be expressed as $$\frac {2+2\frac ba}{\sqrt{1+(\frac ba)^2}}$$ where the dependence on the proportions of the rectangle is explicit.  For a regular hexagon, the constant is 3.  It will approach $\pi$ as the number of sides increases.  You might see Wikipedia under Polygon approximation era for the story of Archimedes calculating $\pi$ in exactly this way.
Comment: @RahulTaneja:  The units are wrong.  a has units of length, while $\pi$ is dimensionless.  The perimeter is $4a$ and the diagonal is $2a \cos \frac \theta 2$ giving $Rhombus_\pi=\frac 2{\cos \frac \theta 2}$
Comment: Thanks, I already figured it out, even for rhombus, parallelogram etc. Means I am right.
Comment: like, for Rhombus,

$Rhombus_\pi = {4a \over 2 cos(\theta/2)}$

Where, $\theta$ is smaller angle in rhombus. As per my assumption, this is a 2 variable figure.
Comment: @RahulTaneja:  it shouldn't depend upon the side length, only the angle.  The long diagonal will scale with the side length.
Comment: I don't think so. You can say that the long diagonal will depend on the angle only but $Rhombus_\pi$ will depend on both, And you can see putting $\theta = 90 $degree
Comment: it is so because, Rhombus is a 2 variable figure, as was rectangle, so it wont be constant for every rhombus. As we cant say about the similarity of two rectangles, same as we cant say it about rhombus, until we know the angle
Comment: @RahulTaneja:  true, but similar rhombuses, which are ones with the same angle, will have the same value of $Rhombus_\pi$.  It will not depend on the length of the side.  Rectangles, too, are similar when the side ratios match, and the value only depends on the ratio of the sides, not the size of the rectangle.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4630/discussion-between-rahul-taneja-and-ross-millikan)

A new way of thinking about $\pi$


Two skew lines on a smooth projective surface

Question: Let $X$ be a smooth complex projective surface. Let $L_1,L_2$ be two skew lines on $X$ i.e $L_1.L_2=0$. Then can we conclude that $h^0(\mathcal O_{L_1}(-L_2))=0$?
From what I know this only happens if the product intersection number is negative. Is there a special reason for this to happen in this particular situation?
Any insight from anyone on whether this is right or wrong is appreciated.
Answer: No, the assumption $L_1 \cdot L_2 = 0$ implies
$$
\mathcal{O}_X(-L_2)\vert_{L_1} \cong \mathcal{O}_{L_1},
$$
hence it has a non-zero global section.


Which hive-site.xml is used by Hive's CLI

Question: A test server contains a lot of hive-site.xml files.
I run Hive's CLI by hive command.
How to identify which hive-site.xml file is used by that Hive's CLI?
HIVE_CONF_DIR environment variable is not set.
Answer: Execute this
hive --hiveconf hive.root.logger=DEBUG,console -e '' 2>&1 | grep hive-site.xml

Demo
bash-4.1$ hive --hiveconf hive.root.logger=DEBUG,console -e '' 2>&1 | grep hive-site.xml
17/05/29 07:45:38 [main]: DEBUG common.LogUtils: Using hive-site.xml found on CLASSPATH at /etc/hive/conf.dist/hive-site.xml
bash-4.1$


HTML POST and fetch array

Question: I have two problems here:
1. I have a problem with the value of the checkbox
2. I have a problem with the mysql_fetch_array($variable, ASSOC); method --> all the data from my database are VARCHAR type
1. All the variable with, at the end 'Cb', signified that this value is from a checkbox of a FORM. If a checkbox is checked, it means that the row (ex: Username) will be in the Select method for my Database (ex: SELECT Username FROM...)
I receive this Error
1. Undefined index: fonctionCb in C:\wamp\www\Projet Compte Utilisateur\manip_liste.php on line 7
2. Undefined variable: tab in C:\wamp\www\Projet Compte Utilisateur\manip_liste.php on line 14
...etc from all the checkbox if they are not checked .. here is my PHP code
<?php
$prep = "";

if(!$_POST['username'])
    echo 'Nom d\'utilisateur manquant';

if(($_POST["userCb"]) && ($_POST["suffixeCb"]) && ($_POST["fonctionCb"]) && ($_POST["passwordCb"])){
    $prep = " * ";
    $tab = "User    SUFFIXE     SITE    FONCTION    PASSWD";
}
else{
        if($_POST["userCb"]){
            $prep += "username ,";
            $tab += "USER   ";
        }
        if($_POST["suffixeCb"]){
            $prep += "suffixe ,";
            $tab += "SUFFIXE    ";
        }
        if($_POST["passwordCb"]){
            $prep += "password ,";
            $tab += "PASSWD ";
        }
        if($_POST["siteCb"]){
            $prep += "siteWeb ,";
            $tab += "SITE   ";
        }
        if($_POST["fonctionCb"]){
            $prep += "fonction ";
            $tab += "Fx ";
        }
    }//ELSE

require("db_action.php");   //Require in the database connection.
$bd = db_open();
$data = db_select($prep,  $_POST["username"]); //Envoie des variables à afficher et du Username pour le SELECT

echo "'$tab'";
echo "'$data'";    ?>

2. The second ERROR
and also I got this error from the fetch_array method
Error: Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in C:\wamp\www\Projet Compte Utilisateur\db_action.php on line 68
Here is the code from my method
function db_select($prep, $username){

        $querycon = "SELECT '$prep' FROM info_compte WHERE username = '$username'";
        if(!mysql_query($querycon)){
            echo "Il n\'y a aucun '$username' dans la base de données";
            $response = "";
        }
        else{
                while ($row = mysql_fetch_array(mysql_query($querycon), MYSQL_ASSOC))
                    printf("%s  %s  %s  %s  %s", $row["username"], $row["suffixe"], $row["password"], $row["siteWeb"], $row["fonction"]);  //The PRINTF dont work
            }

        return $response;
}//db_select

Thank you all to answer and i specify that i'm a beginner in practice who wants to learn ..
Comment: @ThorDozer: You should be concatenating strings with `.=` rather than `+=`. Also, try using something along the lines of `isset()` to check if a value is set. And I'm assuming your `$tab` variable is not being set as that if conditional is failing, therefore your attempts at concatenating are throwing errors.
Comment: I'm sorry, that was not my intention
Comment: @Russel Dias: What do you mean with the isset(); method. Where should i put it?
Comment: @ThorDozer: Any variable you are testing the existence of.
Comment: First Question is already answered. The second is still appearing
Comment: @ThorDozer: Answered. I think...
Comment: @ThorDozer I've added a big update to my answer that should help you make progress.
Answer: Perhaps defining $tab along with $prep at the top will get rid of the "Undefined Variable"-error
Answer: For part 1, one problem is that you may have a trailing comma on the end of $prep depending on what columns you end up selecting.  To solve this try the below code (note I've added backticks around your column names, it's good practice but not required).  The isset() function checks if a variable actually exists.  Currently you are trying to access variables that may not exist, hence the errors.
<?php
$prep = array();
$tab = '';

if(!isset($_POST['username']))
    echo 'Nom d\'utilisateur manquant';

if(isset($_POST["userCb"]) && isset($_POST["suffixeCb"]) && isset($_POST["fonctionCb"]) && isset($_POST["passwordCb"])){
    $prep[] = "*";
    $tab = "User    SUFFIXE     SITE    FONCTION    PASSWD";
}
else{
        if(isset($_POST["userCb"])){
            $prep[] = "`username`";
            $tab .= "USER   ";
        }
        if(isset($_POST["suffixeCb"])){
            $prep[] = "`suffixe`";
            $tab .= "SUFFIXE    ";
        }
        if(isset($_POST["passwordCb"])){
            $prep[] = "`password`";
            $tab .= "PASSWD ";
        }
        if(isset($_POST["siteCb"])){
            $prep[] = "`siteWeb`";
            $tab .= "SITE   ";
        }
        if(isset($_POST["fonctionCb"])){
            $prep[] = "`fonction`";
            $tab .= "Fx ";
        }
    }//ELSE

// This line glues the pieces of the $prep array back together
$prep = implode(',', $prep);

require("db_action.php");   //Require in the database connection.
$bd = db_open();
$data = db_select($prep,  $_POST["username"]); //Envoie des variables à afficher et du Username pour le SELECT

echo "'$tab'";
echo "'$data'";    ?>

For your part 2 error, you have to assign the return of the mysql_query into a variable and pass that to mysql_fetch_array.  You don't just pass it the query string.  Try this:
function db_select($prep, $username){
        $username = mysql_real_escape_string($username);
        $querycon = "SELECT $prep FROM info_compte WHERE username = '$username'";
        $response = mysql_query($querycon);
        if(!$response){
            echo "Il n\'y a aucun '$username' dans la base de données";
            $response = "";
        }
        else{
                while ($row = mysql_fetch_array($response, MYSQL_ASSOC))
                    foreach($row as $item)
                    {
                        echo $item.' ';
                    }
                }

        return $response;
}//db_select

UPDATE:
Note as well as the large addition for part 1, I've removed the single quotes around $prep in you SQL statement in part 2.
Read up on isset() but also, you can consider using array_key_exists().  I'm not sure on the relative performance comparison of the two.
Comment: All my variable from the `printf` are Undefined Index
Comment: @ThorDozer Then your value of $prep is probably wrong, and it probably shouldn't have single quotes around it.  Are the columns in your info_compte table "username", "suffixe", etc... that you use as array keys?
Comment: @Endophage: yes i verify it four times.
Comment: @Endophage: Yes I'm doing it right now.. But do i really need to do the single quotes around the word in the variable `$prep`?
Comment: @ThorDozer They're not single quotes.  This is a single quote: '  This is a backtick: `  Backticks are used to delineate database, table and column names in SQL.  You don't have to use them but it's a good practice in case at some point you accidentally use an SQL reserved keyword as a column name.  The backticks will make sure SQL doesn't error in that scenario.
Comment: @Endophage: Here's the Error now:Warning: implode() [function.implode]: Invalid arguments passed in C:\wamp\www\Projet Compte Utilisateur\manip_liste.php on line 36
Also, `db_action` return something as 'echo' : "Il n\'y a aucun Test dans la base de données"
But, in my Database, There is a User named `Test`
Comment: @ThorDozer I forgot the ; after `implode()`.  Those are the correct arguments.  Did you also make the necessary updates to $prep from my part 1 code.  $prep should now be an array.  While you may have a user named Test in the database, is that the value in $_POST['username']?
Comment: @Endophage: OK, now  a good line from the database appear but only one time.. because i have two user named `Test` and now all the index `$row['username']`, for example, at the line where's the `printf` is are Undefined
Comment: @Endophage: Correction --> the two appear BUT the checkbox who're not checked appear as undefined Index
Comment: @Endophage: And for your question --> it's the value in `$_POST['username']` to verify if it exists
Comment: @ThorDozer OK, so here's what I believe is the problem.  When you do printf you are trying to print out all the columns regardless of whether the checkbox was checked or not.  If you didn't select that column from your checkboxes it won't exist in the $row array.  Use a foreach to loop over $row and print out the elements.
Comment: @Endophage: I'm a beginner, i need an example
Comment: @ThorDozer I've added an update to the part 2 code with the foreach loop.
Comment: Oh, and I don't know how I missed it earlier, you should use .= not += for concatenating the $tab string.
Comment: @Endophage: Oh, last question --> How can I seperate each row (Like each row have his own line) At then end of each row, we put
Comment: @ThorDozer using a `` would be the normal way to do it.  Alternatively use a table as this is very tabular style data.  However, stick with the  for now.  You'll run into fewer problems.
Answer: As for your second question the expects parameter 1 to be resource, string given states that you have given it a string. In your code you have simply given it the values of $querycon which is $querycon = "SELECT '$prep' FROM info_compte WHERE username = '$username'";
 a string.
You should assign a $variable to the mysql_query function and use that in the mysql_fetch_array method as the first param.
For the sake of completeness:
To answer your first question, your $tab variable is not being set as that if conditional is failing, therefore your attempts at concatenating are throwing errors.
Comment: @ThorDozer: There's no need to call `mysql_query` twice. Simply assign a variable to it before your first `if` statement. Also, can you do a `var_dump` of the `$row` in the while loop ?
Comment: DONE --> but ..if you look at the 'printf' .. when i execute it...nothing appear except the value of $tab
Comment: @Russel Diaz: I'm sorry :S like I said i'm a begginer and also .. i'm French so I don't understand the entire part of your last comment. About the var_dump .. what do i need to do?
Comment: @ThorDozer: `var_dump` is a good way to dump data regarding a variable. I just want to see if `$row` returns anything at all. Because your code looks OK to me ... also, just to be sure, at the start of your document set `error_reporting(-1);`.
Comment: @Russel Dias: Every Variable on the line of the `printf` are Undefined Index and the variable  `$row['username']` for example, return nothing (null)
Comment: @ThorDozer: Maybe your query is failing? or the assignment of `$row` to `mysql_fetch_array`

HTML POST and fetch array


Are $A^TP+PA<0$, $P>0$ and $A^TP+PA\leq-I$, $P\geq I$ equivalent?

Question: Consider the LMI, where $A$ is a Hurwitz matrix:
$A^TP+PA<0$, $P>0$, minimize trace(P)
According to Stephen Boyd's book, the inequalities are homogeneous in $P$ and hence can by replaced with the nonstrict inequalities:
$A^TP+PA\leq-I$, $P\geq I$, minimize trace(P)
I do not understand why this is equivalent. Apparently the solution $P$ changes.
Comment: Boyd wrote several books
Answer: If $P$ is a solution to $A^\top P + P\,A \leq -I,\ P \geq I$ then scaling $P$ by some arbitrary small positive constant $\gamma$ the strict inequalities are also always satisfied, since
$$
\begin{array}{c}
A^\top \gamma\,P + \gamma\,P\,A \leq -\gamma\,I < 0, \\
\gamma\,P \geq \gamma\,I > 0.
\end{array}
$$
So the solution to the nonstrict inequalities can always give you a solution to the strict inequalities.
Comment: (+1) just to add, my understanding of the "homogeneous in $P$" part in Boyd's book is that if we define the function $F(P) = A^T P + PA$, then $$F(\gamma \cdot P) = A^T (\gamma \cdot P) + (\gamma \cdot P)A = \gamma \cdot (A^T P + PA) = \gamma \cdot F(P)$$
Answer: Because $A^T P + P A$ and $P$ are homogenous functions of $P$, they are equivalent in the following sense:

Any solution of the non-strict inequalities ($A^T P + P A \leq -I$ and $P \geq I$) is necessarily a solution of the strict inequalities ($A^T P + P A < 0$ and $P > 0$).
For any solution of the strict inequalities there exists a solution of the non-strict inequalities (which itself will satisfy the non-strict inequalities)

We conclude that the LMI $A^T P + P A < 0$ and $P > 0$ has a solution if and only if $A^T P + P A \leq -I$ and $P \geq I$ has one.
See this answer for a detailed explanation of why homogeneity is needed to show this.
Answer: Here is a more formal proof that complements the other answers.
We want to solve the following feasibility problem
$$
\begin{aligned}
\textrm{find} \quad & X \\
\textrm{s.t.} \quad & X \succ 0 \\
\quad & A^T X + XA \prec 0
\end{aligned} \tag{1}
$$
by solving the following feasibility problem instead
$$
\begin{aligned}
\textrm{find} \quad & X \\
\textrm{s.t.} \quad & X \succeq I \\
\quad & A^T X + XA \preceq -I
\end{aligned} \tag{2}
$$
There are two possible outcomes of the problem in $(2)$: Either an $X$ exists that satisfies the feasibility constraints, or it doesn't. When an $X$ exists that satisfies the feasibility constraints in $(2)$, we want to be able to say that this same $X$ also satisfies the feasibility constraints in $(1)$. Similarly, when an $X$ that satisfies the feasibility constraints in $(2)$ does not exist, then we want to be able to say that there also does not exist an $X$ that satisfies the feasibility constraints in $(1)$.
Therefore, we want to prove the following two statements:

If there exists an $X$ such that $X \succeq I$ and $A^T X + XA \preceq -I$, then $X \succ 0$ and $A^T X + XA \prec 0$.
If there does not exist a $Y$ such that $Y \succeq I$ and $A^T Y + YA \preceq -I$, then there does not exist an $X$ such that $X \succ 0$ and $A^T X + XA \prec 0$.

We first prove statement (1) as follows. Suppose that there exists an $X$ such that $X \succeq I$ and $A^T X + XA \preceq -I$. Because $X \succeq I$ and $I \succ 0$, then $X \succ 0$. Similarly, because $A^TX + XA \preceq -I$ and $-I \prec 0$, then $A^TX + XA \prec 0$, as desired. Note that we did not need to use the fact that $F(X) = A^TX + XA$ is homogeneous in $X$ here.
Next, we prove statement (2). We do so by proving the contrapositive of statement (2), which is: "If there exists an $X$ such that $X \succ 0$ and $A^TX + XA \prec 0$. then there exists a $Y$ such that $Y \succeq I$ and $A^TY + YA \preceq -I$". Suppose that there exists an $X$ such that $X \succ 0$ and $A^TX + XA \prec 0$. For any $X \succ 0$, there exists a $\lambda_1 \in (0,\lambda_\min(X)]$ such that $X - \lambda_1 I \succeq 0$, or $X \succeq \lambda_1 I$, where $\lambda_\min(X)$ is the smallest positive eigenvalue of $X$. Similarly, because $A^TX + XA \prec 0$, then there exists a $\lambda_2 \in (0,|\lambda_\max(A^TX + XA)|]$ such that $A^TX + XA + \lambda_2I \preceq 0$, or $A^TX + XA \preceq -\lambda_2I$, where $\lambda_\max(A^TX + XA)$ is the largest negative eigenvalue of $A^TX + XA$.
So, as a first step, choose $\lambda_1$ and $\lambda_2$ such that $\lambda_1 \leq \lambda_2$. This choice is guaranteed to exist, since when $\lambda_\min(X) > |\lambda_\max(A^TX + XA)|$, such that $\lambda_1 \in (0,\lambda_\min(X)]$ and $\lambda_2 \in (0,|\lambda_\max(A^TX + XA)|]$, we can choose $\lambda_1 \in (0,|\lambda_\max(A^TX + XA)| - \varepsilon]$ for a small enough $\varepsilon > 0$, and then choose $\lambda_2 \geq \lambda_1$. All other cases follow similarly.
Next, let $Y = \frac{1}{\lambda_1}X$. Since $X \succeq \lambda_1 I$ as shown above, then $Y \succeq I$, as desired. Similarly, since $A^TX + XA \preceq -\lambda_2I$, then we can multiply both sides of this inequality by $\frac{1}{\lambda_1}$ to get
$$
\begin{align}
\frac{1}{\lambda_1} \cdot \left(A^TX + XA\right) &\preceq -\frac{\lambda_2}{\lambda_1}I \\
A^T \left(\frac{1}{\lambda_1}X\right) + \left(\frac{1}{\lambda_1}X\right) A &\preceq -\frac{\lambda_2}{\lambda_1}I \\
A^T Y + Y A &\preceq -\frac{\lambda_2}{\lambda_1}I
\end{align}
$$
Because $\lambda_1 \leq \lambda_2$, then $-\frac{\lambda_2}{\lambda_1}I \preceq -I$, and so $A^T Y + YA \preceq -I$, as desired. Note that we used the fact that $F(X) = A^TX + XA$ is homogeneous in $X$ here.


Find all matrices satisfying $X^3=I-X$

Question: We are studying for a qualifying exam and have come across the following problem in a previous exam.

Determine the solutions (if any) of the matrix equation $X^3=I-X$ in the $2 \times 2$-matrices over $\mathbb{R}$.

Any hints in the right direction would be much appreciate for this.
Comment: Start from the diagonal case.Then you will identify necessary conditions for eigenvalues. After this it is easy to prove that if $X$ is solution then  $VXV^{-1}$ for any non singular $V$ is also a solution.Actually you even don't have to diagonalize. If $\lambda$ is eigenvalue and $u$ is eigenvector than you have $\lambda^3=1-\lambda$ . Solve the equation. All matrices with such eigenvalues will be solutions.
Answer: The polynomial $x^3+x-1$ has one real root $\alpha$ and two conjugate complex non real roots $\beta$ and $\overline \beta$. Since this polynomial annihilates the matrix $X$ then their eigenvalues belong to the set of roots of the polynomial and since $X$ is a real matrix then there's two cases:

$\alpha$ is the only eigenvalue of $X$ and if $X$ isn't diagonalizable then the minimal polynomial is $(x-\alpha)^2$ divides the given polynomial which isn't true so $X$ is diagonalizable and then $X$ is similar to $\alpha I_2$.
$\beta$ and $\overline\beta$ are the eigenvalues of $X$ so the minimal polynomial of $X$ is $(x-\beta)(x-\overline\beta)=x^2-2\operatorname{Re}(\beta) x+|\beta|^2$ so let
$$X=\begin{pmatrix}a&b\\c&d\end{pmatrix}$$
and since
$$\chi_X(x)=\det(X-xI_2)=(a-x)(d-x)-cb=x^2-(a+d)x+ad-cb$$
hence we choose $a,b,c$ and $d$ such that
$$a+d=2\operatorname{Re}(\beta)\quad;\quad ad-cb=|\beta|^2$$
Comment: Being similar to $\alpha I$ means being equal to $\alpha I$.
Comment: Absolutely right:-)
Comment: Also, possibly worth noting that $|\beta|^2 = \beta\bar\beta = \alpha^{-1}$, and $\beta+\bar\beta=2\mathrm{Re}(\beta)=-\alpha$.
Comment: Why would $\beta$ be related to $\alpha$?
Answer: Hint: The matrix satisfies $X^3+X-I=0$. What can you say about the minimal polynomial?
Answer: The equation is $x^3+x-1=0$ now a two by two matrix has a minimal polynomial of degree $\leq 2$. So which quadratic or linear polynomials divide tbe above cubic ?
Comment: Notice that, if there is a quadratic polynomial that divides $x^3+x-1$ then there must be also a linear polynomial that divides it (the quotient). Hence, it suffices to check whether or not there is a linear polynomial that divides the matrix.
Comment: @bartgol Well it has just one real root. So see the accepted answer, it is not really clear what the best from to express the matrices with quadratic minimal poly. I would like to know what the intended answer was, since it is for a qualifying exam.
Answer: Hint
You can start looking at the eigenvalues of $X$. What kind of relationship there is? Can you find the eigenvalues of $X$?
Answer: Note that this polynomial has one real root and two complex conjugates.  For a real matrix, if one of the complex solutions is an eigenvalue then so is the other.  A real $2 \times 2$ matrix with eigenvalues $a \pm bi$ is
$$ \pmatrix{ s & t \cr -((a-s)^2 + b^2)/t & 2a - s }$$
for arbitrary $s$ and $t \ne 0$.
On the other hand, if the real root $r$ is an eigenvalue, it is the only one, and
has geometric multiplicity $2$, so the matrix is $r I$.

Find all matrices satisfying $X^3=I-X$


What does a p-value of 0 imply in a Ljung Box statistic?

Question: What does a p-value of 0 in the Ljung-Box statistic imply?
When I use the multivariate time series and fit a VARMA model, the Ljung-Box statistic (applied to residuals) gives values larger than 0.05 for all lags but the first two which are 1.
On the contrary, when I use difference series, I get 0's for all the lags but the first two which are 1.
According to my understanding, the 0's imply that correlation exists in the fitted model.
Answer: The null hypothesis of the Ljung-Box test is that the autocorrelations (for the chosen lags) in the population from which the sample is taken are all zero. (See this thread for some more details on the test and the distribution of its statistic under the null.)
If your p-value is below your chosen significance level, you reject the null hypothesis in favour of the alternative that at least one of the autocorrelations is not zero in population.
When applying the test on model residuals, you wish not to reject as otherwise the model assumptions are likely to be violated (we typically assume the errors are not autocorrelated).

What does a p-value of 0 imply in a Ljung Box statistic?

When applied on model residuals, it implies the model errors are autocorrelated, and thus you might not trust the model output (if the model is built under the assumption of non-autocorrelated errors, which it normally is).
Edit: as indicated by Michael Chernick, a p-value would not be exactly zero as that would only happen if the test statistic were infinitely large. But the p-value could be close to zero for a sufficiently large statistic, and then the software could round it to zero.
But read this thread which warns against using the Ljung-Box test on residuals from ARMA models.
Comment: The answer contains very useful information.  But under what circumstance would a p-value of exactly 0 be obtained? I don't think it would.
Comment: @MichaelChernick, thank you, I will update the post.