How to determine % effect on quantitative variable from beta and se values?

Question: I am trying to understand a GWAS paper which reports the effect of a SNP on outcome as a % variation, e.g., 15% variation in xxx levels.
The only information reported are the beta, standard error and p-values. I tried to read the paper but there is no mention of how this is calculated.
The paper in question is Genome-wide association meta-analysis for total serum bilirubin levels (Hum. Mol. Genetics, 2009).
Paragraph in question = These SNPs accounts for approximately 17.5, 18.1 and
16.7% of the variation...
If anyone has any clue, please help. I'll be most appreciative.
Comment: It looks to me like you can't calculate these values yourself from the data in the paper, because they don't give data on all four of the SNPs for each sample (there is only data for the pooled analysis in the supplementary data). But in general, I believe you could do this by calculating h^2 (heritability) from the regression model - although I have not done this combining multiple SNPs so I'm not sure how that might change the calculation.
Comment: Thanks for your input, I am trying to determine the % variation from one SNP in the supplementary data but it looks like I can't from whatever information provide.
Answer: These appear to be simply $R^2$ values (also called coefficient of determination), that is, the variance accounted for in the outcome variable based on the covariates/predictors included in the model. In this case, the outcome variable is the bilirubin level (log transformed) and the covariates/predictors are the SNPs. In the footnotes of Table 1, the authors write: "The $\beta$ coefficient represents the change in log-transformed bilirubin with one additional copy of the allele modeled", so the authors used an additive model for the SNPs (where you use the number of alleles as the predictor).
In the FHS sample, the authors used a mixed-effects model to account for familial clustering/correlation. In such models, the computation of $R^2$ is a bit more intricate and, as far as I can tell, the authors do not provide a reference for what approach they used here. See, for example, this question for some references on this.
Comment: Thank you for your comment, I will look at your links more thoroughly.


What is the meaning of the inner product of a vector and a gradient?

Question: Recently I came across the following expression:
$$ \langle \nabla f(x_1),x_2 \rangle$$
I do understand how to calculate the value of the expression. You take the derivatives of each of the entry in the function and then substitute $x_1$ in it and then take the dot product between the resulting value and $x_2$. But is there any meaning for this expression? What does this expression represent?
Please help.
Comment: a short answer: it gives the gradient of $f$ in $x_1$ in direction of $x_2$.
Answer: The inner product $\langle \nabla f(\mathrm x_1), \mathrm x_2 \rangle$ is the directional derivative of $f$ in the direction of $\mathrm x_2$ at $\mathrm x_1$.
$$\lim_{h \to 0} \frac{f (\mathrm x_1 + h \mathrm x_2) - f (\mathrm x_1)}{h} = \langle \nabla f(\mathrm x_1), \mathrm x_2 \rangle$$
Answer: $\nabla f(x_1)$ is the jacobian matrix of the scalar-valued function $f$ at $x_1$. Now the differential $Df(x_1)$ is a linear map, in this case simply given by $\langle \nabla f(x_1),x_2 \rangle$. So the answer to your question is: The differential of a scalar-valued function $f$ in $x_1$ evaluated in $x_2$. To make this more visible, we have $$\begin{pmatrix} \partial_1f(x_1) & \dots \partial_nf(x_1)\end{pmatrix} \begin{pmatrix} x^1_2\\
\vdots\\
x_2^n\end{pmatrix} = \langle \nabla f(x_1),x_2 \rangle$$
$\langle \nabla f(x_1),x_2 \rangle$ is also reffered as directional derivative along $x_2$.
Answer: Note that the following identity holds:
$$
\frac{\partial f}{\partial v}=\lim_{h \to 0}=\frac{f(x_1+hv)-f(x_1)}{h}=<\nabla f(x_1),v>
$$
In other words, it is the derivative of $f$ in $x_1$ in the direction $v$
Answer: Consider the following curve:
$$\alpha: \mathbb{R} \to \mathbb{R}^n : t \mapsto x_1 + tx_2$$
We can compute $(f \circ \alpha)'(0)$, that is the derivative with respect to $t$ and evaluate it in $0$. Using the chain rule, we find that
$$(f \circ \alpha)'(0) = Df(\alpha(0)) \alpha'(0) = Df(x_1) (x_2)$$
where $Df$ is the derivative of $f$, or as you say it: the gradient of $f$. This is a linear map:
$$Df(x_1): \mathbb{R}^n \to \mathbb{R}^n,$$
so it makes sense to apply this map to a vector $x_2$.
In the case where $f : \mathbb{R} \to \mathbb{R}^n$, we find that it corresponds to the inproduct you wrote down. But you can apply this for any function $f: \mathbb{R}^m \to \mathbb{R}^n$.


How do I run Apache & IIS 7 on the same IP address (different ports)?

Question: I have a Windows Server 2008 machine which is running Apache at the moment for a public facing PHP site (port 80). IIS is stopped.
I now need to start running IIS on the same IP address as Apache, but I can happily use another port as it's internal only e.g. 8080. We have no other IP addresses available.
I presume it can be done, but I'm new to Apache and need to ensure that I don't break the current PHP site when starting IIS. I understand that IIS tends to hog all ports on an IP by default? Or has that changed since IIS 6?
What configuration steps do I need to take to achieve this?
Many thanks,
Tim
Answer: The steps for IIS7 involves:

Microsoft Internet Information Services 7.0:
1. Open Internet Information Services (IIS) Manager.
2. Select the Web site that you wish to configure.
3. In the Action pane, click Bindings.
4. Click Add to add a new site binding, or click Edit to change an existing binding.
5. Click OK to apply the changes.

From How to change the TCP port for IIS Services
Comment: Thanks, didn't think just doing that would work... Glad it was simple.
Answer: Or you can try this for Apache: Binding to Addresses and Ports
The short version modify the listen line:

Listen <ipaddress>:<port>
Comment: Welcome to Server Fault! Things have moved on a bit since 2010 and these days we really do prefer that answers contain content not pointers to content. Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Criar Fibonacci em uma função linear com delegate

Question: Usando uma lista para o Delegate(aprendi que isso se chama função linear, é isso mesmo?) eu decremento a lista para ela ir pegando os respectivos valores, mas não consigo fazer uma operação aritmética simples com "X", pois eu tenho uma lista e "X" passa ser essa lista, conforme Omni e ramaral me explicaram nos posts abaixo.
A Fibonacci eu sei fazer, quero é fazê-la da forma citada.
Sei que Fibonacci é: Fn = F(n-1) + F(n-2).
O x - 1 e o x - 2 dá erro.
Nesse caso o retorno da função seria uma lista(Fibonacci)
Veja como ficou meu método.
List<int> lista = new List<int>();

Func<List<int>, List<int>> calcFib = null;

for(int i = 0; i <= tamanho-1; i++)
    lista.Add(i);

calcFib = x => x.Count == 0 ? 0 : (x - 1 + x - 2) + calcFib(x.Take(x.Count - 1).ToList<int>());

return calcFib(lista);

A minha lista, é o limite da sequência que eu quero implementar o Fibonacci. No caso, a var tamanho. Se tamanho for 10, por exemplo, seria o resultado: 0,1,1,2,3,5,8,13,21,34
public List<int> novoFibonacci(int tamanho)
        {
            List<int> lista = new List<int>();

            Func<List<int>, List<int>> calcFib = null;

            for(int i = 0; i <= tamanho-1; i++)
                lista.Add(i);

            calcFib = x => x

            return calcFib(lista);
        }

Comment: O que é essa `lista`?
Comment: Perdão, é que eu copiei do post anterior meu. Vou editar e recolocar, assim explico melhor.
Answer: Você deve pegar em cada um dos valores da sua lista e calcular o valor correspondente na serie de Fibonacci
Seria algo assim:
public List<int> novoFibonacci(int tamanho)
{
    List<int> lista = new List<int>();
    for (int i = 0; i <= tamanho - 1; i++)
    {
        lista.Add(i);
    }

    //O Select executa GetFibonacciAt() passando a ela cada um dos elementos da lista,
    //returnado um IEnumerable<int> contendo cada um dos resultados.

    return lista.Select(n => GetFibonacciAt(n)).ToList();
}

Você tem de criar o método int GetFibonacciAt(int n) que calcule o valor correspondente a n na serie de Fibonacci.
Se quiser eu posto essa função.
EDIT
Solução com uma função em linha como pedido:
public List<int> novoFibonacci(int tamanho)
{
    Func<int, int> getFibonacciAt =
               n => (n <= 1) ? n : getFibonacciAt(n - 1) + getFibonacciAt(n - 2);

    var lista = new List<int>();
    for (int i = 0; i <= tamanho - 1; i++)
    {
        lista.Add(i);
    }
    return lista.Select(n => getFibonacciAt(n)).ToList();
}

Comment: Deixa eu tentar primeiro. Se quebrar a cabeça e não consegui, aí te peço ajuda. Desde já, grato.
Comment: Entendi, era exatamente isso que eu buscava, entendimento. Isso tudo é um estudo que eu estou fazendo para ter maior domínio sobre determinados assuntos. O dia-a-dia de um programador é vivido em cima de decisões baseadas em certezas, em padrões já testados. É isso que eu estou fazendo. Obrigado.
Comment: Pelo visto, será um método que retorne um Fib, tipo: Fn = (Fn-1 + Fn-2), exatamente o que eu tenho feito por aí, acho que é isso, certo?
Comment: fazer um método linear semelhante a esse não dá, certo?  qdr = square => square.Count == 0 ? 0 : square.Last() * square.Last() + qdr(square.Take(square.Count - 1).ToList()); Esse aí eu faço a soma dos quadrados dos elementos em um array.  Era isso que eu gostaria de fazer, só que com Fibonacci.
Comment: Julgo que de forma linear não dá porque o próximo valor é calculado em função do anterior.
Comment: Estive a pensar melhor no assunto e encontrei um modo de fazer isso em linha.
Answer: Você pode usar duas funções em linha, ou somente uma mais complexa, uma para calcular o Fibonacci.
    //função 1 recursividade (usando duas funções em linha)
    Func<int, int> calcFib = null;
    calcFib =
        x =>
        (x < 2) ? x : calcFib(x-1) + calcFib(x-2);
    Func<int, List<int>> Fibonacci =
        x =>
        Enumerable.Range(1, x).Select(s => calcFib(s)).ToList();

    //função 2 somente linq (usando apenas uma função em linha)
    Func<int, List<int>> Fibonacci2 =
        x =>
        Enumerable.Range(1, x).Select(
            a =>
            Enumerable.Range(1, a).Skip(2).Aggregate(
                new KeyValuePair<int, int>(1, 1),
                (seq, index) =>
                new KeyValuePair<int, int>(seq.Value, seq.Key + seq.Value)
            ).Value
        ).ToList();

Exemplo no DotNetFiddle


Provide an integer for an array index in OpenGL ES 2.0?

Question: I am developing an OpenGL application for the iPhone. In my vertex shader, I need a way to change the color of a large number of (but not all) of my vertices, at once, so I settled on color indexing. This will allow me to leave the VBO static, and modify a single uniform variable rather than looping through each vertex and modifying color information between each frame.
My plan is to create a uniform with a color array, add an integer containing an index in the attributes. Here is my vertex shader:
<code>uniform mat4 u_mvp_matrix;
uniform vec4 u_color_array[];

attribute vec4 a_position;
attribute int a_colorIndex;

varying lowp vec4 v_color;

