'Error serializing body'. Problem calling Fedex webservice through .NET 3.5

Question: I'm using Fedex's web services and getting an annoying error right up front before I can actually get anywhere.
There was an error in serializing body of message addressValidationRequest1: 'Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement[]' to 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement'
error CS0029: Cannot implicitly convert type 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement' to 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement[]'
'.  Please see InnerException for more details.
I'm using .NET 3.5 and get a horrible named class generated for me (I'm not sure why it isn't just AddressValidationService):
AddressValidationPortTypeClient addressValidationService = new ...;
on this class I make my web service call:
addressValidationService.addressValidation(request);
This is when I get this error.
The only references I can find to this error come from ancient 1.1 projects. In my case my DLL has references to System.Web and System.Web.Services which seemed to be an issue back then.
Comment: FWIW, it also appears like this is happening with the WCF Service Client...
Answer: You only need change the [][], not the single [].
In Reference.cs change
private ParsedElement[][] parsedStreetLineField;
to
private ParsedElement[] parsedStreetLineField;
and
public ParsedElement[][] ParsedStreetLine {
to
public ParsedElement[] ParsedStreetLine {

Comment: are people still needing this answer really! cmon fedex!
Comment: ParcelForce's API has the same issue with its ParcelContents, Address and ServiceCodes properties.
Answer: Turns out Fedex's own documentation covers this specifically!
I am using wsdl.exe from Microsoft to generate code and I get an error CS0029: Cannot implicitly convert type 'fedexreq.ParsedElement' to 'fedexreq.ParsedElement[]'.
This is an error generated by Web Services Description Language Tool (Wsdl.exe) to generate the client information. When you publish a schema that contains nested nodes that have the maxOccurs attribute set to the "unbounded" value, the Wsdl.exe tool creates multidimensional arrays in the generated code file. Therefore, the generated code contains incorrect types for the nested nodes. To solve modify the generated code by removing the bracket ([]) array characters from the data type delectation statements. For more information see http://support.microsoft.com/kb/326790/en-us and http://support.microsoft.com/kb/891386
Answer: Note: To access the Reference.cs file that Simon_Weaver is referring to, open the project in visual studio, and in the Solution Explorer, click on the Web Reference and then look at the little icons at the top of Solution Explorer.  Click the "Show All Files" icon to show hidden files.  Now expand the web reference, then expand the Reference.map inside, and finally you will see Reference.cs which you can edit, replacing [][] with []
Do not confuse this Reference.cs with the Reference.cs you may have obtained from Fedex when downloading their sample code.
Comment: Couldn't this have been better as a comment on the answer that you were referring to?


Scatter plot with ggplot and predict() R

Question: I'm not a R specialist, and I've to do some stuff with R... But I stacked even in simple tasks... Sorry if it is a basic question but I haven't seen any issues like mine here in stackoverflow...
I'm having a bad time here with ggplot2 and predict() in R.
If someone could help me I'll appreciate it =]
    setwd("/home/kaihami/Desktop/Python/RR_Bioinfo/")

library("ggplot2")

data_total <- data.frame(bac, Phylum, Domain, CDS, Total)

#model (Total)
modlinear <- lm(Total ~ CDS)
xmin <- min(logCds2)
xmax <- max(logCds2)
predicted <- data.frame(logCds2=seq(xmin, xmax, length.out=length(logCds2)))
predicted$Total <- predict(modlinear, predicted)

#Total RR (ln)geom_line(aes(x=x, y=y.hat), col=2)
ggplot(data_total, aes(x = CDS, y = Total, colour = Domain))+
  geom_point(size=3.2, alpha = 0.4) +
  theme_bw()+theme(axis.line = element_line(colour = "black"),
                   panel.grid.major = element_blank(),
                   panel.grid.minor = element_blank(),
                   panel.border = element_blank(),
                   panel.background = element_blank(),
                   legend.title=element_blank(),
                   legend.key=element_blank()) +
  geom_abline(data = predicted)

With this code I got my graph that I want to, with the right axis and values...
But when I tried to put the regression line, I got a really bad graph, with the regression line dislocated... (sorry but I can't post images yet)
So I tried to check if my model was right and it was using summary(modlinear).
My question is, anybody here know how to fix it? Anybody ever experienced it?
Another silly question... What is the main difference between geom_abline and geom_line?
Comment: Start here: http://docs.ggplot2.org/current/geom_smooth.html  Look for method = "lm" and the se argument if you want confidence bands, That should replace most of your model fitting code.
Answer: geom_abline() is like saying y=ax+b, and you specify the slope and intercept.
geom_line() plots a line fitting data. Check the docs.ggplot2.org site as @Dennis commented.
So you have two options here. If your regression line is linear, use geom_abline() and specify your slope and intercept, or, if you want to plot predicted data, use geom_line(data=predicted...) and appropriate arguments. Make more sense?


Using external Angular 4 component in my own component

Question: I am trying to use jqWidgets Angular components in my project:
import { Component, ViewChild } from '@angular/core';

import 'jqwidgets-framework';
import { jqxTreeComponent } from "jqwidgets-framework/jqwidgets-ts/angular_jqxtree";

@Component({
    selector: 'tree-component',
    templateUrl: './tree.component.html',
    styleUrls: ['./tree.component.css']
})
export class TreeComponent {
    @ViewChild('treeReference')
    private tree: jqxTreeComponent;
}

The problem is that inside my TreeComponent class I don't get type information for the jqxTreeComponent since it is trying to find it in this component (Error message: "Could not find symbol 'jqxTreeComponent' in external module tree.component.ts.").
The import works and the external component is rendered on the site, only the type information is missing.
How can I get it or force it to search for it in the external component's .ts file?
Answer: Add the external component to the declarations array in your AppModule.
Comment: I already did that, but I forgot to mention that the AppModule has the same kind of problem. The import works, but in the declarations it says: "Symbol 'jqxTreeComponent' cannot be properly resolved, probably it is located in inaccessible module."
Comment: Did you import the component in the AppModule file?
Comment: Yes I did, but I found the solution just now. It seems that ReSharper can't pick up the type information, as soon as I suspended it it works. Thanks for the help, I will try to configure ReSharper somehow.


Volume of spherical shell with $dr$ thickness

Question: Let's consider two spheres in the $(x,y,z)$ 3D-space, both centered in the origin: the inner with radius $r$ and the outer with radius $r + dr$.
To compute the volume of the spherical shell between their two surfaces, one should simply proceed as follows:
$$dV = \frac{4}{3} \pi (r + dr)^3 - \frac{4}{3} \pi r^3 = \frac{4}{3} \pi (r^3 + 3 r^2 dr + 3 r dr^2 + dr^3 - r^3)$$
$$dV = \frac{4}{3} \pi (3 r^2 dr + 3 r dr^2 + dr^3)$$
but usually the last two terms between the brackets are neglected. I know $dr$ is infinitesimal, but can infinitesimals (raised to $n$-th power, $n>1$) be neglected and still obtain an exact result? How can this be justified?
Comment: When you studied limits I'm sure you learnt how to find functions equivalent to your function, up to an infinitesimal difference that got to 0 after you simplified all the terms. Here you are doing the same: integration (at least in Riemann terms) is a limit operation and $d x^2 + d x^3 \approx o(d x)$
Comment: Sometimes you have to compromise between "exactness" and "simplicity/feasibility"
Comment: Don't we therefore get $\frac{dV}{dr} = 4\pi r^2$ as $dr \to 0$, in a heuristic sense?
Answer: Let's forget about "infinitesimal" quantities and just look at the difference that you've computed: $$V(r+h) = V(r)+4\pi r^2h+4\pi rh^2+\frac43\pi h^3.\tag{1}$$ Now, one way to define the differential of a function is as the best linear approximation to the way its value changes near a given point, i.e., $dV_r$ is a linear function such that $$V(r+h)=V(r)+dV_r[h]+\phi(h)$$ where the error $\phi(h)$ "goes to zero" faster than $h$. More formally, $\lim_{h\to0}{\phi(h)\over h}=0$, or, $\phi(h)=o(h)$. You can check for yourself that this is consistent with the usual limit-of-a-quotient definition of a derivative of a single-variable function. This condition ensures that the total accumulated error that you get by adding up these approximations to the shell volumes can be made arbitrarily small by making the shells thin enough.
In practical terms, what the above means is that when computing a differential we can collect all terms that are higher than linear in the displacement $h$ into the error term $\phi(h)$. Equation (1) then becomes $$V(r+h)=V(r)+4\pi r^2h+\phi(h)$$ and so $$dV_r[h]=4\pi r^2h,$$ but $h$ is just $dr$ in disguise.
The key idea to take away from this is that $dV$ is a linear approximation to the change in volume relative to a change in radius, so we can throw out the higher-order terms.
Answer: You seem to think neglecting something is inaccuracy.
OK, if you want exact result do not go in for $ dr$ at all, but use full $ \Delta V= 4 \pi (R^3-r^3)/3$ instead.
When $R \approx r $ then the radial difference is $ dr$, higher order terms you gave in last line can be neglected with $ dr$ powers.
Using differentiation of volume $ V = 4 \pi r^3/3 $ w.r.t. radius,we get area (rate of change of volume is area)
$$ \frac {dV} {dr}= 4 \pi r^{2}, {dV}= 4 \pi r^2 \, dr  $$
So the procedure has automatically neglected higher powers without such calculation.
Answer: If $dr$ is defined as infinitessimal at the outset then presumably it is not the thickness  of a single shell that you are interested in but something else such as the volume of a sphere made up of an infinitely large number of infinitessimally thick shells.
One way to mentally rationalize the neglect of the minor terms in such a case is to examine the magnitude of their total summed over all the shells in the sphere. Then observe how the relative magnitude of that sum diminishes (relative to the magnitude of the sum of the major term) as you increase the number (and decrease the thickness) of the shells.
For example, assuming the volume of a sphere is given by $\frac{4\pi }{3}R^3$, we can derive an exact formula for the volume of any spherical shell as
$$Vshell = \frac{4\pi }{3}(3r^2 h + \frac{h^3}{4})$$
where $h$ is shell thickness and $r$ is the radius to the middle of the shell.  This expression can be used to calculate the exact volume of a sphere composed of a small number of shells with finite thickness $h$.
$$Vsphere = \frac{4\pi }{3}\sum_{r=1} ^{r=n}  (3 r^2 h + \frac{h^3}{4} )$$
The minor term $\frac{4\pi }{3}\frac{h^3}{4}$ cannot be neglected in this case.
For example in a sphere of radius $R$ and $n=4$ shells, each of thickness $h=R/4$, the total sum of the minor term represents 1/64th of the shell volume. (In this example the shell radii are $\frac{h}{2}$, $\frac{3h}{2}$, $\frac{5h}{2}$ and $\frac{7h}{2}$).
In all cases, the total of the minor term summed over all the shells is $\frac{4\pi }{3}\frac{nh^3}{4}$ which (using $n=\frac{R}{h})$ reduces to $\frac{\pi}{3}Rh^2$.  It is clear that this minor total will become progressively smaller as the shell thickness h is reduced, tending to zero as $h$ tends to $\frac{1}{\infty}$.  Concurrently (as $h$ is reduced) the major term total will tend towards $\frac{4\pi }{3}R^3$ with the decrease in $h$ being compensated completely by the increase in the number of shells ($n$).


clr.AddReference and clr.ImportExtensions give an "expected type, got str" error

Question: I can't seem to add a reference or import any extension methods in my IronPython scripts. For instance, with this script from one of my unit tests:
import clr;
clr.ImportExtensions('FrEee.Utility.Extensions');
from System import Math;
x * y

I get the error "expected type, got str". I tried removing the quotes from 'FrEee.Utility.Extensions', and changing them to double quotes, but nothing works. What am I doing wrong?
(For reference, the values for x and y are injected into the script scope by the unit test.)
Answer: Oh, I figured it out.
I needed to import the namespace containing the extension methods as a module, and pass the module into clr.ImportExtensions. I also needed to use clr.AddReferenceToFileAndPath to load the DLL containing the code I wanted to import.
import clr;
clr.AddReferenceToFileAndPath('FrEee.Core.dll');
from FrEee.Utility import Extensions;
clr.ImportExtensions(Extensions);
x * y


uniform convergence to zero

Question: Consider the sequence of functions $\{y_{m}(x)\}$ on $[a,b]$. Assume that $|y_{m}(x)|\leq M_{m}$ for all $x\in [a,b]$ and all $m\in Z^{+}$ .  Suppose $\Sigma_{m=1}^{+\infty}M_{m}<+\infty$. Is it possible to say $y_{m}(x)$ uniformly converges to zero on $[a,b]$? (The sequence $\{M_{m}\}$ is a numeric sequence in $R$)
Comment: Well,  $(M_m)$ must converge to $0$...
Comment: I see. I know that $y_{m}(x)$ converges to zero pointwisely on $[a,b]$. Can we say it also converges uniformly?
Comment: Yes. Given $\epsilon>0$, choose $N$ with $M_m<\epsilon$ for all $m\ge N$. Then for all $m\ge N$ and all $x\in[a,b]$, you have $|y_m(x)|\le M_m<\epsilon$. (In fact, the series $\sum y_m(x)$ converges uniformly. Google "Weierstrass M-Test".)
Comment: @T.A.Ben: You are asking if the sequence $(y_{m})$ converges uniformly, right? It follows directly from $M_{m} \to 0$.
Answer: If $\sum_{m}M_{m}$ converges, then $M_{m} \to 0$ by an elementary result in analysis. If $|y_{m}(x)| \leq M_{m}$ for all $x \in [a,b]$ and all $m \geq 1$, then $|y_{m}| \to 0$ uniformly on $[a,b]$, so $y_{m} \to 0$ uniformly on $[a,b]$.

uniform convergence to zero


likelihood function for Tobit

Question: I am trying to sort out the likelihood function for a two-limit Tobit model (data censored from above and below).
To start off, suppose you have data censored from below at zero. The log-likelihood of the one-limit Tobit model is
$$
\text{ln} L(\beta, \sigma) = \sum_{i=1}^n \left(
    \underbrace{(1 - D_i)~ \text{ln}~ [ 1 - \Phi \frac{x_i \beta}{\sigma} ]}_{\text{Censored}}
     +
     \underbrace{D_i~ [\text{ln} ~\phi (\frac{y_i - x_i \beta}{\sigma}) - \text{ln}~ \sigma ]}_{\text{Uncensored}} \right)
$$
where $\Phi$ and $\phi$ are the Gaussian CDF and PDF, and $D_i = 0$ if $y_i = 0$. The first brace shows the likelihood contribution of a censored observation; the second shows the likelihood contribution of an uncensored observation.
Now suppose the data are also censored from above at 20. How would $L(\beta, \sigma)$ be rewritten to capture this?
What I am thinking is $L(\beta, \sigma)$ should look like
$$
\text{ln}  L(\beta, \sigma) = L_{\text{censored below}} + L_{\text{uncensored}} + L_{\text{censored above}}
$$
Answer: Yes, you are exactly on the right track. The log-likelihood can be decomposed into the three parts pertaining to those observations $y_i$ that are left-censored, uncensored, and right-censored, respectively.

For the uncensored observations, the likelihood contribution is simply the density $f(y_i)$.
For the left-censored observations the contribution is the probability of falling below the censoring point, e.g., in the case of $0$ it is simply the cumulative distribution function $F(0)$.
And in the case of right-censoring at 20, you get the probability to be above the censoring point, i.e., $1 - F(20)$.

Thus, more formally, we can write this for a normally distributed model in terms of the standard normal PDF $\phi(\cdot)$ and CDF $\Phi(\cdot)$, respectively, by applying the proper scaling.

$f(y_i; x_i^\top\beta, \sigma) = \phi\left(\frac{y_i - x_i^\top\beta}{s}\right)/\sigma$
$P(y_i \le 0) = F(0; x_i^\top\beta, \sigma)) = \Phi\left(\frac{0 - x_i^\top\beta}{\sigma}\right) = 1 - \Phi\left(\frac{x_i^\top\beta}{\sigma}\right)$
$P(y_i > 20) = 1 - F(20; x_i^\top\beta, \sigma)) = 1 - \Phi\left(\frac{20 - x_i^\top\beta}{\sigma}\right)$

And then you need to take logs and sum them up across all observations (i.e., within each of the three groups and across the groups).

likelihood function for Tobit


Implicit differenciation of $u(x,y) := h(x-uy)$

Question: I am trying to verify that $u(x,y) := h(x-uy)$ is the general solution for a PDE. I have obtained it using the method of characteristics for the Cauchy problem:

$\left\{\begin{matrix}
uu_{x}+u_{y}=0 \\
u(x,0)=h(x)
\end{matrix}\right.$

So I wanted to check if that result is correct, and I have obtained the partial derivatives:

$u_{x}=(1-yu_{x})h', \hspace{1cm} u_{y}=-(u+yu_{y})h'$

Are these correct? Because I haven't been able to verify if I have solved the PDE.
Comment: yes, they are correct.
Answer: You have:
$u_x = (1-u_xy)h'$ (correct) and $u_y=-(u+yu_y)h'$ (almost correct). So, go ahead and solve the equations:
$u_x= \frac{h'}{1+yh'}$
$u_y = \frac{-h'u}{1+h'y}$
Now if you put what we have obatined int your equation it's clearly an identity


Please, help to get a value for a webelement

Question: I would like to ask the help - I need to get the value from WebElement 'input'. I tried general methods like getText(), but it doesn't work. Then I tried JavaScript in console and in console it works fine:
"document.evaluate('(//div[@id="CreateOrderBlock"]//input[@class="el-input__inner"])[3]',document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value;"

But how to handle it in the test? (Selenium WebDriver + Java) How to convert it to int java?
Maybe I need JavascriptExecutor , but in any case I would like to get an example.
I tried like:
 String summValueString = (String)((JavascriptExecutor) driver).executeScript("document.evaluate('(//div[@id='CreateOrderBlock']//input[@class='el-input__inner'])[3]',document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value;");

<input autocomplete="off" type="text" rows="2" validateevent="true" class="el-input__inner">

Thank you in advance
Answer: To get the value of an input text, please use the .getAttribute("value") method instead of .getText().


How to store data to multiple collections with same ID in Firestore?

Question: I have data that I want to store in multiple collections and apply the best practices of Firebase Firestore. Here's a document:
 [
       "postID": documentID,
       "category": self.category,
       "title": self.postTitle,
       "description": self.postDescription,
       "date": self.postDate,
       "imageURL": self.postImageURL
 ]

My idea is to store the same document in multiple places by same ID so it's faster to retrieve. Here's what I'm trying to do:
let documentID: String = db.collection("collectionName").document().documentID

let allPosts: DocumentReference = db.collection("allPosts").document(documentID)
let postsByDate: DocumentReference = db.collection("dates").document(self.postDate).collection(documentID)
let postsByCategory: DocumentReference = db.collection("category").document.(self.category).collection(documentID)

When I have generated documentID once for all, I don't want to addDocument but rather setData so that it doesn't nest the data with another ID but CollectionReference doesn't seem to have setData.
I even tried using db.document("dates").setData() but that throws an error:
Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid document reference. Document references must have an even number of segments, but dates has 1'

How should I go about this?
Answer: You can use setData() with your three existing DocumentReference objects and pass it the dictionary with the data to add to the collection.  You don't need to call other any methods on a CollectionReference other than what you're already doing.
let data = ... // your dictionary of data
allPosts.setData(data)

Comment: The right thing to do is whatever satisfies your queries.  There are as many ways to model your data as there are kinds of queries you might want to perform.  If a model doesn't satisfy your query, it's not a very good model.
Comment: Yes, that shall work fine. But for other references, I'd want to nest the documents with, let's say, dates like `db.collection("dates").document(self.postDate).collection(documentID)` so that each date has multiple documents. Is that achievable and is the right way to do?


Comparing different norms on $C[0,1]$

Question: Let $X_i=(C[0, 1], d_i), i = 1, 2, 3$, be the metric spaces where
$$\begin{aligned}d_1(f, g) &= \sup_{x∈[0,1]} |f(x) − g(x)|\\
d_2(f, g) &=\int_{0}^{1}|f(x) − g(x)| \, \mathrm dx\\
d_3(f, g) &= \left(\int_{0}^{1}|f(x) − g(x)|^2 \, \mathrm dx\right)^{1/2}\end{aligned}$$
Let $\operatorname{id}$ be the identity map of $C[0, 1]$ onto itself. Pick out the true statements.

a) $\operatorname{id} : X_1 \to X_2$ is continuous.
b) $\operatorname{id} : X_2 \to X_1$ is continuous.
c) $\operatorname{id} : X_3 \to X_2$ is continuous.

