Pegar id do ultimo registro inserido no banco

Question: Queria saber se tem como eu inserir um registro no banco e ja retorna o id deste registro em android sqlite
uso este metodo para inserir
public boolean insertH(HistoricoObjeto historico) {

    /* Mapa com a coluna e os valores de cada coluna. */
    ContentValues values = new ContentValues();
    values.put("datahora", historico.getDatahora());
    values.put("mensagem", historico.getMensagem());

    /* Executa um insert no banco de dados usando o mapa de valores. */
    /* Retorna -1 caso ocorra algum erro no INSERT. */
    long retorno = this.banco.insert("historico", null, values);

    if(retorno != -1)
        return true;
    else
        return false;
}

Comment: http://www.sqlite.org/lang_corefunc.html#last_insert_rowid
Comment: Já pensou em fazer uma query retornando o ultimo registro inserido por ordem descrescente.
Answer: Tenta assim:
SELECT *
FROM    TABLE
WHERE   ID = (SELECT MAX(ID)  FROM TABLE);

Answer: Bem, na verdade, a classe SQLiteDatabase tem seu próprio método de inserção que retorna o ID da linha recém-criado. Penso que esta é a melhor maneira de obter o novo ID. Você pode verificar sua documentação:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Answer: public long insertH(HistoricoObjeto historico) {

/* Mapa com a coluna e os valores de cada coluna. */
ContentValues values = new ContentValues();
values.put("datahora", historico.getDatahora());
values.put("mensagem", historico.getMensagem());

/* Executa um insert no banco de dados usando o mapa de valores. */
/* Retorna -1 caso ocorra algum erro no INSERT. */
long retorno = this.banco.insert("historico", null, values);
return retorno;
}

este retorno fica com o id no ultimo histórico inserido


SQL Group by Count and Date

Question: I have two tables
Table 1:
'table1Id' int,
'date' date

Table 2:
'table2Id' int,
'table1Id' int,
'switchVal' int DEFAULT NULL,
FOREIGN KEY 'table1Id' REFERENCES table1('table1Id')

How do I go about displaying the count table1Id grouped by date assuming that switchVal is not null?
Comment: Which dbms are you using? (Those single quotes are confusing me.)
Answer: Something like this:
SELECT        SUM(dbo.Table_1.table1Id) AS Expr1, dbo.Table_2.switch1val, dbo.Table_1.date
FROM            dbo.Table_1 INNER JOIN
                         dbo.Table_2 ON dbo.Table_1.table1Id = dbo.Table_2.table1id
GROUP BY dbo.Table_2.switch1val, dbo.Table_1.date
HAVING        (dbo.Table_2.switch1val IS NOT NULL)

Comment: Had to make a couple small changes to this, but this helped immensely. Thanks!
Comment: Thanks, give is an upvote if that worked for you.
Comment: Why did you put switch1val IS NOT NULL in the HAVING clause instead of in WHERE?
Answer: You need to join the tables and group by based on the column table1Id.
Select t1.date, count(t1.table1Id) as 'Count' from Table1 t1 inner join Table2 t2 on t1.table1Id = t2.table1Id
where t2.[switchVal] is not null
group by t1.date

SQL Group by Count and Date


software for genome wide associations studies (GWAS)

Question: I have just started learning about genome wide associations studies (GWAS) as I will have to run some of them in the near future, and I am pretty confused about which are the best computational tools available for my dataset.
In particular, I have almost 10 millions SNPs that I would like to test against clinical numerical covariates such as blood pressure. Moreover, I have some high dimensional phenotypes that I would like to reduce to 40/50 variables using dimensionality reduction (PCA etc.) and test them in the same multivariate model.
Which software/implementation would you advise for performing this statistical analysis, please?
Answer: While I personally make my own models in Python there are out of the box libraries for R like SNPassoc
I'm going to assume you're an academic if you're asking this question so here's also the link to the paper.
Comment: @fastDio even if you choose to run the computations yourself, if you are at an academic institution get advice early on from a statistician trained in these analyses, as there are many ways the analyses and interpretations can go wrong. You don't want to be in a situation where, after much work, you have to start over again when a reviewer of your manuscript notes a fatal flaw in your approach.
Answer: Depending on the number of samples

PLINK Smaller datasets
BOLT-LMM Larger datasets, for example UK Biobank approx. 500K samples / participants

You can find a more comprehensive list here:
https://omictools.com/association-mapping-category


Rationale for different activation function neural network pretraining vs. supervised training?

Question: I was reading a paper that used neural networks to predict protein conformation, Improving prediction of secondary
structure, local backbone angles,
and solvent accessible surface
area of proteins by iterative deep
learning:

Linear activation function was used for the hidden layers of
  auto encoder training whereas sigmoid activation function was employed at the stage of back propagation.

Little unclear, but I interpret this to mean they did their sparse autoencoder parameter initialization training with a linear activation, then did the supervised training with a sigmoidal activation.
What's the rationale for this? I assumed that NN weights were only meaningful in the context of a particular activation function, and the whole point of the autoencoder-y initialization was to make the weights relevant for the supervised training...?
Answer: The excerpt:

Deep neural-network learning
Here, we employed the same deep learning neural network as we have employed for prediction of Cα-based θ and τ angles prediction by SPIDER16. Briefly, the deep artificial Neural Network (ANN) consists of three hidden layers, each with 150 nodes. Input data was normalized to the range of 0 to 1. Weights for each layer were initialized in a greedy layer-wise manner, using stacked sparse auto-encoders which map the layer's inputs back to themselves32 and refined using standard backward propagation. The learning rate for auto encoder stage was 0.05 and the number of epochs in auto encoder stage was 10. The learning rates for backward propagation were 1, 0.5, 0.2, and 0.05, respectively, with 30 epochs at each learning rate. In this study, we used the deep neural network MATLAB toolbox, implemented by Palm33. Linear activation function was used for the hidden layers of auto encoder training whereas sigmoid activation function was employed at the stage of back propagation. All these hyper parameters were obtained by a few initial studies of a single fold (90% for training and 10% for test), randomly selected from the training TR4590 dataset.

So yeah, I believe what you said is right. Their stacked autoencoder approach uses linear activations, while sigmoid activation is used in the final model.
What you said about using the same activation for both the pre-training and refinement makes sense. The inputs to the second layer should be bounded by the sigmoid activation of the previous layer, which is not respected when using linear activations.
Consider, however, that the pre-training does not aim to retrieve optimal weights for the supervised refinement. Its main objective is to supply meaningful starting values (the autoencoder captures inter-observation variability, which should be partially explainable by the output of the supervised model).
So, that's why, even though the distribution of the weights in the pre-training deviates from the distribution of the weights in the refinement phase, it's still possible to get good results out of the procedure solely from the fact that the pre-training put the network on track of good weights.


Admin control in C# giving error

Question: I'm writing a control to add a button to edit my pages. The control is named adminlinks and it contains a link that should only be visible to the role admin. Any Ideas on why i'm getting the error invalid token with this script? Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.UserControl;
using Microsoft.Ajax.Utilities;

public partial class Controls_adminlinks : System.Web.UI.UserControl
{
protected void Page_Load(object sender, System.EventArgs e);

if (Context.User.IsInRole("Admin"))
{
    uc1:adminlinks.Visible = true;
}
else
{
    uc1:adminlinks.Visible = false;
}

Comment: which line gives you the error?
Comment: This LIne:if (Context.User.IsInRole("Admin"))
    {
        uc1:adminlinks.Visible = true;
    }
    else
Comment: but does it fail at the `if (Context.User.IsInRole("Admin"))` or at the `uc1:adminlinks.Visible = true;`
Comment: Apologies if fails at the if
Comment: It states: invalid token "if" in class, struct, or interface member declaration
Answer: You need a method.
Your if statement is in the class and not a method.  For example:
    public void TestMethod()
    {
          if (Context.User.IsInRole("Admin"))
           {
             uc1:adminlinks.Visible = true;
            }
          else
         {
           uc1:adminlinks.Visible = false;
         }
    }

Answer: you issue is that the code is not containted in you Page_Load function.  You have:
protected void Page_Load(object sender, System.EventArgs e);

But it should be:
protected void Page_Load(object sender, System.EventArgs e){

    if (Context.User.IsInRole("Admin"))
    {
        uc1:adminlinks.Visible = true;
    }
    else
    {
        uc1:adminlinks.Visible = false;
    }
}

Admin control in C# giving error


apache2 mod_proxy in conjuction with mod_rewrite not working as expected

Question: I am trying to use mod_rewrite in conjunction with mod_proxy to deliver contents from a different internal webserver (http://webserver.internal.com/foo) through a (fake) subdirectory "foo" (http://example.com/foo).
Using mod_proxy with ProxyPass directive I was able to do this already with this configuration in /etc/apache2/mods-enabled/proxy.conf
ProxyPass /foo http://webserver.internal.com/foo
ProxyPassReverse /foo http://webserver.internal.com/foo

Now I have the additional requirement to enforce rewriting all requests to dynamic resources from http://example.com to https:// example.com, which again standalone works as well, but not together with the ProxyPass rules stated above. It seems the proxy configuration has always precedence over the rewrite rules.
As as far as my research has shown me utilizing mod_proxy from within my rewrite rules should be as easy as adding
RewriteCond %{REQUEST_URI} ^/foo
 RewriteRule ^/foo(.*) http://webserver.internal.com/foo$1 [P]
to my rewrite rules and the rewritten URI will be automatically passed through mod_proxy. I turned on RewriteLog with a LogLevel of 9, but I am not able to see the matching of ^/foo and execution of the following Proxy-RewriteRule afterwards. There is nothing like go-ahead proxy, or any mention of proxying, not even an error entry within the RewriteLog.
I have the following proxy modules activated in my apache2 configuration
proxy
proxy_connect
proxy_http

I tried to test my RewriteCondition with another example - this time matching ^/foo and redirecting to www.google.com
RewriteCond %{REQUEST_URI} ^/foo
RewriteRule ^(.*)$ http://www.google.com/ [R=302,L]

which is working as intended, with the following results in the RewriteLog:
RewriteCond: input='/foo' pattern='^/foo' => matched
 rewrite 'foo' -> 'http://www.google.com/'
 explicitly forcing redirect with http://www.google.com/
 escaping http://www.google.com/ for redirect
 redirect to http://www.google.com/ [REDIRECT/302]
Following below is the rewrite configuraiton I am using within a directory section of my vhost.
    <Directory /my/app/webroot >
            RewriteEngine On
            RewriteBase /

            #redirect all http requests to https - WORKING
            # incoming request was forwarded as http from ELB
            RewriteCond %{HTTP:X-Forwarded-Proto} =http
            # avoid https rewriting for static files like images, javascripts, files and templates
            # for folders /img, /js, /css, /files and /templates under webroot
            RewriteCond %{REQUEST_URI} !^/(img|js|css|files|templates)
            RewriteRule (.*) https:// example.com%{REQUEST_URI}  [R=301,L]

            # requests to /foo *should* be handled by mod_proxy - NOT WORKING
            RewriteCond %{REQUEST_URI} ^/foo
            RewriteRule ^/foo(.*) http://webserver.internal.com/foo$1 [P]

            #pretty URLS for web-application - WORKING
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
    </Directory>

The machine in question is a basic debian server installation, with apache2 and php and is hosted in the amazon cloud behind a Elastic Load Balancer.
If you read down this far - first of all - thank you for patience!
It would be great if somebody could help with resolving this problem. Maybe it is just a little think I've overseen.
Many thanks in advance!
Answer: Wrong:
RewriteRule ^/foo(.*) http://webserver.internal.com/foo$1 [P]

Сorrectly:
RewriteRule ^foo(.*)$ http://webserver.internal.com/foo$1 [P,L]

Will be a problem, write to email.


CodeIgniter abre muitas conexões com o Banco de dados

Question: Tenho uma aplicação no cliente e eles estão reclamando que ela está abrindo muitas conexões com o banco de dados, fazendo cair o servidor.
Procurei na internet e não achei algo relacionado.
Gostaria de saber se o CodeIgniter fecha automaticmente a conexão com o banco quando ela é realizada ou se tem algo para fechar.
Sou novo com CodeIgniter e a aplicação já estava feita quando entrei aqui. Ela está usando Active Record para fazer as queries.
Comment: Obteve alguma resposta LigDark???
Answer: Em application/config/database.php, verifique se a configuração $db['default']['pconnect'] = TRUE; coloque FALSE, porque, com TRUE a conexão fica persistente.
$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'senha';
$db['default']['database'] = 'testdb';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE; // Coloque FALSE
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Obs: É a única configuração que tem esse perfil de deixar a conexão aberta
Comment: Mandei a solução para o cliente , e não obtive retorno ainda, mas acho que deu certo.
Valeu mano.
Comment: Alguma Noticia @LigDark
Comment: Cara, acho que funcionou , não tive um retorno negativo do cliente... obg :)
Answer: No caso da conexão acima desabilita o db_debug ($db['default'][''] = FALSE);
As conexões com o banco vão ter um desempenho melhor.


how to check if it's Saturday and set to nearest Day in the same month

Question: How to check if the date falls on a Saturday, then it will be set to nearest day in the same month?
2 Scenarios:

E.g. If Saturday falls on 21st, then it will be set to 20th,
Friday
E.g. If Saturday falls on 1st, then it will be set to
3rd (Monday)
Comment: how does the 2nd scenario satisfy "then it will be set to nearest day in the same month"?
Comment: You probably want to look up `java.util.Calendar` - https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Comment: I'd suggest to avoid Calendar like the plague if you are using Java 8 and instead look at the new javax.time APIs
Comment: Thanks for the highlight. Have change the question. :)
Answer: Not really sure if I have understood exactly what you want, but do you want something like this (Java 8 needed...)
<code>public static void main(String[] args) {
    System.out.println(toNearestDayInSameMonthIfSaturday(LocalDate.of(2015, 4, 4))); // Print 2015-04-05
    System.out.println(toNearestDayInSameMonthIfSaturday(LocalDate.of(2015, 4, 18))); // Print 2015-04-19
    System.out.println(toNearestDayInSameMonthIfSaturday(LocalDate.of(2015, 4, 25))); // Print 2015-04-25
}