void main()
{
    v_color = u_color_array[a_colorIndex];

    gl_Position = u_mvp_matrix * a_position;
}
</code>
This raises an error:

int can't be an in in the vertex shader

I did some research. The iPhone supports OpenGL ES 2.0 at the latest, which means it supports GLSL 1.2 at the latest, and apparently integers are only supported in GLSL 1.3 and later. I tried changing a_colorIndex to a float. I didn't expect it to work, and it didn't.
How can I specify a color index for each vertex?
Comment: "which means it supports GLSL 1.2 at the latest" No it doesn't. GL ES 2.0 means that it supports the GLSL ***ES*** shading language, which is *different* from the desktop GLSL language. GLSL ES is based on GLSL 1.2, but they're *not the same thing.*
Comment: Maybe consider a texture lookup, where your index is a uv float, instead of an array lookup? Or can you cast/round the float to an int?
Answer: Specify the attribute as a float. You can use floats as indices into arrays.
Comment: I get this error "Index expression has type 'float' but should have integral type" if I do what you said. Is it safe to do array[int(fIndex)] or will it run into precision errors?
Comment: I get into the same issue as weezor ("...should have integral type") (at least in some cases). It would be nice to clarify.
Comment: ES2 language spec says: "Array elements are accessed using an expression whose type is an integer." So yes, cast to int (lenient platforms do an implicit cast, so answer probably works on answerer's machine).


Is there ever any reason to discretise continuous ground truth if doing classification?

Question: Is there a case where discretising continuous response improves classification performance?
For example:
A response variable is in the range 0 to 99.
There are 10 classes defined by the following set of ranges $Sr = \{0-9,10-19...89-99\}$
Does it always make more sense to use regression models for this task, or can discretising and multi-class classification be beneficial?
Answer: I think this is purely based on what you really want to predict. Let's say that I have a restaurant and have the characteristics of my customers and want to predict how many time they do spend on it. Is the time important? Whether they spent 59min or 60min inside it? This is a perfect case where you could make the time spent inside the restaurant discrete (e.g. being for 30min is bad, 30-60 average, etc). Do you have real case to discuss? Any other thought?


Is $\liminf\Bbb P(X_nY_n\leq b)\geq\Bbb P(Xy\leq b) $ if $X_n\to X$ in distribution and $Y_n\to y\in\Bbb R$ in probability?

Question: Take $b\in\mathbb{R}$. Suppose $X_n\to X$ in distribution  and suppose $Y_n\to y$ in probability, where $y$ is a constant. How to prove $$\Bbb P(Xy\leq b) \leq \liminf_{n\to\infty}\Bbb P(X_nY_n\leq b)?$$
I've asked the question before but I didn't get any answer. So I tried myself and hopefully someone can follow my reasoning.
Note: I know that this follows from Slutsky's theorem, but I'm trying to use this question to prove Slutsky's theorem.

My try: Since $X_n\to X$ in distribution, then given $\epsilon>0$ there an $n\in\mathbb{N}$ such that for all $n\geq N$
$$\Bbb P(Xy\leq b)\leq\epsilon+\Bbb P(X_ny\leq b),\;\;\text{ and so }\;\;\; \Bbb P(Xy\leq b)\leq\epsilon+\inf_{n\geq N}\Bbb P(X_ny\leq b).$$
Now we need to use the fact that $Y_n\to y$ in probability.
We can write the set
$$\{X_ny\leq b\}=\{X_ny\leq b,Y_n\in (y-\epsilon,y+\epsilon) \}\cup \{X_ny\leq b,Y_n\not\in (y-\epsilon,y+\epsilon) \},$$
and so $$
\{X_ny\leq b\}\subseteq\underbrace{\{X_nY_n\leq b+\epsilon}_{:=A_n} \}\cup \underbrace{\{Y_n\not\in (y-\epsilon,y+\epsilon) \}}_{:=B_n},$$
Now we know that $\liminf_{n\to\infty}\Bbb P(B_n)=0$. Now let's look at $A_n$. For the sake of simplicity let's assume $X_n>0$.
Then we have that
$$A_n=\{X_nY_n\leq b\}\cup \underbrace{\{b<X_nY_n\leq b+\epsilon\}}_{C_n}.$$
In total, we have that
$$\Bbb P(X_ny\leq b)\leq \Bbb P(B_n) + \Bbb P(X_nY_n\leq b)+\mathbb{P}(C_n) $$
and
$$ \Bbb P(Xy\leq b)\leq \Bbb P(X_nY_n\leq b)+\epsilon + \Bbb P(B_n) +\mathbb{P}(C_n) $$
and so finally we have made the set $\{X_nY_n\leq b\}$ appear. Taking $\liminf$ we have that
$$ \Bbb P(Xy\leq b)\leq \liminf_{n\to\infty}\Bbb P(X_nY_n\leq b)+\epsilon  +\liminf_{n\to\infty}\mathbb{P}(C_n) $$
But then is it possible to bound the probability of $C_n=\{b<X_nY_n\leq b+\epsilon\}$ as a function of $\epsilon$?
Comment: It is only true if $b$ is a continuity point of $Xy$ . Otherwise it should not be true. The equivalent condition of $X_{n}\xrightarrow{d}X$ if and only if $\lim\inf P(X_{n}\in G)\geq P(X\in G)$ for all open sets $G$. As you can see $(-\infty,b]$ is not open. What you can certainly prove is that for $\lim\inf P(X_{n}Y_{n}<b)\geq P(Xy<b)$. And as you can see if $b$ is a continuity point then you'll get $\leq b$ also . However I am struggling to come up with a specific counter example. It should be easy though , I am just not seeing it now.
Comment: Do you know anything more about $X$? It doesn't seem to be correct. Note that $X_nY_n\to Xy$ in distribution under your hypothesis. The conclusion from one of the equivalent criterion of convergence says that $\limsup P(X_nY_n\leq b)\leq P(Xy\leq b)$.
Comment: I'm trying to prove that $X_nY_n \to Xy$ in distribution. That is the purpose of my question. I already proved that $\limsup P(X_nY_n\leq b)\leq P(Xy\leq b)$. Now I need the $\liminf$ inequality.
Answer: As I said in the comments , what you claim is true if you assume $b$ is a continuity point(which is what you want to prove when showing convergence of the cdf's ).
I'll show in two steps.
We show that for any compatcly supported continuous $f$ , we have $E(f(X_{n}Y_{n}))\to E(f(Xy))$ .
Fix $\epsilon$ positive.
Then by uniform continuity, there exists $\delta(\epsilon)>0$ such that $|f(x)-f(y)|<\epsilon$ when $|x-y|<\delta$ .
Now $\bigg|E(f(X_{n}Y_{n})-f(Xy))\bigg|=\bigg|E(f(X_{n}Y_{n})-E(f(X_{n}y)+E(f(X_{n}y)-Ef(Xy)\bigg|$ .
Now as $Y_{n}\xrightarrow{P} y$ . Hence $P(|Y_{n}-y|\geq \delta)\to 0$ .
Hence we have $|E(f(X_{n}Y_{n})-E(f(X_{n}y)|\leq \\\bigg|\bigg(E(f(X_{n}Y_{n})-E(f(X_{n}y)\bigg)\mathbf{1}_{|Y_{n}-y|< \delta}\bigg| +\bigg|\bigg(E((f(X_{n}Y_{n})-E(f(X_{n}y))\bigg)\mathbf{1}_{|Y_{n}-y|\geq \delta}\bigg| $
Which can be bounded by
$$\epsilon + \sup_{x}|f|\cdot P(|Y_{n}-y|\geq \delta)$$ which can be made less than $2\epsilon$ by choosing $n$ large enough.
And the last term $|E(f(X_{n}y))-E(f(Xy))|\to 0$ as $X_{n}y\xrightarrow{d}Xy$ . (If you don't know this already, this is an equivalent criteria for convergence in distribution. You can directly use Skorohod's Representation theorem(to make it easier, it is not necessary though) and DCT to prove this.
Now let $g=\mathbf{1}_{(-\infty,b)}$ . Take $f_{n}$ to be a sequence of uniformly continuous functions such that $f_{n}$ decrease to $g$. You can certainly do this by just considering $\mathbf{1}_{(-\infty,b-\frac{1}{n}]}$ and then just linearly joining to the $x$ axis.
$P(X_{n}Y_{n}<b)=E(g(X_{n}Y_{n}))\geq E(f_{m}(X_{n}Y_{n}))\to E(f_{m}(Xy))=P(Xy\leq b-\frac{1}{m}) $
Now by monotone convergence theorem $E(f_{m}(Xy))\to E(g(Xy))$ and hence $P(Xy\leq b-\frac{1}{m})\to P(Xy <b)$
Thus $P(X_{n}Y_{n}<b)\geq P(Xy<b)$ for all $n$ large enough. And thus
Thus $$\lim\inf_{n}P(X_{n}Y_{n}\leq b)\geq \lim\inf_{n}P(X_{n}Y_{n}<b)\geq P(Xy<b)$$.
And as $b$ is a continuity point, you have  $$\lim\inf_{n}P(X_{n}Y_{n}\leq b)\geq P(Xy<b)=P(Xy\leq b)$$
Comment: Just to check: some typos in the last inequalities in the probabilities?
Comment: I have edited thanks.


Is it bad practice to pass null to a constructor args in PHP?

Question: I just want to know if  it's a bad practise to pass null to constructor args in order to manage the non-override?
For example :
class Car
{
    private $brand;
    private $color;

    public function __construct($brand, $color=null)
    {
        // ...
    }
}

Comment: Not a problem doing that
Comment: This would be called "optional argument" with default  value null. And it's not a problem at all.
Comment: It just means that the parameter is optional, that's no problem. Just make sure the rest of the code can handle `null` values.
Comment: PHP doesn't allow overloaded functions and allowing defaults to parameters is the way it compensates so setting a default to be `null` is fine.
Comment: what makes you think that it may be a bad practise?
Comment: Good that you're already preparing to handle colourless cars correctly... ;-P
Answer: It is not. null is completely valid in PHP in terms of safeness (stuff like empty string or "0" or something like that is more potent to fail).
I think the correct question here is "is it bad to give default value to parameter of a contructor", but to that question too, it is not.
My reasoning is that sometimes you want to imply default behaviour that would be used in most of the cases, and in some, say 5 % of cases, you need to alter behaviour of the object somehow, you'd want to be able to tell in the constructor that there is this kind of difference.
Sometimes, especially if the argument would make major change in the object, or if there is multiple values which are all used widely, it may more sense to use a method to set it. In you case, that method would be something like $car->color("foo");, and it would be implied to default to null.
Comment: "is it bad to give default value to parameter of a contructor" - you said "no" but it's entirely dependant on the scenario and code. Sometimes it is very bad, for me "most times" I prefer to force people to use a method explicitly. This avoids bugs and confusion for other devs "they don't pass some value did they mean to or want to use the default". But again, scenario dependant, sometimes default makes sense.


Swift - Custom textLabel in TableViewCell

Question: at the moment I have a UITableView where the user can add cells that have a textLabel inside of it.
That is how I set the label:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath)
    let currentWish = self.wishList[indexPath.row]
    cell.textLabel?.text = currentWish.wishName
    cell.backgroundColor = .clear

    return cell
}

My question is, how I can custom textLabel (font, constraints,...). I tried creating a custom UILabel inside my WishCell class but I can not access it in cellforRowAt with cell.theLabel.
I hope you understand my problem, I am very grateful for every help :)
SOLVED
I just forgot the as! WhishCell in cellForRowAt. Thanks for all your help :)
Comment: yes, I am doing that. But my problem is that I need to custom `textLabel` and I don't know how
Comment: Possible duplicate of [Custom UITableViewCell programmatically using Swift](https://stackoverflow.com/questions/25413239/custom-uitableviewcell-programmatically-using-swift)
Answer: You need to cast to you cell custom class name
let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath) as! CellName
cell.lbl.text = ////

 class CellName:UITableViewCell {
    let lbl = UILabel()
   override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
       lbl.backgroundColor = UIColor.red
       self.contentView.addSubview(lbl)
       // set constraints here
    }

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    }
 }

Comment: you can change the font but not constraints , you need to do this with `lbl` in your custom cell
Comment: any way I can create a `customLabel` inside my `Class WhishCell`  so I can call `cell.customLabel.text = currentWish.wishName` inside `cellForRowAt`?
Comment: aaah I was just an idiot... I missed the `as! WhishCell` ! Thanks man :D
Answer: Dont force un-wrap it.. try using guard or if let
guard let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath) as? WhishCell else{
  return UITableViewCell()
}
cell.lbl.text = "my text"
let currentWish = self.wishList[indexPath.row]
cell.textLabel?.text = currentWish.wishName
cell.backgroundColor = .clear

return cell


How to generate XML feed with nested tags using Xpath Parser?

Question: I have a XML file as below
<rss>
  <channel>
    <title>Channel Title</title>
    <description>Channel Description</description>
    <owner>
      <owner:name>Owner Name</owner:name>
      <owner:email>Owner Name</owner:email>
    </owner>
    <item>
      <title>Item 1 title</title>
      <author>Item 1 author</author>
    </item>
    <item>
      <title>Item 2 title</title>
      <author>Item 2 author</author>
    </item>
  </channel>
</rss>

In my Xpath parser settings, I gave /rss/channel/item as context and I am getting only the item title and item author into my node. How it is possible to add title,description and owner details into my node?. And I also want the same structured XML output using Views data export.
Answer: You need to move your context 1 level back.
context: /rss/channel
title: title
description: description
owner name: owner/owner:name
owner email: owner/owner:email
item title: item/title
item author: item/author


How to set a different theme for editing one's account

Question: I read somewhere that editing account information can be done a different theme or in the admin theme but can't for the life of me find it neither on google.
Answer: If you go to admin/settings/admin you can select your admin theme as well as using it for content editing.
Comment: Hi yes this sets a bunch of administration pages and content editing pages to the default admin theme but unfortunately not the user account editing pages.
Answer: Maybe you should install and check out the administration theme module - http://drupal.org/project/admin_theme
We have used it to show the admin theme on certain urls, like the user edit page.
Here is a description from the project page:
The Administration theme module allows you to use this theme on more pages like :
- batch processing pages
- devel node load and render pages
- coder code review pages
- pages you define yourself in the provided textarea
Hope that helps
Comment: Does the trick beautifully


Difference between $\mathrm{Poisson}(x_1)$, $\mathrm{Poisson}(x_2)$ and $\mathrm{BPoisson}(x_1, x_2)$

Question: I am trying to find out the difference between treating two random variables as poisson distributions, $\mathrm{Poisson}(x_1)$, $\mathrm{Poisson}(x_2)$, and using a bivariate poisson,  $\mathrm{BPoisson}(x_1, x_2)$.  I know the different forms these take but I am more interested in understanding the different assumptions behind their use.
Comment: Can you say more, or provide some context/ an e?
Answer: Any multivariate distribution describes joint distribution of some variables. Karlis and Ntzoufras (2003) define bivariate Poisson distribution pmf as
$$
f(x,y) = \exp\{-(\lambda_1+\lambda_2+\lambda_3)\}
\frac{\lambda_1^x}{x!}
\frac{\lambda_2^y}{y!}
\sum^{\min(x,y)}_{k=0}
{x \choose k}
{y \choose k}
k!\left(\frac{\lambda_3}{\lambda_1\lambda_2}\right)^k
$$
$E(X) = \lambda_1+\lambda_3$ and $E(Y) = \lambda_2+\lambda_3$, where $\mathrm{cov}(X,Y) = \lambda_3$, so you can treat $\lambda_3$ as a measure of dependence between the two marginal Poisson distributions. Example of such distribution is plotted below.

and two marginal distributions

by marginal distribution we mean how would joint distribution "look like" if we looked at it "from the $X$ side", or "from the $Y$ side". Marginal distributions of $X$ and $Y$ are Poisson distributions with parameters $\lambda_X = \lambda_1+\lambda_3$ and $\lambda_Y = \lambda_2+\lambda_3$.
What is different from looking only at two independent Poisson distributions is that we do not account anyhow for dependence between them (i.e. we assume $\lambda_3 = 0$). Using bivariate distribution lets you account for covariance between $X$ and $Y$.
Check also the following threads Is it possible to have a pair of Gaussian random variables for which the joint distribution is not Gaussian? and Deriving the bivariate Poisson distribution

Karlis, D., & Ntzoufras, I. (2003). Analysis of sports data by using bivariate Poisson models. Journal of the Royal Statistical Society: Series D (The Statistician), 52(3), 381-393.
Comment: @JMzance no big math is needed here: bivariate Poisson is constructed from three independent Poisson distributed variables $X',Y',Z$ so that $X=X'+Z$ and $Y=Y'+Z$ with parameters $\lambda_1,\lambda_2,\lambda_3$. So $Z$ is the "common thing" that is added to $X'$ and $Y'$...
Comment: Plotting these discrete distributions with continuous curves and surfaces, as if they had PDFs, may mislead people.
Comment: @whuber I totally agree but it is much easier like this and the resulting plot is much more readable.
Comment: Why not use a barplot-like visualization to emphasize the discreteness?
Comment: Great answer.  Could I possibly ask a follow up - is it clear from f(x, y) that lambda_3 is the covariance of X and Y?
Comment: @JMzance I do not understand your question... $\lambda_3$ is a parameter of this distribution.
Comment: Ok so the $\lambda_3$ isnt related to the amount of dependence between X and Y?  Also for what its worth I disagree with @whuber - it was much easier to see the plots when they were continuous - especially the 3D one
Comment: Basically I'm asking how you would show cov(X, Y) = $\lambda_3$ from the definition of f(x,y)


Residual Networks - Non-image use cases

Question: I've been doing some research into computer vision lately and constantly come across the ability of residual networks to improve performance. Intuitively I think I grasp them, however, I struggle to understand why they are not more prolific in other non-image based fields. I'm currently specialized in NLP and I rarely see them.
My question is, what non-image use-cases have you seen residual networks succeed? And why do you think they did?
Answer: Residual Networks are designed to avoid the vanishing gradient problem in deep neural networks. LSTM cells, which are commonly used in NLP, have a 'natural' way to avoid these, see e.g. (How does LSTM prevent the vanishing gradient problem?).
However there is research using residual connections combined with LSTMs for NLP, see Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation.

Residual Networks - Non-image use cases


Do the model results of multiple linear regressions remain the same if I take the log of dependent variable?

Question: I have results of 2 multiple linear regression models, one with log of dependent variable and other with the original variable. I notice the change in significance and goodness of fit. Why is that?
Wit y:
Call:
lm(formula = (Duration_CS.x.x) ~ gap.s_lcf + acc_pedal_pos_EF +
    expr_lt1 + speed.kph.ED_lcf, data = ds_c_trucks)

Residuals:
    Min      1Q  Median      3Q     Max
-5.3740 -1.1398 -0.1173  1.2491  7.8812

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)      12.586614   1.131682  11.122   <2e-16 ***
gap.s_lcf         0.141980   0.081959   1.732   0.0856 .
acc_pedal_pos_EF -1.625288   0.622018  -2.613   0.0100 *
expr_lt11        -1.550120   0.702220  -2.207   0.0290 *
speed.kph.ED_lcf -0.017690   0.009388  -1.884   0.0617 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.125 on 131 degrees of freedom
  (3 observations deleted due to missingness)
Multiple R-squared:  0.1478,    Adjusted R-squared:  0.1217
F-statistic: 5.678 on 4 and 131 DF,  p-value: 0.0003023

With log(y)
Call:
lm(formula = log(Duration_CS.x.x) ~ gap.s_lcf + acc_pedal_pos_EF +
    expr_lt1 + speed.kph.ED_lcf, data = ds_c_trucks)

Residuals:
     Min       1Q   Median       3Q      Max
-0.84821 -0.09087  0.00549  0.13228  0.60341

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)
(Intercept)       2.5797819  0.1161440  22.212   <2e-16 ***
gap.s_lcf         0.0146764  0.0084115   1.745   0.0834 .
acc_pedal_pos_EF -0.2046169  0.0638375  -3.205   0.0017 **
expr_lt11        -0.1564983  0.0720685  -2.172   0.0317 *
speed.kph.ED_lcf -0.0020781  0.0009635  -2.157   0.0328 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.218 on 131 degrees of freedom
  (3 observations deleted due to missingness)
Multiple R-squared:  0.1761,    Adjusted R-squared:  0.151
F-statistic: 7.002 on 4 and 131 DF,  p-value: 3.86e-05

Comment: You are transforming the variable. After that, do you expect no change in results?
Comment: The response variable is measured on a completely different scale and the fit on the original scale is entirely different. Why would anything be the same?
Answer: It's very easy to imagine why this would be different, looking at one of the most simple parameters available in statistics: the mean.
Take a random set of numbers, e.g.:
2  5  9 14 25 17 26 68  3 67 35 65. The mean of this set of numbers is 28. Now log transform this set:
0.6931472 1.6094379 2.1972246 2.6390573 3.2188758 2.8332133 3.2580965 4.2195077 1.0986123 4.2046926 3.5553481 4.1743873
The mean of this is 2.808467, which is 16.58447 when you exponentiate it!
Knowing this, it seems to me it's not hard to see that any other kind of statistics would suffer a similar fate. The question you should consider is: Why did you choose to try a model with the log-transformed dependent variable? There is always a reason to consider transforming your data.
Comment: Thanks for your answer. I realize now that there is no change in the interpretation of results (sign of coefficients) after the transformation.


Removal of child from aggregate root and database persistence

Question: (This is possibly a duplicate, but I didn't find any satisfactory answers in the other questions I've read.)
I need some guidance on how removal of child entities of an aggregate root can be propagated to the database layer. I've though/read about a couple of different ways to handle it:

Keep removed children i separate collection. Let the repository remove all items in the collection on save.
Call some kind of data mapping layer or repository directly.
Execute some type of delegate/event that a repository/UoW may provide/listen to.
Do nothing. Let the Unit of work or repository compare the whole aggregate root with a "non-dirty" copy.

It's worth noting that my real aggregate root implementation contains multiple collections of children that possibly could be removed.
For the sake of clarity, here is a simple example:
public class AggregateRoot
{
    private List<ChildEntity> _children;
    public IEnumerable<ChildEntity> Children
    {
        get
        {
            return _children;
        }
    }
    public void RemoveChild(ChildEntity child)
    {
        _children.Remove(child);

        // What to do here?

        // Option 1: Keep removed children i separate collection. Let
        // the repository remove them on save.
        RemovedChildren.Add(child);

        // Option 2: Call some kind of data mapping layer or repository directly
        _childRepository.Delete(child);

        // Option 3: Execute some type of delegate/event that a repository
        // may provide/listen to.
        _onChildRemoved(this, child);

        // Option 4: Do nothing. Let the Unit of work or repository compare
        // the whole aggregate root with a "non-dirty" copy.

    }
}

Options 1 and 2 are not very elegant I think.
Option 4 is nice as I don't have to implent any logic inside the aggregate root, but as my real implementation is quite large, I would have to compare a lot of properties and collections.
I tend to favor option 3. The problem with it is that it potentially may require a lot of delegates/events. Maybe I could implement a generic delegate/event though.
This must be a fairly common problem, but I've seen surprisingly few examples of this. How would you handle this problem?
Comment: If you have a unit of work, you may have a repository that is scoped within the UoW lifespan. Record the removal in the repository (where it should be) and on commit of the UoW, the repository can review its removed items and remove them as needed from the underlying source. If this is something like EF, then it is handled for you.
Comment: When you remove the item you can raise a domain event so that ambient change tracking can catch it for later reference, or you can promote the idea in your domain model itself (that an item can be removed and so not usable).
Comment: @AdamHouldsworth How would you notify the repository of the removal then? (I'm not using EF by the way)
Answer: Option 1:
I guess that in your business there isn't such concept as RemovedChildren, so aggregate shouldn't contain such collection in my opinion. Please mind that sometimes there might be such concept like ChildrenHistory, HistoricalChildren
Option 2:
I have read plenty of times that aggregate shouldn't use repository, and aggregate shouldn't have any services injected. However you can use double dispatch pattern and provide method signature like:
public void RemoveChild(ChildEntity child, IChildRepository repository)
{
    // check conditions, business logic etc
    // remove using repository

However it forces caller to supply repository which might be hard to achieve in some cases
Option 3:
I didn't use events for this purpose before. But it seems pretty ok for me. You can use event bus to notify interested repositories about entity deletion.
Option 4:
In my opinion this is best way, UoW should handle item deletion. You can mark your entity as removed either by setting some kind of flag on them or by setting their ParentId to 0 (that is what EF does under the hood). On commit you can inspect all objects loaded into memory and remove those that are marked for deletion. This forces us to write least infrastructure code in domain layer, however we need to write additional code in our UoW for deleting orphaned children.
Comment: Thanks for an answer that broadened my thoughts about this issue.

I actually went with option 3 and let the aggregate root's repository delete any children as there was no repositories implemented for the child entities.

I will probably go with option 4 the next time, but it seems to require a bit more general implementation of entity deletion in the UoW.

One option could be a combination of option 3 and 4 though - raise an event that the UoW listens to...


Stem direction on voices in Guitar Pro 7

Question: How do I keep the stem direction same on each different Voice on Guitar Pro 7, GP7?
I have used GP7 moderately.  I feel there is a setting to lock stem direction on each Voice.  When I input notes on different bar keeping the same voice GP7 automatically changes the direction of the stems and this is taking time to correct.
Comment: Are you entering the voices in numerical order for each measure? I've notice in other software that if I enter voice 2 before voice 1, the stems will be in the wrong direction (though they correct themselves when entering voice 1).
Comment: In addition to what Aaron suggests, it's always good practice to *first* enter everything related to basic notation, all voices, all parts and articulations, then add any indication about technique, lyrics, etc; *finally* fix all "aesthetic", like stem directions. Maybe this is not about this specific issue, but it's worth mentioning anyway.
Answer: Answer: There is no way to force stems to automatically only go one way in GP7.

Workaround: You can manually change stem direction. You will avoid giving yourself a headache if you either do this all at the end of in batches, rather than as you're writing, because it can be a very tedious process and really only serves an aesthetic purpose (as pointed out by musicamante).
Take this (admittedly contrived) example, where one voice overlaps the other:

In Guitar Pro 7, there are two options to manipulate stems: "Automatic Stems" and "Invert Stems". In cases where you want to invert stems for a particular voice, you can select a specific note (or highlight a section), and select "Invert Stems" in the left-hand Edition Palette here:

Alternatively, this option can be found in Note -> Design -> Invert Stems
The output of this looks like:


Change the "add entity" page title on a custom content entity type using alterRoutes()?

Question: I created a custom content entity type dog using drush generate entity:content.
When I go to www.example.com/dog/add, the page title (the one in the <title> tag, not the
 tag) is "Add dog".  I want to change this to "Send a dog to outer space (and bring him back safely)".
It seems there is no place to set the title in the entity annotations, so I attempted to add an event subscriber:
dog/src/Routing/DogRouteSubscriber.php
class DogRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.dog.add_form')) {
      $route->setDefault('_title', 'Send a dog to outer space (and bring him back safely)');
    }
  }
}

dog.services.yml
services:
  dog.route_subscriber:
    class: Drupal\dog\Routing\DogRouteSubscriber
    tags:
      - { name: event_subscriber }

I am using $route->setDefault('_title', 'Send a dog to outer space (and bring him back safely)' based on code in this blog post, but even after rebuilding the cache, the page title isn't changed.
So: Where do I alter (or set) the entity add form's page title?
Similar but different questions:

How can I change the page title? (general question about page titles)
How can I change the title of the node/add page of a specific content type? (question about node content types, not custom entity types in general)
Answer: If your entity uses DefaultHtmlRouteProvider as route_provider handler then it sets a title callback which has a higher priority than the static title.
So you would need to remove this default in alterRoutes().
However, if this is your own entity, a more straightforward approach would be to edit the entity annotations and replace the route_provider handler with your own class  , which extends DefaultHtmlRouteProvider and overrides the method getAddPageRoute():
  protected function getAddPageRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('add-page') && $entity_type->getKey('bundle')) {
      $route = new Route($entity_type->getLinkTemplate('add-page'));
      $route->setDefault('_controller', EntityController::class . '::addPage');
      $route->setDefault('_title_callback', EntityController::class . '::addTitle');
      $route->setDefault('entity_type_id', $entity_type->id());
      $route->setRequirement('_entity_create_any_access', $entity_type->id());

      return $route;
    }
  }

Or keep the dynamic controller method and return the static text from there.
Answer: Wow, this turned out to be way more complex than I thought.
In addition to the DogRouteSubscriber shown in the original question, I had to override getAddFormRoute (because the basic entity type generated with drush generate does not have an add-page route) with my own DogHtmlRouteProvider class (as described in 4uk4's answer):
class DogHtmlRouteProvider extends DefaultHtmlRouteProvider {

  /**
   * Gets the add-form route.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type.
   *
   * @return \Symfony\Component\Routing\Route|null
   *   The generated route, if available.
   */
  protected function getAddFormRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('add-form')) {
      $entity_type_id = $entity_type->id();
      $route = new Route($entity_type->getLinkTemplate('add-form'));
      // Use the add form handler, if available, otherwise default.
      $operation = 'default';
      if ($entity_type->getFormClass('add')) {
        $operation = 'add';
      }
      $route->setDefaults([
        '_entity_form' => "{$entity_type_id}.{$operation}",
        'entity_type_id' => $entity_type_id,
      ]);

      $route
        ->setRequirement('_entity_create_access', $entity_type_id);

      return $route;
    }
  }

Here, I removed the line $route->setDefault('_title_callback', EntityController::class . '::addTitle');  I did not override this with another method because _title_callback apparently only accepts a method on a descendant of EntityController, and my module doesn't have such a controller.
Comment: Adding this patch reduces a lot of boilerplate code https://www.drupal.org/project/drupal/issues/2976861


findassoc function in tm package of R giving error

Question: I have a term document matrix build from youtube comments
about 977 documents
created a term document matrix using:
dtm <- DocumentTermMatrix(doc_corpus)

and then on applying the function
findAssocs(dtm,"hello", 0.6)

getting the following (translated from french)
Error in which (x [term],> corlimit): index out of bounds

all the other functions are working like findFreqTerms and hclus etc
Comment: check if the word esixt in the terms...something like `'hello' %in% Terms(dtm)`, what do you get ?
Comment: the word doesn't exist and for existing words it's working. thanks a lot!
Answer: You get an error beacause the word does not exist in the terms sets. You can check this using :
'hello' %in% Terms(dtm)

which should return FALSE.
Comment: You could contact the author(s)
Comment: thank you. this works. i wish there was a better exception handling for this one.
Comment: @codious or put this  in simple `trycatch`.


Funcionamento da funcão fork()

Question: Alguém pode explicar como funciona a funcão fork() relativamente ao estado das variáveis a cada chamada ao processo filho neste pedaço de código:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    int pid,x=2;
    if (0 == (pid =fork())) {
        fork();
        pid=fork();
        if (pid==0) {
            x--;
        }
    }
    else{
        printf("aki\n");
        execl("bin/date", "date",0);
        x=x+2;
    }

    printf("x=%d\n",x);
    exit(0);
}