My attempt: I know that $d_1$ is complete in $C[0,1]$  and $d_2$ and $d_3$ are not  complete in $C[0,1].$ So option a) it will not be continuous, because $d_1$ is complete and $d_2$ is not complete, they don't match.
Option b) and option c) are both correct because both are  incomplete, there will  be homeomorphism between $d_1$ and $d_2.$
Is my answer correct or not? I would be more thankful if my mistakes are corrected.
Comment: Hint: observe that $d_2(f,g)\leq d_1(f,g)$ and $d_3(f,g)\leq d_1(f,g)$. So if $B$ is an open ball centered at $x$ in $X_2$ of $X_3$ then you can easily find on open ball $B'$ in $X_1$ centered at $x$.
Comment: which is greater d2 or d3   i  mean d2 is greater than d3 or d3 is greater than d2 @drhab
Comment: Haven't thought about it, but I suspect that they are not comparable.
Comment: @drhab. $d_3\geq d_2$. See my answer.
Comment: Incompleteness  or completeness of metrics will not suffice to answer this kind of Q....  For example with $d(x,y)=|x-y|$ and $e(x,y)= \arctan |x-y|,$  the  function id$_{\mathbb R}$ is a homeomorphism from $(\mathbb R, d)$ to $(\mathbb R,e)$ but $d$ is complete while $e$ is not.
Answer: Notice that $$d_2(f,g)=\int_{0}^1|f(x)-g(x)|\mathrm{d}x\leq \sup_{x\in [0,1]}|f(x)-g(x)|=d_1(f,g).$$ Suppose $(f_n)_n$ is a convergent sequence in $(X_1,d_1)$ with limit $f$, then by the above inequality we also have that $(f_n)_n$ converges to $f$ w.r.t. the metric $d_2$. Thus $Id:X_1\rightarrow X_2$ maps converging sequences to converging sequences. Since $d_1$ is complete this is equivalent to $Id:X_1\rightarrow X_2$ maps Cauchy sequences to Cauchy sequences. Hence this map is continuous.
Consider the functions $f_n$ defined by $$f_n(x)=\begin{cases}
0 & \mbox{ if } x\in [0,\frac{1}{2}-\frac{1}{n}]\cup [\frac{1}{2}+\frac{1}{n},1]\\
n(x-\frac{1}{2}+\frac{1}{n}) & \mbox{ if } x\in [\frac{1}{2}-\frac{1}{n}, \frac{1}{2}]\\
1-n(x-\frac{1}{2}) & \mbox{ if } x\in [\frac{1}{2},\frac{1}{2}+\frac{1}{n}]
\end{cases}.$$
It is straightforward to check that $\lim_{n\rightarrow \infty}\int_{0}^1|f_n(x)|\mathrm{d}x=0$. Thus $f_n\rightarrow 0$ in w.r.t. the $d_2$-metric. But $f_n$ does not converge to $0$ in the $d_1$-metric.
Try to think in terms of sequences. Can you find the rest?
Comment: that mean d3 will also map to d1   and d2,,,,,@ mathematician 42
Comment: I'm not sure what you mean by that comment.
Answer: Every metric space is first countable thus sequential continuity inplies continuity.