private static LocalDate toNearestDayInSameMonthIfSaturday(LocalDate local) {
    LocalDate result;
    if (local.getDayOfWeek() == DayOfWeek.SATURDAY) {
        LocalDate plusOneDay = local.plusDays(1);
        LocalDate minusOneDay = local.minusDays(1);

        if (plusOneDay.getMonthValue() != local.getMonthValue()) {
            result = minusOneDay;
        } else {
            result = plusOneDay;
        }
    } else {
        result = local;
    }

    return result;
}
</code>


A stronger way to solve $T\left ( n \right )= 2T\left ( n/4 \right )+ n^{1/2+ \epsilon}$ where $\epsilon= 0.01$, excluding the Master theorem

Question: I want to ask you a further way to solve $T\left ( n \right )= 2T\left ( n/4 \right )+ n^{1/2+ \epsilon}$ where $\epsilon= 0.01$, excluding the Master theorem.
By Master theorem, we have $b= a^{2}$ and $f\left ( n \right )= \Omega\left ( n^{1/2+ \epsilon} \right )$ and the regularity condition holds, then $T\left ( n \right )= \Theta\left ( f\left ( n \right ) \right )$ for $f\left ( n \right )= n^{1/2+ \epsilon}$.
How could we deal the $\epsilon= 0.01$ of the new stronger algorithm? For example, using $\ln 2\ln 2+ \epsilon< 1/2$.
I need your help. Thank you so much!
Answer: Hint.
Make $n=4^m$ and the recurrence recast to
$$
r_m = 2r_{m-1}+\left(4^m\right)^{\frac 12+\epsilon}
$$
with solution
$$
r_m= 2^{m-1}c_0+\frac{2^m\cdot 4^{(m+1)\epsilon}-2^{m+2\epsilon}}{4^{\epsilon}-1}
$$


If two sample means of $X$ differ significantly and $X$ predicts $Y$, can it be inferred that the samples differ in their $Y$?

Question: In the following model:
$Y = \beta_0 + \beta_1 X + \epsilon $
$X$ is found to be significantly related to $Y$.
Now, I observe $X$ within two groups. I compare the two means and find that the $X$ values significantly differ between the two groups, on average.
Can I conclude that $Y$ is significantly different between the two groups?
Comment: Could you clarify what you mean by "observe $X$ within two groups?" It is crucial to know whether these observations are part of the dataset used to fit the model or whether they are independent observations.
Comment: Thats a smart remark. They are used to fit the overall model. The sample used to estimate the model consists (exclusively) of the two abovementioned group samples.
Comment: You can't conclude much from this information, but why bother?  Couldn't you just directly test the two sets of $Y$ values corresponding to the two groups?  What is preventing that?
Comment: In general, you are right. I was just interested in wether one could draw such a conclusion or not.
Answer: No, you cannot.
Slightly simplified, you are saying that you do know that $cor(X, Y) \neq 0$, and that $cor(X, G) \neq 0$, where $G$ is the group indicator.
But correlation (or, more generally, statistical dependence) is not "transitive", so $cor(X, G) \neq 0$ does not follow.
The simplest counterexample is the causal graph $Y \rightarrow X \leftarrow G$. In this graph, $X$ and $Y$ are dependent, as well as $X$ and $G$, but $Y$ and $G$ are independent.


Como adicionar 0 n frente de numeros menores que 9 para um timer?

Question: Estou fazendo um timer a para a função que escrevi, não estou conseguindo adicionar o 0 na frente dos numeros menores que 9. Ja tentei declarar dentro de timer():
if (seconds.innerText < 10) {
seconds.innerText = `0${seconds.innerText}`;
}

deu certo, mas no final, quando reseta o timer fica 15:000  ao invés de 15:00. Fiz a mesma coisa para minutos :
if (minutes.innerText < 10) {
minutes.innerText = `0${minutes.innerText}`;
}

mas quando aperto play, a partir de 9 min começa a acrescentar infinitos 0s ao invés de só 1. Será que conseguem ajudar? :)

var start = document.getElementById("start");
var reset = document.getElementById("reset");

var minutes = document.getElementById("minutes");
var seconds = document.getElementById("seconds");

var bell_meditate = new Audio("./midia/bell_meditate.mp3");

var startCountner;

function Start() {
  bell_meditate.play();
  if (startCountner === undefined) {
    startCountner = setInterval(timer, 1000);
    document.getElementById("daily-title").innerHTML = "Your daily";
    document.getElementById("daily-title").classList.add("daily-title");
    document.getElementById("meditation-title").innerHTML = "Meditation";
    document
      .getElementById("meditation-title")
      .classList.add("meditation-title");
    document.getElementById("pulse").style.animation =
      "pulse 4s infinite alternate";
  } else alert("Time is already running");
}

function Reset() {
  minutes.innerText = 15;
  seconds.innerText = "00";
  stopInterval();
  startCountner = undefined;
}

function timer() {
  if (seconds.innerText != 0) {
    seconds.innerText--;
  } else if (minutes.innerText != 0 && seconds.innerText == 0) {
    seconds.innerText = 59;
    minutes.innerText--;
  } else if (seconds.innerText == 0 && minutes.innerText == 0) {
    document.getElementById("daily-title").innerHTML = "";
    document.getElementById("meditation-title").innerHTML = "Namastê";
    document
      .getElementById("meditation-title")
      .classList.add("message-namaste");
    audio();
    Reset();
  }

}

function audio() {
  bell_meditate.play();
}

function stopInterval() {
  clearInterval(startCountner);
  document.getElementById("pulse").style.animation = "none";
}
Answer: Para resolver isso você pode ao invés de utilizar strings nos minutos e segundos, utilizar numeros, e na hora de mostrar esses numeros converter pra string e adicionar o padStart, onde você coloca str.padStart(comprimentoDesejadoDaString, oQueVocêQuerAdicionar).
Se você colocar 2 no comprimentoDesejadoDaString a função vai preencher com oQueVocêQuerAdicionar até você ter 2 de comprimento.
O oQueVocêQuerAdicionar então é qualquer coisa que você queira preencher até chegar no comprimentoDesejadoDaString, se você colocar 0, vai preencher com 0's, se você não colocar nada ele vai preencher com um espaço em branco ( ).
Quando você for diminuir os valores você transforma em string pra retornar pra tela.
...
function timer() {
  if (seconds.innerText != 0) {
     parseInt(seconds.innerText--);
     seconds.innerText = seconds.innerText.toString().padStart(2,'0');
  } else if (minutes.innerText != 0 && seconds.innerText == 0) {
    seconds.innerText = 59;
    parseInt(minutes.innerText--);
    minutes.innerText = minutes.innerText.toString().padStart(2,'0');
  }
   ...
}

Coloquei um exemplo rodando por console.log pra você ver, nesse exemplo eu não estou trocando nada no codigo, só no console.log que eu transformo em string. No seu caso seria no momento que você troca na tela. Assim como descrito acima.

var minutes = 15;
var seconds = 0;

var startCountner;

function Start() {
    if (startCountner === undefined) {
        startCountner = setInterval(timer, 1000);
    } else alert("Time is already running");
}

function stopInterval() {
    clearInterval(startCountner);
}

function Reset() {
    minutes = 15;
    seconds = 0;
    stopInterval();
    startCountner = undefined;
}

function timer() {
    console.log(minutes.toString().padStart(2,'0'), seconds.toString().padStart(2,'0'))
    if (seconds != 0) {
        seconds--;
    } else if (minutes != 0 && seconds == 0) {
        seconds = 59;
        minutes--;
    } else if (seconds == 0 && minutes == 0) {
        Reset();
    }

}

Start()
Comment: muito obrigada!! Eu consegui, ao final, fazer funcionar de outra maneira, mas ficou meio confuso. Eu não conhecia o padStart, ficou muito melhor! Obrigada!
Comment: @KelaW se vocè considera a resposta como valida marque ela como "soluçao" :)


Expectation of $\frac{X_1^4}{(X_1^2 + \cdots + X_d^2)^2}$

Question:
Let $X_1$, $X_2$, $\cdots$, $X_d \sim \mathcal{N}(0, 1)$ and be independent. What is the expectation of $\frac{X_1^4}{(X_1^2 + \cdots + X_d^2)^2}$?

It is easy to find $\mathbb{E}\left(\frac{X_1^2}{X_1^2 + \cdots + X_d^2}\right) = \frac{1}{d}$ by symmetry. But I do not know how to find the expectation of $\frac{X_1^4}{(X_1^2 + \cdots + X_d^2)^2}$. Could you please provide some hints?
What I have obtained so far
I wanted to find $\mathbb{E}\left(\frac{X_1^4}{(X_1^2 + \cdots + X_d^2)^2}\right)$ by symmetry. But this case is different from that for $\mathbb{E}\left(\frac{X_1^2}{X_1^2 + \cdots + X_d^2}\right)$ because $\mathbb{E}\left(\frac{X_i^4}{(X_1^2 + \cdots + X_d^2)^2}\right)$ may be not equal to $\mathbb{E}\left(\frac{X_i^2X_j^2}{(X_1^2 + \cdots + X_d^2)^2}\right)$. So I need some other ideas to find the expectation.
Where this question comes from
A question in mathematics stack exchange asks for the variance of $\|Ax\|_2^2$ for a unit uniform random vector $x$ on $S^{d-1}$. My derivation shows that the answer depends sorely on the values of $\mathbb{E}\left(\frac{X_i^4}{(X_1^2 + \cdots + X_d^2)^2}\right)$ and $\mathbb{E}\left(\frac{X_i^2X_j^2}{(X_1^2 + \cdots + X_d^2)^2}\right)$ for $i \neq j$. Since
$$
\sum_{i \neq j}\mathbb{E} \left( \frac{X_i^2X_j^2}{(X_1^2 + \cdots + X_d^2)^2}\right) + \sum_i \mathbb{E}\left(\frac{X_i^4}{(X_1^2 + \cdots + X_d^2)^2}\right) = 1
$$
and by symmetry, we only need to know the value of $\mathbb{E}\left(\frac{X_1^4}{(X_1^2 + \cdots + X_d^2)^2}\right)$ to obtain other expectations.
Answer: The distribution of $X_i^2$ is chi-square (and also a special case of gamma).
The distribution of $\frac{X_1^2}{X_1^2 + \cdots + X_d^2}$ is thereby beta.
The expectation of the square of a beta isn't difficult.
Answer: This answer expands @Glen_b's answer.