Estava a tentar perceber mas eu nao sei qual o valor que é passado para a variável do processo filho x=?
Answer: A função fork abre um processo filho com uma cópia dos valores das variáveis do processo pai. Nesse exemplo o else será executado para o processo filho e x irá para 4. Já no pai irá para 1.
EDIT:
Acontece que o fork quando executado abre um segundo processo e ambos os processos executam a próxima linha que está logo a seguir do fork original com isso temos o seguinte:
Acontece o primeiro fork no if onde é feita uma atribuição para a variável pid. O resultado disso é 0 que na condição de teste está ok e entra no bloco. A primeira linha desse bloco é um fork que não atribui nada a pid, com isso temos um processo filho que não entra no else e começa a executar na próxima linha que é um outro fork atribuindo a pid. Mas logo em seguida o processo pai desse segundo filho também executa o fork atribuindo ao pid. Como um desses é o pai vai atribuir 0 a pid equanto o outro não diminui a variável x.
Com isso temos:
pid=45750x=2 filho de um fork dentro do if
pid=45751x=2 filho de um fork do outro filho dentro do if
pid=0x=1 pai original
pid=0x=1 filho do original e pai do segundo fork dentro do if
No processo filho do original entra no else que faz o x=x+2; esse imprime pid=45748x=4.
Comment: o que nao percebo é ,o que é carregado para as variáveis nas outros 2 fork()
Comment: @user48571 Você já [executou o código](https://ideone.com/pNx6xp) pra ver os valores das variáveis?
Comment: no minha maquina retorna aki
pid=45748x=4
pid=45750x=2
pid=45751x=2
pid=0x=1
pid=0x=1
Comment: @user48571 Agora com a saída adicionei mais explicações
Comment: quando eu faço uma chamada ao fork, o que é executado no processo filho também inclui um novo fork() no processo filho?
Comment: Sim porque você só colocou o if testando o resultado no primeiro. Nos outros fez a chamada sozinha e eles também funcionam.

Funcionamento da funcão fork()


How to import certification correctly in HttpsURLConnection?


Finding the roots of the polynomial $t^{1000} + t^{100} +1$ in the field with $13$ elements

Question: My attempt so far has been to figure out the $\gcd(t^{1000} +t^{100}+1, t^{13}-t) \pmod{13}$ as shown in class but I am not sure why this method works, so explanation on this would be great.
Next, I reduced to finding the $\gcd(2t^4 +1, t^{13} -t)$ by Fermat's little theorem. Finally, I tried to factor $2t^4+1$ but found it is an irreducible polynomial as it is equal to $2(t^4-6)$. So what can I say about the gcd then?
Comment: I don't see how this is better than using fermat's little theorem
Comment: Might simplify matters to substitute $z=t^{100}$.   Then you are first looking to solve $z^{10}+z+1=0$.
Comment: Note that $t\equiv 0$ is not a solution, Now reduction mod $12$ gers us to $2t^4+1\equiv 0$, Thus if we want to do no further thinking trying $t=1$ ro $6$ will do the job.
Comment: sorry why did you check 1 and 6?
Answer:
By FLT, $t^{13}\equiv t\pmod{13}$.  Hence finding the gcd is equivalent to using FLT "as much as possible" to reduce the problem.
Once you have $2t^4+1$, just plug in all 13 values to find the roots.
Comment: The $13$ values can be reduced to $7$ due to parity.
Comment: oh ok! Thank you very much P.S How do you know when you have reduced the complexity of a number theory problem enough to just brute force it?


Approximation for the integral $\int_0^{\infty } \frac{x}{(a x+1)^2} \, dx$

Question: I want to find the mean of random variable $x$. In my analysis, I came up with an integral  $$I=\int_0^{\infty } \frac{x}{(a x+1)^2} \, dx$$
which does not have a closed-form solution, probably it does not converge $\{0,\infty \}$.
However, I am wondering whether or not there is an approximation when $a\in[0,\infty)$. Ideas are welcome.
Answer: $$I(t)=\int_0^{t} \frac{x}{(a x+1)^2}dx=\frac{1}{a}\int_0^{t } \frac{ax}{(a x+1)^2}\, dx =\frac{1}{a}\left(\int_0^{t } \frac{1}{(a x+1)}dx-\int_0^{t } \frac{1}{(a x+1)^2}dx\right)$$
the first integral integrates to $\frac{1}{a}\ln(ax+1)$ and the second one to $\frac{1}{a(ax+1)} $ you can see in particular the it does not converge in $+\infty$


Synth controls greyed out in Ableton Live 11

Question: Utter noob here. A couple of weeks ago I created some basic tones using operator/synth lead, exported them as WAVs and that was that. I've now changed laptop and have re-opened the Live project to make some tweaks on the new laptop. Now, the synth controls I'd normally use to modify frequency etc (bottom panel) are 'greyed out' and I can't work out why. Both laptops have used Live 11 Trial. Help!
Answer: Facepalm: I'd somehow managed to 'freeze' the track and solved this by right-clicking on the track and clicking 'unfreeze'.


Conditional Expectation and Conditional Varience

Question: Suppose that X|Y = p has a Binomial(n,p) distribution for 0 < p <1 and Y has a U(0,1) distribution. Find E(X) and Var(X).
Comment: What mean $X|Y=p$ ?
Comment: Thanks for the welcome, but i did not understand the question at all, because there is a binomial and uniform distribution.
Answer: $\mathsf EX=\mathsf E(\mathsf E(X\mid Y))=\mathsf EnY=n\mathsf EY=\frac12n$.
You can find $\mathsf{Var}X$ on base of $\mathsf{Var}(X)=\mathsf EX^2-(\mathsf EX)^2$ and:
$\mathsf EX^2=\mathsf E(\mathsf E(X^2\mid Y))=\dots$
I leave the rest to you.
Comment: Thanks, but how do I work around between the two distributions?
Comment: Have you been able to find $\mathsf{Var}X$? If so then your question has been answered. If not then tell me where you get stuck. I don't really understand what you are asking in your comment. You could make it more clear, but if it is not about finding expectation and variance then you should ask a new question on this site.


Como salvar um arquivo XLSX (Excel) ao invés de CSV?

Question: Hoje eu tenho o código abaixo, que salva um arquivo em formato CSV.
O que preciso alterar para salvar em formato XLSX (Excel)?

public static void buildCSV(string filename = "resultado.xlsx")
        {
            Console.WriteLine("Escrevendo no arquivo.");

            StringBuilder csvBuilder = new StringBuilder();

            //cria o header
            csvBuilder.AppendLine("Nome;Cpf;Cep;ID Cliente");

            foreach (var item in BAG)
            {
                csvBuilder.AppendLine(item);
            }

            File.WriteAllText(filename, csvBuilder.ToString(), Encoding.UTF8);
        }
    }
}