$a)$Let $f_n \in X_1$ such that $f_n \to f$.
In other words $\sup_{x \in [0,1]}|f_n(x)-f(x)| \to 0$.
Thus $d_2(I(f_n),I(f))=d_2(f_n,f)= \int_0^1|f_n(x)-f(x)|dx \leq \sup_{x \in [0,1]}|f_n(x)-f(x)| \to 0$
So $I:X_1 \to X_2$ is continuous.

.

$c)$Let $f_n \in X_3$ such that $f_n \to f$ in $X_3$
In other words $\sqrt{\int_0^1|f_n(x)-f(x)|^2dx} \to 0$
Now $$d_2(I(f_n),I(f))=d_2(f_n,f)=\int_0^1|f_n(x)-f(x)|dx=$$ $$\int_0^11|f_n(x)-f(x)| \ dx \leq \sqrt{\int_0^1 1^2dx} \sqrt{\int_0^1|f_n(x)-f(x)|^2dx} \to 0$$
Thus $I:X_3 \to X_2$ is continuous

.

$b)$Here take $f_n=x^n$ and $f=0$
We have that $d_2(f_n,f) \to 0$ but $d_1(I(f_n),I(f))=d_1(f_n,f)=1$ which does not go to zero.
So $I:X_2 \to X_1$ not continuous at the zero function.
Comment: Thanks a lot @ mario Gretsas..for detailed beautiful solution..
Answer: An answer to part of it.
To show that $d_3\geq d_2$: Let $h(x)=|f(x)-g(x)|.$ Then $$d_3(f,g)\geq d_2(f,g)\iff$$ $$\iff  2\int_0^1h(x)^2dx\geq 2\int_0^1h(x)dx \cdot \int_0^1h(y)dy \iff$$ $$\iff \int_{x=0}^1\int_{y=0}^1 h(x)^2dxdy+\int_{x=0}^1\int_{y=0}^1h(y)^2dxdy\geq 2\int_{x=0}^1\int_{y=0}^1 h(x)h(y)dxdy \iff$$ $$\iff \int_{x=0}^1\int_{y=0}^1(h(x)-h(y))^2dxdy\geq 0.$$
Hence id$_{[0,1]}:X_3\to X_2$ is continuous.
Comment: Thnaks @ Daniel Wainfleet.. now i understand  d3 >d2
Answer: a) and c) are continuous but b) is not. The question has no relation to completeness. Just use sequential continuity.
Comment: how can we use sequential continuity,,,, metric space is different..as there are d1,d2 and d3 @ kavi rama murthy
Answer: Essentially everything has been said to understand the problem, but let me point out how your problem relates to measure theory and functional analysis. This makes the solution very clear in my eyes.
Note that in this case (certainly not always) $\vert\vert f \vert\vert_i = d_i(f,0)$ ($i=1,2,3$) define norms on the vector space $C[0,1]$. These norms are just the $L^p-$norms for $p=\infty$ (in case of $d_1$), $p=1$ (in case of $d_2$) and $p=2$ (in case of $d_3$). Since $(0,1)$ is a finite measure space, the Hölder inequality implies
$$ \vert\vert u\vert \vert_{L^1} \le c_1 \vert \vert u \vert \vert_{L_2} \le c_2 \vert \vert u\vert\vert_{L^\infty}.$$
Now to functional analysis: You can show that a linear map $T:( E,\vert\vert\cdot\vert\vert_E) \rightarrow ( F,\vert\vert\cdot\vert\vert_F)$ between normes spaces is continuous if and only if it is bounded, i.e. there is a constant $c>0$ with
$$ \vert\vert Tu\vert\vert_F \le c \vert\vert u \vert\vert_E.$$
From the previous  inequalities you can simply conclude that the identity is continuous as a map
$$ X_1 \rightarrow X_3 \quad \text{and}\quad X_3 \rightarrow X_2 \quad \text{and}\quad X_1 \rightarrow X_2$$
This solves a) and c) of your question.
If b) was true you would also have an inequality of the form
$$\vert\vert u \vert\vert_{L^\infty} \le c_3 \vert\vert u \vert\vert_{L^1}.$$
To show there is no such inequality you can use the sequence of functions suggested by Mathematician 42.

Comparing different norms on $C[0,1]$


Do linear independent sets of a central (Lie-)algebra remain linear independent in scalar extensions?