Fact 1: If $X_1$, $X_2$, $\cdots$, $X_n$ are independent standard normal distribution random variables, then the sum of their squares has the chi-squared distribution with $n$ degrees of freedom. In other words,
  $$
X_1^2 + \cdots + X_n^2 \sim \chi^2(n)
$$

Therefore, $X_1^2 \sim \chi^2(1)$ and $X_2^2 + \cdots + X_d^2 \sim \chi^2(d-1)$.

Fact 2: If $X \sim \chi^2(\lambda_1)$ and $Y \sim \chi^2(\lambda_2)$, then
  $$
\frac{X}{X + Y} \sim \texttt{beta}(\frac{\lambda_1}{2}, \frac{\lambda_2}{2})
$$

Therefore, $Y = \frac{X_1^2}{X_1^2 + \cdots + X_d^2} \sim \texttt{beta}(\frac{1}{2}, \frac{d-1}{2})$.

Fact 3: If $X \sim \texttt{beta}(\alpha, \beta)$, then
  $$
\mathbb{E}(X) = \frac{\alpha}{\alpha + \beta}
$$
  and
  $$
\mathbb{Var}(X) = \frac{\alpha\beta}{(\alpha + \beta)^2(\alpha + \beta + 1)}
$$

Therefore,
$$\mathbb{E}(Y) = \frac{1}{d}$$
and
$$
\mathbb{Var}(Y) = \frac{2(d-1)}{d^2(d+2)}
$$