Comment: Possível duplicata de [Convertendo arquivo word para pdf](https://pt.stackoverflow.com/questions/316400/convertendo-arquivo-word-para-pdf)
Comment: @MatheusMiranda, não creio que possa ser considerada como duplicata já que o Word e o Excel têm estruturas bem diferentes, o Excel têm worksheets e células, por exemplo, e uma das dúvidas dessa pergunta era sobre como salvar no formato XLSX, enquanto que a dúvida da sua pergunta era sobre como salvar o documento do Word em PDF.
Comment: Tenho a mesma duvida que vc, quando tento executar recebo essa mensagem de erro -> 'O acesso ao caminho 'C:\Program Files (x86)\IIS Express\resultado.xlsx' foi negado.'
Como faço pra salvar o arquivo em outra pasta que nao seja essa ?
Answer: Você pode fazer isso usando a biblioteca de interoperabilidade do Excel (Microsoft.Office.Interop.Excel.dll), mas para isso o Excel terá que estar instalado no computador que for executar a sua aplicação.
Para usar esse código é necessário primeiro fazer referência ao namespace Microsoft.Office.Interop.Excel. Uma forma fácil para fazer isso é usando o NuGet. No Visual Studio acesse o menu Tools > NuGet Package Manager > Manage NuGet Packages for Solution > Browse, pesquise por Microsoft.Office.Interop.Excel e instale o pacote. Ou faça assim.
O código para criar o arquivo XLSX é esse:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

   public static void CriarArquivoXlsx(string filename = "resultado.xlsx")
   {
      _CriarArquivoXlsx(filename);

      // Libera os objetos COM do Excel.
      GC.Collect();
      GC.WaitForPendingFinalizers();
   }

   private static void _CriarArquivoXlsx(string filename)
   {
      Excel.Application xlApp = new Excel.Application();
      if (xlApp == null)
      {
         MessageBox.Show("Excel não está instalado!");
         return;
      }

      Excel.Workbook xlWorkbook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
      Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];

      // Cabeçalho.
      // A indicação da coluna pode ser por números (1, 2, 3, etc.)
      // ou por texto ("A", "B", "C", etc.).
      int row = 1;
      xlWorksheet.Cells[row, 1] = "Nome";
      xlWorksheet.Cells[row, 2] = "Cpf";
      xlWorksheet.Cells[row, 3] = "Cep";
      xlWorksheet.Cells[row, 4] = "ID Cliente";

      foreach (string item in BAG)
      {
         row++;
         int col = 0;
         foreach (string campo in item.Split(';'))
         {
            col++;
            xlWorksheet.Cells[row, col] = campo;
         }
      }

      xlWorkbook.SaveAs(filename, XlFileFormat.xlOpenXMLWorkbook);

      xlWorkbook.Close();
      xlApp.Quit();
   }