Question: Let K'/K be a field extension, L' a K'-(Lie-)algebra and L a K-(Lie-)algebra, such that $L'\subseteq \K'\otimes_K L$ (by injective embedding).
Than we can review $L'=\K'\cdot L$. Consider there is a K-linear independent set $U\subseteq L$, which is NOT K'-linear independent in L'. Can we conclude that L is not central?
Answer: Edit: OP has significantly altered the question. Answer to new formulation below the bar.
Your first question has nothing to do with the Lie algebra structure, simplicity etc.: If $K' \vert K$ is any field extension, and $V$ is any vector space over $K$, and if by scalar extension $V_{K'}$ we mean $K' \otimes_K V$, then $\dim_K V = \dim_{K'} V_{K'}$. Namely, for any $K$-basis ${v_i: i \in I}$ of $V$ it is straightforward that ${1\otimes v_i: i \in I}$ is a $K'$-basis of $V_{K'}$. This should be one of the first things that is addressed when discussing scalar extensions in any source.
This means that in the lead-up to your second question, necessarily all $k_i =0$. I do not understand how asking about the centroid is then an "alternative formulation". If centroid means what it usually means in this theory, and if $L$ being central simple means that it's simple and $C(L)=K$, then of course you cannot conclude from anything that $C(L) \neq K$.

Answer to new formulation: To answer the question in the title: Linearly independet sets in vector spaces remain linearly independent in scalar extensions.
To expand a bit on the new formulation: First of all, ok, one can speak of a $K'$-Lie algebra $L'$ contained in $K' \otimes_K L$. Then it makes sense to speak of $K' \cdot L$, however as a set that is literally the same as $K' \otimes_K L$. This means however that if you're assuming $L' \color{red}{=} K' \cdot L$ you are just assuming that $L'$ $\color{red}{is}$ the entire scalar extension $K' \otimes_K L$, not just contained therein.
But regardless, again: If $U$ is any $K$-linearly independent set in any $K$-vector space $V$, and $K'\vert K$ is any field extension, then the set $U$ considered as subset of $K' \otimes_K V$ (i.e., formally the set $\lbrace 1 \otimes u: u \in U\rbrace$ which is the image of $U$ under the injection $V \hookrightarrow K'\otimes_K V$)) is linearly independent over $K'$. In a way, that is a special case of what I wrote above. So there is no such set $U$ as you assume to exist, hence one cannot draw any conclusions from that.

I have a feeling that you must mean something else, but I do not see what it is. Maybe write down a simple example.
Maybe you mean something like this: consider $V := \mathbb C$ as a two-dimensional $\mathbb R$-vector space. Then the vectors $1$ and $i$ are $\mathbb R$-linearly independent. However, when considered over $\mathbb C$, they are of course not. Further, you might mean this by writing $\mathbb C \cdot V$. Your question might make sense as
comparing the $\mathbb C$- vector space $V$ --- to the $\mathbb R$-vector space $Res_{\mathbb C \vert \mathbb R} V$
So I suggest what you actually want to ask about, for a field extension $K'\vert K$, is
a $K'$-Lie algebra $L'$ --- versus its scalar restriction to $K$, maybe call it $L:= Res_{K'\vert K} L'$
Notice that scalar restriction and scalar extension are not inverse to each other. In particular, in the above, the $\mathbb C$-vector space $V$ is not, and should not be called, the scalar extension of the $\mathbb R$-vector space $Res_{\mathbb C \vert \mathbb R} V$.
Comment: Thank you. First, in the second formulation I do not require, that L is simple.
To the first formulation: I probably have not the right thoughts about scalar extensions. Among my idea I mean some thing like $K'\cdot L$. Then e.g. the scalar extension of the K-LA $L_{K'}$ on K' would be L_{K'} itself. An exact formula for my idea of scalar extensions should be $L_{K'}=(K' \otimes_K L)/ \~$, whereas $k\otimes l \~ k'\otimes l' \Leftrightarrow k\cdot ad(l)(x) = k'\cdot ad(l')(x)\ \forall x\in K' \otimes_K L$. Would that fit to the second formulation?
Comment: $K' \cdot L$ makes no sense if $L$ is just given as a $K$-Lie algebra. Maybe what you have in mind is that you start with some Lie algebra over $K'$, then first do scalar restriction to $K$ (this multiplies the dimension with $[K':K]$), and then perform scalar extension back up to $K'$? --- If you do not require $L$ to be simple for your second paragraph, maybe remove that you do say that in there. But regardless: Do we agree that $L$ is a central $K$-Lie algebra, by definition, if and only if $C(L)=K$? Then if $L$ is a central Lie algebra, obviously no true statement can contradict $C(L)=K$.
Comment: I agree on the definition of centrality


How to embed the preceding knowledge in the training?

Question: I am trying to train a neural network that takes Height(X0) and Weight(X1) as input, output the corresponding prediction to calories(y).
First 4 columns below are part of the training set, the last column is the prediction by the model.
   Height(X0)  Weight(X1)  Calories(y)  Measurement(C)  Prediction(y_hat)
1      177.11       69.85       2800.0             0.0             2800.1
2      167.11       59.85       2600.0            -0.1             2800.2
3      197.11       79.85       3500.0             0.2             2800.3
...

Calories(y) is the target value in the dataset for training.
"Measurement" is some kind of measurement of Calories(y), whose absolute value is closer to 0, the better, which indicates how precisely the values of Calories(y) is. The negative and positive sign of C denote the direction, negative means less than, positive mean greater than.
For instance, first record means 2800.0 Calories is the exact amount a person needs whose Height(X0) = 177.11 and Weight(X1) = 69.85;
2nd record means 2600.0 is actually less than the exact amount a person needs whose Height(X0) = 167.11 and Weight(X1) = 59.85;
3rd record means 3500.0 is actually greater than the exact amount a person needs whose Height(X0) = 197.11 and Weight(X1) = 79.85;
Well, those numbers are just used to explain how does the system work, may be wrong to nutritionists.
As to the last column, the learning/training algorithm should keep the prediction for record 1 around 2800, so, 2800.1 is pretty good; prediction for 2nd record would be a bit greater than 2600.0; prediction for 3rd record would be a bit less than 3500.0.
The question is that:
How to put the preceding knowledge "Measurement" in training?
Answer: I think the most sensible way to incorporate this information is by adding it to your loss function when training your model.
For example we could take the standard loss function of mean square error or mean absolute error and modify it.
You say it is another question to encode what value the model should predict given $B$ (which I'm going to refer to as $y$) and $C$. Lets just say there is a function $f$ that exists that encodes this. So the best prediction would be $y+f(C)$ instead of $y$ and in the simplest case might be something like $f(C)=C$.
You could then use the loss function something like
$loss = \frac{(\hat{y}-(y+f(C)))^2}{|\hat{y}-y|}$ if $sign(\hat{y}-y)\neq sign(C)$ else $V$
where $V$ is just some large value. This is shown in the code and plot below. This gives an equivalent of the mean absolute loss.
You could modify this to higher order (to mean square loss) using something like
$loss = \frac{(|\hat{y}-(y+f(C))|)^3}{|\hat{y}-y|}$
set order=2 below.
Hopefully this form is enough to get you started.
import numpy as np
import matplotlib.pyplot as plt

y0=0 # value of target

ys = y_hats=np.linspace(-3, 3, 10000) # potential predictions of y0, the target

def f(c):
    return c

def loss(y_hat, y, c, order=1, clipval=10):
    sign_penalty = (np.sign(y_hat-y)!= np.sign(c))*clipval
    value_penalty = np.abs(y_hat-(y + f(c)))**(order+1)  * np.abs(y_hat-y)**-1
    penalty = sign_penalty + value_penalty
    return np.clip(penalty, 0, clipval)

plt.plot(ys, loss(ys, y0, c=1, order=1), label='$c=1$')
plt.plot(ys, loss(ys, y0, c=-0.5, order=1), label='$c=-0.5$')
plt.xlabel('y_hat')
plt.ylabel('loss')
plt.legend()
plt.show()

Comment: Your answer is very informative. Thank you so much. Does `y0` in code refer to the "B" or "C" in OP? The answer says y denotes "B" while the comments in code says `y0` represents the measurement, which is actually "C" in OP.
Comment: Why does $loss = \frac{(\hat{y}-(y+f(C)))^2}{|\hat{y}-y|} = 0 \text{ or } =10$ could represent sign? In other words, what does the large value clipval(V)  do?
Comment: I see you have edited the question since I answered, but now I think our notation lines up. `y0` would be $y$ as you have it in your edited question. Our `y_hat`s are the same.
Comment: The reason for this clip value is just to set some upper (and lower) limit on what the loss could be, and also to remove the symmetry of the graph around zero. Otherwise if you predicted $\hat{y}-y$=0 then your loss would go to infinity, and $loss(-y)=loss(y)$ (if `y0=0`). I arbitrarily chose an upper limit of 10 because that made the graph look nicer (I set the lower limit of 0 but that does nothing as this loss will never be negative anyway). You can see what the clipval does by taking this code and playing around with it.
Comment: Also, generally I just meant this as an example metric you could pick and wanted to set you up with some code to experiment with and modify to choose a metric. If C=-0.5 then the loss for $y_hat=y$ is the same as $y_hat=y-11$ and maybe $y_hat=y$ is actually a 'better' estimate? Also note that $y_hat=y$ gets the same penalty as any other value where $y_hat>y$ and maybe you might like to put a slope on this loss so that worse bad estimates are further penalised.
Comment: Thank you.  "$y_{hat}=y$ gets the **same penalty** as any other value where $y_{hat}>y$", "same penalty" means "same penalty sign", or the direction, right? Assume the target $y = 0$, $y_{hat}=0$" getting penalty is to avoid infinity, $y_{hat}>0$" getting penalty is to make it closer to 0, the value of target. Is my understanding right?


How to fix an expected an indented block error?

Question: I was trying to create a BMI calculator in Python, but when I run the program, it says: 'IndentationError: expected an indented block'. It says that the error is in line 7, but what did I wrong? I'm using Python 3.5.1
print ('Give your weight in kg: ')
weight_kg = float(raw_input())
print ('Give your length in meters: ')
length_meters = float(raw_input())
bmi = weight_kg / (length_meters * length_meters)
if bmi <= 18.5:
print ('Your BMI is'), bmi, ('what means that you have got underweight')
elif bmi > 18.5 and bmi <= 25:
print ('Your BMI is'), bmi, ('what means that you have got a normal weight')
elif bmi > 25 and bmi < 30:
print ('Your BMI is'), bmi, 'what means that you have got overweight')
elif bmi >= 30:
print ('Your BMI is'), bmi, ('what means that you have got obese')

Comment: You fix the indented block error by fixing the indented block.  Python relies on indentation to describe which code is in which blocks.  If you had an `if` inside of an `if` with no indentation and said `elif`, how would Python know which `if` the `elif` was for?  How would Python know if the second `if` is inside or outside of the first `if`?  Indentation makes it clear what you mean.
Comment: A basic tutorial might spare you some pain. The [official tutorial](https://docs.python.org/3.5/tutorial/introduction.html#first-steps-towards-programming) has this to say about indentation: "indentation is Python's way of grouping statements. [...] Note that each line within a basic block must be indented by the same amount."
Comment: after opening any block give 4 spaces to indent that block, try it.
Answer: In Python, subordinate statements are identified by their indentation level, in contrast to curly braces or begin/end keywords used by some other languages.  As such, proper indentation in Python is more than mere stylistic convention, but is in fact required for correct functionality.  In your case, you need to indent your subordinate statements.  Try the following:
print ('Give your weight in kg: ')
weight_kg = float(input())
print ('Give your length in meters: ')
length_meters = float(input())
bmi = weight_kg / (length_meters * length_meters)
if bmi <= 18.5:
    print ('Your BMI is', bmi, 'what means that you have got underweight')
elif bmi > 18.5 and bmi <= 25:
    print ('Your BMI is', bmi, 'what means that you have got a normal weight')
elif bmi > 25 and bmi < 30:
    print ('Your BMI is', bmi, 'what means that you have got overweight')
elif bmi >= 30:
    print ('Your BMI is', bmi, 'what means that you have got obese')

Comment: Your editing of his strings has caused a syntax error.
Comment: Thank you for answering my question, but now I got another problem: the program can run, but it says that it doesn't know what float(raw_input()) means. I changed the float in int, but this doesn't work either.
Comment: @zondo Thanks, I hadn't actually tried to load it.  The original strings had `'...you've...'` in them, which caused the syntax errors.  I see now that the post has been changed to use `'...you have...'` instead, so I edited my answer accodingly.
Comment: @L.Peters: Does it have a `NameError: name 'raw_input' is not defined`?  If it does, you are using Python3 and should use `input()` instead.
Comment: Sorry, there were some additional syntax errors in the original post which I've corrected as well.  Are you still having problems?  This should work in Python 2 now.
Comment: @zondo agreed, for Python 3 `raw_input` needs to be changed.
Comment: I changed my answer to use `input()` in place of `raw_input()`.  In this instance, it should work in both Python 2 and Python 3.  Let me know if you experience any more problems.
Comment: @zondo thanks! The error is fixed, I was still thinking about the Python 2.7 version. Now it says something that it can't make the calculation, but my  main problem is fixed, thanks!


How can I set NSHighResolutionCapable in Info.plist via CMake?

Question: I am currently using CMake to build a Mac app. I can set a number of Info.plist files with commands like this:
SET(MACOSX_BUNDLE_LONG_VERSION_STRING ${MYAPP_VERSION})

I would like to set NSHighResolutionCapable in my Info.plist file. Unfortunately, there isn't a property like MACOSX_BUNDLE_HIGH_RESOLUTION_CAPABLE. How can I set this Info.plist value programmatically with CMake?
Comment: See this question:
https://stackoverflow.com/questions/1792632/how-to-add-an-extra-plist-property-using-cmake
Answer: You can`t. You only can edit from CMake a few set of Info.plist properties. Show here. But you can provide your own Info.plist template for use in your OSX Bundles in CMake. Here´s the code I use:

function(osxBundle bundleName subDirList dependList)

    processTarget("${bundleName}" APPLE_BUNDLE "${subDirList}" "${dependList}")

    # Info.plist configure
    # Proyect provides its own Info.plist?
    if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist)
        set_target_properties(${bundleName} PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist)
    # Use default template
    else()
        set_target_properties(${bundleName} PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_SCRIPTS_PATH}/Info.plist)
    endif()

    # Overwrite some properties (not used yet)
    # MACOSX_BUNDLE_BUNDLE_NAME
    # MACOSX_BUNDLE_BUNDLE_VERSION
    # MACOSX_BUNDLE_COPYRIGHT
    # MACOSX_BUNDLE_GUI_IDENTIFIER
    # set_target_properties(${bundleName} PROPERTIES MACOSX_BUNDLE_ICON_FILE logo.icns)
    # MACOSX_BUNDLE_INFO_STRING
    # MACOSX_BUNDLE_LONG_VERSION_STRING
    # MACOSX_BUNDLE_SHORT_VERSION_STRING

    target_link_libraries(${bundleName} ${COCOA_LIB})

endfunction()
Answer: Another solution is to run a post build command to modify the plist:
  add_custom_command(
      TARGET foobar
      POST_BUILD
      COMMAND plutil -replace NSHighResolutionCapable -bool true foobar.app/Contents/Info.plist
      )


Normal Distribution of a randomly selected sample

Question:
Suppose the score of each student in an exam follows a Normal distribution with mean $\mu=75$ and standard deviation $\sigma=0.8$. If we take a random sample of 20 of these students, then what is the probability that more than 2 students will score less than 74.4

I know that for a sample size $n$, the mean of the random sample remains the same ($\mu$) as the population but the standard deviation becomes $\frac{\sigma}{\sqrt{n}}$.
The thing which is confusing me here is this part: probability that more than 2 students will score less than 74.4
If they would have asked about the probability of the mean score of the 20 randomly selected samples being less than 74.4, then the solution was simple. This is what I would have done
$$
z = \frac{74.4-75}{\frac{0.8}{\sqrt{20}}}=-3.354 \\
P(z<-3.354) = 0.0004
$$
But how to deal with the situation which is asked in the original question. Any help would be appreciated.
Thanks in advance :)
Comment: In R: code `1 - pbinom(1, 20, pnorm(74.4, 75, .8))` returns
$0.9598072.$
Answer: Hint:

find the probability of one individual getting a score of 74.4 or less,
use the binomial distribution to incorporate sample size.


How to execute code after the block of "click" is processed?

Question: This is currectly what is executed in my webform :
<code>1 - Page_Load
2 - protected void cmdSend_Click(object sender, EventArgs e)
</code>
which, this last, is linked to an asp:linkbutton.
Than, I'd like to execute another event, even if button it is not clicked (so, not only in the postback).
How can I do it? After_Load() ?
Answer: Try PreRender

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Have a look at this article about ASP.NET Page Life Cycle Overview


Why do ice hockey players get thrown out of the face off circle?

Question: Why are players thrown out of a face-off? I've heard there is a certain procedure for these circumstances, but I haven't found a list of things that are considered 'illegal'.
Answer: As stated in the Official NHL (National Hockey League) Rulebook in rule 76.6, players must comply by the following standards, otherwise it will result in a face-off violation:

i) Encroachment by any player other than the center into the face-off
  area prior to the puck being dropped.
ii) Encroachment by any player into the area between the hash marks on
  the outer edges of the face-off circle prior to the puck being
  dropped. Players must also ensure that both of their skates do not
  cross their respective hash marks.
iii) Any physical contact with an opponent prior to the puck being
  dropped.
iv) Failure by either center taking the face-off to properly position
  himself behind the restraining lines or place his stick on the ice (as
  outlined in Rule 76.4).
v) The blade of the stick must then be placed on the ice (at least the
  toe of the blade of the stick) within the designated face-off area.
Violation of these rules will result in removal from the face-off (the
  center) and normally one of the wingers comes in to take the re-drop.
Any 2 face-off violations committed by the same team during the same
  face-off will result in a Delay of Game minor penalty for 2 minutes.

Included is also a link to the Official Rulebook for further reading and long form rules:
http://www.nhl.com/nhl/en/v3/ext/pdfs/2012-13_RuleBook.pdf


How to allocate memory for a struct variable whose members are of type string

Question: My struct:
struct Company {
    string name;
    string profit_tax;
    string address;
};

I allocated by using line:
Company* a = (Company*)calloc(m, sizeof(Company));