Finally,
$$
\mathbb{E}(Y^2) = \mathbb{Var}(Y) + \mathbb{E}(Y)^2 = \frac{3d}{d^2(d+2)}.
$$
Comment: @NP-hard: It seems that you in fact asked this question in order to be able to answer [this question](http://math.stackexchange.com/questions/1853954)? Why not just mention that?
Comment: @joriki Thanks. I will add the link to the question.


Register multiple singletons with same interface but different constructor parameters values

Question: I got stuck and need some advice or pointer to a solution.
A web API with ASP.NET Core 3.1
Startup.cs
services.AddSingleton<ITopicClient>(s => new TopicClient({connectionstring},{topic}));

TopicRepository.cs
 public class TopicRepository : ITopicRepository
 {
        private readonly ITopicClient _topicClient1;
       private readonly ITopicClient _topicClient2;

        public TopicRepository (ITopicClient topicClient1, ITopicClient topicClient2)
        {
            _topicClient1 = topicClient1;
            _topicClient2 = topicClient2;
        }
        public async Task<Response> SendToTopicAsync(string message, string topic)
        {
           if( topic == "topic1")
           await _topicClient1.send(message);
           else if (topic == "topic2")
           await _topicClient2.send(message);
        }
}

TopicClient.cs in a shared library
        public TopicClient(string serviceBusConnectionString, string topicName)
        {
           _topicClient = new TopicClient(_serviceBusConnectionString,topicName);
        }

I need to send message to different topics. I would like to register services with different topic names in startup.cs. I want to reuse topicClient connection.
services.AddSingleton(s => new TopicClient({connectionstring},{topic1}));
services.AddSingleton(s => new TopicClient({connectionstring},{topic2}));
How can I achieve this by registering singleton instances of same type using same interface ?
Thank you in advance!
Comment: Or create a type for each topic and register a Topic123TopicClient for each one.  Like database connection strings, your app probably uses a small, fixed set of Topics.
Comment: You don't need a service for each topic, what you need is some connection factory that is responsible for managing your single connection then you inject that into your services and call that to return the connection for you.
Comment: Is there any other way that I could implement, becasue at present I need TopicClient instances for only 5 topics, but down the line it may grow.?
Answer: You could use a client resolver that holds your registered clients with a wrapper around the client.
First create a wrapper around your client with a name or enum for how to resolve it. As I'm not a fan of magic strings I decided to go with an enum in the example.
// Wrapper for your TopicClients
public interface ICustomTopicClient
{
    public ITopicClient TopicClient { get; }
    public TopicName TopicName { get; }
}

// Implement the ICustomTopicClient interface
public class CustomTopicClient : ICustomTopicClient
{
    public ITopicClient TopicClient { get; }
    public TopicName TopicName { get; }

    public CustomTopicClient(ITopicClient topicClient, TopicName topicName)
    {
        TopicClient = topicClient;
        TopicName = topicName;
    }
}

// Enum for how to resolve the requested TopicClient
public enum TopicName
{
    Topic1 = 0,
    Topic2 = 1
}

// Register all ICustomTopicClients in your container
services.AddSingleton<ICustomTopicClient>(s => new CustomTopicClient(new TopicClient({connectionstring},{topic}), TopicName.Topic1));
services.AddSingleton<ICustomTopicClient>(s => new CustomTopicClient(new TopicClient({connectionstring},{topic2}), TopicName.Topic2));

Then you create a resolver that holds all custom clients.
You inject the collection of clients from the container and create a dictionary with a public method to resolve the clients.
public interface IMessageClientResolver
{
    ITopicClient ResolveClient(TopicName name);
}

public class MessageClientResolver : IMessageClientResolver
{
    private readonly Dictionary<TopicName, ITopicClient> topicClients;

    public MessageClientResolver(IEnumerable<ICustomTopicClient> clients)
    {
         topicClients = clients.ToDictionary(k => k.TopicName, v => v.TopicClient);
    }

    public ITopicClient ResolveClient(TopicName name)
    {
        topicClients.TryGetValue(name, out var client);
        if (client is null)
            throw new ArgumentException(nameof(client));

        return client;
    }
}

Register the resolver to the container.
services.AddSingleton<IMessageClientResolver, MessageClientResolver>();

And then use it like this:
public class Foo
{
    private readonly ITopicClient topicClient;
    private readonly ITopicClient topicClient2;

    public Foo(IMessageClientResolver clientResolver)
    {
        topicClient = clientResolver.ResolveClient(TopicName.Topic1);
        topicClient2 = clientResolver.ResolveClient(TopicName.Topic2);
    }
}

You can use the same pattern and extend the resolver with IQueueClients. And add a resolve method to return the IQueueClient by a QueueName enum.
Answer: You can already register multiple instances as the same interface, so when you do:
services.AddSingleton<ITopicClient>(_ => new TopicClient("topic1"));
services.AddSingleton<ITopicClient>(_ => new TopicClient("topic2"));

you already added two instances to the container.
It is just when you resolve interface ITopicClient, you always get the last added instance. For example, if you resolve:
// instance = topic2
var instance = container.GetService<ITopicClient>();

If you need all instances, you should resolve / inject IEnumerable<ITopicClient>.
class TopicRepository
{
    public TopicRepository(IEnumerable<ITopicClient> clients)
    {
        // clients contains topic1 and topic2
    }
}


Chain rule and matrices - I'm confused

Question: I googled around and searched inside the forum but I'm still confused about a problem.
I have 2 matrix functions $f,g : \mathbb{R}^{n \times n} \times \mathbb{R}^{a \times b} \rightarrow \mathbb{R}^{n \times n}$. Starting from this, I have the following expression:
$$ t(Q, X, Y) = \text{tr}(f(g(Q, X),Y))$$
where $\text{tr}$ is the trace operator and $X, Y \in \mathbb{R}^{a \times b}$ and $Q \in \mathbb{R}^{n \times n}$.
How do I evaluate $\frac{\partial t(Q,X, Y)}{\partial X}$ and $\frac{\partial t(Q,X, Y)}{\partial Y}$?
I mean, I would like to know how to correctly apply the chain rule.
* Addition *
I will try to give more information about my problem.
Suppose that $a = b = n$ and that $f(A,B) = AB$ and $g(A,B) = BA + AB$ (actually this is only an example of possible functions $f$ and $g$).
Then I have that:
$$f(g(Q,X),Y) = f(XQ + QX, Y) = XQY + QXY$$
Then, using matrix calculus (hoping there are no error!), I have that:
$$ \frac{\partial t(Q,X,Y)}{\partial X} = QY + YQ\\
\frac{\partial t(Q,X,Y)}{\partial Y} = XQ + QX$$
I can easily compute the result if I know the form of $f$ and $g$. Notice that the derivatives I obtained are in a matrix form.
But actually I need to deal with generic functions. And for this reason I need to use the chain rule.
The problem is that the chain rule formulas I know are helpful to derive the derivative with respect to a certain element of the matrix $X$ (or $Y$). In this case, I'm not able to have a matrix form of the derivatives.
So, my question is... there is a chain rule formula I'm missing which let me describe these derivatives in a matrix form?
* Addition 2 *
The chain rule formulas that I know are reported here http://en.wikipedia.org/wiki/Matrix_calculus#Scalar-by-matrix_identities (see the 7th row of the table)
Comment: It might help to consider the function $h(Q,X,Y) = (g(Q,X),Y)$, whose differential is easily calculated. Then $t(Q,X,Y) = l \circ f \circ h (Q,X,Y)$, where $l$ is the trace
Comment: nice question .... +1
Comment: I know this formula (http://en.wikipedia.org/wiki/Matrix_calculus#Scalar-by-matrix_identities - it is the 7th formula into the table). This is performed on each $X_{i,j}$ separately! I would like to know the formula with respect to all $X$.
Comment: I'm going to try to give more details in my question
Answer: $
\def\LR#1{\left(#1\right)}
$Let's use uppercase letters for the matrix variables, so they're easy to distinguish from the lowercase scalars, and $I$ for the identity matrix
$$\eqalign{
G &= G(Q,X) \cr
F &= F(G,Y) \cr
t &= {\rm tr}(F) = I:F \cr
dt &= I:dF \cr
}$$
First, let's calculate the differential and gradient wrt $Y$
$$\eqalign{
dt &= I:\LR{\frac{\partial F}{\partial Y}:dY} \\
\frac{\partial t}{\partial Y} &= I:\frac{\partial F}{\partial Y} \\
}$$
And now wrt $X$
$$\eqalign{
dt &= I:\LR{\frac{\partial F}{\partial G}:\frac{\partial G}{\partial X}:dX} \\
\frac{\partial t}{\partial X} &= I:\frac{\partial F}{\partial G}:\frac{\partial G}{\partial X} \\\\
}$$
Note that the matrix-by-matrix gradients are $4^{th}$ order tensors. For example, here is one of the gradients in component form
$$\eqalign{
\LR{\frac{\partial G}{\partial X}}_{ijkl} = \frac{\partial G_{ij}}{\partial X_{kl}} \\\\
}$$
Also note that colons are used to denote the double-contraction product, e.g.
$$\LR{\frac{\partial F}{\partial G}:\frac{\partial G}{\partial X}}_{ijkl} = \sum_p\sum_q\;\frac{\partial F_{ij}\;}{\partial G_{pq}}\;\frac{\partial G_{pq}}{\partial X_{kl}\;}$$

Chain rule and matrices - I'm confused


Fourier Series Proof

Question: I have concerns about this problem
Let $f_e(x)$ and $f_o(x)$ represent general continuous even and odd functions on $[-L,L]$.
Prove that $\int_{-L}^{L} f_e(x) dx$ = 2 $\int_{0}^{L} f_e(x) dx$
My attempt:
$\int_{-L}^{L} f_e(x) dx$ = $\int_{-L}^{L} \frac{1}{2}[ f(x)+f(-x)] dx$ =  $\frac{1}{2} \int_{-L}^{L} f(x) dx$ + $ \frac{1}{2} \int_{-L}^{L} f(-x) dx$. By the Fundamental Theorem Of Calculus, I would have
$\frac{1}{2} [F(L) -F(-L)] + \frac{1}{2} [F(-L) - F(L)]$. Is this correct?
Answer: This has nothing to do with the Fourier series.
It holds for every even function $f$, that
$$\int_{-L}^{0} f(x) dx = \int_{-(-L)}^{0} f(-x) d(-x) =  \int_{0}^{L} f(x) dx.$$
The first step uses integration by substitution with $u(x)=-x$ and the second step the defining property of even functions $f(x)=f(-x)$.
Answer: Consider $J = \int_{x=-L}^0 f_e(x) dx$.  Let $v = -x$; then $dx = -dv$ and
$$
J = - \int_{v=+L}^0 f_e(-v) dv = \int_{v=0}{L} f_e(-v)dv$$
Now use the fact that $f_e$ is even to write this as
$$ J = \int_{v=0}{L} f_e(v)dv = \int_{x=0}{L} f_e(x)dx$$$$
Finally,
$$\int_{x=-L}^L f_e(x) dx = J + \int_{x=0}^L f_e(x) dx = 2\int_{x=0}^L f_e(x) dx $$

Fourier Series Proof


PHP radio buttons and submit()

Question: I am using On/off radio button inside my wordpress to hide post from a particular category and I've done well so far,
I mean when i set the button to 'On', posts from category whose id is 495 disappears and when i turn if off the posts comes back,
here is the problem i am facing,
I set the button to 'Off' so the posts from category id 495 disappears then i click on 'older posts' link and goes to previous pages but then when i chose 'On' i automatically jumped back to page number 1 :S
why is this happening ? Why am i automatically jumping back to 1st page when click 'On' ? :S
here is the code,
This is the header code,
<?php
session_start();
if (isset($_POST['r1'])){
    $_SESSION['r1']=$_POST['r1'];
    }
?>

these are my two radio buttons,

<input type="radio" name="r1" value="o" onClick="submit();" <?php echo ($_SESSION['r1'] == "o") ? 'checked="checked"' : ''; ?> />On

<input type="radio" name="r1" value="p" onClick="submit();" <?php echo ($_SESSION['r1'] == "p") ? 'checked="checked"' : ''; ?> />Off

and this is the code in index.php,
<?php
    if ($_POST['r1']=='o') // Family Filter !!! If 'ON'
    query_posts('cat=-495'); // Remove Post from Category whose Id is 495
    else {echo "";} // When off is selected
?>

is there something wrong with the code inside index.php ??
Answer: Once form is submitted parameter page is lost. It appears in query string after clicking on "Older posts". By default it equsls to 1.
You have pass it to query_post function and use something like this
query_posts('cat=-495&page='.$page);
where
$page=(int)$_GET['page']; // I don't remeber exactly parameter name.

PHP radio buttons and submit()


How to hide a view programmatically?

Question: I need hide a view when some GET param exists. It should be hidden like if you insert 'Global: Null' in contextual filter(It hides view if no results). This view placed in panel*
I tried to find the solution but failed. How to do this?
Comment: check this I think this may help you.. http://drupal.stackexchange.com/questions/51731/how-to-hide-field-from-entity-display-view-programmatically
Comment: This is about fields. But I need hide view.
Answer: I am guessing you are adding it as a block to a specific path.
If yes, follow the steps below:

Go to the block configuration
Scroll down to the Visibility Settings
Click on "Pages" tab
Select the option "Pages on which this PHP code returns TRUE (experts only)"
Write your PHP logic to read the GET parameters and return true only if the specific parameter you are looking for is not found.
Comment: First, I don't use blocks I use content panes. Second, how do I know that view have empty result?
Comment: Ew ew ew ew ew ew. Don't use PHP inside views, you should be using hooks.
Answer: You just have to specify a validation criteria in a contextual filter, could be Global:null as you said. Then choose the action you want to take when validation fails.
You can implement your validation logic in PHP, preferably inside a function in your code and you just call it from the view.
Hope that helps.
Answer: Maybe if you override the views template and add a if statement, something like if (function == true) { //do something } (Sorry, really horrible in PHP...)

How to hide a view programmatically?


How do I calculate solution of two differential equations?

Question: Given are two differential equations:
$\ddot{x} (t)+16x(t)=0$ and $\ddot{y}(t)+16y(t)=2sin(4t)$.
How do I calculate solution of two differential equations if the begning values are $x(0)=0$,$\dot{x}(0)=1$ and $y(0)=0$, $\dot{y}(0)=1$
Answer: Periodic boundary conditions, a sinusoidal right-hand side for the non-homogeneous equation.  I'd say, use the Fourier transform.
Answer: The x- and y- motions are not coupled, they are independent. We can superpose by eliminating $t$ from the two solutions obtained independently for a relation between x- and y-.


Como inserir uma informação em um objeto Json?

Question: Meu problema é parecido com dessa pergunta:
Pergunta Stackoverflow
Porém nesse caso é usado o objeto Json para popular a tabela.
Controller
 public ActionResult GetDadosItensVenda(int? Codigo)
    {
        try
        {
            db.Configuration.ProxyCreationEnabled = false;
            db.Configuration.LazyLoadingEnabled = false;

            List<ItensVenda> itensVenda = new List<ItensVenda>();

            itensVenda = db.ItensVenda.Include(s => s.Produto).Where(s => s.CodigoVenda == Codigo && s.Ativo == true).ToList();
            return Json(itensVenda, JsonRequestBehavior.AllowGet);

        }
        catch (Exception)
        {
            throw;
        }
    }

Script


Fluent Nhibernate table with value object mapping

Question: Can you suggest a valid mapping for the following scenario. Two tables:
CREATE TABLE "ORDER"
  (
    "ID"      NUMBER(20,0) NOT NULL ENABLE,
    "STATUS_ID"  NVARCHAR2(10,0)
  );

CREATE TABLE "STATUS"
  (
    "ID"      NVARCHAR2(10,0) NOT NULL ENABLE,
    "DESCRIPTION"  NVARCHAR2(250,0)
  );

The respective classes are:
public class Order
{
    public virtual Id { get; set; }
    public virtual Status { get; set; }
}

public class Status
{
    public virtual Id { get; set; }
    public virtual Description { get; set; }
}

Status table is static table of value object for the property Proposal.Status and should never be manipulated by code. I want the Order to always be loaded with Status description and code, i.e. Eager Load Proposal.Status.
I've read this Ayende's blog post but there is no exactly the same scenario, albeit I believe it's quite common.
Edit: note I'm trying to do this as Component Map.
Answer: You are trying to map a regular entity with identity as a component (value object). From Ayende's post:

In DDD you have the notion of entities and value objects. The latter
  are immutable and have no identity. In NHibernate they are mapped as
  Component and its fields are embedded in the same table as the
  containing entity.

Component mapping should be used when you are mapping a value type to the same table as the parent entity. You can find more information about NHibernate types in documentation.
Try instead to do it using References mapping, although you might be tempted to use HasOne.
Comment: Funny enough, I've started with `HasOne` before I realised it wasn't appropriate. I did think that Status is a Value Object, but yes it will have a natural Id field (`StatusCode`), so I guess it isn't. `References` does the job allright.


How to start views list at specific ID

Question: I have a list of images(nodes) displaying horizontally and I would like to start from a certain id in this list. The way I have it now it starts at most recent added image(node).
Is there a way to start at a specific id in views?
NOTES:  Would like it to look like the second image on page load. You can see in the first image there is white space to the left. I want this to be filled by an image. The navigation is fixed.
Answer: I would suggest perhaps using a Nodequeue - http://drupal.org/project/nodequeue.
This way you can order the images in whichever order you like.
Alternatively, if it is just one node that you want to appear first and then sort by something else you could perhaps utilise the 'sticky' feature?
OR do you want the order to start from ID 5 and continue 6, 7, 8 etc?
Comment: I have updated the post with some photos to better understand my question. Thank you for pointing me to Nodequeue as well.

How to start views list at specific ID


R Error with ADF test in Time Series Lapply

Question: I have a data frame with time series, and I am trying to iteratively test whether each is stationary. R is giving me a strange error that if (interpol==min(tablep)) warning...: missing value where TRUE/FALSE needed.
df <- structure(list(DATE = structure(c(15405, 15406, 15407, 15408, 15409, 15405,
  15406, 15407, 15408, 15409, 15405, 15406, 15407, 15408, 15409), class = "Date"),
  ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L),
  VALUE = c(5.67, 3.45, 4.56, 20.3, 5.1, 5.67, 3.45, 4.56, 5.28, 5.1, 5.67, 7.8,
  8.79, 9.43, 10.99)), .Names = c("DATE", "ID", "VALUE"), row.names = c(NA, -15L),
  class = "data.frame")
ids <- 1:3

test<-lapply(ids, function(i) {
  if(!any(is.na(df[df$ID==i,3]))) {adf.test(df[df$ID==i, 3])} else {NA} })

Error in if (interpol == min(tablep)) warning("p-value smaller than printed p-value") else warning("p-value greater than printed p-value") :
  missing value where TRUE/FALSE needed

Thoughts on what this could mean?
Comment: A shorter way to write your code is `lapply(split(df$VALUE, df$ID), adf.test)`.  It also avoids the potential issue that `ids` could have a value that doesn't exist in `df$ID` (e.g. `ids <- 1:4`).
Answer: You're getting an error because you're trying to estimate 4 parameters (constant, time trend, lagged x level, lagged x diff) with 3 data points.  Simply put, you don't have enough data to run this test.
You need at least 5 data points, if k=0 and even more data points if k>0.
library(tseries)
adf.test(rnorm(5),k=0)  # works without error

Comment: Huh... very strange. But this is definitely helpful. Any word on where you read about this/how you figured out that this is the problem?
Comment: @OlgaMu: I started by debugging the `adf.test` code (`debug(adf.test)`) and noticed that one of the model estimates was `NA`.  Then, I looked up the model on [Wikipedia](http://en.wikipedia.org/wiki/Augmented_Dickey%E2%80%93Fuller_test) and read `?adf.test` (the Details section says it tests the first order autoregressive coefficient). Then I simply counted coefficients and data (you lose 2 obs from taking the lag and the difference).


Ignore LINE BREAK

Question: I have a code which I extracted from a text file. Every character in the text file have been embedded into array including line breaks. I want to ignore the line breaks. I've tried so many ways but it fails.
Can you help me? :)
Comment: Could you show us what you have tried already?
Comment: Can you post the snippet of code where you read the file?
Comment: Second what blorgbeard has said... depending on how you read the file, you can probably tell the reader to strip out the line breaks
Answer: Did you try
str_replace("\n", "", $text);

..?
http://ideone.com/rpQCq
Comment: You might need to replace \r as well (see http://php.net/manual/en/function.str-replace.php Example #2)
Answer: If you mean you have an array of lines ending with \n, you can remove them like so...
$line = rtrim($line, "\n");

Comment: i did it. thanks! i used trim before dont even realise this kind of function exist :))

Ignore LINE BREAK


Closure Library with ASP.NET

Question: Google's Closure Library looks like it has a lot of great features, but I'm not seeing any examples of it used with ASP.NET sites. I'm just wondering if anyone has any experience using the two together and what parts. Is is a good or bad experience?
EDIT:
To clarify, I'm asking about Closure Library and not Closure Compiler or Closure Templates. For example, if I use the calendar control from Closure Library, it seems to decorate a text box so that text might have to be converted to a DateTime on post back. Whereas other ASP.NET controls will expose a SelectedDate property, for example. There are probably some cases where this incomplete integration is annoying, and probably some cases where the controls in the Library provide features that are compelling enough that it is worth dealing with any quirks.
Answer: Closure Library is platform agnostic. It is as useful with
ASP.NET as it is with any other platform.
Closure Templates (another member of the Closure Tools family),
does have a server-side component that's limited to
Java. However, that does not limit the utility of Closure Library
in any way.
For any production application using Closure Library, you will
need to compile your code using Closure Compiler. To do this
locally, you will need to install both Python and Java. Neither
of these are needed in your deployment environment, though.
Answer: With Microsoft providing their own JavaScript minifier ( http://aspnet.codeplex.com/releases/view/34488 ) and embracing and supporting JQuery (+ intellisense and documentation) in Visual Studio I am not surprised ASP.NET folks are skipping Google's Closure.

Closure Library with ASP.NET


Como ignorar arquivos de acordo com a sua extensão no TFS?

Question: No git é possível utilizar o arquivo .gitignore para ignorar algumas extensões de arquivos, mas gostaria de saber se isso também pode ser feito no Team Foundation Service ou se existe algo semelhante para ignorar arquivos com determinadas extensões.
Answer: No workspace local você tera o arquivo .tfignore (TFS 2012, 2013, 2015 e superior)
No workspace local, você pode usar o .tfignore (que é equivalente ao .gitignore do Git)
.tfignore exemplo:
<code>######################################
# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
#
# Ignore .txt files in this folder
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll
</code>
Lembrando que o .tfignore é valido para novos arquivos.
Comment: qualquer coisa da uma olhada https://stackoverflow.com/questions/36768954/visual-studio-2015-tfs-tfignore-file pode ser o formato do arquivo que nao esta correto
Comment: Eu já tenho um projeto no controle de versão, por isso criei o arquivo .tfignore com as extensões a serem excluídas e dei check-in, porém os arquivos com as respectivas extensões continuam na lista de included changes.
Comment: e na lista de changes se der um botao da direita ignore funciona para você?
Comment: Bom, o que acontece é que o .tfignore só é válido para os arquivos que ainda não estão no controle de versão, por isso eu não estava conseguindo. Obrigado pelo link, ajudou muito !
Comment: @Carlinhos adicionei o comentario na resposta, se te ajudou marque como resolvido.


Quando usar o SQLite?

Question: Quando eu devo e não devo usar o SQLite?
Tenho um projeto que pretendo fazer não tenho ideia de quantas tabelas vão ser, mas acredito que mais de 15 com cerca de pelo menos mil linhas em algumas tabelas.
Seria viável fazer no SQLite?
Comment: Em que tipo de aplicação vc vai utilizar o `SQLite`?
Comment: Precisa dar mais detalhes sobre a aplicação.
Comment: Uma palestra que resume muito: https://www.youtube.com/watch?v=Jib2AmRb_rk
Answer: Antes de começar usar um ferramenta você deve estudá-la profundamente. E depois de estudá-la terá informações para decidir por conta própria se ela é viável para seu caso ou não. Não confie em pessoas aleatórias na internet para dizer para você o que é bom ou não para você.
Se você estudar o SQLite certamente chegará nessa página. Ela diz onde o SQLite pode ser usado. Em resumo:

Dispositivos móveis e embarcados
Formato de arquivos
"Pequenos" websites
Análise de dados
Cache para dados corporativos
Banco de dados apenas no lado do servidor
Arquivamento de dados
Substituto para operações com arquivos comuns
Bancos temporários ou internos
Substituto para outros SGDBs em tarefas de teste e demonstração
Treinamento em banco de dados.

Lá diz onde não deve usar:

Aplicações cliente-servidor (tem como usar se souber fazer)
Websites de grande volume (lá fala em 1% dos sites, minha experiência mostra que é mais raro ainda)
Conjunto de dados absurdamente grandes (mas é raro quem tem esse volume todo)
Alta concorrência (o maior problema dele, mas poucos possuem essa necessidade)

Ou seja, o SQLite é adequado para quase todos os casos. E os casos onde ele não é adequado, a pessoa saberá, porque aí o problema é tão complexo que alguém inexperiente não estará envolvido. E se isto acontecer, a escolha errada do banco de dados será um problema pequeno perto dos outros que ela cometerá.
Claro que ele pode não te agradar, mas aí é outro problema. Eu uso o SQLite sempre que eu posso. Ele não é tão completo em recursos quanto outros bancos. Ele é ótimo para armazenamento e relacionamento básico. Em geral, os recursos dos outros banco de dados podem parecer ótimos no começo, mas é preciso aprender tudo e usar corretamente. Muitas vezes ter apenas o básico torna o trabalho mais simples sem perder funcionalidade importante. A maioria dos recursos existentes em produtos mais "potentes" são apenas facilitadores que podem ajudar ou atrapalhar. Eles não estão ali sem cobrar um preço.
O seu caso é extremamente simples e não deve ter problemas. Mas é preciso analisar como os dados serão acessados. Haverá grande concorrência? Duvido, então acho que não precisa se preocupar com isto. O acesso será por uma aplicação na mesma máquina? Isto é importante. O SQLite não se dá bem em acessos sendo feitos por outra máquina.
Ele não pode ser acessado confiavelmente de outras máquinas. Na prática á raro dar problema, mas pode acontecer. A solução é ter uma aplicação na máquina que o acesse e permita que outras máquinas se comuniquem com esta aplicação (veja o link acima). Por isto websites funcionam bem. O servidor HTTP e o código do website seguem justamente este modelo. Porque as pessoas não seguem o mesmo modelo para outros tipos de aplicação? Provavelmente porque seguem receitas de bolo e não pensam fora da caixa. Ou talvez porque não sabem como fazer.
Esta é a real decisão se deve usá-lo ou não. O volume de dados é secundário.
Então estude o produto para entender as limitações que ele possui em facilidades extras, em volume de concorrência (real), e acesso direto remoto. Sabendo disto saberá onde pode usar ou não. O site oficial é muito informativo.
Um exemplo de uso do SQLite em alta escala. Algumas pessoas não o usam, e acham que ele não escala, que não pode ser usado em quase todos os cenários no lugar de soluções mais completas. Ele só não é bom com muita concorrência de escrita e para ferramentas auxiliares ao banco de dados. Curiosamente essas pessoas costumam acreditar em NoSQL que costumam ser piores de leitura que o SQLite. As pessoas precisam pensar fora da caixa, investigar antes de fazer afirmações que atingem sua credibilidade.
Coloquei no GitHub para referência futura.
Comment: É pode ser útil, mas é limitado a uma utilização específica dele.
Comment: @MarconcilioSouza dei uma espiada, e parece muito mais complexo do que usar a interface nativa dele (dificilmente vai ter coisa mais fácil de usar que a interface nativa do SQLite que já tem tudo pronto). Pra eu entender melhor, quais seriam as vantagens dessa sua indicação, em relação à nativa?
Comment: @MarconcilioSouza mas já adianto que até gostei da abstração das coisas sem usar SQL. Para certas coisas pode ser interessante (mas não como substituto geral para as funções nativas).
Comment: @JedaiasRodrigues o excesso de execução não pode ser prejudicial pra um bom resultado? Cada um escolhe o que acha melhor, eu jamais vou pelo caminho pior porque entrega mais rápido. Eu entrego qualidade. Isso passa por performance boa, custo mais baixo, usabilidade melhor, operacionalização mais fácil, e simplicidade geral. Claro que isso tem um custo inicial pra aprender fazer. Em geral fazer de qualquer jeito é a desculpa de quem não quer ou não pode aprender certo, até porque o certo sempre passa por ser mais fácil, depois da curva de aprendizado ultrapassada.
Comment: Para uma facilita com o uso deste banco tem o `com.orm.SugarRecord;` ajuda bastante na criação das tabelas.. e para leitura, alteração e deleta os dados. [Site Do sugar](http://satyan.github.io/sugar/getting-started.html)
Comment: Obrigado a todos!
Comment: @Bacco, em algumas funcionalidade, é útil, **mas não como substituto geral para as funções nativas**, por exemplo em criação de tabelas, eu simplesmente crio minha classe o sugar si vira para gera a tabela no banco... Bom mais para falar sobre funcionalidade de um ou de outro seria algo para uma pergunta e resposta mais elaborada.
Comment: @MarconcilioSouza claro, só perguntei pra ver se tinha algum ponto em especial que você recomendasse. Mas ta aqui separado para eu ler melhor depois. Vou tentar entender onde pode se encaixar bem essa recomendação.
Comment: @Maniero o excesso de análise não pode se tornar uma barreira para a execução?
Answer: SQLite vc usa se tiver a necessidade de ter um cenário de dados em modo desconectado.
Exemplo:
Vc tem o seu sistema corporativo (15 tabelas com 1000 registros cada), mas precisa ir à campo (ambiente desconectado) usar uma aplicação com dados do seu sistema.
Então, vc cria uma base SQLite no dispositivo que vai a campo (mobile, laptop, etc) e traz para essa base apenas dados que irão atender a necessidade desta ida à campo. E, assim que esse dispositivo retornar à rede corporativa, vc cria uma logica de sincronismo para trazer os dados do SQLite de volta para a base de dados principal.
Comment: +1, não vejo por que de tantos downvotes,  sua resposta não está totalmente errada, algumas empresas utilizam o sqlite para isto, mas o sqlite tem poder para fazer muito mais, além de suportar ate 140TB ele é escolhido por vários por sua acessibilidade visto que  ele possui suporte nativo em vários devices Android, iOS, Windows Phone, Blackberry
Comment: Uma pena ver que alguém tão supostamente influente aqui no SO pregue que boas práticas, arquitetura e responsabilidade DevOps sejam baboseiras.
Comment: @bigown, "99,99% dos sites possuem os bancos junto ao servidor HTTP." só se for dos 100% que vc conhece. Isso é uma péssima prática. Aplicação e base de dados tem que ser separados SIM. Eles possuem necessidades diferentes e se comportam diferentes. Em nenhum momento eu disso ou quis dizer que middleware é ruim, eu disse que, é ruim decidir por usar middleware para acertar um cenário inadequado. E middleware é para fazer integração, e não separação.
Comment: Mas @bigown, SQLite tem limitações. Vc mesmo citou "Ele não pode ser acessado confiavelmente de outras máquinas. Pode dar problemas.". No próprio [site](http://sqlite.com/whentouse.html) deles eles não recomendam cenários cliente-servidor.
Comment: Esta é uma simplificação do problema.
Comment: @bigown, citando do site oficial: "SQLite strives to provide local data storage for individual applications and devices./SQLite se dedica a fornecer armazenamento local de dados para aplicações individuais e dispositivos." - Ambiente desconectado, como eu respondi. É para isso é que é feito, e é para isso que é para ser usado.
Comment: @bigown, usar SQLite para website, apenas se vc hospedar o BD no mesmo host do website (no site ele diz que o site oficial é feito assim, host compartilhado). Diferente disso, será que ser criado um middleware (ex:API) para satisfazer. Arquiteturalmente, isso é ruim. Server de aplicação deve ser diferente do server de repositório. E neste ambiente, SQLite não atende.
Comment: Obrigado pelo esclarecimento!
Comment: A resposta leva uma pessoa que não sabe sobre o assunto acreditar que o SQLite é isso, o que é uma limitação do que ele pode fazer. Este é apenas um cenário. E nem é o cenário proposto na pergunta. A aceitação foi feita por um usuário que não entende o sistema e aceitou a primeira resposta postada sem entender o que isto significava.
Comment: @bigown, SQLite é um poderoso banco self-contained. Bancos assim são para fins específicos, quando não há cenário cliente-servidor (como vc mesmo disse). Então é ideal para trabalhar em ambientes desconectados (em campo). A pergunta foi: "Qdo usar ou não?" Respondi: "Use qdo precisar usar um BD com as características do SQLite.". O que foi que não te agradou?
Comment: Mas isto é incorreto, ou pelo menos limitador. Não é questão de me agradar ou não, é questão de dizer que o SQLite é feito para este cenário, quando na verdade ele é feito para vários. Eu uso o SQLite em ambiente cliente-servidor muito bem. E diversos outros cenários.
Comment: Todo produto tem, mas ele não é nem de longe tão limitado como sua resposta indica. Eu coloquei essa citação na minha resposta, E mostrei que ela não é real. Basta saber fazer. Justamente este é o problema da resposta. Ela limita por desconhecimento de como usar a ferramenta do jeito correto nos diversos cenários possíveis. O fato de uma pessoa não saber como fazer não significa que não possa ser feito. O site não recomenda o uso direto, mas indiretamente é possível usar sem problema algum. E de fato é usado e eles recomendam em um cenário cliente-servidor, que é o website.
Comment: Mas esse é o problema, você está pegando uma frase do que está lá isoladamente, não está lendo o site todo, nem vendo os que as pessoas fazem de fato. E está ignorando o que eu estou dizendo aqui. Você está tirando as coisas do contexto para dar um resposta errada. Programação é achar solução, não é ficar lento fragmentos de texto para se conformar e dizer que não tem solução. O problema da resposta é justamente esta atitude de se apegar a um detalhe como se ele definisse o todo.
Comment: Agora você começou despejar as baboseiras do "isso é certo, isso é errado", aí alguém pergunta porque e a resposta é "porque eu li em algum lugar que é assim". As coisas precisam ser usadas de acordo com fatos não com achismos, de acordo com receitas sem contexto. 99,99% dos sites possuem os bancos junto ao servidor HTTP. O mesmo vale para outros tipos de aplicação. Não que eu ache que deva, mas se precisar criar um middleware, crie, pelos motivos certos. Não tem nada errado com isto. Eu nunca falei que o SQLite atende todos os cenários. Atende quase todos. Você disse que ele atende só um!
Comment: Fora a incoerência de dizer que middleware é ruim e que servidor de aplicação e repositório devem ser separados. Primeiro isso tudo é regrinha boba que não olha o contexto, não busca solução, e depois o middleware é justamente para fazer esta separação.
Comment: Não vou perder tempo com você que gosta de vomitar "boas práticas". Eu sou pragmático, eu não sigo receitas de bolo. Eu produzo soluções de acordo com as necessidades. Fique com suas boas práticas sem sentido, eu fico com soluções reais. Teorias não resolvem problemas. Tanto que as pessoas não seguem o que você está dizendo, a não ser nos raros casos onde elas cabem ou quando a pessoa só gosta de seguir receitas sem olhar o contexto. Não é necessário um canhão para matar passarinho. Mas se você gosta disto, pode usar nas suas "soluções", não vai me atrapalhar nada.
Answer: O SQLite pode ser usado sempre que você tem de armazenar dados localmente de forma estruturada e resistente a corrupção. O código do SQLite é considerado um dos melhores em lidar com arquivos locais de modo a minimizar a chance de perda de dados, quem estuda o tema é aconselhado a estudar o código dele, então é preferível mesmo usar SQLite a tentar escrever código de manipulação de arquivos, mesmo em se tratando de dados simples como uma configuração de aplicação.

Quando usar o SQLite?


How to change Vertical Alignment of Text in TextBox Windows Phone 8.1

Question: How to set VerticalAlignment of Text which entered in TextBox. TextBox only have TextAlignment property which use to set Text alignment horizontally only.
XAML:
<TextBox MinWidth="300" MinHeight="45" TextAlignment="Left" VerticalAlignment="Center"/>

EDIT
After adding VerticalContentAlignment property XAML looks like:
<TextBox VerticalContentAlignment="Center" />
<TextBox  VerticalContentAlignment="Bottom"/>
<PasswordBox VerticalContentAlignment="Stretch"/>

Output:

Clearly property VerticalContentAlignment not working. Anything I am missing here?
Comment: [VerticalContentAlignment](https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.control.verticalcontentalignment)
Comment: were you able to solve this issue ?
Comment: @w.b I thinks setting padding only option to set vertical margin..
Comment: @ChrisW. Looks like `VerticalContentAlignment` not working!
Comment: Looks like you're right, if we go look at the [default style template](https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj710191.aspx) sure enough they dont have that property bound like they say in the docs (imagine that). So what you can do is go add `VerticalAlignment={TemplateBinding VerticalContentAlignment}` to the `ContentControl` in the style template.
Answer: I have the answer for your prayers.. :-) What you do is simply to change the default style for the TextBox... Since you remove the scrollviewer, i guess its not possible to use more lines.. I did not need that functionality though... :)
Original TextBox Style:

New Style :

Your welcome :-)
Comment: what an extremely complicated process for a very simple achievement


Norm of the operator and Riesz-Markov-Kakutani measure - example functional

Question:
Let $X = C[0,1]$ with supremum norm. Define linear functional:
$$
\varphi(f) = \int_0^1f(x)cos(\pi x)dx - f(\frac{1}{2})
$$
Show that $\varphi$ is bounded and compute its norm. Using the Riesz–Markov–Kakutani representation theorem give the complex measure that is associated with that functional.

My attempt was:
Bounded:
$$
\|\varphi\| = \sup_{\|f\|_{\infty}=1}|\varphi(f)| = \sup_{\|f\|_{\infty}=1}|\int_0^1f(x)cos(\pi x)dx - f(\frac{1}{2})| = \\
\leq \sup_{\|f\|_{\infty}=1}\int_0^1|f(x)cos(\pi x)|dx + |f(\frac{1}{2})| \\
\leq \sup_{\|f\|_{\infty}=1}\|f\|_{\infty}\int_0^1|cos(\pi x)|dx + \|f\|_{\infty} \leq 1 + 1 = 2
$$
Where last equation is due to cosine function being bounded by 1.
Now the norm, letting $f = 2$ (constant):
$$
\|\varphi(f)\| = |2\int_0^1cos(\pi x) - 2| = |0 - 2| = 2
$$
so the norm (taking the bound into account) is equal to 2.
Lastly, the measure seems to be:
$$
\mu(A) = \cos{(\pi x)}d\lambda(A) - \delta_{\frac{1}{2}}(A)
$$
because then
$$
\int_0^1fd\mu = \int_0^1fd\cos{(\pi x)}- \delta_{\frac{1}{2}} = \int_0^1f(x)cos(\pi x)dx - f(\frac{1}{2})
$$
It was an exam task and I only got half of the points. Could anyone show me the correct answer? I suppose my measure is wrong ($\lambda(A)$ doesn't make much sense) but I didn't have better ideas that time.
Comment: Can you state this Riesz-Markov-Kakutani theorem, or at least point to somewhere where it is stated? thanks
Comment: Oh, it must be the statement that the dual of $C([0,1])$ is the space of complex measures on $[0, 1]$
Comment: Basically this one https://en.wikipedia.org/wiki/Riesz–Markov–Kakutani_representation_theorem
Answer: Turns out:

Bound can be made tighter:

$$
|\int_0^1f(x)\cos(\pi x)dx - f(\frac{1}{2})| \leq \|f\|_{\infty}\frac{2}{\pi} + \|f\|_{\infty} \implies \sup_{\|f\|_{\infty}=1} \varphi(f) \leq \frac{2}{\pi}+1
$$

Proper measure is:

$$
\mu(A) = \int_A\cos{\pi x}dx - \delta_\frac{1}{2}(A)
$$

using Riesz-Markov-Kakutani measure we know that the norm of the functional equals to the variation of the measure

$$
|\mu|(X) = \int_0^{\frac{1}{2}}\cos{\pi x}dx + \int_{\frac{1}{2}}^1-\cos{\pi x}dx + 1 = \frac{2}{\pi} + 1 = \|\varphi\|
$$
Comment: Oh, maybe because $\| \varphi(f) \| = 2$ but $\|f \| \neq 1$.
Comment: So, where is the mistake in your computation above? Isn't $\varphi(2)=2$? Because the measure you gave is essentially correct. What penalized you must have something to do with the norm of $\varphi$.
Comment: I'm also not sure. My bound was correct but it could have been made smaller(I limited $\int_0^1|\cos{\pi x}|dx$ by 1 while in fact it can be easily calculated and equals $\frac{2}{\pi} < 1$). I don't see however, why $\| \varphi(f) \|$ where $f = 2$ is not 2.
Comment: Yes, that's it. Therefore, you only gave an estimate for the norm of $\varphi$, you did not compute its exact value. That's good; I don't think you will be doing the same mistake again, now. :-) I also still remember similar mistakes I did as a student. Learning through error is the best.


Solve $\frac{\tan^2x}{1+\tan^2x} = \sin^2x$

Question: I'm having troubles with some problems here is an example :
$$\begin{align}
{\frac{\tan^2x}{1+\tan^2x}} & = \sin^2x \\
\end{align}$$
Can someone explain to me step by step on how you got the answer.
Comment: Many of us can take it step by step. Can you show some effort?
Answer: All you need is:

$\tan(x) = \dfrac{\sin(x)}{\cos(x)},$
$\sin^2(x) + \cos^2(x) = 1$.

Try getting rid of the $\tan$'s first, then simplifying the fraction on the left a bit, and finally applying $\sin^2(x) + \cos^2(x) = 1$.
Answer: The left hand side is $$\dfrac{\tan ^2 x}{\sec ^2 x} = \tan ^2 x \cdot \cos ^2 x$$
Can you take it from here?
Comment: Joe, please do not edit my answer(s) to include reasoning that I omitted. If you would like to see an answer that is more thorough, or that spoon feeds the OP, feel free to write your own. I have rolled back to original.
Answer: The first time I ever saw the identity
$$
\tan(\alpha+\beta)=\text{a function of }\tan\alpha\text{ and }\tan\beta
$$
it was proved by changing it to
$$
\frac{\sin(\alpha+\beta)}{\cos(\alpha+\beta)}
$$
and then applying the previously demostrated identities involving those.  The same thing works here:
$$
\frac{\tan^2 x}{1+\tan^2x} = \frac{\left(\frac{\sin^2 x}{\cos^2 x}\right)}{1+\frac{\sin^2 x}{\cos^2 x}}
$$
Multiplying both the top and bottom by $\cos^2 x$ gets rid of the fractions-within-fractions and gives you $\cos^2 x+\sin^2 x$ in the denominator.  You probably know that $\cos^2 x+\sin^2 x$ can be greatly simplified.
Comment: I saved this answer about 45 minutes ago, and it says here I answer two minutes ago.
Comment: ....and 30 seconds after I posted the comment above, it says I posted it "7 mins ago".
Comment: ....and _then_, a minute after _that_, it says my first comment above was "1 min ago".
Comment: I never edited my answer here after posting it.  I don't know what only the bottom half would appear.


An inequality with a prime number

Question: I have this to purpose :

Let $a,b,c$ be real positive numbers such that $abc=1$ prove that :
  $$\frac{a^2}{(a^{11}+1)^2}+\frac{b^2}{(b^{11}+1)^2}+\frac{c^2}{(c^{11}+1)^2}\leq \frac{10^7}{9193531}$$

Where $9193531$ is a prime number wich makes the problem harder .
Really I have no ideas to prove this and all my classical methods fails automatically when I want solve this problem .
Furthermore I do not know which class of functions belongs $f(x)$ where :
$$f(x)=\frac{x^2}{(x^{11}+1)^2}$$
Maybe we can find a way with the concept of Quasiconvex function
If you have any hints it would be nice.
Thanks
Comment: Not sure why primality makes it harder..
Comment: I fed it to [Alpha](http://www.wolframalpha.com/input/?i=maximize++x%5E2%2F(x%5E11%2B1)%5E2+%2B+y%5E2%2F(y%5E11%2B1)%5E2%2Bz%5E2%2F(z%5E11%2B1)%5E2+subject+to+xyz%3D1) and the limit is very tight.  It found a maximum of $1.08772$ at about $(1.51865, 0.811465, 0.811465)$  The right side is about  $1.08772136$
Comment: Have you tried Lagrange multipliers? That's usually the method to find extreme values of functions under constraints, though it can be quite tedious..
Comment: @user496634 I used Lagrange multipliers in my answer to show that the smaller two values are the same.
Comment: @max8128 Do you know where this question is from?
Answer: Let
$$f(x)=\frac{x^2}{(x^{11}+1)^2}.$$
By a compactness argument, there exists a triple $(a,b,c)$ of positive real numbers that maximizes the sum $f(a)+f(b)+f(c)$ subject to the constraint $abc=1$.
We may assume that $0<a\leq b\leq c$.
Then $a\leq1$ and $c\geq1$.
If $a<10^{-1/11}$ then increasing $a$ and decreasing $c$ contradicts the maximality of $(a,b,c)$.
Thus, $a\geq10^{-1/11}$.
If $b>1$ then
$$f(a)+f(b)+f(c)\leq f(10^{-1/11})+f(1)+f(1)\leq1.044$$
which contradicts the maximality of $(a,b,c)$ (there are better solutions than $1.044$).
Thus, $b\leq1$.
In summary,
$$10^{-1/11}\leq a\leq b\leq1\leq c.$$
By Lagrange multipliers,
$$\left\langle f^\prime(a),f^\prime(b),f^\prime(c)\right\rangle=\lambda\left\langle bc,ac,ab\right\rangle=\lambda\left\langle\frac{1}{a},\frac{1}{b},\frac{1}{c}\right\rangle.$$
If we set $p(x)=xf^\prime(x)$ then $p(a)=p(b)=p(c)$.
Since $a\leq b\leq1$, looking at the graph of $p(x)$ shows that $a=b$.
Then we wish to maximize the one-variable function
$$g(x)=2f(x)+f\left(\frac{1}{x^2}\right)=2\left(\frac{x}{x^{11}+1}\right)^2+\left(\frac{x^{20}}{x^{22}+1}\right)^2.$$
The maximum occurs slightly above $x=10^{-1/11}$.
We can find the maximum by setting $g^\prime(x)=0$.
We can compute
$$g^\prime(x)=\frac{4x(1-10x^{11})}{(x^{11}+1)^3}+\frac{4x^{39}(10-x^{22})}{(x^{22}+1)^3}.$$
Setting $g^\prime(x)=0$ gives
$$\frac{1-10x^{11}}{(x^{11}+1)^3}+\frac{x^{38}(10-x^{22})}{(x^{22}+1)^3}=0.$$
Clearing denominators gives
$$(1-10x^{11})(x^{22}+1)^3+x^{38}(10-x^{22})(x^{11}+1)^3=0.$$
The root of this polynomial can be found to arbitrary precision using Newton's method:
$$x\approx0.8114699441003698687884808010408458056245.$$
Then
$$g(x)\approx1.0877212680663091337501932514101994261908490$$
which is about $0.0000000873$ below $10^7/9193531$.
To make this 100% rigorous, you need to use bounds on $g^\prime(x)$ (this is rather tedious and was done in an earlier version of this answer).
Answer: Geometric Explanation "min/max at x=y"
(Not an Answer)

Using $c=1/(ab)$, Let $a=x$, $b=y$ and define:
$$
\begin{align}
&f(x,y)=\frac{10^7}{9193531}-\frac{x^{2}}{\left(x^{11}+1\right)^2}-\frac{y^{2}}{\left(y^{11}+1\right)^2}-\frac{(xy)^{20}}{\left((xy)^{11}+1\right)^2}=f(y,x) \\
&f({\small-\frac{8}{10}},{\small-\frac{9}{10}})\approx-1.4\lt0, \quad f({\small2},{\small2})\approx+1.0\gt0
\end{align}
$$

Benefiting from the function symmetric behavior $f(x,y)=f(y,x)$, the inequality holds for the special case min/max accord at $x=y$. Thus, re-define:
$$
\begin{align}
&f(x)=\frac{10^7}{9193531}-\frac{2x^{2}}{\left(x^{11}+1\right)^2}-\frac{x^{40}}{\left(x^{22}+1\right)^2} \\
&\qquad=\color{blue}{\frac{10^7}{9193531}-\frac{2x^{2}+4x^{24}+x^{40}+2x^{46}+2x^{51}+x^{62}}{1+2x^{11}+3x^{22}+4x^{33}+3x^{44}+2x^{55}+x^{66}}}
\end{align}
$$
And the question now turns to be about $\,{\small f(x)}\,$ roots for $\,{\small x\gt0}\,$.

Putting $\,{\small f(x)=0}\,$ and simplifying, gives the equivalent polynomial:
$$
\begin{align}
p(x)=\,&\,\color{red}{{10^7}\left({1+2x^{11}+3x^{22}+4x^{33}+3x^{44}+2x^{55}+x^{66}}\right)} \\
&\,\color{red}{-{9193531}\left(2x^{2}+4x^{24}+x^{40}+2x^{46}+2x^{51}+x^{62}\right)}
\end{align}
$$
Because the polynomial degree is high, and to determine if $\,{\small p(x)}\,$ has any $\,{\color{red}{\small\text{real root}}}\,$ for $\,{\small x\gt0}\,$, it is enough to use Sturm theorem to compare number of roots inside the two regions $\,{\small [-1,0]}\,$ and $\,{\small [-1,\infty)}\,$, which should result in only $\,{\color{red}{\small\text{ONE}}}\,$ root in both, hence $\,{\small p(x)\ne0\,\,\colon\,x\in(0,\infty)}\,$.

Comment: @ThomasBrowning : $(xy)^{20}$ appears after simplifying: $$ f(x,y)=\frac{10^7}{9193531}-\frac{x^{2}}{\left(x^{11}+1\right)^2}-\frac{y^{2}}{\left(y^{11}+1\right)^2}-\frac{\left(\frac{1}{xy}\right)^2}{\left(\left(\frac{1}{xy}\right)^{11}+1\right)^2} $$ Your second comment is correct (Thank you!). Indeed $f(x_0,y_0)=f(y_0,x_0)=0$ don't imply $x_0=y_0$ (I shall edit this). I'll mark my answer as a geometry explanation of the special case $x=y$. On the other hand, I still believe the min/max of $f(x,y)$ shall occurred at $x=y$ though I don't know how to show this. Thanks again.
Comment: Why is it $(xy)^{20}$ in the definition of $f(x,y)$?
Comment: Also, why does $f(x_0,y_0)=f(y_0,x_0)=0$ imply that $x_0=y_0$?

An inequality with a prime number


Como gerar automaticamente e redirecionar o link no cabeçalho

Question: Eu estou precisando gerar um sistema onde possuo uma página template (o perfil do fb por exemplo) e que vai ser alimentada pelo meu banco de dados com as informações de acordo com o ID de um usuário.
O meu problema é: não quero que o link do parâmetro passado (id) seja exposto no cabeçalho da página e sim uma variável desse usuário que dei query (o usuario dele por exemplo) e que ao mesmo tempo se eu acessar esse link (www.meusite.com/usuario) ele seja redirecionado para essa mesma página (dando o query no BD e puxando as informações normalmente)
Isso é possivel via PHP ou JS?
Obrigado desde já!
Answer: É possível sim,
Para configurar a url da página veja esses links:
Como fazer URL Amigável ou Como faço url amigável no PHP
Para teste você pode pegar a url atual com $_SERVER["REQUEST_URI"]
Com JS existe uma pergunta aqui no StackOverflow sobre pegar url da página anterior
Com o valor dessa url você pode usar as funções substr() para pegar o valor após a "/" e enviar para o controle do seu sistema, lá você faz a consulta passando esse valor
Para enviar o id do usuário sem ser por $_GET você pode usar $_SESSION ou $_POST


How to get the active #comment-cid when a comment permalink is clicked?

Question: I am trying to get the comments on my website to change color when they are active. More specifically, I am looking to do something very similar to what StackExchange sites do when you click on a notification in your inbox (like this). So what I initially tried to do, was to wrap the comment class in another div class called comment_active using an if statement to see whether the current page url contained the string "#comment-". (being that the permalink for a comment is /node/nid#comment-cid I am trying to get drupal to know what the current cid is) I am having some problems figuring out how to do this. Is placing, for example #comment-1 even part of the url? or does it just bring you to the part of the page that contains that element id? is there a way that I can have the comment.tpl.php know whether a comment is active? Or should I be doing it some other way entirely?
Answer: Try to add a custom javascript file to in theme.info file
 jQuery(document).ready(function() {
    //get the current path
    var pathname = window.location.hash;
    jQuery(pathname).next().addClass('active-comment');
    //here add your custom animation
    jQuery('.active-comment').fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn();

});

here is a plugin to animate the background color of the wrapper :here
Hope this will Help You
Comment: I'm confused as to what this does. does this add the class `active_comment` to the `.comment_class`? or does this create a class for every element with an `id`?
Comment: I forgot to add .next() , because the structure of drupal comment is , now the code above will add the class to the comment wrapper instead of adding it to the  ,
Comment: I added a comments.js file with that code, and pointed to it in the theme.info file, but it doesn't seem to working. Is there something else I'm supposed to be doing, I'm new to jquery with drupal. Also, when I look up online on how to use jquery with drupal,other people seem to be using `JQuery();` instead of `$()`. Does that make a difference hear at all. I'm using drupal 7.12
Comment: Out of curiosity, would there also be a way to do this using php?
Comment: I've updated my code snippets , and it's a tested code and working for me
Comment: The `addClass` part worked great, but I ended up using
`@keyframes activecomment
{
from {background: red;}
to {background: #535B6B;}
}`
in the css for the animation


g++ compilier how to include boost::regex

Question: I've installed boost, so i'm trying to run compiler like this:g++ -LC:\MinGW\boost_1_55_0\stage\lib -lboost_regex-mgw49-mt-1_55 test.cpp
My programm test.cpp is not very complicated:
#include <iostream>
int main()
{
  std::cout << "Hello, world!" << std::endl;
  boost::regex rex("[test]");
}

I'm of course failed: error: 'boost' has not been declared. I can't understand what I must write in my test.cpp file next to #include <iostream>? #include <boost> doesn't work, i'm getting error fatal error: boost: No such file or directory.
#include <boost/regex.hpp> also yield this error, maybe #include <boost_regex-mgw49-mt-1_55>? But it still doesn't work.
Answer: You need to include regex.hpp in your main. You hint that you tried to, but it apparently didn't work.
Make sure regex.hpp is where you tell the compiler it is relative to one of your search directories. It's not good enough to tell the compiler to include boost/regex.hpp, the file has to actually exist where the compiler is looking for it to be able to find it.
You will need to copy that file from wherever you downloaded it to somewhere the compiler will know to look for it. Once you do that, it should find it and that error should go away.
Also note that the same applies to the object file you're trying to link in. If the linker can't find that file, you'll just get a linker error once you clear up this compiler error.
Comment: Thanks! So, i've found regex.hpp in 'C:\MinGW\boost_1_55_0\boost'. Copied it to C:\MinGW\boost_1_55_0\stage\lib and even C:\MinGW\boost_1_55_0\stage. I've added  in test.cpp but still error.
Comment: You don't want a header file in a lib directory. The compiler has different search directories for the linker and the compiler. You may need to specify a new search directory for the compiler, but I don't see any reason why you couldn't just create a boost folder inside your project source folder and put regex.hpp there. Then "#include "boost/regex.hpp" should work.
Comment: I have explained what you need to do. Use the -I option to add search directories for the compiler.
Comment: Even if i try to run g++ test.cpp -I/C:/MinGW/boost_1_55_0/boost i'm getting error. In this directory i have endeed regex.hpp. I've typed "#include ". But  fatal error: regex.hpp: No such file or directory
Comment: You have an extra slash between -I and C:. Other than that, there's really nothing else I can see. That error means the compiler cannot find the hpp file.


How to combine partially pre-cached MemoryStream with FileStream?

Question: For a time-critical media presentation application, it is important that media files be presented right at the instance when the user selects it. Those files reside in a truly humongous directory structure, comprised of thousands of media files.
Clearly, caching the media files in a MemoryStream is the way to go; however, due to the sheer amount of files, it's not feasible to cache each file entirely. Instead, my idea is to pre-cache a certain buffer of each file, and once the file is presented, play from that cache until the rest of the file is loaded from the hard disk.
What I don't see is how to "concatenate" both the MemoryStream and the FileStream so as to provide a seamless playback experience. I'm not very strong in data streams (yet), and I see several problems:

How does one keep track of the current read position within the MemoryStream and provide that to the FileStream without the MemoryStream reading more than that?
How does one switch from one stream to the other without having both streams either partially overlap each other or creating a "playback break"?
If using a queue of streams (as suggested in How do I concatenate two System.Io.Stream instances into one?), how can I specify that the second stream has to be ready for read access instantaneously after the first stream is done? Here, in particular, I don't see how the MemoryStream would help at all, since the FileStream, as second one in the queue, would only begin accessing the hard disk once it's actually used.
Is it really a feasible approach to have literally hundreds, if not thousands of open streams at once?

Note that I don't need write access—reading is fully sufficient for the problem at hand. Also, this question is similar to Composite Stream Wrapper providing partial MemoryStream and full original Stream, but the solution provided there is a bug fix for Windows Phone 8 that doesn't apply in my case.
I'd very much like to widen my rather limited understanding of this, so any help is greatly appreciated.
Answer: I would suggest something like the following solution:

Inherit your own CachableFileStream from FileStream
Implement a very simple Cache which uses a data structure you prefer (like a Queue)
Allow Preloading data into the internal cache
Allow Reloading data into the internal cache
Modify the original Read behaviour in a way, that your cache is used

To give you an idea of my idea I would suggest some implementation like the following one:
The usage could be like that:
CachableFileStream cachedStream = new CachableFileStream(...)
{
    PreloadSize = 8192,
    ReloadSize = 4096,
};

// Force preloading data into the cache
cachedStream.Preload();

...
cachedStream.Read(buffer, 0, buffer.Length);
...

Warning: The code below is neither correctly tested nor ideal - this shall just give you an idea!
The CachableFileStream class:
using System;
using System.IO;
using System.Threading.Tasks;

///
/// Represents a filestream with cache.
///
public class CachableFileStream : FileStream
{
    private Cache<byte> cache;
    private int preloadSize;
    private int reloadSize;

    ///
    /// Gets or sets the amount of bytes to be preloaded.
    ///
    public int PreloadSize
    {
        get
        {
            return this.preloadSize;
        }

        set
        {
            if (value <= 0)
                throw new ArgumentOutOfRangeException(nameof(value), "The specified preload size must not be smaller than or equal to zero.");

            this.preloadSize = value;
        }
    }

    ///
    /// Gets or sets the amount of bytes to be reloaded.
    ///
    public int ReloadSize
    {
        get
        {
            return this.reloadSize;
        }

        set
        {
            if (value <= 0)
                throw new ArgumentOutOfRangeException(nameof(value), "The specified reload size must not be smaller than or equal to zero.");

            this.reloadSize = value;
        }
    }

    ///
    /// Initializes a new instance of the <see cref="CachableFileStream"/> class with the specified path and creation mode.
    ///
    /// <param name="path">A relative or absolute path for the file that the current CachableFileStream object will encapsulate</param>
    /// <param name="mode">A constant that determines how to open or create the file.</param>
    /// <exception cref="System.ArgumentException">
    /// Path is an empty string (""), contains only white space, or contains one or more invalid characters.
    /// -or- path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
    /// </exception>
    /// <exception cref="System.NotSupportedException">
    /// Path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
    /// </exception>
    /// <exception cref="System.ArgumentNullException">
    /// Path is null.
    /// </exception>
    /// <exception cref="System.Security.SecurityException">
    /// The caller does not have the required permission.
    /// </exception>
    /// <exception cref="System.IO.FileNotFoundException">
    /// The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist.
    /// The file must already exist in these modes.
    /// </exception>
    /// <exception cref="System.IO.IOException">
    /// An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.-or-The stream has been closed.
    /// </exception>
    /// <exception cref="System.IO.DirectoryNotFoundException">
    /// The specified path is invalid, such as being on an unmapped drive.
    /// </exception>
    /// <exception cref="System.IO.PathTooLongException">
    /// The specified path, file name, or both exceed the system-defined maximum length.
    /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
    /// </exception>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// Mode contains an invalid value
    /// </exception>
    public CachableFileStream(string path, FileMode mode) : base(path, mode)
    {
        this.cache = new Cache<byte>();
        this.cache.CacheIsRunningLow += CacheIsRunningLow;
    }

    ///
    /// Reads a block of bytes from the stream and writes the data in a given buffer.
    ///
    /// <param name="array">
    /// When this method returns, contains the specified byte array with the values between
    /// offset and (offset + count - 1) replaced by the bytes read from the current source.
    /// </param>
    /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param>
    /// <param name="count">The maximum number of bytes to read.</param>
    /// <returns>
    /// The total number of bytes read into the buffer. This might be less than the number
    /// of bytes requested if that number of bytes are not currently available, or zero
    /// if the end of the stream is reached.
    /// </returns>
    /// <exception cref="System.ArgumentNullException">
    /// Array is null.
    /// </exception>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// Offset or count is negative.
    /// </exception>
    /// <exception cref="System.NotSupportedException">
    /// The stream does not support reading.
    /// </exception>
    /// <exception cref="System.IO.IOException">
    /// An I/O error occurred.
    /// </exception>
    /// <exception cref="System.ArgumentException">
    /// Offset and count describe an invalid range in array.
    /// </exception>
    /// <exception cref="System.ObjectDisposedException">
    /// Methods were called after the stream was closed.
    /// </exception>
    public override int Read(byte[] array, int offset, int count)
    {
        int readBytesFromCache;

        for (readBytesFromCache = 0; readBytesFromCache < count; readBytesFromCache++)
        {
            if (this.cache.Size == 0)
                break;

            array[offset + readBytesFromCache] = this.cache.Read();
        }

        if (readBytesFromCache < count)
            readBytesFromCache += base.Read(array, offset + readBytesFromCache, count - readBytesFromCache);

        return readBytesFromCache;
    }

    ///
    /// Preload data into the cache.
    ///
    public void Preload()
    {
        this.LoadBytesFromStreamIntoCache(this.PreloadSize);
    }

    ///
    /// Reload data into the cache.
    ///
    public void Reload()
    {
        this.LoadBytesFromStreamIntoCache(this.ReloadSize);
    }

    ///
    /// Loads bytes from the stream into the cache.
    ///
    /// <param name="count">The number of bytes to read.</param>
    private void LoadBytesFromStreamIntoCache(int count)
    {
        byte[] buffer = new byte[count];
        int readBytes = base.Read(buffer, 0, buffer.Length);

        this.cache.AddRange(buffer, 0, readBytes);
    }

    ///
    /// Represents the event handler for the CacheIsRunningLow event.
    ///
    /// <param name="sender">The sender of the event.</param>
    /// <param name="e">Event arguments.</param>
    private void CacheIsRunningLow(object sender, EventArgs e)
    {
        this.cache.WarnIfRunningLow = false;

        new Task(() =>
        {
            Reload();
            this.cache.WarnIfRunningLow = true;
        }).Start();
    }
}

The Cache class:
using System;
using System.Collections.Concurrent;

///
/// Represents a generic cache.
///
/// <typeparam name="T">Defines the type of the items in the cache.</typeparam>
public class Cache<T>
{
    private ConcurrentQueue<T> queue;

    ///
    /// Is executed when the number of items within the cache run below the
    /// specified warning limit and WarnIfRunningLow is set.
    ///
    public event EventHandler CacheIsRunningLow;

    ///
    /// Gets or sets a value indicating whether the CacheIsRunningLow event shall be fired or not.
    ///
    public bool WarnIfRunningLow
    {
        get;
        set;
    }

    ///
    /// Gets or sets a value that represents the lower warning limit.
    ///
    public int LowerWarningLimit
    {
        get;
        set;
    }

    ///
    /// Gets the number of items currently stored in the cache.
    ///
    public int Size
    {
        get;
        private set;
    }

    ///
    /// Initializes a new instance of the <see cref="Cache{T}"/> class.
    ///
    public Cache()
    {
        this.queue = new ConcurrentQueue<T>();
        this.Size = 0;
        this.LowerWarningLimit = 1024;
        this.WarnIfRunningLow = true;
    }

    ///
    /// Adds an item into the cache.
    ///
    /// <param name="item">The item to be added to the cache.</param>
    public void Add(T item)
    {
        this.queue.Enqueue(item);
        this.Size++;
    }

    ///
    /// Adds the items of the specified array to the end of the cache.
    ///
    /// <param name="items">The items to be added.</param>
    public void AddRange(T[] items)
    {
        this.AddRange(items, 0, items.Length);
    }

    ///
    /// Adds the specified count of items of the specified array starting
    /// from offset to the end of the cache.
    ///
    /// <param name="items">The array that contains the items.</param>
    /// <param name="offset">The offset that shall be used.</param>
    /// <param name="count">The number of items that shall be added.</param>
    public void AddRange(T[] items, int offset, int count)
    {
        for (int i = offset; i < count; i++)
            this.Add(items[i]);
    }

    ///
    /// Reads one item from the cache.
    ///
    /// <returns>The item that has been read from the cache.</returns>
    /// <exception cref="System.InvalidOperationException">
    /// The cache is empty.
    /// </exception>
    public T Read()
    {
        T item;

        if (!this.queue.TryDequeue(out item))
            throw new InvalidOperationException("The cache is empty.");

        this.Size--;

        if (this.WarnIfRunningLow &&
            this.Size < this.LowerWarningLimit)
        {
            this.CacheIsRunningLow?.Invoke(this, EventArgs.Empty);
        }

        return item;
    }

    ///
    /// Peeks the next item from cache.
    ///
    /// <returns>The item that has been read from the cache (without deletion).</returns>
    /// <exception cref="System.InvalidOperationException">
    /// The cache is empty.
    /// </exception>
    public T Peek()
    {
        T item;

        if (!this.queue.TryPeek(out item))
            throw new InvalidOperationException("The cache is empty.");

        return item;
    }
}

I hope this helps, have fun ;-)
Comment: Thank you, this is a very solid solution. I particularly like the concurrent reloading if the cache runs low. There's a problem inherent with the media file context, though: once a given file was presented, re-playing it will be slow (needs loading from the disk), similarly for stop & rewind or seek & play. Maybe this could be solved with a `Cache` that doesn't empty itself when reading from it—I'll have to think about that.
Comment: Hi @markus-safar, my apologies for the delay. The project experienced a re-focus, and a couldn't follow up on this problem until very recently. Your suggestion works very well and put me on the right track. (I tweaked it and modified its behavior so that parts of a media file remain persistent in main memory while the software is running, and stream handling turned out to be easier with a byte array instead of a queue.)
Comment: @Informagic: If you find my solution useful, I would be happy if you accept it (temporary) as [anwser](https://stackoverflow.com/help/accepted-answer) :-)