Eu criei a função privada _CriarArquivoXlsx(), que faz o trabalho de verdade, e a função pública CriarArquivoXlsx(), que chama a função privada e depois dispara o GC (GarbageCollector) para liberar as referências dos objetos COM criados na função privada.
Isso é importante porque, como a biblioteca de interoperabilidade com o Office cria objetos COM, que são gerenciados pelo .NET, e portanto pelo Coletor de Lixo (Garbage Collector) do .NET, o processo do Excel pode ficar "pendurado" por tempo indeterminado enquando a aplicação estiver sendo executada. Por isso é necessário forçar uma coleçao imediata do lixo, liberando assim as referências dos objetos COM do Excel.
O fato de ter colocado a coleção de lixo fora da função que cria os objetos COM é meramente um artifício para que isso funcione corretamente também no modo debug da aplicação, veja aqui a explicação do porquê se fazer dessa forma.
Referências usadas para a criação do código:

I want to create xlsx (Excel) file from c# - Stack Overflow
Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y].Style? - Stack Overflow
Clean up Excel Interop Objects with IDisposable - Stack Overflow (mesmo link citado acima)
How to: Access Office Interop Objects by Using Visual C# Features (C# Programming Guide) | Microsoft Docs

Também há uma biblioteca open source que permite criar arquivos XLSX sem precisar do Excel instalado, chamada EPPlus. Mais detalhes aqui:

Create Excel (.XLS and .XLSX) file from C# - Stack Overflow


Dúvidas sobre relacionamento e mapeamento com Fluent API para o EF 6

Question: Sempre que eu tiver uma classe com propriedades que são do tipo de outras classes, o que a nível de banco de dados representa uma chave estrangeira, eu sempre vou precisar das propriedades de navegação?
E vejam este exemplo:
Revenda -> ClienteRevenda -> Empresa -> ClienteEmpresa
public class Revenda
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public string Nome {get; set;}
    // Navigation Property
    public ICollection<ClienteRevenda> Clientes {get; set;}
}

public class ClienteRevenda
{
    [Key, Column(0)]
    public int RevendaId {get; set;}
    [ForeignKey("RevendaId")]
    public Empresa Empresa {get; set;}