with long long m =pow(10,9)+9
but pointer a is a null pointer after allocating. I don't know why this happened?. Please tell me solution, thanks!
Comment: @StefanRiedel I disagree. Much better would be `std::vector a(m);`.
Comment: Size of `std::string` is something like 24 or 32 bytes on 64-bit architecture. Are you aware that you are allocating 72 or 96 GB? How much RAM do you have?
Comment: BTW, do you really want just to allocate memory (storage), or do you also want objects in this storage to be constructed?
Comment: In 99% of the time, the solution would be `auto a = new Company[m];`
Comment: @DanielLangr, I know it, my laptop has 8gb RAM. But  this is task of my exercise. I think it
 is wrong
Comment: please include the exact requirement of the exercise. Unlikely `Company* a = (Company*)calloc(m, sizeof(Company));` with `long long m =pow(10,9)+9` is what you need to do. What you need to do instead is unclear
Comment: @DanielLangr Yes a vector would indeed be better. My comment was aimed at situations where you want manual memory management. But as it stands it just looks like bad advice.
Comment: @StefanRiedel Note that with `new` expression, you also don't have a _manual memory management_. `new` expression internally calls memory allocation function `operator new` for you automatically and you have no "manual control" over it. `std::vector` with a default allocator template argument effectively does the same.
Comment: @DanielLangr Yes but you can also argue that `malloc` isn't really manual memory management because it calls `sbrk` and stuff automatically for you. I would consider `new` and `delete` (and variants) "manual" enough to call it "manual memory management". Like "manual transmission" isn't pushing the gears by hand either.
Answer: You're allocating way too much memory for your computer (unless you have a huge amount of memory).
See this godbolt example, the computation shows that on their hardware you would be trying to allocate 96GB of memory!
If this is an exercise, maybe you have a typo somewhere on the size you have to allocate?
If not, you can try to replace the std::string to indexes/pointers to where the strings are stored. It should save some memory, but you'll still have issues. Otherwise you'll have to process the data differently, by processing it in chunks.
If you're using C++, why are you using calloc? You could simply have std::vector<company> companies(m); and that will allocate the memory AND construct all your objects. Less error-prone, and more readable.
Comment: That link doesn't work. It would probably be better anyway that you modify your question with any relevant information you have.
Comment: I am learing about hash, so the task requires create hash table with size as I mentioned. I used new, then i you calloc but both are not successfull.
Comment: All will fail if you can't allocate the memory you asked for.
Comment: link my  exercise [link]https://drive.google.com/drive/recent


How do I add CSS body classes for logged-in and logged-out users?

Question: In Drupal 7 I would add a theme process function to add the body classes needed.
function template_preprocess_html(&$variables) {
  $variables['classes_array'][] = $variables['is_front'] ? 'front' : 'not-front';
  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
}

In D8 this theme function exists but they don't have all the variables need for users.
Answer: Ok I think I figured this out as in Drupal 8 it uses TWIG to print the body classes for content types or users we need.
In the html.html.twig
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.hasPermission('administer')  ? 'isAdmin',
    user.getRoles()|join(' role_')
  ]
%}

Then make sure this line is added to the body classes

So if the user is logged out we can use the role class to identify them.
   .anonymous { }

Or we can use the :not Css selector
:not
   :not.user-logged-in {}

Answer: In html.html.twig and page.html.twig we have various variable available like logged_in, is_front, is_admin by default. Using these variables as condition we can add class to body tag. Some classes like path-frontpage, page-node-type-* are by default present in node and they is no need to add them explicitly.


Impact of the model error in numerical model prediction

Question: I'm having trouble wrapping my head around characterizing model prediction uncertainties in the case of a calibrated numerical model.  Let's assume we are trying to calibrate a set of input parameters $X$ for our model $f$ based on some data $Y$, i.e.:
$Y=f(X)+ε_y$
If we assume a Bayesian viewpoint, built into this equation is one set of fixed variables (our data: $Y$), and two random variables (uncertainty in our parameters: $X$ and the model error: $ε_y$). An MCMC analysis could then be conducted to obtain the uncertainty in $X$ and $ε_y$.
The issue I'm trying to figure out is how do we then use this to make predictions from our numerical model.  For example, say we want to generate some future random realization for $Y$.  To do this, we need to take into consideration both the uncertainty in the input parameters ($X$) as well as the estimated model errors ($ε_y$).  This is relatively straightforward when estimating unseen $Y$ outputs, but becomes more difficult if we want to modify our models to estimate a future condition $Z$.
In numerical modelling terms, what I am trying to get at here is that we calibrate our models ($f$) to some data ($Y$), then after calibration we modify our models ($f→g$) to include the future conditions and want to predict the impact of such conditions ($Z$).  The confusion I'm having is that I don't think we can just take our current model ($f$), modify it by adding the future conditions ($f→g$), and then drive the estimated uncertainty in our parameter set ($X$) through it, i.e.:
$Z=g(X)$
The issue I see with this is that it will cause our uncertainty estimates to be over-fit, as if fails to drive through the full uncertainty in the problem by dropping the modelling error ($ε_y$) term.  In reality should the equation not have an additional model error ($ε_z$) with respect to $Z$, i.e.:
$Z=g(X)+ε_z$
However, since it is impossible to infer the error of future unobservable states ($ε_z$), isn't this problem inherently unknowable?
Comment: Model errors are typically systematic (not random). Your first have to be clear on the distributional properties of $\epsilon_y$ before making predictions with it....
Answer: I'm not sure I'm addressing all of your concerns exactly, but perhaps this will provide a framework to get you moving in the right direction.
Suppose
\begin{equation}
y_t = f(x_t,\theta) + \varepsilon_t
\end{equation}
where
\begin{equation}
\varepsilon_t \stackrel{\text{iid}}{\sim} \textsf{N}(0,\sigma^2) .
\end{equation}
In this setup, $x_t$ is an observed covariate (a "condition"?) and $\theta$ is an unobserved parameter vector. The observation $y_t$ is normally distributed with mean $f(x_t,\theta)$ and variance $\sigma^2$.
Given $T$ observations (and associated covariates/conditions), we have
\begin{equation}
p(y_{1:T}|x_{1:T},\theta,\sigma^2) = \prod_{t=1}^T p(y_t|x_t,\theta,\sigma^2),
\end{equation}
where
\begin{equation}
p(y_t|x_t,\theta,\sigma^2) = \textsf{N}(y_t|f(x_t,\theta),\sigma^2) .
\end{equation}
Given a prior distribution for the unobserved parameter, $p(\theta,\sigma^2)$, we can compute the posterior distribution
\begin{equation}
p(\theta,\sigma^2|y_{1:T},x_{1:T}) = \frac{p(y_{1:T}|x_{1:T},\theta,\sigma^2)\,p(\theta,\sigma^2)}{p(y_{1:T}|x_{1:T})} ,
\end{equation}
where
\begin{equation}
p(y_{1:T}|x_{1:T}) = \iint p(y_{1:T}|x_{1:T},\theta,\sigma^2)\,p(\theta,\sigma^2)\,d\theta\,d\sigma^2 .
\end{equation}
We now turn to prediction. We wish to predict $y_{T+1}$. We will need $x_{T+1}$. If we knew $\theta$ and $\sigma^2$, then the prediction would be
\begin{equation}
p(y_{T+1}|x_{T+1},\theta,\sigma^2) = \textsf{N}(y_{T+1}|f(x_{T+1},\theta),\sigma^2) .
\end{equation}
The "prediction" is a probability distribution, from which we can compute the mean or the median or an interval --- whatever is appropriate for the problem.
Since we don't know $\theta$ and $\sigma^2$, we use the posterior distribution (which is what we do know) to integrate out our uncertainty:
\begin{equation}
p(y_{T+1}|y_{1:T},x_{1:T+1}) = \iint p(y_{T+1}|x_{T+1},\theta,\sigma^2)\,p(\theta,\sigma^2|y_{1:T},x_{1:T})\,d\theta\,d\sigma^2 .
\end{equation}
This "predictive distribution" is based on (1) the model, (2) what we have observed, and (3) the assumed covariate/condition for the "next" observation. It takes into account our uncertainty about the unknown model parameters and the unknown model error.


Rotate a Point on an ellipse by an angle and calculate the distance between them

Question: I am given a starting point $S=(s_1,s_2)^T$, the Center Point $C=(c_1,c_2)^T$ of the ellipse, with major radius $a$ and minor radius $b$, also the major axis is rotated w.r.t. the X axis by an angle of $\alpha$. I am also given an angle $\phi$ that is between the starting point $S$ and a target point $T$ looking from $C$. ($\phi$ can be >360°, e.g 540°, that would mean that the distance from $S$ to $T$ would be $d=1,5\cdot$ Perimeter of ellipse)
I now have to get the target point $T$ and the distance on the ellipse between $S$ and $T$.
My Idea to get $T$ was :
1) rotate $A$ around origin  by $\phi$ (name it $A'$
2) make a line $l$ from $C$ to $A'$
($l=C+(A-C)\cdot x)$
3) calculate intersection of this line with the ellipse
Problem: I have no clue how to do that either.
Appreciate any help.
Comment: Welcome to Math.SE. You might want to take a look at the [parametric representation](https://en.wikipedia.org/wiki/Ellipse#de_La_Hire's_point_construction) of an ellipse.
Answer: Your proposed method for finding $T$ is pretty good, although it can be simplified a bit. The tricky part is finding the distance, which I'll call $d$, along the arc of the ellipse. The best you'll do for this is a numerical approximation, because the exact distance involves an integral that cannot be expressed in elementary terms (indeed, the phrase "elliptic integrals" is a standard term precisely because of this).
First, let's write down two equations for your ellipse. I'm going to assume that the center, $C$ is at $(0,0)$, because that makes everything a little easier. To make this work, you replace $S$ by $S' = S - C$, you compute $T' = T - C$, and then you add $C$ back to $T'$ to get the point $T$ that you really wanted. This follows the general rule in physics (and linear algebra) that you're best off choosing the right coordinate frame to work in.
My next step is to work in a rotated coordinate system, in which
$$
\pmatrix{x'\\y'} = \pmatrix{c & s \\ -s & c} \pmatrix{x\\y}
$$
where $c = \cos \alpha, s = \sin \alpha$. In this coordinate system, the major axis is aligned with the $x'$-axis, and the minor with the $y'$-axis, so the ellipse equation is
$$
\left(\frac{x}{a}\right) ^2 + \left(\frac{y}{b} \right) ^2 = 1,
$$
which is probably easier to work with if we multiply through by $a^2 b^2$ and move everything to one side:
$$
b^2 x^2 + a^2 y^2 - a^2 b^2 = 0.
$$
Now you need to find the point $S$, but in the rotated-and-translated coordinate system. The coordinates are
$$
\pmatrix{s_1''\\s_2''} = \pmatrix{c & s \\ -s & c}\pmatrix{s_1 - c_1 \\ s_2 - c_2}
$$
and we can now work with the coordinates in the "double-prime" system. We're going to find the (counterclockwise) angle between $(s_1'', s_2'')$ and the positive $x'$-axis. That's
$$
\beta = atan2(s_2'', s_1'')
$$
in just about any programming language. To move clockwise from there by $\phi$, you'll compute
$$
\gamma = \beta - \phi
$$
The point $T$ you're looking for lies somewhere along a ray in the $\gamma$ direction from the origin of the primed coordinate system, i.e., it has the form (in the primed coordinate system)
$$
T'' = \pmatrix{t_1''\\ t_2''} = \pmatrix{r \cos \gamma\\ r \sin \gamma},
$$
where $r > 0$.
And this must satisfy the ellipse equation, i.e., you need to find the value of $r$ that makes
$$
b^2 (r\sin \gamma)^2 + a^2 (r \cos \gamma)^2 - a^2b^2 = 0.
$$
Writing that out with a little algebra, we get
\begin{align}
r^2 \biggl( b^2 \sin^2 \gamma + a^2 \cos^2 \gamma \biggr) &= a^2 b^2\\
r^2 &= \frac{a^2 b^2}{b^2 \sin^2 \gamma + a^2 \cos^2 \gamma}\\
r &= \frac{a b}{\sqrt{b^2 \sin^2 \gamma + a^2 \cos^2 \gamma}}
\end{align}
Now, having the value for $r$ (you have to pick the positive one!), you want to convert back to regular coordinates. To do so, compute
$$
\pmatrix{t_1'\\t_2'} = \pmatrix{c & -s \\ s & c}\pmatrix{t_1''\\ t_2''}
$$
(notice that the "$-s$" has switched positions!), and then compute
$$
\pmatrix{t_1\\t_2} = \pmatrix{t_1'\\t_2
}+\pmatrix{c_1\\ c_2}.
$$
So that gets you the position of $T$.
As for the arclength, I can only suggest a numerical computation. It'll be easiest to work in the primed coordinate system. You basically need to compute a whole lot of angles between $\beta$ and $\gamma$, and compute a corresponding ellipse-point for each one, and then sum up the distances between successive ellipse-points (i.e., you're approximating the ellipse with an inscribed polygon with many many vertices). By taking the number of points to be large, your error can be made small, but that's about the best I can do for you.
Comment: Thanks for the answer. With your help I managed to implement an algorithm to achieve my goal. But your ellipse equation  where you first used $r$ has an error. It needs to be $b^2(r cos(\gamma)^2 + a^2(r sin(\gamma)^2 -a^2b^2 = 0$.
Comment: Uh...the thing you claim is "correct" has 4 left-parentheses and 2 right-parentheses. I think maybe both of us are wrong. :) Anyhow, I'm glad I was of some use.
Comment: Yeah, I noticed the missing parenthesis after posting it on the mobile phone.  And I can't find an option to edit my comment to correct it


leaflet for R issues with shape file

Question: I try to make a map with the leaflet package on Rstudio.
I try many examples and self options and they all work properly.
But I would like to use a shape file I have at work.
It work with all the software (QGIS, R spplot etc.) but when I use the shape file in leaflet it dosen't work, a blue line appear on the top of the map.
Here is the code i use :

dat<-readOGR(dsn="shape/Shape ER 2015", layer=filename,encoding='UTF-8')
leaflet(dat)%>%addTiles()%>%
addPolgons(data=dat, weight=2)

Here is the result with the code :

and here is the map obtained with spplot :
spplot(dat, zcol=1, col.regions="gray", col="blue")

I have used the same file with http://leaflet.calvinmetcalf.com/ to see if the issue come from my data. But it appear that it come from readOGR
I put here some informations of the SpatialPolygonDataframe
  str(dat@polygons[[1]],2)

Formal class 'Polygons' [package "sp"] with 5 slots
  ..@ Polygons :List of 1
  ..@ plotOrder: int 1
  ..@ labpt    : num [1:2] 953652 6808716
  ..@ ID       : chr "0"
  ..@ area     : num 4.32e+10

 str(dat@polygons[[1]]@Polygons[[1]],2)

Formal class 'Polygon' [package "sp"] with 5 slots
  ..@ labpt  : num [1:2] 953652 6808716
  ..@ area   : num 4.32e+10
  ..@ hole   : logi FALSE
  ..@ ringDir: int 1
  ..@ coords : num [1:1063, 1:2] 940343 939824 936328 933274 933649 ...

 head(dat@polygons[[1]]@Polygons[[1]]@coords)

       [,1]    [,2]
[1,] 940343 6611180
[2,] 939824 6610705
[3,] 936328 6613788
[4,] 933274 6616467
[5,] 933649 6617058
[6,] 934305 6617147

Hope it's clear, thank you in advance.
Answer: You most likely need to transform your projection.
Try:
PRO <- sp::CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0')
DAT <- sp::spTransform(dat,PRO)

Comment: Your're my hero !
Can you explain me the idea ? How it works ?
Comment: Leaflet's default projection is EPSG:3857, also known as "Google Mercator" or "Web Mercator"

leaflet for R issues with shape file


Can CCxyCCNxyy Get Proven in Less Than Or Equal to 50 Detachments in This System?

Question: Suppose that the axioms consist of the following three meaningful expressions, or correspond to the following three axioms if the formation rules get written differently:
Axiom          Alternative                           Name
CxCyx          C(x, C(y, x))                         Recursive Letter Prefixing
CCxCyzCCxyCxz  C(C(x, C(y, z)), C(C(x, y), C(x, z))) Conditional Distribution
CCNxNyCyx      C(C(N(x), N(y)), C(y, x))             Transposed Negation Elimination

Suppose that the only rules of inference allow for consistent substitution for letters with meaningful expressions (substitution in a meaningful expression has to work out as uniform... if we substitute one letter with some meaningful expression in one spot in a meaningful expression, we have to substitute it with an equiform/"the same" meaningful expression in another spot), and detachment:
From $\vdash$C$\alpha$$\beta$ and $\vdash$$\alpha$ we may infer that $\vdash$$\beta$.
I will refer to CCxyCCNxyy or any correspondent meaningful expression as "Eliminated Excluded Middle" hereafter, since it can get obtained from the law of the excluded middle AxNx and CAxyCCxzCCyzz.
Eliminated Excluded Middle gets listed in A. N. Prior's appendix as an axiom in a system used by Hilbert in a 1922 text.  Reading elsewhere suggests that the text is Hilbert and Ackermann's Grundzuge der theoretischen Logik (translated as "Principles of Mathematical Logic").  Mauro Allerganza used Eliminated Excluded Middle recently in an answer to another question.  Eliminated Excluded Middle also got derived in Elliot Mendelson's Introduction to Mathematical Logic as the last part of Lemma 1.11 (g) on p. 38 and then used in the metalogical proof of the completeness theorem (did Kalmar also use Eliminated Excluded Middle?).
Can a proof of Eliminated Excluded Middle get proven from Recursive Letter Prefixing, Conditional Distribution, and Transposed Negation Elimination in less than or equal to 50 detachments?
Using an automated reasoning program it has suggested that it comes as possible to write a proof with 74 detachments, 73 detachments, 69 detachments, 113 detachments, 93 detachments, 75 detachments, 76 detachments, 124 detachments, 61 detachments, 60 detachments, 63 detachments, 68 detachments, 71 detachments, a distinct proof with 68 detachments, 72 detachments, a distinct proof with 61 detachments, a distinct proof with 74 detachments, 117 detachments, a distinct proof with 60 detachments, and to write a proof with 59 detachments of Eliminated Excluded Middle from the above 3 axioms.
Edit: The automated reasoning program has suggested some more proofs, including a proof with 58 detachments.
Edit 2: A 57 detachment proof also can get written.
Comment: @DanielV I'm not familiar with how SAT solvers work.  But, do they output something where there exists a sequence of formulas such that *every single step* corresponds to a tautology in propositional logic, using only the axioms and the rule of detachment/condensed detachment?  If they do, have you tried this problem with an SAT solver and has it produced a proof?  Or does it run into problems because it has to keep track of ever so many formulas and gets lost exploring too much of the theory?
Comment: Can you explain why this sort of question is of interest?
Comment: I'm curious why you are using "automated reasoning" for simple propositional logic.  Negate the formula, feed it to a SAT solver.  Asymptotically, the sat solver is your shortest proof.
Comment: @MarianoSuárez-Álvarez If you check the link where Mauro posted his answer (see above), you'll see that we both posted proofs. At the time I believed that if he had proved CCxyCCNxyy (or it's correlate in another notation scheme) using just substitution and detachment, he would need more detachments to construct a proof relying on CCxyCCNxyy. But, now I'm not so sure. Also, this isn't necessarily an all too easy problem for a theorem prover to even find a proof in that it may require some input from the user to find a solution a fair amount of time. Also, the formula seems to have importance.
Answer: At the end of this answer is a hyperresolution proof, used with permission, which Larry Wos obtained with the help of O.T.T.E.R.
Before that, though, I will display a proof of only 23 detachments with appropriate substitutions.  This should not got interpreted as meaning that necessarily no shorter proof exists.  The numerals in what follows only correspond to the proof below when a detachment gets made.  There is no correspondence when a substitution gets made.  Perhaps it is objectionable to do so during a course of a proof, but some different prefix notations will get used in the course of this demonstration.  When in doubt as to how a notation works, we drop all parentheses and remove all spaces to see a form which fits with a definition suitable for the axioms.
Axiom                              3 CxCyx
Axiom                              4 CCxCyzCCxyCxz
Axiom                              5 CCNxNyCyx
3 x/CxCyx, y/z * 6                 6 CCxCyxCzCxCyx
6 * C3-25                         25 (C z (C x (C y x)))
4 x/CxCyz, y/Cxy, z/Cxz           26 CCCxCyzCCxyCxzCCCxCyzCxyCCxCyzCxz
26 * C4-27                        27 C C C x C y z C x y C C x C y z C x z
27 y/Cyx * 28                     28 CCCxCCyxzCxCyxCCxCCyxzCxz
25 z/CxCCyxz * 29                 29 CCxCCyxzCxCyx
28 * C28-32                       32 C C x C C y x z C x z
3 x/CCxCCyxzCxz, y/u *33          33 CCCxCCyxzCxzCuCCxCCyxzCxz
33 * C32-41                       41 C u C C x C C y x z C x z
32 y/x, x/CCyxz, z/Cxz * 42       42 CCCCyxzCCxCCyxzCxzCCCyxzCxz
41 u/CCyxz * 43                   43 CCCyxzCCxCCyxzCxz
42 * C43-45                       45 C(C(C(y,x),z),C(x,z))
45 y/Nx, x/Ny, z/Cyx              46 CCCNxNyCyxCNyCyx
46 * C5-51                        51 C (N y) (C y x)
45 y/x, x/Cyz, z/CCxyCxz * 52     52 CCCxCyzCCxyCxzCCyzCCxyCxz
52 * C4-53                        53 C Cyz CCxyCxz
4 x/Ny, z/x * 54                  54 CCNyCyxCCNyyCNyx
54 * C51-60                       60 C (CNyy) C (Ny) (x)
53 y/CCyxz, z/Cxz, x/u * 61       61 CCCCyxzCxzCCuCCyxzCuCxz
61 * C45-62                       62 C CuCCyxz CuCxz
53 y/CNxNy, z/Cyx, x/z            63 CCCNxNyCyxCCzCNxNyCzCyx
63 * C5-64                        64 C CzCNxNy C z C y x
62 u/CxCyz, y/x, x/y, z/Cxz * 65  65 CCCxCyzCCxyCxzCCxCyzCyCxz
65 * C4-79                        79 C C x C y z C y C x z
64 z/CNyy, x/y, y/z * 80          80 CCCNyyCNyNzCCNyyCzy
60 x/Nz * 81                      81 CCNyyCNyNz
80 * C81-82                       82 (C (C (N y) y) (C z y))
79 x/Cyz, y/Cxy, z/Cxz * 83       83 CCCyzCCxyCxzCCxyCCyzCxz
83 * C53-96                       96 C Cxy C Cyz Cxz
82 z/Cyx * 97                     97 CCNyyCCyxy
32 x/CNyy, z/y                    98 CCCNyyCCyxzCCNyyy
98 * C97-104                     104 (C (C (N y) y) y)