    [Key, Column(1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public string Nome {get; set;}
    // Navigation Property
    public ICollection<Empresa> Empresas {get; set;}
}

public class Empresa
{
    [Key, Column(0)]
    public int RevendaId {get; set;}
    [ForeignKey("RevendaId")]
    public Revenda Revenda {get; set;}

    [Key, Column(1)]
    public int ClienteRevendaId {get; set;}
    [ForeignKey("RevendaId, ClienteRevendaId")]
    public ClienteRevenda ClienteRevenda {get; set;}

    [Key, Column(2)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public string Nome {get; set;}
    // Navigation Property
    public ICollection<ClienteEmpresa> ClientesEmpresa {get; set;}
}

public class ClienteEmpresa
{
    [Key, Column(0)]
    public int RevendaId {get; set;}
    [ForeignKey("RevendaId")]
    public Revenda Revenda {get; set;}

    [Key, Column(1)]
    public int ClienteRevendaId {get; set;}
    [ForeignKey("RevendaId, ClienteRevendaId")]
    public ClienteRevenda ClienteRevenda {get; set;}

    [Key, Column(2)]
    public int EmpresaId {get; set;}
    [ForeignKey("RevendaId, ClienteRevendaId, EmpresaId")]
    public Empresa Empresa {get; set;}

    [Key, Column(3)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public string Nome {get; set;}
}

Notem que estou fazendo chaves compostas porque preciso de registros únicos.
Nesse caso, eu precisaria adicionar na classe Revenda as Navigation Properties para Empresa e ClienteEmpresa também?
Como ficaria esse mapeamento com a Fluent API?
public class RevendaMap : EntityTypeConfiguration<Revenda>
{
    public RevendaMap()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

public class ClienteRevendaMap : EntityTypeConfiguration<ClienteRevenda>
{
    public ClienteRevendaMap()
    {
        HasKey(p => new { p.RevendaId, p.Id });
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(p => p.Revenda).WithMany(r => r.Clientes).HasForeignKey(p => p.RevendaId);
    }
}

public class EmpresaMap : EntityTypeConfiguration<Empresa>
{
    public EmpresaMap()
    {
        HasKey(p => new { p.RevendaId, p.ClienteRevendaId, p.Id });
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(p => p.Revenda).WithMany( ??? ).HasForeignKey(p => p.RevendaId);
        HasRequired(p => p.ClienteRevenda).WithMany(cr => cr.Empresas).HasForeignKey(p => p.ClienteRevendaId);
    }
}

public class ClienteEmpresaMap : EntityTypeConfiguration<ClienteEmpresa>
{
    public ClienteEmpresaMap()
    {
        HasKey(p => new { p.RevendaId, p.ClienteRevendaId, p.EmpresaId, p.Id });
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(p => p.Revenda).WithMany( ??? ).HasForeignKey(p => p.RevendaId);
        HasRequired(p => p.ClienteRevenda).WithMany( ??? ).HasForeignKey(p => p.ClienteRevendaId);
        HasRequired(p => p.Empresa).WithMany(e => e.ClientesEmpresa).HasForeignKey(p => p.EmpresaId);
    }
}

Notem nas duas últimas classes de mapeamento que elas possuem o método WithMany( ??? ). Minha pergunta se a classe Revenda deveria ter uma navigation property para cada uma das outras classes e também perguntando por conta dessas outras classes e esses métodos. O que deveria ser informado neles?
Ou é a estrutura de classes que está errada, ou o mapeamento que está errado...?
Comment: Poderia editar a pergunta e explicar o porque daquele relacionamento? Pq se fosse pra fazer a chave composta, poderia fazer por fluent assim: `modelBuilder.Entity().HasKey(r => new { r.RevendaId, r.Id });`
Comment: A idéia seria ter chaves compostas?
Comment: Sim, pela estrutura/segurança dos dados, certo?
Comment: Eu até perguntei se essa era uma forma certa de escrever o modelo. Não sei, talvez não seria necessário fazer chaves compostas, mas deixar apenas o **Id** de cada classe como chave primária, o restante fazer apenas chave estrangeira obrigatória.. mas é sobre as regras de mapeamento para o EF que mais tenho dúvida.
Comment: A questão maior não é as chaves, eu posso até remover as chaves. As chaves eu coloquei para complicar ainda mais a questão da necessidade das propriedades de navegação. Porque, já que há inserção de propriedade da primeira classe na última, aumentou a necessidade de propriedades de navegação. Então, a questão é se eu preciso sair inserindo propriedade de navegação de todas as camadas? Como exemplo, se eu preciso inserir `ICollection` na classe `Revenda` ?
Comment: Não não... Por exemplo... quem vai ter propriedade de navegação de `ClienteEmpresa` vai ser somente empresa
Comment: Isso que eu queria saber, que inclusive foi algo que o @CiganoMorrisonMendez achou estranho na minha pergunta anterior. Porque já que minha classe `Revenda` não tem propriedade de navegação para a classe `ClienteEmpresa`, logo, na minha classe `ClienteRevendaMap` essa atribuição `HasRequired(p => p.Revenda).WithMany().HasForeignKey(p => p.RevendaId);` estaria correta, certo???
Comment: Não entendi o relaciomento entre as entidades. Uma `Revenda` tem n `ClienteEmpresa`? Uma empresa tem n `ClienteEmpresa`? Uma `Empresa` tem n `ClienteEmpresa`?
Comment: Então @CiganoMorrisonMendez, meu problema era aprender sobre como montar os relacionamentos para o EF, principalmente sobre propriedades de navegação para o correto entendimento do EF. E o exemplo que montei criou toda esse nó por conta das chaves primárias compostas, de onde eu quis saber então se por conta da existência dessas chaves eu precisaria sair incluindo propriedade de navegação desde a primeira classe, a de `Revenda`.
Comment: @Tiago Tá bem errada sua abordagem. Eu estou tentando escrever uma resposta, mas não entendi o relacionamento entre as entidades.
Comment: Deixa eu tentar trazer para um exemplo real. Eu desenvolvo softwares, minhas revendas possuem Clientes ( `ClienteRevenda` , distribuidoras, por exemplo ), e esses clientes atendem outras empresas ( `Empresa` , varejo). Empresas essas que possuem seus clientes ( `ClienteEmpresa` , cliente final). Botando isso num sistema que engloba tudo, por exemplo, eu já começaria por ter várias revendas em minha base de dados, logo fiz a separação de Clientes das Revendas, Empresas e Clientes das Empresas forçando a integridade dos dados com campos de chaves compostas.
Answer: A co-relação entre as properties deveria ser algo da seguinte maneira
//Revenda
public ICollection<ClienteRevenda> { get; set; }  //Navigation para os ClientesRevendas que possui

//ClienteRevenda
public Revenda Revenda { get; set; } //Navigation para a superior(que pertence)
public ICollection<Empresa> { get; set; }

//Empresa
public ClienteRevenda ClienteRevenda { get; set; } //Navigation para a superior
public ICollection<ClienteEmpresa> { get; set; }

//ClienteEmpresa
public Empresa Empresa{ get; set; } //Navigation para a superior

Comment: Ok, isso já me esclareceu 50% de minhas dúvidas. ;)
Comment: Como boas práticas para o EF, chaves compostas dessa forma como montei e o que você mostrou ser o ideal já não é bom. Correto? Você não incluiu propriedade **navigation para a superior** como eu fiz por contas das chaves compostas.
Answer: Chaves Compostas
A ideia em nada melhora a segurança ou estrutura, dificultando inclusive a implementação dos seus Controllers e Views. Basta uma property como chave primária que as demais Id's são acessíveis através das classes virtuais declaradas. Este uso pode até ser considerado uma má prática.
Modelagem das Entidades
public class Revenda
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    [Required]
    public string Nome {get; set;}

    public virtual ICollection<ClienteRevenda> Clientes {get; set;}
}

public class ClienteRevenda
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public int RevendaId {get; set;}

    [Required]
    public string Nome {get; set;}

    public virtual Revenda Revenda {get; set;}

    public virtual ICollection<Empresa> Empresas {get; set;}
}

public class Empresa
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public int ClienteRevendaId {get; set;}

    [Required]
    public string Nome {get; set;}

    public virtual ClienteRevenda ClienteRevenda {get; set;}

    public virtual ICollection<ClienteEmpresa> ClientesEmpresa {get; set;}
}

public class ClienteEmpresa
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public int EmpresaId {get; set;}

    [Required]
    public string Nome {get; set;}

    public virtual Empresa Empresa {get; set;}
}

Mapeamentos
public class RevendaMap : EntityTypeConfiguration<Revenda>
{
    public RevendaMap()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

public class ClienteRevendaMap : EntityTypeConfiguration<ClienteRevenda>
{
    public ClienteRevendaMap()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(p => p.Revenda).WithMany(r => r.Clientes).HasForeignKey(p => p.RevendaId);
    }
}

public class EmpresaMap : EntityTypeConfiguration<Empresa>
{
    public EmpresaMap()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(p => p.ClienteRevenda).WithMany(cr => cr.Empresas).HasForeignKey(p => p.ClienteRevendaId);
    }
}

public class ClienteEmpresaMap : EntityTypeConfiguration<ClienteEmpresa>
{
    public ClienteEmpresaMap()
    {
        HasKey(p => new p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(p => p.Empresa).WithMany(e => e.ClientesEmpresa).HasForeignKey(p => p.EmpresaId);
    }
}

Comment: No caso ainda os Key, Colunm podem ser removidos
Comment: Já editei. Valeu!
Answer: @Tiago não tem a ver com a resposta em si da perguntar, mas sim em outro pronto que você deve se atentar a isso, é a maneira como irá trabalhar o load dessas dependencias...
Por exemplo, caso você precise acessar o primeiro ClienteEmpresa da sua primeira Empresa da sua primeira ClienteRevenda da sua Revenda dentro um laço foreach, seria algo mais ou menos assim (da maneira digamos mais comum de fazer).
foreach(var item in ctx.Revendas) {
    var nome = item.Revenda
    .ClienteRevendas().FirstOrDefault()
    .Empresas().FirstOrDefault()
    .ClienteEmpresas().FirstOrDefault().Nome;
    //faz alguma coisa por exemplo
}

Dependendo da maneira como for carregado sua lista, pode se tornar muito, mas muito, mas muito custoso para o sistema. Porque para cada .ClienteRevendas() e .Empresas() ele vai ter que ficar indo e voltando do servidor toda hora.
Existem várias maneiras de como carregar, você pode dar um Include ou fazer o Linq pra trazer uma consulta mais enxuta tbm...
Nesse link tem algumas boas práticas ao se trabalhar com o Entity, dê uma olhada em especial nos Items 5,7,8 que envolvem bem aquilo que eu gostaria de passar aqui.


Getting Culture specific errors from Roslyn Compilation

Question: I am trying to compile some code which has incorrect syntax using the Roslyn Emit Api. The thread compiling the code has Culture set to "fr-Fr"
but the diagnostic messages I obtain from the Roslyn api are in English.
e.g.

error BC30037: Character is not valid.

I am wondering if there is a way to get the error messages in the thread specific culture.
Same happens with codeDom too.
Comment: Could you provide a tiny example of the code you're using? Given the error number, it sounds like you're using the VB compiler rather than C#. (More importantly, if we have an example we can experiment with, we can be more confident if we think we have a solution.)
Answer: This is probably not a viable answer, but I'll post it anyway in case it's of interest.
The Roslyn compiler is open source, so it can be modified, and in this way the error messages can be changed from English to French, or whatever. Just be aware that Roslyn is a huge program, and rebuilding it is not all that easy, at least in my experience.
I've written a few blog articles about my experiences with modifying Roslyn. My latest modification included adding a new error message - that's how I happened to find this question.
https://renniestechblog.com/information/33-modifying-roslyn-step-1-initial-test
https://renniestechblog.com/information/39-modifying-roslyn-step-6-fake-attribute-yacksserialization
It may even be possible to make Roslyn multilingual, by adding an additional CSharpResources.fr-FR.resx file to the project, and letting ResourceManager automatically choose the correct .resx file. This definitely works with .Net Framework WinForms projects, but I don't know if this functionality has been preserved in the new .Net Standard format.


UrlHelper in Controller Action does not build correct URL

Question: I have an issue, when I'm trying to build the url for action in controller, the value of vm after assigning is "/". If I try to create url with other action name then everything works fine, like Url.Action("Edit", "Contact").
public class ContactController : Controller
{
    public ActionResult List()
    {
        string vm = Url.Action("Create", "Contact");     // equals "/"
        string editUrl = Url.Action("Edit", "Contact"); // all is fine

        return View("List", vm);
    }

    public ActionResult Create()
    {
        return HttpNotFound();
    }

    public ActionResult Edit()
    {
        return HttpNotFound();
    }
}

What's wrong with that code?
Comment: In my asp-net-mvc 5 application your code works as expected.
Comment: Please post your routing code (all of it). This is likely a case of a route matching that shouldn't be matching.
Comment: `routes.MapRoute(
 "Default",
 "{controller}/{action}/{id}",
 new { controller = "Contact", action = "Create", id = String.Empty },
 null
);`
Comment: Strange, If i set the another action as default, code in question works fine :/
Answer: It is because your route specifies them as defaults.
Your route is:
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Contact", action = "Create", id = String.Empty }, null);

Essentially, it is because you specify the default values controller = "Contact", action = "Create". When you specify these as default you are saying if the value is not provided in the URL then use these.
For examples all these URLs are the same: /, /Contact & /Contact/Create. By default MVC generates you the shortest URL.
You could either change the default values or remove them like this:
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { id = String.Empty }, null);

Comment: Thank you for the explanation!


Adding class to the webform submit button

Question: By default, the web form is displayed with <?php print drupal_render($form['submitted']); ?> .
I need to make a small edit and add class="btn" to the submit button.
I can change its value with $form['actions']['submit']['#value'] = "click to become a member";
But I couldnt find a way to add the class.
Please help!
Thank you
Answer: I think that you have to do something like this (add an array):
$form['actions']['submit']['#value'] = "click to become a member", array('attributes' => array('class' => array('btn'), 'style' => array('CUSTOM STYLE DIRECTLY') ));

I'm not really sure if is there is the right place the you have to add that code, but that generally it's this code:
, array('attributes' => array('class' => array('btn'), 'style' => array('CUSTOM STYLE DIRECTLY') ))

Comment: I get syntax error with this code.
Comment: Ok, it's normal. Can you provide more details of code that you are working on? Copy the block code or the function and paste it here that i can analyze it.


questions about ORM mappers like nhibernate etc

Question: Few questions on ORM mappers like nhibernate (for .net/c# environment).

When queries are run against a sqlserver database, does it use parameter sizes internally?
paramaters.Add("@column1", SqlDataType.Int, 4)
Do they all use reflection at runtime? i.e. hand coding is always a tad faster?
does it support temp tables, table variables?
Answer: ORM World is powerfull and full featured one, I think today obstacles are peoples theirself, this to say that using ORM's needs to take changes in mind, in the way of thinkng applications, architectures and patterns.
To answer you questions:

Query execution depends on more factors, it's possible to fully customize the engine/environment to take advantages of various features like, deffered execution, future queries (queries executed in a future moment), multiple queries, and last but not least, session management involves in this area:

Deferred execution is based on concepts like lazy-loading and lazy execution, this means that queries are executed against the database just qhen you perform some actions, like accessing to methods of the NHibernate Session like ToList(), another example of deferred execution is with using of LinqToNhibernate, where just when you access to certain objects, queries are executed
Future queries are as I said beforre queries executed in a future moment, Ayende speaks well about that
Multiple queries are queries that can be "packed" together and executed in one time avoiding multiple roundtrips to the DB, and this could be a very cool feature
Session Management, this is another chapter to mention... but take in mind that if you manage well your session, or better, let NHibernate engine to manage well the session, sometime it's not needed to go to the DN to obtain data

in all the cases, tools like NHibernate generates queries for you, and parametrized queries are managed well with parameters even depending on the underlying DB engine and conseguently DB Dialect you choose!

It's clear that frameworks like NHibernate, most of the time, use reflection at runtime, but it's needed to mention the multiple Reflection optimization are used, see for example Dynamic Proxies... It's clear that somethime, or maybe all the time direct code could be faster, but just in the unit, in the big picture this could involve in more mistakes and bottlenecks
Talking about NHibernate, or better saying, It's usefull to understand what you mean when talk about Temp Tables and temp data.. In terms as are, NHibernate, as I know, doesn't support natively Temp Tables, in the sense of Runtime tables, but this could be done because NHibernate permit to create object mapping at runtime, so a mechanism of Temp data could be implemented using that api

I hope I provided an usefull answer!
...and oops, sorry for my bad english!
Answer: nhiberate uses an optimised form of reflection that creates proxy objects on startup that perform better than plain reflection, as it only incurs a one time cost. You have the option of disabling this feature as well which has nhibernate behave in a more typical manner, with the permanent use of reflection.
This feature is set with the following key:
<code><add key="hibernate.use_reflection_optimizer" value="true" />
</code>
Nhibernate can be used with variable table names. See this SO thread for a good solution.
Answer:
NHibernate and SubSonic, LinqToSql, EF and I think most of the other ones use parameterized sql.
Most ORM's use some sort of reflection, there are some that generate all the code and SQL Query for you at design time so they don't have to use reflection code it might work a bit faster but it makes you domain a real mess and you have to use their application to regenerate all your code.
I am almost sure that they all don't support that but most have a way that you can use SP's and Views to do this.

You can check this out NHibernate Screencast Series http://www.summerofnhibernate.com/


$\forall M \in \mathrm{SL}(2, \mathbb{R})$ has a neighborhood diffeomorphic to $\mathbb{R}^3$?

Question: $\forall M \in \mathrm{SL}(2, \mathbb{R})$ has a neighborhood diffeomorphic to $\mathbb{R}^3$?
Known that $\mathrm{SL}(2, \mathbb{R})$ is a three-dimensional manifold.
Comment: isn't every three dimensional manifold locally diffeomorphic to $\mathbb{R}^3$?
Comment: @JamesS.Cook: Lee's *Introduction to Smooth Manifolds* has a definition of a manifold with corners.
Comment: Thank you James!! Now I got it!!! I thought "manifold" means "manifold with or without boundary", but now I realized "manifold" means "manifold without boundary". thank you :)
Comment: ah ha, yes, no edges by default. Which is a bit funny when you think about all the integration we do in calculus three, always a manifold with boundary. Well, that's even inaccurate, a square is not a manifold with boundary as I've seen it defined. The corners mess it up. Honestly, I've yet to see an abstract manifold-type definition which covers the all the constructions we make in ordinary multivariate calculus.
Comment: @MichaelAlbanese thanks! Sadly I do not have that one yet... however, you just gave me an idea for the library purchase at my school this year.
Answer: (Just so this question has an answer.)
The answer to your question is yes. Any point in a smooth $n$-dimensional manifold has a neighbourhood diffeomorphic to $\mathbb{R}^n$ (this is part of the definition). In particular, any $M \in \operatorname{SL}(2, \mathbb{R})$ has a neighbourhood diffeomorphic to $\mathbb{R}^3$ as $\operatorname{SL}(2, \mathbb{R})$ is a smooth three-dimensional manifold.


Get nonzeros row of a SparseTensor

Question: I want to get all nonzeros from a row in a SparseTensor so "m" is the sparse tensor object that I have and row is a row I want to get all nonzeros values and indices from. So I want to return an array of the pair that is [(index, values)]. I hope I can get som help on the subject.
def nonzeros( m, row):
    res = []
    indices = m.indices
    values = m.values
    userindices = tf.where(tf.equal(indices[:,0], tf.constant(0, dtype=tf.int64)))
    res = tf.map_fn(lambda index:(indices[index][1], values[index]), userindices)
    return res

Error message in terminal
TypeError: Input 'strides' of 'StridedSlice' Op has type int32 that does not match type int64 of argument 'begin'.

EDIT:
Input for nonzeros
cm is a coo_matrix with values
m = tf.SparseTensor(indices=np.array([row,col]).T,
                        values=cm.data,
                        dense_shape=[10, 10])
nonzeros(m, 1)

if the data is
[[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  2.]
 [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]

result should be
[index, value]
[4,1]
[9,2]

Comment: Could you please report an input-output example? In this way we can better understand how to obtain what you want.
Answer: The problem is that index inside the lambda is a Tensor and you can't use that directly to index into e.g. indices. You could use tf.gather instead. Also, you didn't make use of the row parameter in the code you posted.
Try this instead:
import tensorflow as tf
import numpy as np

def nonzeros(m, row):
    indices = m.indices
    values = m.values
    userindices = tf.where(tf.equal(indices[:, 0], row))
    found_idx = tf.gather(indices, userindices)[:, 0, 1]
    found_vals = tf.gather(values, userindices)[:, 0:1]
    res = tf.concat(1, [tf.expand_dims(tf.cast(found_idx, tf.float64), -1), found_vals])
    return res

data = np.array([[0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
                [0., 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  2.]])

m = tf.SparseTensor(indices=np.array([[0, 1], [0, 9], [1, 4], [1, 9]]),
                    values=np.array([1.0, 1.0, 1.0, 2.0]),
                    shape=[2, 10])

with tf.Session() as sess:
    result = nonzeros(m, 1)
    print(sess.run(result))

which prints:
[[ 4.  1.]
 [ 9.  2.]]

Get nonzeros row of a SparseTensor


get list of php files consuming resources

Question: Does there exist a way to output a list of currently executing PHP files, in Apache in debian? (and if it is possible, also listing the resources used by that instance).
We are having some performance issues and need some external way -- without touching the php code -- to monitor what file/process of the site is consuming a specific amount of resources.
Regards.
Answer: Apache has an ExtendedStatus that you can enable that will show you details about the requests it is handling at that moment.
Comment: i enabled it and tried to see the status with `apachectl status` but it didn't show me the name of the files, what i'm doing wrong?
Comment: you should use `apachectl fullstatus` to see the files being requested


SDL-Image: Couldn't open image, only error msg

Question: Game Engine Creation course work, questions about SDL, currently learning C++ SDL.
Met a question about SDL_Image, Couldn't open image.
When I run the code it closed instantly
bool InitSDL()
{
    //Setup SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        cout << "SDL did not initialise. Error: " << SDL_GetError();
        return false;
    }
    else
    {
        gWindow = SDL_CreateWindow(
            "GEC_SDL",
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            SCREEN_WIDTH,
            SCREEN_HEIGHT,
            SDL_WINDOW_SHOWN
            );
        if (gWindow == NULL)
        {
            cout << "Window was not created. Error: " << SDL_GetError();
            return false;
        }
    }

    gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
    if (gRenderer != NULL)
    {
        cout << "Renderer initialised." << endl;
        //Initialise PNG loading.
        int imageFlags = IMG_INIT_PNG;
        if (!(IMG_Init(imageFlags) & imageFlags))
        {
            cout << "SDL_Image could not initialise. Error: " << IMG_GetError;
            return false;
        }
        else {
            cout << "SDL_Image initialised." << endl;
        }
    }
    else
    {
        cout << "Renderer could not initialise. Error: " << SDL_GetError;
        return false;
    }

    gTexture = LoadTextureFromFile("D:/_a'Programs/School/GEC_SDL/GEC_SDL/Images/text.bmp");
    if (gTexture == NULL)
    {
        return false;
    }

    return true;
}

Error Messgae
Tried full path: D:_a'Programs\School\GEC_SDL\GEC_SDL\Images
Error Messgae
Load texture from file function
SDL_Texture* LoadTextureFromFile(string path)
{
    FreeTexture();

    SDL_Texture* pTexture = NULL;

    //Load the image.
    SDL_Surface* pSurface = IMG_Load( path.c_str() );
    if (pSurface != NULL)
    {
        //Create the texture from the pixels on the surface.
        pTexture = SDL_CreateTextureFromSurface(gRenderer, pSurface);
        if (pTexture == NULL)
        {
            cout << "Unable to create texture from surface. Error: " << SDL_GetError() << endl;
        }
        SDL_FreeSurface(pSurface);
    }
    else
    {
        cout << "Unable to create texture from surface. Error: " << IMG_GetError() << endl;
    }

    return pTexture;
}

I searched similar question in the forum and tried their ways, none of them works, please help.
Comment: @CraigEstey Forward slash `/` is perfectly fine as a path separator on Windows as well as on UNIX.
Comment: The `'` in the filename is suspicious. And, if you're _not_ using something that translates `/` to `\\ ` (e.g. `cygwin`), don't you need backslashes instead of forward slashes in the filename?
Comment: Tried: "D:\\_a\'Programs\\School\\GEC_SDL\\GEC_SDL\\Images\\text.bmp"
Comment: @JesperJuhl Well, bless me :-) I assumed that a posix-like layer had to do it, but, [I just looked]  under the win32 API: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file `/` is a reserved char. But, if one reads the fine print, it does [explicitly] state that `/` will be autotranslated. Is the reason that it's not more widely used in documentation is that some programs use `/` as an option argument prefix?
Answer: OMG, yes it's ''s problem, I rename the folder, now it works...
PS: stupid character sets


Lightning JS Chart causing crashes and not showing data correctly