Break...
96 x/Cxy, y/CCyzCxz, z/u * 105   105 CCCxyCCyzCxzCCCCyzCxzuCCxyu
105 * C96-112                    112 C C C C y z C x z u C C x y u
53 y/CNyy, z/y, x/z * 113        113 CCCNyyyCCzCNyyCzy
113 * C104-118                   118 C C z C N y y C z y
118 z/Cyx, y/x                   119 CCCyxCNxxCCyxx
112 z/x, x/Nx, u/CCyxx           120 CCCCyxCNxxCCyxxCCNxyCCyxx
120 * C119-134                   134 C CNxy C Cyx x
96 x/CNxy, y/CCyxx * 135         135 CCCNxyCCyxxCCCCyxxzCCNxyz
135 * C134-144                   144 C C C C y x x z C C N x y z
134 x/y, y/Cyx * 145             145 CCNyCyxCCCyxyy
145 * C51-146                    146 C(C(C(y,x),y),y)
53 y/CCyxy, z/y, x/z * 147       147 CCCCyxyyCCzCCyxyCzy
147 * C146-158                   158 C C z C C y x y C z y
158 z/Cay * 159                  159 CCCayCCyxyCCayy
112 x/Cyx, z/y, u/CCayy, y/a    159' CCCCayCCyxyCCayyCCCyxaCCayy
159' * C159-160                  160 C (C C y x a) C (C a y) y
160 a/x * 161                    161 CCCyxxCCxyy
144 z/CCxyy                      162 CCCCyxxCCxyyCCNxyCCxyy
162 * C161-163                   163 C CNxy C Cxy y
79 x/CNxy, y/Cxy, z/y            164 CCCNxyCCxyyCCxyCCNxyy
164 * 163-174                    174 CCxyCCNxyy

----- Otter 3.3g-work, Jan 2005 ----- The process was started by wos on vanquish, Wed Nov  9 21:08:42 2016 The command was "otter".  The
process ID is 17263.
----> UNIT CONFLICT at  0.02 sec ----> 175 [binary,174.1,11.1] $ANS(TAR).
Length of proof is 23.  Level of proof is 15.
---------------- PROOF ----------------
1 [] -P(i(x,y))| -P(x)|P(y).
3 [] P(i(x,i(y,x))).
4 [] P(i(i(x,i(y,z)),i(i(x,y),i(x,z)))).
5 [] P(i(i(n(x),n(y)),i(y,x))).
11 [] -P(i(i(a1,a2),i(i(n(a1),a2),a2)))|$ANS(TAR).
25 [hyper,1,3,3] P(i(x,i(y,i(z,y)))).
27 [hyper,1,4,4] P(i(i(i(x,i(y,z)),i(x,y)),i(i(x,i(y,z)),i(x,z)))).
32 [hyper,1,27,25] P(i(i(x,i(i(y,x),z)),i(x,z))).
41 [hyper,1,3,32] P(i(x,i(i(y,i(i(z,y),u)),i(y,u)))).
45 [hyper,1,32,41] P(i(i(i(x,y),z),i(y,z))).
51 [hyper,1,45,5] P(i(n(x),i(x,y))).
53 [hyper,1,45,4] P(i(i(x,y),i(i(z,x),i(z,y)))).
60 [hyper,1,4,51] P(i(i(n(x),x),i(n(x),y))).
62 [hyper,1,53,45] P(i(i(x,i(i(y,z),u)),i(x,i(z,u)))).
64 [hyper,1,53,5] P(i(i(x,i(n(y),n(z))),i(x,i(z,y)))).
79 [hyper,1,62,4] P(i(i(x,i(y,z)),i(y,i(x,z)))).
82 [hyper,1,64,60] P(i(i(n(x),x),i(y,x))).
96 [hyper,1,79,53] P(i(i(x,y),i(i(y,z),i(x,z)))).
104 [hyper,1,32,82] P(i(i(n(x),x),x)).
112 [hyper,1,96,96] P(i(i(i(i(x,y),i(z,y)),u),i(i(z,x),u))).
118 [hyper,1,53,104] P(i(i(x,i(n(y),y)),i(x,y))).
134 [hyper,1,112,118] P(i(i(n(x),y),i(i(y,x),x))).
144 [hyper,1,96,134] P(i(i(i(i(x,y),y),z),i(i(n(y),x),z))).
146 [hyper,1,134,51] P(i(i(i(x,y),x),x)).
158 [hyper,1,53,146] P(i(i(x,i(i(y,z),y)),i(x,y))).
160 [hyper,1,112,158] P(i(i(i(x,y),z),i(i(z,x),x))).
166 [hyper,1,144,160] P(i(i(n(x),y),i(i(x,y),y))).
174 [hyper,1,79,166] P(i(i(x,y),i(i(n(x),y),y))).
175 [binary,174.1,11.1] $ANS(TAR).


How to get the custom class added to a view

Question: Views let people to add custom css class to a display. I'm looking to get this information and add to the body tag.
I try with this two functions and the dpm() function from devel:
views_get_view('name');
views_get_page_view();

But I'm not able to find the custom class that I add to the view.
Do you have any idea how to get this information?
Comment: If you found the answer, please write it as answer. Questions and answers needs to be separated, since this is a Q&A site.
Answer: If you only need to get this information, you can use template_preprocess_views_view
/**
 * Preprocess the primary theme implementation for a view.
 */
function YOURTHEME_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'your_view_name' :
      // print out the array with all options to see what you're dealing with
      drupal_set_message('
' . print_r($view->display['display_name']->display_options, true) . '
');
      break;
  }
}

But if you will need to override this custom class, you'll need to use hook_views_pre_render()
function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view' :

      // override the view settings
      // for example: $view->field['fieldname']->options['label'] = 'Some label';

      break;
  }
}

Comment: Sorry jack-Pl, I don't explain fine, I want to add the new css class to the body html tag. So I need to load the view within the hook_preprocess_html().
Comment: no problem, I'll edit this, but if you have the view object within hook_preprocess_html() and all information is there, so where is the issue?
Comment: I don't realize about the information in hook_preprocess_html. I'm going to check it.


Continuous random variables conditioned on discrete random variables

Question: Suppose I have two continuous random variables $X_1 \sim N(0,\sigma_1^2)$ and $X_2 \sim N(0,\sigma_2^2)$
Then I have a discrete random variable $Z$ and $\theta$ such that
$$
\theta = \begin{cases}
    \theta_1,& p\\
    \theta_2,& (1-p)
\end{cases}
$$
$$
Z = \begin{cases}
    X_1,& \theta=\theta_1\\
    X_2,& \theta =\theta_2
\end{cases}
$$
I would like to compute $P(Z|\theta)$, $P(Z,\theta)$, and $P(Z)$.
Here's my attempt, I am wondering if I can tackle this problem similar to discrete cases.
I start with a conditional probability matrix
\begin{array}{l|ll}
P(Z|\theta) &X_1 &X_2 \\ \hline
\theta_1 &f(x_1) &0 \\
\theta_2 &0 &f(x_2)
\end{array}
Here, the rows of the conditional probability matrix integrate/sum to 1. Would this be a valid probability matrix?
So $P(Z|\theta = \theta_1) = [f(x_1), \ 0]$.
Then $P(Z\in X_1|\theta=\theta_1) = 1$ since $f(x_1)$ integrates to 1.
So $P(Z=x_1|\theta=\theta_1) = f(x_1)$
Then,
$$
P(Z |\theta) = \begin{cases}
    f(x_1),& Z=x_1\\
    f(x_2),& Z=x_2
\end{cases}
$$
Now for computing $P(Z,\theta) = P(Z|\theta)P(\theta)$, I have a joint probability matrix,
\begin{array}{l|ll}
P(Z,\theta) &X_1 &X_2 \\ \hline
\theta_1 &pf(x_1) &0 \\
\theta_2 &0 &(1-p)f(x_2)
\end{array}
which is
$$
P(Z ,\theta) = \begin{cases}
    pf(x_1),& \theta=\theta_1\\
    (1-p)f(x_2),& \theta=\theta_2
\end{cases}
$$
Now using this logic, to find $P(Z)$ we have $P(Z) = \sum_\theta P(Z,\theta)$, then,
$$
P(Z) = [pf(x_1), \ (1-p)f(x_2)]
$$
So then
$$
P(Z) = P(Z,\theta) = \begin{cases}
    pf(x_1),& Z=x_1\\
    (1-p)f(x_2),& Z=x_2
\end{cases}
$$
I'm not sure if making use of the probability matrix is the right approach to take and if this is correct. Though using matrices does seem handy in visualization, I don't know if this would generalize well. Further, would $Z$ be considered a random vector? Apparently, the variance of $Z$ is $Var(Z) = p\sigma_1 + (1-p)\sigma_2$, but I'm not sure how to find that.
Any help, guidance, comments would be appreciated :) Thank you.
Comment: The question is meaningless without some independence assumptions. None of these quantities can be computed in general.
Comment: Hmm.. Im not sure how independence/dependence would affect the problem. I suppose considering the independence case would be a start.
Answer: As defined, $Z$ is continuous, with a probability density function given by the Law of Total Probability.
Now, presuming the Bernoulli random variable, $\theta$, is independent of the Normal random variables, $X_1$ and $X_2$...
$$\begin{align}f_{\small Z\mid\theta}(z\mid\theta)&= f_{\small X_1}(z)\,\mathbf 1_{\theta=\theta_1}+f_{\small X_2}(z)\,\mathbf 1_{\theta=\theta_2}\\[2ex] f_{\small Z,\theta}(z,\theta)&= p\,f_{\small X_1}(z)\,\mathbf 1_{\theta=\theta_1}+(1-p)\,f_{\small X_2}(z)\,\mathbf 1_{\theta=\theta_2}\\[2ex]f_{\small Z}(z) &=f_{\small Z,\theta}(z,\theta_1)+f_{\small Z,\theta}(z,\theta_2) \\[1ex] &= p\,f_{\small X_1}(z)+(1-p)\,f_{\small X_2}(z)\\[1ex]&=\left(\dfrac{p\,\mathrm e^{-z^2/2\sigma_1^2}}{\sigma_{\small 1}\sqrt{2\pi~}}+\dfrac{(1-p)\,\mathrm e^{-z^2/2\sigma_2^2}}{\sigma_{\small 2}\sqrt{2\pi~}}\right)\,\mathbf 1_{z\in\Bbb R}\end{align}$$

NB: The bold faced $\bf 1$ is an indicator function, equalling $1$ when the event occurs and $0$ otherwise.
$$\mathbf 1_E=\begin{cases} 1 &:& E\\0&:& \text{otherwise}\end{cases}$$


When to include interactions in a glm?

Question: I am using glms to model if the inclusion of a predictor variable is significant in the ability to predict the dependent variable bu comparing residual deviances between the models:
Analysis of Deviance Table

Model 1: count ~ variable
Model 2: count ~ origin + variable
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       524     706.39
2       523     699.06  1    7.328 0.006789 **
---

However when I include an interaction term between originand variable I lose the significance:
Analysis of Deviance Table

Model 1: count ~ variable
Model 2: count ~ origin + variable + origin * variable
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       524     706.39
2       520     699.05  4   7.3378   0.1191

I imagine this is to do with the degrees of freedom. So my question is, how do I make the choice to include the interaction term of not?
The inclusion of the term barely changes the AIC:
Including it: 1380.3
Not including it: 1374.3

Edit to add model outputs:
Inclusion of the interaction:
Call:
glm(formula = count ~ origin + variable + origin * variable,
    family = "poisson", data = count_filt_FGT_free)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.6877  -0.6963  -0.3758   0.0306   5.1953

Coefficients:
                                 Estimate Std. Error z value Pr(>|z|)