Question: I have a component that I want to show a graph with multiple line series representing price changes over the last 24 hours. I have an endpoint that sends this data and I use the code below to show it.
One of the issues comes from errors seeming to come from the library itself meaning the graph will not even show up. Errors from the console when I load the page.
Other times, the page will load for a second and then go white and drain enough CPU to cause a crash.
The few times that the graph actually shows up on screen, it does not show any lines until the lines 81-85 are uncommented which it then shows the lines but does not zoom in on them leaving a mess on the screen.
Any help would be much appreciated.
/* eslint-disable new-cap */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-magic-numbers */
import React, { useEffect, useState } from "react";
import { LegendBoxBuilders, lightningChart, Themes } from "@arction/lcjs";
import "./TopCurrencyGraph.css";
import axios from "axios";
export interface data {
  data: dataPoint[];
}

export interface dataPoint {
  currency: string;
  percentage: number;
  timestamp: string;
}

interface graphPoint {
  x: number;
  y: number;
}

const TopCurrencyGraph = () => {
  const historicalAddr = `http://${
    process.env.back || "localhost:8000"
  }/historical24hChangeData`;

  useEffect(() => {
    const map: { [name: string]: graphPoint[] } = {};
    axios
      .get(historicalAddr)
      .then((res) => {
        const { points } = res.data;
        const pointList = points as dataPoint[];
        pointList.forEach((obj) => {
          const newPoint = {
            x: new Date(obj.timestamp).getTime() * (60 * 24),
            y: obj.percentage * 100,
          };
          if (obj.currency in map) {
            map[obj.currency].push(newPoint);
          } else {
            map[obj.currency] = [newPoint];
          }
        });
      })
      .catch((err) => {
        console.log(err, historicalAddr);
      });
    const chart = lightningChart().ChartXY({
      theme: Themes.lightNew,
      container: "currency-graph",
    });
    chart.setTitle("Top Currencies");
    chart.getDefaultAxisX().setTitle("Time");
    chart.getDefaultAxisY().setTitle("Percentage Change");

    const entries = Object.entries(map);
    const names = entries.map(([a, _b]) => a);
    const lists = entries.map(([_, b]) => b);

    const seriesArray = new Array(5).fill(null).map((_, idx) =>
      chart
        .addLineSeries({
          dataPattern: {
            pattern: "ProgressiveX",
          },
        })
        // eslint-disable-next-line arrow-parens
        .setStrokeStyle((stroke) => stroke.setThickness(1))
        .setName(names[idx])
    );

    seriesArray.forEach((series, idx) => {
      if (idx === 1) {
        series.add(lists[idx]);
      }
    });

    chart.addLegendBox(LegendBoxBuilders.HorizontalLegendBox).add(chart);

    return () => {
      chart.dispose();
    };
  }, []);

  // done thnx
  return (

  );
};

export default TopCurrencyGraph;

Answer: Your code looks syntax wise correct, but I believe you are running into issues due to not managing asynchronous code (axios getting data from your endpoint) properly.
const map: { [name: string]: graphPoint[] } = {};
axios
   .get(historicalAddr)
   .then((res) => {
      // This code is NOT executed immediately, but only after some time later.
      ...
   })

// This code and everything below is executed BEFORE the code inside `then` block.
// Because of this, you end up supplying `undefined` or other incorrect values to series / charts which shows as errors.
const chart = lightningChart().ChartXY({
   theme: Themes.lightNew,
   container: "currency-graph",
});

You might find it useful to debug the values you supply to series, for example like below. I think the values are not what you would expect.
seriesArray.forEach((series, idx) => {
   if (idx === 1) {
      console.log('series.add', lists[idx])
      series.add(lists[idx]);
   }
});

Improvement suggestion
Here's my attempt at modifying the code you supplied to manage the asynchronous data loading correctly, by moving all code that relies on the data after the data is processed.
/* eslint-disable new-cap */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-magic-numbers */
import React, { useEffect, useState } from "react";
import { LegendBoxBuilders, lightningChart, Themes } from "@arction/lcjs";
import "./TopCurrencyGraph.css";
import axios from "axios";
export interface data {
  data: dataPoint[];
}

export interface dataPoint {
  currency: string;
  percentage: number;
  timestamp: string;
}

interface graphPoint {
  x: number;
  y: number;
}

const TopCurrencyGraph = () => {
  const historicalAddr = `http://${
    process.env.back || "localhost:8000"
  }/historical24hChangeData`;

  useEffect(() => {
    const chart = lightningChart().ChartXY({
      theme: Themes.lightNew,
      container: "currency-graph",
    });
    chart.setTitle("Top Currencies");
    chart.getDefaultAxisX().setTitle("Time");
    chart.getDefaultAxisY().setTitle("Percentage Change");

    const seriesArray = new Array(5).fill(null).map((_, idx) =>
      chart
        .addLineSeries({
          dataPattern: {
            pattern: "ProgressiveX",
          },
        })
        // eslint-disable-next-line arrow-parens
        .setStrokeStyle((stroke) => stroke.setThickness(1))
    );

    chart.addLegendBox(LegendBoxBuilders.HorizontalLegendBox).add(chart);

    axios
      .get(historicalAddr)
      .then((res) => {
        const { points } = res.data;
        const pointList = points as dataPoint[];
        const map: { [name: string]: graphPoint[] } = {};
        pointList.forEach((obj) => {
          const newPoint = {
            x: new Date(obj.timestamp).getTime() * (60 * 24),
            y: obj.percentage * 100,
          };
          if (obj.currency in map) {
            map[obj.currency].push(newPoint);
          } else {
            map[obj.currency] = [newPoint];
          }
        });

        const entries = Object.entries(map);
        const names = entries.map(([a, _b]) => a);
        const lists = entries.map(([_, b]) => b);

        seriesArray.forEach((series, idx) => {
          series.setName(names[idx])
          if (idx === 1) {
            series.add(lists[idx]);
          }
        });
      })
      .catch((err) => {
        console.log(err, historicalAddr);
      });

    return () => {
      chart.dispose();
    };
  }, []);

  // done thnx
  return (

  );
};

export default TopCurrencyGraph;


For how many ones is $N =11\dots1$ prime?

Question: Suppose $N=111\dots1$ ($n$ ones). For which numbers $n$ is $N$ prime?
$n \ne 1, 3k$ is all progress I have made!
Comment: If there are $n$ digits in the representation, the number can be represented as $(10^n - 1)/9$.
Comment: All composite n does not work
Comment: I would write $N$ as $$\sum_{k=0}^{n-1} 10^k $$. That way $n$ will be the number of digits in $N$.
Comment: I found out that $n \ne 4k$, where $k$ is a positive integer. The reason is that since $1111$ | $101$, $1111 1111$ (8 digits) can be represented as $1111 * 110011$, $1111 1111 1111$ (12 digits) can be represented as $1001* 111000111$ and so on.
Comment: The only $n$ I have been able to find that makes this prime (through limited trial and error) is $n=2$. Not a clue how to prove if this is the only answer though
Comment: You might want to see this @Edi: This question (https://math.stackexchange.com/questions/1485350/factor-10n-1) relates to this question as well.
Comment: Some primes of this form are known: https://oeis.org/A004023
Answer: It is a well-known open problem to establish whether there exist infinitely many Mersenne primes, i.e., primes of the form $2^p-1$ for some prime $p$.
This question is its analogue which replaces $2$ with $10$. Indeed, if $\frac{1}{9}(10^n-1)$ is prime then $n$ is necessarily prime because $\frac{1}{9}(10^m-1)$ divides $\frac{1}{9}(10^n-1)$ whenever $m$ divides $n$.
Edit: It can be checked that
$$
\{n\in [2,1000]: \frac{10^n-1}{9}\text{ is prime}\}=\{2,19,23,317\}.
$$
Michael Stoker points out in the above comments also this longer OEIS sequence.
A related MSE question here.
Comment: There might not be infinitely many solutions, but can I ask do you know another solution to the (base 10) problem where $n \ne 2$?
Comment: @TobyMak I added you some other solutions ;)


jquery onclick runs twice

Question: I have the following javascript when my script is loaded:
var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
    //removes the hover color from the previous selected
    current_selected_note.removeClass('hover active');
    // sets the currently selected equal to the selected note
    current_selected_note = $(this);
    // adds the hover active to the currently selected
    current_selected_note.addClass('hover active');
    //adds the title of the currently selected to the title input field
    $('#txt_new_note_title').val($(this).find('Strong').text());
    selected_note_id = $(this).get(0).id;
    getNote(selected_note_id);
    load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );

Now AFTER this is loaded i click one of my buttons which has the following javascript:
    $('#note-item-lists').on('click','.close',function(){
    var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
    if(r == true){
        deleteNote($(this));
       $( "#note-item-lists").find('li').first().click();
    }
})

    function deleteNote(button){
    var id = button.closest('li').get(0).id;
    $.ajax({
        type: 'POST',
        url: '/solo/ajax_delete',
        dataType: 'json',
        data: {
            id: id
        },
        success: function (data) {
        }
    });
    button.closest('li').remove();
}

When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.
Anyone tried this before?
Answer: Try this, It will call one time.
 $('#note-item-lists .close').on('click',function(){
          alert("Hello");
 });

Comment: Yeah it did only once what does this mean? why isnt it adding the class then?
Answer: Try using .off()
$('#note-item-lists').on('click', '.list-group-item', function () {
    $(this).off();  //add this here

jquery onclick runs twice


How to disable UAC on a domain controller?

Question: I need to disable UAC on a Windows Server 2008 R2 domain controller, but I can't access its settings through the usual path (Control Panel -> User Accounts -> User Accounts), because a DC doesn't have a local user database, so the "User Accounts" icon in the Control Panel simply doesn't work.
How can I access the UI for UAC settings on a domain controller?

I know I can use a GPO for this, but I'd prefer to manually configure it on this single server.
Answer: You could do it from a command prompt:
<code>runas /user:DOMAIN\youraccount "REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f"
</code>
Comment: Or through Regedit. Good.


An elegant way to get Jekyll collection item by name?

Question: In Jekyll 2.5.3, I use albums collection (because I need not only data stored, but also pages generated).
When Jekyll Data Files are used, you can get a data for particular item as simple as: site.data.albums[foo]
But with collections, things are much worse. All those ways I've tried just do nothing:

site.albums[foo]
site.collections.albums[foo]
site.collections.albums.docs[foo]
site.collections.albums.files[foo]

So I need to:

Loop through all collection items
For each of them get a bare name
Compare this name with some target name
If the name matches, finally assign collection item data to some variable to use

Any better suggestions?
Answer: As of Jekyll 3.2, you can use the filter where_exp to filter a collection by any of its properties. So if I have the following item in an albums collection:
---
title: My Amazing Album
---
...

I can grab the first match for an item by that name:
{% assign album = site.albums
    | where_exp:"album", "album.title == 'My Amazing Album'"
    | first %}

Note that I use the first filter because where_exp returns an array of matched items.
And then use it any way I like:

{{ album.title }}

I can't vouch for the build performance of this method, but I have to imagine it's better than a Liquid loop.
Answer: I have just done this today, you are correct with your assertions. Here's how I did it:

{% for item in site.albums %}
    {% assign name = item.path | split:"/" | last | split:"." | first %}
    {% if name == include.name %}
        {% assign collectionItem = item %}
    {% endif %}
{% endfor %}

Usage
{{ collectionItem.title }}
{{ collectionItem.url }}
{{ collectionItem.path }}

It can even be used to populate values in other partials, like so:
{% include card.html title=workItem.title bg=workItem.card.bg href=workItem.url %}

Comment: This is going to kill build time. Too bad there isn't a better way.