(Intercept)                      0.217065   0.110432   1.966   0.0493 *
originfree                      -0.247836   0.166794  -1.486   0.1373
variableDuplication              0.136576   0.151107   0.904   0.3661
variableKnown_target            -1.634130   0.273254  -5.980 2.23e-09 ***
variablePhylogeny                0.125880   0.151485   0.831   0.4060
originfree:variableDuplication   0.008606   0.227974   0.038   0.9699
originfree:variableKnown_target  0.040197   0.408914   0.098   0.9217
originfree:variablePhylogeny     0.005696   0.228629   0.025   0.9801
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 842.35  on 527  degrees of freedom
Residual deviance: 699.05  on 520  degrees of freedom
AIC: 1380.3

Exclusion of the interaction:
Call:
glm(formula = count ~ origin + variable, family = "poisson",
    data = count_filt_FGT_free)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.6883  -0.7015  -0.3766   0.0267   5.1789

Coefficients:
                     Estimate Std. Error z value Pr(>|z|)
(Intercept)           0.21399    0.09162   2.336  0.01950 *
originfree           -0.24084    0.08929  -2.697  0.00699 **
variableDuplication   0.14036    0.11314   1.241  0.21479
variableKnown_target -1.61631    0.20329  -7.951 1.85e-15 ***
variablePhylogeny     0.12838    0.11346   1.131  0.25784
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 842.35  on 527  degrees of freedom
Residual deviance: 699.06  on 523  degrees of freedom
AIC: 1374.3

Comment: Something that I encounter is if the inclusion of a variable influences the outcome, even if that influence is through an interaction. Consequently, I compare the model that only has one variable (say `origin`) to the model that has both variables and the interaction. Does this sound like what you want to do? (I am a different Dave from the user who posted.)
Comment: @Dave Is that not effectively what I have done? Or are you suggesting drop origin from model 2 also?
Answer: First note that count ~ origin + variable + origin * variable, does not make sene and will be reduced by the software to count ~ origin + variable + origin:variable
The output from the anova and AIC both suggest that the interaction term is not needed in your model.
The guiding principle for variable selection should be the underlying theory of the data generating process, not a statistical test based on arbitrary thresholds of p values.
Comment: Does this answer your question ? If so, please consider marking it as the accepted answer, and if not please let us know why.
Comment: thank you for this response. Does not including the interaction term reduce my understanding of the model as then I can only see changes in estimates between `origin` at it's reference level and `variable`categories? Where as including it also shown me differences for estimates when `origin`at its other levels for all `variable`levels? I have added some model output to illustrate what I mean.
Comment: My reason for this concern is as when I exclude the interaction we see the inclusion  of origin has some evidence for increasing the predictive ability of the model. With that being the case I want to identify if a `variable` category is driving this.
Comment: There is no evidence for an interaction effect, so the effects you see in the model without interaction are independent of the other variable.
Comment: ah okay that makes sense. Just to clarify. The interaction is showing the estimations for `origin` free against all other `variable` levels and excluding it just shows me estimations for `origin` at reference level and all `variable`levels along with `origin` free against `variable` reference level?
Answer: First of all, origin * variable = origin + variable + origin:variable. So, perhaps, when you evaluate count ~ origin + variable + origin * variable you're checking 2 times the same thing (count ~ origin + variable + origin + variable + origin : variable).
Then, my suggestiong would be to use model 2 as count ~ origin + variable + origin : variable.
If this is not a problem (because the code of the analysis of deviance is clever). I would suggest two options:

Strictly follow the AIC criteria.
Split your data in training-test samples, and check the fit and/or predictions over the test sample (with some error measurement) for all the models that you want to compare.

Whatever your option is, be sure to be transparent of the method that you'll use.
(P.S. I'm not the same "Dave" that commented the original post. Fun fact :P)
Comment: Thanks for the reply Dave. For some reason R wont let me use this format: `count ~ origin + variable + origin : variable` But I think the glm code is clever and notices this.

When to include interactions in a glm?


How to change the name of site only for the developers?

Question: I am new on Drupal 8 , in order to change the site name and the slogan , I want to change the site name just for the developers used my website
is there any way to do that?
I have implemented a code but I want to do it for just developers , is there any hook any way to do that?
<code>$config = \Drupal::service('config.factory')->getEditable('system.site');
$config->set('name', "XXXXXXX");
$config->save();

</code>
Comment: You could put `$config['system.site']['name'] = 'Foobar';` in your settings.php.
Answer: The most common way to use a settings.local.php file that is outside of your git repo.  Each developer can use this to setup their local environment with local DB, etc.
I tend to have a settings.local.php.example file in the repo that dev can copy to their settings.local.php file.
This file can contain any Drupal overrides you want, e.g.: As Leymannx said:  <code>$config['system.site']['name'] = 'Foobar'</code>.
See the docs on overrides for some details.
Drupal also has an example of settings.local.php.
You can also use this to do things like turn off caching and security checks locally.
NOTE: I think the current settings.php files automatically include a test / load for the settings.local.php file.  If not, just search for how to make sure it gets loaded.


mix-blend-mode scroll lag issues

Question: Just using 'mix-blend-mode:overlay' on a text element and it causes my browser to scroll really slow while the text is in the screen view. As soon as you scroll past the text item, the scroll goes back to butter smooth.
The lag effect, which affects both chrome and firefox is solved if I remove the mix-blend-mode.
Has anyone else had a similar problem with mix-blend-mode?
Comment: Don't do much web work but do you have something expensive to process in the background behind the foreground text element, like a massive image or something that is drawn in an expensive procedural fashion (ex: through client-side script)?  In general drawing the actual text should be quite cheap here but it's possible that the blending mode requires repeatedly processing whatever is in the background that the text is being composited over. So probably if there's a bottleneck somewhere, it has to do with what's behind the text, and one possible way to speed this up is to optimize that...
Comment: ... for example, splitting up whatever is behind the text into smaller sections (ex: image slices on which you draw overlaid text instead of one massive image).
Comment: Thanks.. I've removed the bg and just added a solid color but didn't seem to help.. hmm I'll keep trying a few things but any suggestions are welcome :)
Comment: I can confirm this. In my case is `mix-blend-mode: muliply` on absolutely positioned `:after` pseudoelements (on images). Huge performance drop in FireFox while scrolling (on Chrome it is OK).
Comment: Experience the same issue in Chrome 61. I had one image with mix-blend-mode on the page and my framerate for all animations dropped to 5fps
Answer: Not sure if this will help you in your case, but I had a 'transform: scale(-1);' set on element that had 'mix-blend-mode' enabled. When I removed the transform the performance was silky smooth! So, if you're using any sort of 'transform' I'd remove it and look for an alternative solution if possible.
It may also help if you set 'isolation' property to the layer beneath, as per example here: https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode#HTML_example
Comment: +1 for suggesting isolation, fixed a very similar issue I was having where I couldn't remove the transform from the element!

mix-blend-mode scroll lag issues


How do I change the default product on the "Add to cart" form with combined products

Question: How can I set for example the mp3 as first item?
Now it takes the products (product reference) from a product display node and display it in order of product creation.
In this example the "CD" was created before "MP3", but I want to be able to always display MP3 before CD.
I use a view with an add to cart field and the option "Attempt to combine like products on the same line item in the cart." checked.
Answer: That checkbox you've mentioned is irrelevant, if I understand your request properly. The Add to Cart form assumes whichever product you reference first is the default product when it first builds the form (i.e. it has a product reference field value delta of 0).
Comment: Yes It will take the product reference field with delta 0. The question is how do I make it take the delta 1?
Comment: Well, the simplest thing to do would be to just change the way you're creating products so your desired default is delta 0. If that's untenable in your current situation, then use hook_commerce_product_reference_default_delta_alter() as documented in commerce_product_reference.api.php.


vuejs - pass scope templates down multiple child-levels

Question: I'm building a table with vue, and I use slots for customized formatting. F.e. the table (which is a component), uses a thead-component, where each th is a scoped/named-slot. Specifing a template for the slot only works from parent to child though (or so it seems - vm.$scopedSlots is empty for the thead-component).
This is the outline of what it looks like:
// in index.html
<my-table :data="data">
  <template name="col1-header" props="column">
    {{ column.name }}
  </template>
</my-table

// in my-table component
<template>

    <my-thead :columns="columns">
    </my-thead>
    // tr: v-for over data

</template>

// in my-thead component
<template>

      <slot :name="column.name + '-header'" :item="column" v-for="column in columns">
        {{ column.name }}
      </slot>

  </thead
</template>

Using the template has no use, since it only seems to apply to my-table rather than my-thead. The only way to use the slots defined in my-thead is if I add templates in the my-table-component, but I need to specify them outside of the component.
Is there a way to pass the template that gets specified when using my-table to the my-thead component? As I already mentioned, I tried using vm.$scopedSlots, but this property is read-only and can't be set on the my-thead component. I can access the $scopedSlots of the parent vm though. I also tried using slot and template in the my-table-component to somehow pass on the template to the child, but that didn't work either.
Answer: I had to create a github issue for this problem. As per the comments, there are multiple ways of dealing with this:
Pass the slots to the child, by using a render function, as shown below, and setting the scopedSlot property, or by using a property to pass the scopedSlots, as shown here. Or use the in version 2.2.0 added provide/inject mechanisms to set the scopedSlots (which I haven't tried yet).
render (h) {
  return h('child', {
    scopedSlots: this.$scopedSlots
  })
}


Compare file and remove duplicate

Question: I have two file:
File 1.txt
email@example.com
firstname.lastname@example.com
firstname.lastname@example.com
email@example.com
File 2.txt
firstname.lastname@example.com
email@example.com
email@example.com
firstname.lastname@example.com
email@example.com
firstname.lastname@example.com
I want first detect duplicate and then delete duplicate from File1.
How to do.
Answer: If you read both into their own List<string> then you can do this:
// file1 is a List<string> representing each line of file1
// file2 is a List<string> representing each line of file2
List<string> file1WithoutDupes = (from line in file1
                                  where !file2.Contains(line)
                                  select line).ToList();

And you won't end up merging the two lists.
Answer: One another solution is by using an hash table.
Load entries from first file in hash table having keys = file entries.
Then before inserting entries from second file check if the keys already exists or not.
Answer: Provided you don't already have the contents of the files in a list, here's how you could do it:
var file1 = File.ReadAllLines(file1Path);
var file2 = File.ReadAllLines(file2Path);
var dupes = Array.FindAll(file1, line =>
    Array.Exists(file2, line2 => line2 == line));
var noDupes = Array.FindAll(file1, line =>
    !Array.Exists(dupes, line2 => line2 == line));
File.WriteAllLines(file1Path, noDupes); // write back to file1

However, if you have the contents of file1 and file2 stored in a List<string>, you could write:
// Option #1: LINQ, returns results
var dupes = file1.Intersect(file2);
var noDupes = file1.Except(dupes);
File.WriteAllLines(file1Path, noDupes.ToArray());

// Option #2: generic collection methods
List<string> dupes = file1.FindAll(item => file2.Contains(item));
file1.RemoveAll(item => dupes.Contains(item)); // affects original list
File.WriteAllLines(file1Path, file1.ToArray());

In .NET 4.0 you should be able to use the File.ReadLines method, which returns IEnumerable<string>, and have more flexibility than the string array returned by File.ReadAllLines. Also, the WriteAllLines method is overloaded to accept an IEnumerable<string>, which would allow us to drop the ToArray() call seen in the above snippets.
EDIT: note that in both code samples you could skip the dupes part and go straight to determining the results of noDupes by using file2 instead of the dupes variable in the Array and LINQ approaches, respectively. I left it in for clarity if you needed to refer to the dupes.
Answer: If I understand correctly, you want the lines on file 1 that are not present in file 2. Try this then:
var lines1=File.ReadAllLines("File1.txt");
var lines2=File.ReadAllLines("File2.txt");
var file1OnlyLines=lines1.Except(lines2).ToList();

Compare file and remove duplicate