Graph of polytope and hyperplane

Question: Suppose that $P$ is a compact and convex polytope in $R^d$ and let $G$ be the graph of $P$ ($V(G)$ are the vertices of $P$ and $E(G)$ are the $1$-dimensional faces - for example polyedral graphs are the graphs of polytopes in $R^3$ http://en.wikipedia.org/wiki/Polyhedral_graph)
By Balinski's theorem (http://en.wikipedia.org/wiki/Balinski%27s_theorem) we know that those graphs are $d$-vertex-connected (http://en.wikipedia.org/wiki/Connectivity_%28graph_theory%29).
But I don't know how to prove something stronger. Suppose that we are given a hyperplane $L$ which splits $P$ into two parts. Let $x$, $y$ be two vertices located in the same part of $P$. I would like to prove that there exists a path in $G$, between $x$ and $y$, such that the path uses only vertices from the same part of $P$.
Answer: Say $L^+$ is the closed half-space of $L$ containing $x$ and $y$.
For each vertex $v$ of $P \cap L^+$,
consider $d(v,L)$, the distance from $v$ to $L$.
Since there are finitely many vertices, some vertex or vertices will have the maximum distance
from $L$. If there's more than one vertex with the maximum distance,
then clearly their convex hull $F$ is a face of $P$ (no vertices can lie beyond the hyperplane, parallel to $L$, containing $F$.) Otherwise, let $F$ be the unique vertex with maximum distance from $L$.
If $x$ and $y$ are in $F$, then we are done: a path exists from $x$ to $y$ within $F$.
Otherwise, assume $x \notin F$ and we'll connect $x$ to a vertex of $F$. (Then we're done, since we can connect $y$ to $F$ the same way.)
For all the vertices $w$ adjacent to $x$, some must have $d(w,L) > d(x,L)$.
Otherwise, all the edges incident to $x$ lie in the half-space $\{z : d(z,L) \leq d(x,L)\}$, where we are using the notational convenience that points in $L^-$ have negative distance from $L$. But then all the 2-faces incident to $x$ also lie in that half-space, etc, so that all the faces incident to $x$ lie in that half-space; but $P$ is contained in the cone spanned by $x$ and its incident faces, a contradiction.
So: some edge at $x$ moves further from $L$. Similarly, at every vertex in $P \cap L^+$ but not in $F$, some edge moves further from $L$. Keep choosing these edges and you will construct an edge-path from $x$ into $F$.
Do the same thing for $y$ and we are done.

Graph of polytope and hyperplane


Gensim with MinGW

Question: I seem to be one of the many people struggling to install gensim on windows. I have trawled through countless forums but the errors poster there never appear to match my errors. So hopefully someone can point me in the right direction!
I am running Windows Server 2012 R2 Standard 64-bit. I have installed MinGW & Anaconda 2.2.0 (64-bit), which comes with Python 2.7.9.
I have added a file distutils.cfg into C:\Users\Sam\Anaconda\Lib\distutils  with the contents:
[build]
compiler=mingw32

I have added C:\MinGW\bin to my Environment variables.
If I install gensim using pip I do not get any errors, until I try to run Word2Vec when I get the error:
C:\Users\sam.passmore\AppData\Local\Continuum\Anaconda\lib\site-packages\gensim\models\word2vec.py:459: UserWarning: C extension com
pilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training.

So I have uninstalled gensim and tried to re-install using the mingw32 compiler, but this gives me this error:
python setup.py build --compiler=mingw32
c:\users\sam.passmore\appdata\local\continuum\anaconda\lib\site-packages\setuptools-14.3-py2.7.egg\setuptools\dist.py:282: UserWarni
ng: Normalizing '0.11.1-1' to '0.11.1.post1'
running build
running build_ext
building 'gensim.models.word2vec_inner' extension
C:\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -Igensim\models -IC:\Users\sam.passmore\AppData\Local\Continuum\Anaconda\include -IC:
\Users\sam.passmore\AppData\Local\Continuum\Anaconda\PC -IC:\Users\sam.passmore\AppData\Local\Continuum\Anaconda\lib\site-packages\n
umpy\core\include -c ./gensim/models/word2vec_inner.c -o build\temp.win-amd64-2.7\Release\.\gensim\models\word2vec_inner.o
gcc: error: ./gensim/models/word2vec_inner.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
command 'C:\\MinGW\\bin\\gcc.exe' failed with exit status 1
setup.py:82: UserWarning:
********************************************************************
WARNING: %s could not
be compiled. No C extensions are essential for gensim to run,
although they do result in significant speed improvements for some modules.
%s

Here are some hints for popular operating systems:

If you are seeing this message on Linux you probably need to
install GCC and/or the Python development package for your
version of Python.

Debian and Ubuntu users should issue the following command:

    $ sudo apt-get install build-essential python-dev

RedHat, CentOS, and Fedora users should issue the following command:

    $ sudo yum install gcc python-devel

If you are seeing this message on OSX please read the documentation
here:

http://api.mongodb.org/python/current/installation.html#osx
********************************************************************
The gensim.models.word2vec_inner extension moduleThe output above this warning shows how the compilation failed.
  "The output above this warning shows how the compilation failed.")
building 'gensim.models.doc2vec_inner' extension
C:\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -Igensim\models -IC:\Users\sam.passmore\AppData\Local\Continuum\Anaconda\include -IC:
\Users\sam.passmore\AppData\Local\Continuum\Anaconda\PC -IC:\Users\sam.passmore\AppData\Local\Continuum\Anaconda\lib\site-packages\n
umpy\core\include -c ./gensim/models/doc2vec_inner.c -o build\temp.win-amd64-2.7\Release\.\gensim\models\doc2vec_inner.o
gcc: error: ./gensim/models/doc2vec_inner.c: No such file or directory
gcc: fatal error: no input files
compilation terminated.
command 'C:\\MinGW\\bin\\gcc.exe' failed with exit status 1
setup.py:82: UserWarning:
********************************************************************
WARNING: %s could not
be compiled. No C extensions are essential for gensim to run,
although they do result in significant speed improvements for some modules.
%s

Here are some hints for popular operating systems:

If you are seeing this message on Linux you probably need to
install GCC and/or the Python development package for your
version of Python.

Debian and Ubuntu users should issue the following command:

    $ sudo apt-get install build-essential python-dev

RedHat, CentOS, and Fedora users should issue the following command:

    $ sudo yum install gcc python-devel

If you are seeing this message on OSX please read the documentation
here:

http://api.mongodb.org/python/current/installation.html#osx
********************************************************************
The gensim.models.doc2vec_inner extension moduleThe output above this warning shows how the compilation failed.
  "The output above this warning shows how the compilation failed."

I have exhausted all options I can think of or find, so if anyone could give some advice it would be much appreciated.
Comment: It's not the cause of  your error, but you need to use MinGW-w64 if you want to build C extensions for the 64-bit version of Python.
Comment: Hi both, Thanks for your comments. Another issue I am having is that I do not have administrative privileges. I have tried installing MinGW-w64 as @Ross Ridge suggests- however I can only find versions that require that privilege. Do you know of installers that do not require this?
Comment: If you download the `.tar.bz2` version of the MinGW-w64 you should be able to unpack it to your own directory somewhere. You'll have somehow convince setup.py  to use that version instead of the one installed in `C:\MingGW\bin`.
Answer: I managed to solve this after using conda install for gensim, rather than pip.
conda install gensim

I am not sure what other steps I have included above have contributed to the answer, but this was the last thing I did before I no longer was getting the 'Install a C compiler and reinstall gensim for fast training.' message.
During my research in trying to solve this problem I saw that the most common methods were adding the lines
[build]
compiler=mingw32

to the distutils.cfg file as well as ensuring MinGW is in your path. Also ensuring that the MinGW bit version is the same as your python version.

Gensim with MinGW


Explanation that the prior predictive (marginal) distribution follows from prior and sampling distributions

Question: While I have a vague intuition that this makes sense, I am interested in the formal demonstration that the prior predictive distribution in Bayesian inference is equal to the integral over $\theta$ of the product of the prior distribution $p(\theta)$ and the sampling distribution $p(y|\theta)$, such that:
$$p(y) = \int_{\theta} p(\theta) p(y|\theta)\text{d}\theta.$$
Could one say that the integral makes the distribution unconditional (i.e. it removes the conditionality) by integrating over all possible parameters?
If so, is there a more formal explanation?
Comment: This is not a proof but a definition. This is what we call the _prior_ predictive (or the marginal), as opposed to the _posterior_ predictive$$p(y|y_0)=\int p(\theta|y_0)p(y|\theta)\text{d}\theta,$$where $y_0$ is the observation.
Comment: Another way of explaining why "predictive": if you want to predict the behaviour of anything related with the random variable associated with $p(y|\theta)$, you need to generate first a value of $\theta$ from the prior $p(\theta)$ before you can generate a realisation $y$ from $p(y|\theta)$.
Answer: The equation follows from the definition of marginal distribution:
$$
p(y) = \int_\theta{p(y, \theta)}
$$
And, from factoring the joint probability of data and parameters into conditional probabilities, like so: $$p(y, \theta) = p(y|\theta)p(\theta)$$
(If this is confusing, divide both sides by $p(\theta)$ to get the familiar definition of conditional probability.)
More plainly, and as referenced in comments, the prior predictive distribution is the Bayesian term defined as the marginal distribution of the data over the prior: It denotes an interpretation of a particular marginal distribution.
Answer: Yes it removes the conditionality. Prior Predictive is for predictive a new value BEFORE the sample has been gathered. The only information we have at this stage is our belief about the Prior, $p(\theta$) and sampling distribution i.e. $p(y_{new}|\theta)$.
After the sample has been gathered, we have new information i.e. the likelihood. Hence, now we can predict based on Posterior Predictive Distribution $p(y_{new}|y_{data})$.


IN and OUT instructions

Question: i just want to make sure that i got that right.
when i use the IN and OUT instructions in x86.
the CPU sends the port address to the right I/O controller, how does it know which one is the right one ? it knows by looking up the I/O address space, which basically contain a range of port addresses that correspond to an I/O controller.
so let's say the port addresses 0x1000-0x2000 are for the "disk controller"
and the port address 0x3000-0x4000 are for "network controller"
if i send the port address 0x1003 then the cpu will send the port address to the "disk controller".
then the I/O controller receives that port address it then looks up it's internal mapping table in it's memory to determine what register(could also be a memory) of the I/O device is associated with that port address.
then it request to read or write(depends on the instruction) to one of these I/O device registers.
Comment: Logically at least, all devices listen for all ports, and only respond to certain ports.  So the CPU doesn't have to know what device will respond before it sends a message on the external bus, that's why there's only I/O address space shared by all devices.  On really ancient systems like 8086, there was only one external bus for memory and I/O, with one control line to indicate if it was an I/O or a memory access.  On modern systems with PCIe, something probably does have to figure out where to send a request since it's not a shared bus, it's point-to-point links.
Answer:
if i send the port address 0x1003 then the cpu will send the port address to the "disk controller".

Your idea how in and out work is not completely correct:
I don't know about modern CPUs, but using a simpler CPU (such as the 80386) in and out are variants of the mov instruction accessing different addresses:
If you see the M/IO pin just as an additional address wire, addresses are 33-bit values, not 32-bit values.
The instruction out dx, al does exactly the same as a mov [edx], al instruction with only one difference: out dx, al writes to the (33-bit) address [0x100000000+dx] while mov [edx], al writes to the address [edx].
Now what does the CPU do in this case?
The CPU uses 33 wires (the address bus) to send the address and 8 wires (the data bus) to send the value of al. It uses additional wires to send the information that some 8-bit value is being written.
There is some circuit outside the CPU that checks which address is which device:
This circuit "knows" that addresses 0...0x9FFFF are RAM and when you write to one of these addresses (e.g. you write to address 0x1234 using mov [0x1234],al), the circuit sends an electrical signal to the RAM.
If you write to address 0x100001234 (e.g. using out dx, al with dx=0x1234), the circuit sends some signal to the disk controller (in your example).
Let's say the disk controller uses only addresses 0x1000...0x10FF (actually: 0x100001000...0x1000010FF).
In this case, the disk controller will typically only use the low 8 bits of the address and ignore the other address bits. So if you write to address dx=0x11FF, this has the same effect as writing to address dx=0x10FF.
In this case, only 8 of the 33 signals holding the address coming from the CPU need to be connected to the disk controller.
The disk controller receives the following signals:

The 8 signals containing the value of al (from the CPU)
The 8 low bits of the address being accessed (from the CPU)
The signals saying that an 8-bit value is being written (from the CPU)
The signal saying that the disk controller is being accessed (from the circuit outside the CPU)
Comment: Interesting, I didn't realize that it was implemented by setting a 33rd bit.
Comment: @puppydrum64 Officially, the `M/IO` pin is a "control pin" and not an "address pin". However, actually it is nothing but a 33rd address pin.

IN and OUT instructions


How to select two elements at once and make my code affect both of them with querySelector?

Question: I'm adding my website a night mode. And I've done most of the coding part and while started to change some parts about design. I'm going to need to change my hrs in the HTML and add them a solid border to make them visible in the dark mode. Here's my code:

  Night Mode

What I want to do is that add a class to my hrs as well with this code using querySelector but once I added the hrs to the code it only affects body and not the hrs. What can I do to make the code affect both of them.
The code bellow is working but I also found an eaiser way to do what I wanted. To CSS code I simply added this code and it is working nice as well.
body.dark hr {
border: 1px solid #808080;
}

Comment: change your styles .when body has class dark you can add required styles `hr`
Comment: And how do I do that? I have already created a CSS rule about hr, I just need to add the dark class to "hr"s.
Comment: then you should select hr not the body `document.querySelector('hr')`
Comment: The thing is that I can already select one. What I want is that select both of them, add the same class to both of them with the same code.
Comment: Could you use `querySelectorAll` and use a for loop to iterate through all the `hr`s?
Comment: What is the expected result of `localStorage.setItem('mode', (localStorage.getItem('mode') || 'dark') === 'dark' ? 'light' : 'dark'`?
Comment: To check what is the mode that is stored and make it dark mode if not stored.
Answer: You can use .querySelectorAll() and .forEach() method of NodeList
document.getElementById("moon").addEventListener("click", e => {
  localStorage.setItem('mode', (localStorage.getItem('mode') || 'dark') === 'dark' ? 'light' : 'dark'
  const elements = document.querySelectorAll("body, hr");
  elements.forEach(el => {
    if (localStorage.getItem('mode') === 'dark') {
      el.classList.add('dark')
    } else {
      el.classList.remove('dark')
    }
  })
})

Comment: Should I still be using this in HTML since I have been using other in HTML?
Comment: @BurakSümer Is there a need to use global attribute event handler? Whether to use global attribute event handler or not in HTML is a matter of opinion. That is your own decision. See [When did using global event handler attributes within html become "considered bad practice"? \[duplicate\]](https://stackoverflow.com/questions/36388227/)
Comment: With this code I'm having an issue called " ',' expected. ts(1005)" on const. I have researched and updated TS. What might be causing the problem?
Comment: Found the problem, there was a ) missing before the const. This code seems like working for me. Thank you.


Finding a measure on $[0,1]$

Question: Let $X$ be a metric space with $\sigma$ algebra Borel $B(X)$ and let $\mu$ be a mesure on $X$. We define the support of $\mu$ to be the smallest set $F$ such that $F$ is closed and $\mu(F^C)=0$.
Let $F\subseteq [0,1]$ be a closed set. show there is a measure on $[0,1]$ such that her support is $F$
How to approach this question? What is the intuition beyond the support of a measure?
Comment: @Keen-ameteur Do you actually know something that you think is a proof or are these just random guesses? In fact with either version the union of countably many null sets need not be a null set.
Comment: @DavidC.Ullrich edited, this is how the question was written
Comment: Why not define $\mu(A)=1$ if and only if $A\supseteq F$?
Comment: @Keen-ameteur How do you propose to show countable additivity?
Comment: Okay, what if we revise it to $\mu(A)=\infty$ if $A\supseteq F$ and $\mu(A)=0$ if $A\nsupseteq F$? He didn't add any other assumptions, so it seems to me that there maybe be trivial degenerate measures which satisfy this.
Answer: Take $\mu(A)=\infty$ if $A\cap F\ne \emptyset$ and $0$, otherwise.
Comment: 1. For any $A\in [0,1]$ we have $\mu(A)\geq 0$ 2. $\mu(\emptyset)=0$ 3. how do we show sigma additivity?
Comment: @newhere $\sigma$-additivity is trivial here.
Comment: I can not see it :(
Comment: Suppose you have a disjoint collection of sets $\{A_i\}$. If $\mu(A_i)=0$ for all $i$, then $\bigcup_{i\ge 1}A_i \cap F=\emptyset$ and $\mu\!\left(\bigcup_{i\ge 1}A_i\right)=0$, otherwise $\mu\!\left(\bigcup_{i\ge 1}A_i\right)=\infty$.
Answer: Sort of the same idea as the other answer, but a finite measure:
As often, define a measure $\delta_p$ concentrated at $p$ by $$\delta_p(E)=\begin{cases}1,&(p\in E),
\\0,&(p\notin E).\end{cases}$$
Say $(p_j)_1^\infty$ is a countable dense subset of $F$ and let $$\mu=\sum_{j=1}^\infty 2^{-j}\delta_{p_j}.$$

Finding a measure on $[0,1]$


Orthogonal projection of p on hyperplane M is given by $p - \langle v,p\rangle v$

Question: I am trying to solve this exercise:
The hyper-plane $M$ contains the zero vector and has a normal vector v with $||v|| = 1$. Show that the orthogonal projection of $p$ on $M$ is given by  $p - \langle v,p\rangle v$.
So, the normal vector stands orthogonal on the Hyperplane $M$. But I don't see how to get started.
Thanks for any help!
Answer: The orthogonal projection of $p$ onto $M$ will be some vector $p+t v$ such that
$p+tv \in M$.
Compute $t$.
You know that $M$ has the form $M=\{ x | \langle v ,x \rangle = \alpha \}$
for some $\alpha$. Since $0 \in M$, you can figure out $\alpha$.


Get the value of a field of the taxonomy term referenced with an Entity Reference field

Question: I have a taxonomy vocabulary "Partners", with boolean field field_1. When I create a user, I attach to it a term from the vocabulary "Partners" with an Entity Reference field. Is there a way to get the value of the field_1 field of that term and to bind it to the user?
(In the first case I need this value to limit the access to a page created by Page Manager to the users whose partners has the field_1 field filled with the value 1. I suppose I need the field value also for other cases later.)
The relation of the user and the partner could be made in another way, too, if it will be easier, more intuitive or more practical.
Answer: The user is already associated with the boolean field via the taxonomy term.
For example, load your user's account:
global $user;
$account = user_load($user->uid);

Now load your taxonomy term:
$partner = taxonomy_term_load($account->taxonomy_field_name[LANGUAGE_NONE][0]['tid']);

And then get the boolean value of field_1:
$boolean_value = $partner->field_1[LANGUAGE_NONE][0]['value'];

Comment: Thank you. As I am not a programmer, I'm not sure if I manage to handle this, but I'll try.


Laravel eloquent order by subquery

Question: I have a problem with ordering by columns in subquery (lastname, firstname).
I already tried this code as suggested by other posts:
->with(['customer' => function ($query) {
            $query->orderBy("lastname", "asc")
                ->orderBy("firstname", "asc");
        }])

Here my full code, but it doesn't work.
return Membership::forCompany($companyId)
        ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
        ->where(function ($query) {
            $query->where('end_date', '>=', Carbon::now()->toDateString())
                ->orWhereNull('end_date');
        })
        ->with('federation')
        ->with(['customer' => function ($query) {
            $query->orderBy("lastname", "asc")
                ->orderBy("firstname", "asc");
        }]);

Here the relationships:
In customer model I have:
public function memberships() {
   return $this->hasMany('App\Models\Membership');
}

In Membership model I have:
public function customer() {
    return $this->belongsTo("App\Models\Customer");
}

Comment: You can't apply order on result's by it's subquery. It's totally wrong approach. Order by could be use with joins. If you would like to apply order by in the above situation... you should query from the customer table.
Comment: Thanks @VikashPathak but I need to order sometimes by lastname (customer table), sometimes by end_date (memebership table). How can I solve this labyrinth?
Comment: please share the relationships.
Comment: I added relationships on my original post. Thanks :)
Answer: Try orderBy() with join() like:
$memberships = \DB::table("memberships")
                    ->where("company_id", $companyId)
                    ->where(function ($query) {
                        $query->where('end_date', '>=', Carbon::now()->toDateString())
                            ->orWhereNull('end_date');
                    })
                    ->join("customers", "memberships.customer_id", "customers.id")
                    ->select("customers.*", "memberships.*")
                    ->orderBy("customers.lastname", "asc")
                    ->get();

dd($memberships);

Let me know if you are still having the issue. Note, code not tested! so you may need to verify by yourself once.
Comment: @Swim89 does this help?

Laravel eloquent order by subquery


Tensors: Simplifying system of linear equations by choosing new coordinate system

Question: My textbook starts with the following linear system, where $\mathbf{J}$ and $\mathbf{E}$ are tensors:

$$J_x = \sigma_{xx} E_x + \sigma_{xy}E_y + \sigma_{xz}E_z$$
$$J_y = \sigma_{yx}E_x + \sigma_{yy}E_y + \sigma_{yz}E_z$$
$$J_z = \sigma_{zx}E_x + \sigma_{zy}E_y + \sigma_{zz}E_z$$

It then goes on to say the following:

Based on the basic symmetry of the equations of motion, Onsager demonstrated that the tensor is symmetric, i.e., $\sigma_{ik} = \sigma_{ki}$, so that the nine coefficients are always found to reduce to six. Taking advantage of this symmetry argument and multiplying the expressions by $E_x$, $E_y$, and $E_z$, respectively, one obtain on adding:
$$J_x E_x + J_y E_y + J_z E_z = \sigma_{xx} E^2_x + \sigma_{yy}E^2_y + \sigma_{zz} E^2_z + 2 \sigma_{xy} E_x E_y + 2\sigma_{yz} E_y E_z + 2 \sigma_{zx} E_z E_x$$
To make the mixed terms on the right side of the equation disappear, one chooses a new coordinate system with the coordinates along the principal axes of the quadratic surface represented by this right-hand side (rhs) term, and in this new coordinate system one obtains:
$$J_x = \sigma_1 E_x; J_y = \sigma_2 E_y; J_z = \sigma_3 E_z,$$
where $\sigma_1$, $\sigma_2$, and $\sigma_3$ are the principal conductivities.

I don't understand how the author went from
$$J_x E_x + J_y E_y + J_z E_z = \sigma_{xx} E^2_x + \sigma_{yy}E^2_y + \sigma_{zz} E^2_z + 2 \sigma_{xy} E_x E_y + 2\sigma_{yz} E_y E_z + 2 \sigma_{zx} E_z E_x$$
to
$$J_x = \sigma_1 E_x; J_y = \sigma_2 E_y; J_z = \sigma_3 E_z$$?
I would greatly appreciate it if people could please take the time to clarify this.
Answer: Another way to phrase this is that $J = \Sigma\cdot E$ where $J$ and $E$ are 3-vectors and $\Sigma$ is a $3\times3$ symmetric matrix: the $\cdot$ represents the matrix-vector product.
What the argument reduces to in terms of linear algebra (assuming this is familiar to you) is that, since $\Sigma$ is symmetric, it can be diagonalised: ie, written on the form $\Sigma = UDU^{T}$ where $U$ is a rotation matrix and $D$ is diagonal. Another way to formulate this is that there are eigenvectors $u_1, u_2, u_3$ (which can be picked to be orthogonal and of unit length) with eigenvalues $\sigma_1, \sigma_2, \sigma_3$, ie $\Sigma\cdot u_i = \sigma_i u_i$.
If you express the vectors in the basis $u_1, u_2, u_3$, ie $E=E'_1u_1+E'_2u_2+E'_3u_3$ where $E'_i$ are the coefficient of $E$ in this basis, you get $\Sigma\cdot E = \sigma_1E'_1u_1+\sigma_2E'_2u_2+\sigma_3E'_3u_3$.
Also writing $J=J'_1u_1+J'_2u_2+J'_3u_3$ in this basis, you see that $J'_i=\sigma_i E'_i$.
What may make the presentation in the book a bit confusing (which I have changed) is that they use $E_x, E_y, E_z$ as the coordinates first in the regular coordinate system, and then again in the eigenvector-based coordinate system: ie, the $E_x$ in the original equation is not the same as the $E_x$ in the final equation.
The use of the square expression for which they find the principal axes is just a way to derive at the existence of eigenvectors and eigenvalues: the principal axes correspond to the eigenvectors.
Comment: https://en.wikipedia.org/wiki/Principal_axis_theorem#Motivation


Isotope and Views Load More error - Javascript breaks on some Ajax calls

Question: I've created a view with Views Isotope and Views Load More contributed modules.
The objective is to have a Isitope grid that we can zoom in/out on items.
After long time to get it working I got a strange bug:

When I load the page it works fine.
When I click on load more first time the grid breaks.
When I click on load more second time the grid works fine.
When I click on load more third time the grid breaks.
And so on...

See it working here.
This is my javascript:
(function ($) {
Drupal.behaviors.skeletonthemeCustomBehavior = {

attach: function (context, settings) {

  // $grid.isotope('destroy');

  var $grid = $('#isotope-container').isotope();

  $grid.isotope({
    masonry: {
      columnWidth: 10
    }
  });

$grid.on( 'click', '.isotope-element', function() {
  if ($( this ).hasClass( 'gigante' )) {
    $( this ).toggleClass('gigante');
  } else {
    // change size of item by toggling gigante class
    $( '.isotope-element' ).removeClass( 'gigante' );
    $( this ).toggleClass('gigante');
  }
  $grid.isotope('layout');
});

$('#destroy').bind( 'click' ,function(e) {
  event.preventDefault(e);
  $grid.isotope( 'destroy' );
});

  $('.relayout').bind( 'click' ,function(e) {
    event.preventDefault(e);
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });

  $( document ).ajaxComplete(function() {
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });
}

};
})(jQuery);

Comment: The last time I checked Views load more was pretty buggy. I'm using Jquery IAS for load more functionality. You may also want to check Isotopia module  https://www.drupal.org/sandbox/nyariv/2223945
Answer: I did noticed that after the 1st load more, you can't zoom in, then after the 2nd load more zoom works, and after the 3rd load more zoom doesn't work again.
I believe it's your code. You need to add the zoom in/out part again inside the ajaxComplete function
(function ($) {
Drupal.behaviors.skeletonthemeCustomBehavior = {

attach: function (context, settings) {

  // $grid.isotope('destroy');

  var $grid = $('#isotope-container').isotope();

  $grid.isotope({
    masonry: {
      columnWidth: 10
    }
  });

$grid.on( 'click', '.isotope-element', function() {
  if ($( this ).hasClass( 'gigante' )) {
    $( this ).toggleClass('gigante');
  } else {
    // change size of item by toggling gigante class
    $( '.isotope-element' ).removeClass( 'gigante' );
    $( this ).toggleClass('gigante');
  }
  $grid.isotope('layout');
});

$('#destroy').bind( 'click' ,function(e) {
  event.preventDefault(e);
  $grid.isotope( 'destroy' );
});

  $('.relayout').bind( 'click' ,function(e) {
    event.preventDefault(e);
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });

  $( document ).ajaxComplete(function() {
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
    // adding the zoom in/out after ajax complete
       $grid.on( 'click', '.isotope-element', function() {
       if ($( this ).hasClass( 'gigante' )) {
       $( this ).toggleClass('gigante');
       } else {
       // change size of item by toggling gigante class
       $( '.isotope-element' ).removeClass( 'gigante' );
       $( this ).toggleClass('gigante');
       }
       $grid.isotope('layout');
       });
  });
}

};
})(jQuery);

Comment: Hi, I did what you sugested(No Sssweat) and the behaviour now is diferent. First and second clicks break the zoom functionality of the grid, third and fourth clicks the grid works fine. Fifth click breaks again. I'm going crazy here.
Comment: humm so weird. Try using [Views Infinite Scroll](https://www.drupal.org/project/views_infinite_scroll) module, it has a load more link option.
Answer: It works fine for me. (your site) However if you want to prevent default behaviour you can indeed call e.preventDefault(); You just might want to try omitting the parameter.
new answer, now I understand the question better:
1) Drupal has an old version of jQuery by default with enough code that breaks. An easy solution without breaking modules that depend on the old version is adding a new version og jQuery with drupal_add_js() and then write
var nQuery = $.noConflict(true); //or any name you want
nQuery('#divID').click();//and use it like the $

2) jQuery selectors don't work on elements that are generated (bij XHR /ajax for example) But if you use the .on (a delegate) it does work:
$(document).on('click', '.relayout', function () {
    //show big pic
});

3) combining those:
 nQuery(document).on('click', '.relayout', function () {
        //show big pic
 });

Comment: Sorry but it's not working fine.
Comment: when he said `the grid breaks` he meant the zoom in/out does not work, not the grid structure as one might think if you don't pay close attention to the `The objective is to have a Isitope grid that we can zoom in/out on items` part.
Comment: ah exactly where I went wrong
Comment: @MasterD I've made a new answer based on the additional info I got. Please try it.
Comment: I'm already using the lastest jQuery version with jQuery update module. Your hack didn't work.


How to use Dart HTML's DirectoryEntry and DirectoryReader classes?

Question: I need an example for using the DirectoryEntry and DirectoryReader classes in Dart:HTML. The following code read an image file from img directory and load it as an image element in the browser.
import 'dart:html';

void main() {
  ImageElement image = new ImageElement(src: 'img/car.jpg');
  querySelector('body').append(image);
}

Here is the structure of my webapp directory:

I need to dynamically list and use the content of img directory.
Comment: What do you mean with 'Dart:HTML'? In the browser?
Comment: The classes are part of dart:html library in api.dartlang.org: [DirectoryEntry](https://api.dartlang.org/docs/channels/stable/latest/dart_html/DirectoryEntry.html) and [DirectoryReader](https://api.dartlang.org/docs/channels/stable/latest/dart_html/DirectoryReader.html)
Comment: I want to use these two classes to list the content of an image directory in my webapp.
Comment: So you want to run this on the server? Then you should use `dart:io` not `dart:html`
Comment: No. The client-side webapp has an image directory whose content can be accessed by specifying their filename. Instead of hard-coding the filenames in my app, I want to dynamically list and use the content of that directory.
Comment: I have added an example code and image of the directory to my question for illustration.
Answer: 'img/car.jpg' is a file on the server which the browser requests from your server when you assign the path to an  element.
DirectoryEntry and DirectoryReader work on the client only.
What you need is that the server provides an API (e.g. JSON) that lets you request a list of files/directories from your server (e.g. of your img directory).
If your server has directory listing enabled you could alternatively send a simple HTTP request with /img as URL and parse the response.
Comment: The APIs for `DirectoryEntry` and `DirectoryReader` are part of the FileSystem API for accessing and manipulating a client-side file system. Consider it almost like Cookies or indexeddb with more features. See this for more information: http://www.html5rocks.com/en/tutorials/file/filesystem/
Comment: I suspected this but was not sure. Thank you for the clarification. I'll use an HTTP request.


How to verify a jQuery plugin is compatible with latest version of jQuery?

Question: Are there any tools that can verify whether a jQuery plugin will be compatible with the latest version of jQuery?
Once a large number of jQuery plugins are selected and in use, an unknown number of dependencies can develop.  It would be nice to upgrade jQuery, however not all plugins remain supported or provide consistently architected upgrades.
The only option seems to be adhoc manual regression testing.  It would be nice to have a strategy for dealing with this issue.
Answer: Try to use that plugin with new jquery library
Comment: This does not take into account the numerous configuration options of some plugins which may work under one configuration but not another.  It doesn't consider the complexity of testing the large number of plugins that gradually work their way into an app, and it does not respect the question. I will wait a few days to see if a serious answer is provided.  If nothing appears, I will accept this answer which basically implies that random adhoc testing is indeed the only option at this point.


Identifying $C_c(X)$ with $C_0(U)$ for $U \subseteq X$ open, relative compact

Question: I am currently learning for an exam and came across this sentence in a functional analysis script:
Let $X$ locally compact space, $C_c(X) = \{f:X\to \mathbb C: \operatorname{supp}(f) \text{ is compact}\}$ and $C_0(X) = \{f:X\to \mathbb C: \forall \epsilon > 0 \ \exists K \subseteq X \text{ compact} : \vert f(x) \vert \leq \epsilon \text{ on } X \setminus K\}$.
"For an open and relatively compact subset $U \subseteq X$ the space $C_0(U)$ can
be identified naturally with a subspace of $C_c(X)$."
I really don't see how that works "naturally". I would appreciate some help :)
Comment: Well, every function in $C_0(U)$ is supported in $\overline{U}$, which is compact, right?
Comment: Nice result! ${}$
Comment: @Prahlad Vaidyanathan That makes sense. Thanks, I can't say why I haven't seen that. It's pretty obvious. :)
Comment: @Pralhad, Yaddle: a function  $f\in C_0(U)$ is only defined on $U$ and  $supp f\subset U$  **is not compact in general!**.  The subtle point is that $f\notin C_c(X)$ since $f$ is not defined outside of $U$.
Answer: Let $C_{\bar U}(X)\subset C_c(X)$ be the set of continuous functions on $X$ with support in $\bar U$.
Then there exists an extension map   $$ext:C_0(U)\to   C_{\bar U}(X):f\mapsto extf$$ obtained by extending $f$ to points $x\in X\setminus U$ by decreeing that $(extf)(x)=0$.
We also have a restriction map $$res:   C_{\bar U}(X)\to C_0(U):f\mapsto res f=f\vert U                        $$
 The map $ext$ thus identifies, as required,  $C_0(U)$ with the subspace $C_{\bar U}(X)$ of $C_c(X)$ the inverse identification being given by $res$.
Note carefully
We have $C_0(U) = \{f:U\to \mathbb C: \forall \epsilon > 0 \ \exists K \subseteq U \text{ compact} : \vert f(x) \vert \leq \epsilon \text{ on } U \setminus K\}$
So, a function $f\in C_0(U)$ has  $\operatorname {supp}f\subset U$ but that support is not compact in general: try to find an example!
Be sure to understand that point while reading the answer.


Surfaces and revolution

Question: How can i determine the equation of a surface that is obtained from the revolution of the line r around the line s
Given line r
$$
\left\{
\begin{array}{c}
2x-y-3=0 \\
x+z-2=0 \\
\end{array}
\right.
$$
And line s :
$$
\left\{
\begin{array}{c}
x-y-2=0 \\
z=1 \\
\end{array}
\right.
$$
Is there a specific method that i can use it to solve questions like this ?
The parametric equation of line r
$$
\left\{
\begin{array}{c}
X=2-t \\
Y=1-2t \\
Z=t
\end{array}
\right.
$$
For s :
$$
\left\{
\begin{array}{c}
X=2-t\\
Y=0-t \\
Z=1
\end{array}
\right.
$$
And if there is a method can i use it also to obtain a surface that generated from a rotation of a line r for example around z-axis or x-axis ?
I have an exam soon :(
Comment: The surface you will obtain is a hyperboloid of one sheet (https://en.wikipedia.org/wiki/Hyperboloid). Are you familiar with such a (quadric) surface ?
Comment: Yes i'm familiar with this lesson , but how did you know ?
Comment: It is a classical generation of this surface, which is therefore a **ruled** surface.
Comment: In this particular case, it is a degenerated hyperboloid, i.e., a **cone** because the two lines share a common point $(1,-1,1)$. If it hadn't been the case, the key operation is to find the points $R \in r, S \in S$ such that RS is the smallest line segment.
Answer: We are here in a special case : lines $r$ and $s$ meet at point $C:=(1,-1,1)$.
Therefore the generated surface is a cone.
Considering your parametric representation of line $s$, i.e.,
$$
\left\{
\begin{array}{c}
x=2-t\\
y=0-t \\
z=1
\end{array}
\right.,
$$
it is clear that $\vec{d}:=(-1,-1,0)$ is a directing vector of this line.
The cone can be described as the set of points $M(x,y,z)$ such that the following absolute value is a constant (this constant will be explicitated afterwards):
$$\left|\dfrac{\vec{CM}}{\|\vec{CM}\|}.\vec{d}\right|=k \ \ \iff \ \ (\vec{CM}.\vec{d})^2=k^2 \|\vec{CM}\|^2 \tag{1}$$
(the dot is a dot product). (1) is equivalent to :
$$((x-1)(-1)+(y+1)(-1)+(z-1)(0))^2=k^2((x-1)^2+(y+1)^2+(z-1)^2)\tag{2}$$
which is the looked for equation of the cone.
But what is the value of $k$ ? It is obtained by taking a particular instance of $M$, call it $M_0$, belonging to line $r$. If we take for example $M_0:=(2,1,0)$, we get :
$$k=\left|\dfrac{\vec{CM_0}}{\|\vec{CM_0}\|}.\vec{d}\right|=\dfrac{3}{\sqrt{6}}.$$
It remains to expand (1)...
Comment: Thank you so much Jean Marie...I appreciate your effort
Answer: A very general approach to finding an implicit equation for this surface is to parameterize it and eliminate the parameters. Working with your parameterizations $\mathbf r(t)$ and $\mathbf s(t)$ of the two lines, we let $\mathbf v = \mathbf r(t) - \mathbf s(0)$ and set $\mathbf k$ to the normalized direction vector of $\mathbf s$. By Rodrigues' rotation formula, $\mathbf r(t)$ rotated about $\mathbf s$ through an angle $\theta$ is $$\mathbf s(0)+\mathbf v \cos\theta+(\mathbf k\times\mathbf v)\sin\theta+\mathbf k(\mathbf k\cdot\mathbf v)(1-\cos\theta),$$ which expands to $$\begin{align} x &= \frac12\left(5-3t+(t-1)\cos\theta+\sqrt2(t-1)\sin\theta\right) \\ y &= \frac12\left(1-3t-(t-1)\cos\theta-\sqrt2(t-1)\sin\theta\right) \\ z &= 1+(t-1)\cos\theta-\frac1{\sqrt2}(t-1)\sin\theta.\end{align}$$ Adding twice the second equation to the third produces $2y-z=2-3t-\frac3{\sqrt2}(t-1)\sin\theta$, from which $$\sin\theta = -{\sqrt2(2y+z+3t-2)\over3(t-1)}.$$ Similarly, we get $$\cos\theta = {2x+2z+3t-7\over3(t-1)}$$ from the first and last equations, whereupon $$2(2y+z+3t-2)^2+(2x+2z+3t-7)^2 = (3(t-1))^2.$$ Finally, adding the first two equations produces $x+y=3(1-t)$, which we can substitute back (and change signs to make it prettier) to get $$2(x-y-z-1)^2+(x-y+2z-4)^2 = (x+y)^2.$$ Observe that the parenthesized expressions on the left-hand side describe a pair of perpendicular planes that contain $\mathbf s$, while the parenthesized expression on the right is the plane perpendicular to $\mathbf s$ that passes through the vertex of the cone. This suggests a perhaps easier way to arrive at an equivalent equation.
We know that the two lines intersect at $(1,-1,1)$, so the surface is actually a cone—a degenerate hyperboloid. If we choose a coordinate system with origin at the center of the hyperboloid and $Z$-axis aligned with $\mathbf s$, the canonical Cartesian equation in that coordinate system has the form $$X^2+Y^2=\alpha Z^2.$$ Transforming back to the original coordinate system can be accomplished by substituting suitably normalized expressions for the coordinate planes into this equation.
The $X$-$Y$ plane here has equation $x+y=0$, and for the other two coordinate planes we can choose any convenient pair of orthogonal planes that include $\mathbf s$. The two given defining planes of $\mathbf s$ happen to be orthogonal, so we can use their equations. The cone equation is therefore, after normalizing these plane equations, $$\frac12(x-y-2)^2+(z-1)^2=\frac\alpha2(x+y)^2.$$ Substituting another known point on $\mathbf r$ into this and solving for $\alpha$, we arrive at $$3(x-y-2)^2+6(z-1)^2=(x+y)^2.$$ I'll leave it to you to verify that this is equivalent to the equation arrived at above by the eliminating parameters.
If the hyperboloid were not degenerate, we could do something similar. Its canonical equation is $${X^2+Y^2\over a^2}-{Z^2\over c^2}=1.$$ The origin of the coordinate system is the center of the hyperboloid, which is the closest point on $\mathbf s$ to $\mathbf r$. The parameter $a$ is the distance between the two lines, and $c$ can be found by substituting some other known point on $\mathbf r$ besides the closest one to $\mathbf s$ into this equation. In this coordinate system, the rulings of the hyperboloid take the form $(a\cos\alpha,a\sin\alpha,0)+t(-a\sin\alpha,a\cos\alpha,\pm c)$, so another way to find $c$ might be to map $\mathbf r(t)$ into this coordinate system, but I think that's going to require more work.

Surfaces and revolution


Why are all the tabs except MBeans disabled in JConsole? (when using "Remote Process" connection)

Question: I'm trying to connect to JConsole on a server running:
java version "1.6.0_0"
OpenJDK Runtime Environment (IcedTea6 1.4.1) (6b14-1.4.1-0ubuntu12)
OpenJDK 64-Bit Server VM (build 14.0-b08, mixed mode)
When I connect using the "Local Process" method, all the tabs are enabled -- when I connect via the "Remote Process" method, it connects just fine, but the only tab that is enabled is the MBeans tab.
Answer: Normally, the local process method will connect you to the JVM's platform MBeanServer, which is where all the management MXBeans are registered that supply all the data for those other tabs. However, when you connect remotely (and this varies by application/application server), may applications tend to spin up one or more of their own MBeanServers which do not have the management MXBeans registered. Consequently, JConsole cannot render those tabs because it does not see the MXBeans required to do so.
If you see a bunch of application server specific MBeans in JConsole when you connect remotely  (like jboss, or weblogic) then that's what's going on.
Comment: Can the platform mbean server be accessed instead of the application server one(s)?


Simplifying two constructors into one

Question: Below is my response object which I use to construct a response and send it back to caller as I have a system which is on request/response pattern.
public class DataResponse {

    private String response;
    private DataErrorEnum error;
    private DataStatusEnum status;

    public DataResponse(String response, DataErrorEnum error, DataStatusEnum status) {
        this.response = response;
        this.error = error;
        this.status = status;
    }

    public String getResponse() {
        return this.response;
    }

    public DataErrorEnum getError() {
        return this.error;
    }

    public DataStatusEnum getStatus() {
        return this.status;
    }
}

Now some times in my application code, I am creating response object like this:
new DataResponse(null, errorEnum, statusEnum);

As you can see I am explicitly setting null which is ok but sometimes it cause confusion that which field is null so I decided to create another constructor in DataResponse class like this:
public class DataResponse {

    private String response;
    private DataErrorEnum error;
    private DataStatusEnum status;

    public DataResponse(String response, DataErrorEnum error, DataStatusEnum status) {
        this.response = response;
        this.error = error;
        this.status = status;
    }

    // new constructor
    public DataResponse(DataErrorEnum error, DataStatusEnum status) {
        this.response = null;
        this.error = error;
        this.status = status;
    }

    public String getResponse() {
        return this.response;
    }

    public DataErrorEnum getError() {
        return this.error;
    }

    public DataStatusEnum getStatus() {
        return this.status;
    }
}

So that I can create object now like this: By this, I don't need to send null response since that is by default in my other constructor.
new DataResponse(errorEnum, statusEnum);

Now my question is - Is there any way I can combine both of my constructor into one? Or I need to have two constructor for this always?
Comment: If by "combine both constructors into one" you mean that you want to be able to pass either two or three arguments to the same constructor, no you can't do that. What's wrong with what you've done already?
Answer: You can't combine both constructors into one.
But you can declare main constructor that construct your fields, and the other constructors just call it, for example.
    // new constructor
public DataResponse(DataErrorEnum error, DataStatusEnum status) {
    this(null, error, status);
}

public DataResponse(String response, DataErrorEnum error, DataStatusEnum status) {
    this.response = response;
    this.error = error;
    this.status = status;
}

Comment: Thanks, that's what I was trying to ask.
Answer: If response is always null then the second constructor holds good. Both the constructor are doing similar functionality. Its better to have one constructor for better readability of code.

Simplifying two constructors into one


Como definir a cor da borda de uma tabela sem CSS?

Question: Existe alguma maneira? Não quero CSS nem externo, nem interno, apenas html puro. Segue meu codigo.

Data:

@Model.DatFormulario

Answer: Assim use bordercolor da tag 'table':

Data:

@Model.DatFormulario

Comment: E para manipular a borda de uma tr ou td? Não consegui fazer da mesma maneira que a table utiliza.
Comment: Fizeram uma alteração para mim, usando o bgcolor, obrigado @MatheusBessa
Comment: No firefox fica com borda 3D colorida.
Comment: A única forma que eu achei para ficar com efeito `collapsed`, é usar o truque do background/cellspacing.
Answer: Uma das formas (e que funciona consistentemente em todos os browsers) é definir o background da tabela para uma cor, colocar um cellspacing, e então colorir o fundo de cada célula de branco (ou da cor que desejar), de forma que o fundo da tabela apareça entre as células, e fique parecendo uma borda:

        HTML table borders without CSS

        cellspacing="2"

        bgcolor="#ff6600"

jsfiddle
Referência:
HTML table borders without CSS
Answer: Você pode utilizar o atributo bordercolor

This is the color of the border (if you have the border turned on - that is if you use the border attribute in your TABLE tag).

Que em tradução livre:

Esta é a cor da borda (se você tiver a fronteira ligado - ou seja, se você usar o atributo fronteira na sua tag TABLE). No Netscape, isto só irá colorir o fundo e borda direita.

E você ainda pode definir o padrão para as cores claras e escuras das bordas utilizando os atributos  bordercolorlight and bordercolordark.
Estes atributos se aplicam apenas à borda externa da tabela, não existe nenhum atributo html para se manipular as bordas de tr e td, neste caso será necessário utilizar css.
Answer: Exemplos:
HTML com atributo style para uso CSS interno.

HTML com atributo bordercolor para troca de cor.

bordercolor - usar uma cor em hexadecimal ou nome em inglês (red, black, green, etc).
Comment: @Eduardobrj Sim, foi isso que eu entendi.
Comment: Bom, talvez ele não queria usar arquivo externo CSS, portanto usar o atributo style é considerável. E também o CSS consegue formatar muito bem uma table.
Answer: É possível! Basta colocar dentro da tag table:

Fonte: http://www.criarweb.com/artigos/88.php


pfSense allow one part of the network access to VPN Tunnel

Question: I Have two pfSense routers (Router 1 and Router 2)
ROuter 1 is VPN Server for other routers and  in his LAN network are different servers like domain server, mail server...
Router 2 is WiFI captiv portal. We have one subnet 192.168.1.0/23 and all visitors connected on WiFi can surf on internet.
Is there possibility, and what will be best practise to allow our private laptops to connect to same WiFi and have access to VPN TUnnel and Router 1 and servers?
Topology
Answer: Once you have created the tunnel, you will get a new interface, for which you can create custom rules. If no rules are set, pfSense will block any traffic. As such you need to specifically allow certain devices. Create an alias for the VPN network (172.16..) on Router 1, and another one for the allowed clients.
On router 2, under rules, in the tunnel interface, allow traffic from the VPN network to the whitelisted clients. On the LAN interface, allow traffic from the whitelisted clients to the VPN network.


Lines projective space

Question: I have a question concerning the answer of Georges Elencwajg in Lines in projective space
There he states that the line  $\overline {AB}=\mathbb P(\Lambda)\subset \mathbb P^n$ has  its points of the form $[ua_0+vb_0:\ldots :ua_n+vb_n] \quad (u,v \in k, $ not both zero ).
My question is: Why? I can't see the connection betwwen this form and the vectors which spane a plane, I would really appreciate if someone could explain this a little bit better to me.
Answer: Let's imagine this for $\mathbb P^2$. Your setup is something like this: the affine point $(x, y)$ corresponds to the projective point with homogenous coordinates $(x, y, 1)$. This assumes the standard embedding with last coordinate $z=1$; other choices are of course possible. For homogenous coordinates, any multiple of the coordinate vector denotes the same point, so $(\lambda x, \lambda y, \lambda)$ is the same, as long as $\lambda\neq0$. To reverse the process, you dehomogenize a vector $(x, y, z)$ by first dividing by the last component to obtain $(x/z, y/z, 1)$ and the omitting the last component to end up with $(x/z, y/z)$.
Now let us imagine all of this in $\mathbb R^3$. A single homogenous coordinate vector is a point in space, but as you are not really interested in that particular vector, but instead in all non-zero multiples of that vector, you beter imagine this as a line through the origin of $\mathbb R^3$. So a point in $\mathbb P^2$ corresponds to a 1-dimensional linear subspace (i.e. a line through the origin) of $\mathbb R^3$. To turn this back into an affine point, you intersect that line with the plane at $z=1$. That point of intersection is exactly the multiple of your coordinate vector which has $1$ as it's last coordinate, i.e. it is $(x/z, y/z, 1)$.
You can perform the same considerations for objects of one dimension higher: a line in $\mathbb P^2$ is a 2-dimensional subspace (i.e. a plane through the origin) of $\mathbb R^3$. The affine interpretation of that plane can be obtained by intersecting said plane with the plane $z=1$, which yields de desired line.
So now in the $\mathbb R^3$ image, you are given two lines through the origin, and are interested in finding the plane through the origin which contains them both. This is simply the span of the directions of the lines. Intersecting that plane with $z=1$ will therefore give the line connecting the two projective points. This carries over to higher dimensions, although things become harder to visualize.
This page has a Java applet which will visualize the line connecting two points, both in the $z=1$ plane and in the enclosing $\mathbb R^3$ space. It also draws the normal of the plane, which can be computed using the cross product. The text is all in German, but the applet itself should be useful enough.
Comment: Thanks for your answer, it helped me a lot. Referring to the java application: Since $[g]=[A\times B]$ it follows that $\overline {AB}=\mathbb P(\Lambda)\subset \mathbb P^n$ has  its points of the form $[ua_0+vb_0:\ldots :ua_n+vb_n] \quad (u,v \in k, $ not both zero ).

Lines projective space


How to use pager or term limit for taxonomy_get_tree($vid)?

Question: How to use pager or how to limit terms, when using taxonomy_get_tree($vid)?
I have this code for terms generation:
<?php
$vid = 2;
$terms = taxonomy_get_tree($vid);
$max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;

foreach ($terms as $term) {
if ($term->depth == 0)
{
print "" .l("Auto Insurance for   " .$term->name,'taxonomy/term/'.$term->tid, array('attributes' => array('title' => $term->name, ), 'html' => TRUE) ). "";

}}

?>

But there are thousands of terms or sub terms. Some pages are then loading more then 20 seconds. I need to improve this situation.
Can you advice me please? Do you know some solution? Pager, Jquery, Ajax?
Answer: Add a counter into your for each statement that counts the array index and terminates after X number of items.  That'd fix it.
Comment: Well, that sounds good. But can u show me exactly how? My PHP knowledge is very poor Thank you.


Variable selection for logistic regression with separated data

Question: I have a fairly large dataset ($\approx 3 \bar{M}$ observations for a dozen candidate predictors) and I would like to perform a logistic regression on that dataset.
I have a problem of separation in that dataset so usual model can't converge. That's why I am using Firth penalization (logistf package for R) to have my model to adjust.
I would like to select the best subset of variables for my final model but I can't find the proper way to do that. I know that stepwise selection is out of question and I usually would use L1 or L2 penalized regression so that some coefficients are reduced to 0.
My problem is : the function I am using to adjust my model doesn't handle extra penalization so no Elasticnet-Firth regression.
Is there, apart from stepwise selection, another way to select my variables?
Comment: Posts bearing the Hauck-Donner Effect tag may also be of interest.
Answer: In my experience with logistic regression where $n >> p$, using $L_1$ or $L_2$ regularization on the coefficients has little to no effect on inference. Variables that are selected by $L_1$ will usually have enormous $z$-scores - suggesting they remain in any final model. Furthermore, post-selection inference, or interpretation of $p$-values after performing variable selection, is a difficult and active research field. Since you seem to have ample data, regularization only complicates things.
Instead, standard logistic regression with careful consideration of domain knowledge, collinearity, variable transformations, and quadratic/interaction terms will go a very long way. And since you have so much data, using data splitting techniques can give you further confidence in this (labor intensive) process.
Answer: We can select the most important features using H2O. With H2o we can use all of your data without sampling. one option is using GBM algorithm automatically calculates variable importance and output the absolute and relative predictive strength of each feature in the prediction task.
You can read more here


Is $\mathbb{Q} [X,Y]/[x^{20},y^{20}]$ a local ring?

Question:
Is $\mathbb{Q}[X,Y]/[x^{20},y^{20}]$ is a local ring?

My approach is to look for a maximal ideal, but got stuck how to find a single maximal ideal. Any feedback would be appreciated.
Answer: Well, $\Bbb Q[X,Y]/\langle X^{20},Y^{20}\rangle$ is a local ring.
The ideal $\langle X,Y\rangle$ is maximal in $\Bbb Q[X,Y]$, and as
$\langle X,Y\rangle^{40}\subseteq\langle X^{20},Y^{20}\rangle
\subseteq\langle X,Y\rangle$ the radical of $\langle X^{20},Y^{20}\rangle$
is $\langle X,Y\rangle$. This means that the image of $\langle X,Y\rangle$
in $\Bbb Q[X,Y]/\langle X^{20},Y^{20}\rangle$ is the unique maximal ideal.
Answer: One characterization of local rings is that they have a proper ideal $m$ whose complement consists entirely of units.
In your case, the ideal $(X,Y)$ of $\mathbb Q[X,Y]$ is a (proper) ideal containing $(X^{20},Y^{20})$ and so its image in the quotient is a (proper) ideal. Any element of the complement clearly has to be represented by some polynomial $f(X,Y)$ with nonzero constant term. Then you can write it as
$$f(X,Y) = c + Xg(X,Y) + Yh(X,Y)$$
In the quotient, $c$ is still a unit and both $X$ and $Y$ are nilpotent. As the sum of a unit and a nilpotent is a unit, we see that $f(X,Y)$ is a unit and so by the fact mentioned above this ring is local.


Select the right pathauto alias for a node

Question: I'm working on a drupal 8 project, I need to access the content type X nodes via two aliases depending on some conditions, for this I've created two Pathauto patterns using Pathauto contrib module:
path_1 --> /local/[node:title]

path_2 --> /global/[node:title]

path_1 & path_2 are supposed the machine name of those two patterns.
What are those two patterns? actually what I want to do is check if a node of type X has the checkbox field 'global' checked so use /global/[node:title] as alias for this node else use /local/[node:title].
Which hook should I implements for selecting/altering a pathauto pattern for a node? And can I use those aliases as a route for a controller?
Answer: Another option, and I find this to be preferable to altering the token because it's exposed to site builders and makes what's happening perfectly clear in the UI, is to create your own custom token that will return /global or /local for that piece of the url. You just need to implement hook_token_info and hook_tokens. This blog post walks you through the process.
Ex:
/**
 * Implements hook_token_info().
 */
function MY_MODULE_token_info() {
  $info['tokens']['node']['MY_TOKEN_ID'] = [
    'name' => t('MY TOKEN LABEL'),
    'description' => t('Return "/global" for nodes with the global checkbox checked, otherwise returns "/local".'),
    'type' => 'url-fragment',
  ];
  return $info;
}

/**
 * Implements hook_tokens().
 */
function MY_MODULE_tokens($type, $tokens, array $data, array $options, Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'node' && !empty($data['node']) && isset($tokens['MY_TOKEN_ID'])) {
    $node = $data['node'];
    $global_or_local = '/local';
    if ($node->hasField('MY_GLOBAL_FIELD') && !empty($node->MY_GLOBAL_FIELD->value)) {
      $global_or_local = '/global';
    }
    $replacements['[node:MY_TOKEN_ID]'] = $global_or_local;
  }
  return $replacements;
}

Note: I'm not sure if that logic to determine global or local is perfect, but it should be close.
Answer: Try with hook_pathauto_pattern_alter something like:

/**
 * Implements hook_pathauto_pattern_alter().
 */
function your_module_pathauto_pattern_alter(\Drupal\pathauto\PathautoPatternInterface &$pattern, array $context){
    /* @var $node Drupal\node\Entity\Node */
    //- If you want it just on update operation add $context['op'] == 'update' condition
    if ($context['module'] !== 'node' || !($node = $context['data']['node']) || $node->bundle() !== 'type_X') {
        if ($node->global) {
            $pattern->setPattern('global/[node:title]');
        }else{
             $pattern->setPattern('local/[node:title]');
        }
    }
}

Comment: On creation and update of nodes that hook update the pattern. Depends on the condition. you don't have to update it on BO, at least the new created nodes.
Comment: what does setPattern methode do exactly??
Comment: does setPattern methode update/re-generate the path matching the new pattern value or it's necessary to update/re-generate path via BO


Online learning to maximize profit

Question: I have a software which takes input as investment and gives the output as return on a particular stock. Now profit metric $x_i$ is defined as the ratio of return $g_i$ to maximum possible return $g_{max}$ at $i^{th}$ period of time.
so $x_i = g_i / g_{max}$
$g_{max}$ is constant for any period but varies from stock to stock.
Return for a particular stock at $i_{th}$ period is $g_i$ which depends on the investment $s_i$ for that period.
The relation between $g_i$ and $s_i$ varies from one period to other period.
The question is how to decide $s_i$ based on $s_{i-1}$ and $g_{i-1}$ in order to maximize $x_i$ for a particular stock . Is it possible to build an online learning mechanism to decide the value of $s_i$ based on previous data.
[note : $ 0 < g_i \leq g_{max}$ , $ s_{min} \leq s_i \leq s_{max}$ , $i_{th}$ time period is fixed ,in this case it's six months ]
Answer: If you want an "online learning algorithm", which will try to improve itself during some kind of environmental simulation instead of preparing training data in form of $(x_i,y_i)$, then this looks like a classical use case of reinforcement learning, with input values $s_{i-1}, g_{i-1}$ and some current stock info $data_i$, with reward $g_i$. This is quite wide branch of  machine learning, choice of particular method/algorithm is strongly data dependent. The most common approaches in reinforcement learning are Temporal Difference Learning and Q-learning, I suggest to look this things up.

Online learning to maximize profit


get table without Added column in sql query

Question: I have a Process table in sql server database like this:

I need to select Process if Rolename exists in to RoleTable like this:
 select ID,WorkflowXML
    from
    (
    select m.c.value('@RoleName','nvarchar(max)') as Rolename,p.*
    from Process as p
    outer apply p.WorkflowXML.nodes('/workflow/Tasks/Task[@type="start"]/TaskUsers/TaskUser') as m(c)
    ) as Pro where Pro.Rolename in
    (SELECT * from RoleTable)

In this select Rolename adds to Process. I need to only Process table. I can add Process fields (ID,WorkflowXML) to query. If I change Process table design I should edit query. This is not very good.
Is there a way to select Process table in query without adding Process fields like this?
select Pro
        from
        (
        select m.c.value('@RoleName','nvarchar(max)') as Rolename,p.*
        from Process as p
        outer apply p.WorkflowXML.nodes('/workflow/Tasks/Task[@type="start"]/TaskUsers/TaskUser') as m(c)
        ) as Pro where Pro.Rolename in
        (SELECT * from RoleTable)

Thanks.
Answer: You can join this table like:
select p.*
from Process as p
outer apply p.WorkflowXML.nodes('/Tasks/Task[@type="start"]/TaskUsers/TaskUser') as  m(c)
INNER JOIN RoleTable r
    ON r.Rolename = m.c.value('@RoleName','varchar(max)')


Writing out cdf for joint pdf

Question: Given over the region $0<x<2, 0<y<2, F(x,y)=\frac{1}{44}x^3y+\frac{3}{176}x^2y^2+\frac{1}{44}xy^3$
And we extend the its definition over the entire xy-plane:
$F(x,y)=0, x\leq0 , or, y\leq0$
$F(x,y)=1, x\ge2 , or, y\ge2$
$x\ge2, 0<y<2, F(x,y)=F(2,y)=\frac{2}{11}y+\frac{3}{44}y^2+\frac{1}{22}y^3$
$y\ge2, 0<x<2, F(x,y)=F(x,2)=\frac{2}{11}x+\frac{3}{44}x^2+\frac{1}{22}y^3$
then $F(x,y)$ is written as:
$
F(x,y)=\begin{cases}
      0 & x\leq0 , or, y\leq0\\
      \frac{1}{44}x^3y+\frac{3}{176}x^2y^2+\frac{1}{44}xy^3 & 0<x<2, 0<y<2 \\
      \frac{2}{11}y+\frac{3}{44}y^2+\frac{1}{22}y^3 &x\ge2, 0<y<2 \\
      \frac{2}{11}x+\frac{3}{44}x^2+\frac{1}{22}y^3 & y\ge2, 0<x<2 \\
      1 & x\ge2 , or, y\ge2
   \end{cases}
$
What I don't get is what order to write those functions in the cdf. Because for non joint cdf I just write them up in order of the intervals. Like in this case, obviously the 0 and 1 conditions are written at the top and bottom respectively but in this case I don't know whether I should be writing $F(x,2)$ before $F(2,y)$ as such. Cause the region is a square and I don't believe thinking in terms of what region covers the most area makes sense.
For example I don't know why it couldn't be written like this:
$
F(x,y)=\begin{cases}
      0 & x\leq0 , or, y\leq0\\
      \frac{2}{11}y+\frac{3}{44}y^2+\frac{1}{22}y^3 &x\ge2, 0<y<2 \\
\frac{1}{44}x^3y+\frac{3}{176}x^2y^2+\frac{1}{44}xy^3 & 0<x<2, 0<y<2 \\
      \frac{2}{11}x+\frac{3}{44}x^2+\frac{1}{22}y^3 & y\ge2, 0<x<2 \\
      1 & x\ge2 , or, y\ge2
   \end{cases}
$
Answer:
You probably mean $x\ge2$ and $y \ge 2$, not or, otherwise you have intersecting regions.
The order in which you define the branches does not matter whatsoever, as long as the regions of definition do no intersect.
You computed $F(x,2)$ incorrectly since this is not supposed to depend on $y$ at all and your expression does.

Writing out cdf for joint pdf


What is the mathematical symbol for a predicted value?

Question: Take a simple linear regression $y = ax + b$. Here, $y$ is predicted. In my analysis I need to compare the predicted $y$s to the actual $y$s from my data set upon which the regression was built. What diacritical mark should I use to denote the predicted $y$? ŷ, ý, or maybe $y'$? Is there a standard mathematical symbol for a predicted value? Or should I use another letter?
Comment: A good approximation is y with a circumflex (U+0177): ŷ .... but in MathJax/ LaTeX markup it looks more mathematical (the way it tends to be written by hand): $\hat{y}$
Answer: The predicted outcome is generally expressed as $\large \hat y$ - or "why - hat". You can think of the hat matrix, which "puts a hat on the $\large y$" as in $\large \hat y = H y$, the linear algebra equation that relates the observed values of the response variable, $\large y$, to the predicted values, $\large \hat y$, to make it easy to remember.
What you want to compare are the residuals: $e = \large y - \hat y = y - H y$.
Comment: Why hat?  Because, good sir, it is predicted to rain.
Comment: Exactly, residuals! That is what I am calculating and I will make sure to use $e$ for notation. @MatthewDrury That's a nice one!
Answer: Yes, there is a standard symbol for predicted value. It is $\hat{y}$. You can see that in, e. g., Introduction to Statistical Learning


Unable to load file from resources folder when running app locally

Question: Using Java 8, I have an AWS lambda function that has a flat file in the src/main/resources folder. When running on AWS, I'm having no issues. But when I run locally, my app can't find the file.
Here is what my code looks like:
    ClassLoader classLoader = getClass().getClassLoader();
    URL url =  classLoader.getResource( "./resources/forms/myform.pdf" );

This works fine for loading it when it runs as an AWS lambda, but does not work locally. When running locally, the url variable is null. When I run the code on AWS, the ClassLoader is java.net.URLClassLoader while locally it is sun.misc.Launcher$AppClassLoader. I'm not sure if this matters.
Here is my file structure if it helps:

I'm using my ControllerTest class. I'm not using the LambdaFunctionHandlerTest that was created by default by AWS. Here is all that my ControllerTest does:
public class ControllerTest {

    public static void main( String[] args ) {

        MyController controller = new MyController();
        controller.create();

    }

}

Any ideas how I can get this to work locally and on AWS? It's a maven project in Eclipse and I'm thinking the way I'm executing my controller in my test function is incorrect. Does the run configuration in eclipse need to be altered from the defaults?
Update: Changing my path to forms/myform.pdf fixed the issue running locally. However, it now fails to find the file when running as an AWS lambda function. Here is the folder structure that is created in AWS:
Comment: Files under resources folder are included in the classpath. So change the url path to URL url =  classLoader.getResource( "forms/myform.pdf" );
Comment: @Ramu, for some reason, I have to add the `./resources/` to get it to work on AWS. I'm not sure why though.
Comment: I updated my question a bit. I see that the folder structure is a bit different in AWS when the function is uploaded through Eclipse.
Comment: Did you solve it ? I am facing the same issue ?
Answer: You may check the Maven Standard Directory Layout here:
https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
All your test classes along with test resources will be compiled and placed inside target/test-classes directory. In your case getClassLoader().getResource will return the path to target/test-classes directory where forms/myform.pdf is to be stored.
By default, the test class will find resources from your test-classes directory. If they are not found in the test-classes directory, the classes folder will be searched.


stop receiving email from cron job and smtp every 15 min

Question: I have set a cronjob for every 15 mins and have also set my SMTP email, but this cron job is sending me an email every 15 min with subject as my cron command and user as "root" . so i want to stop receiving this email without disturbing my SMTP config
Answer: i just append this to my cron command
<code>/dev/null 2>&1
</code>
sources:
http://www.cyberciti.biz/faq/disable-the-mail-alert-by-crontab-command/


What determines the spot of a field goal kick in the NFL?

Question: Is there a limit to how close the ball gets spotted behind the line of scrimmage during a field goal attempt?
I regularly watch the NFL and on the field goals the holder awaits for the ball about 8 yards behind the line of scrimmage. It seems like the ball is always kicked from 8 yards behind the scrimmage no matter the yardage of the kick; ie. if it's a 20 yard attempt or a 60 yarder. Although at times this distance looks to be much closer to 7 yards than 8. Is there a rule that dictates this distance has to be respected or all teams have converged to kick about 8 yard behind the scrimmage over time?
Answer: There is no rule about the required exact distance from the line of scrimmage. It can be taken from the line itself or behind. They kick from 7 yards behind the line primarily because they're used to it.
The only rule covering this is Rule 11.4.1 Successful Field Goal (link):

a) The kick must be a placekick or dropkick made by the offense from on
  or behind the line of scrimmage or from the spot of a fair catch (fair
  catch kick). If a fair catch is made or awarded outside the inbound
  line, the spot of the kick is the nearest inbound line.
  (...)

However, because Field Goal trys have little to no margin for errors the players will do anything they can to succeed. This includes a fair distance from the LoS and always the same distance whenever possible...

A shorter distance may get the ball blocked while a longer distance is harder to snap and an unnecessary extra distance for the kick.
The snap needs to be very precise in order to give the holder the chance to place the ball correctly before the kicker arrives. That would be a difficult task if the distance is varying.

TL;DR:
It's allowed to use other distances, but it would be an unnecessary risk (and a lot of extra training work). That's why they don't do that.
Answer: There actually is a rule that applies here, and it pertains to legal formations. Field goals are kicked from a scrimmage kick formation, and in order to be a legal scrimmage kick formation, the holder must be a minimum of 7 yards behind the line of scrimmage.
While it's legal to kick a field goal from a formation that's not a scrimmage kick formation (i.e. it would still count),doing so voids all protections due the kicker, holder, and snapper. It also negates the numbering exception (NCAA: 5 linemen numbered 50-79; NFL: ends must be eligible). So even though there's no reason a kicker can't set up more than 7 yards back (a slight but low possibility for a long, low trajectory kick), you'll never see the kicker be closer than that, because of the formation rules.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


coloring a row based on the column value using pandas

Question: I have a df which looks like this
picture of the df
I want to color the row where the value of value column is 5 using pandas? how to do that?
For above example, I want to color the John and Linda row.
Comment: Do you want to color the row in Excel ? Or in your IDE i.e dataframe ?
Answer: I think if you want to apply color on particular cells, you can simply use lambda function of pandas:
df.style.applymap(lambda x: "background-color: red" if x>0 else "background-color: white")

Pandas has a Styler feature where you can apply conditional formatting type manipulations to Dataframes. Pandas Documentation.
Answer: import pandas as pd
df = pd.DataFrame()
df['Name'] = ['John', 'Doe', 'Linda']
df['value'] = [5, 9, 5]
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'bg_color': '#FF1717',
                               'font_color': '#990000'})
worksheet.conditional_format(1, 1, len(df), 1,
                             {'type': 'cell',
                              'criteria': '==',
                              'value': 5,
                              'format': format1})
writer.save()

The uploaded picture looks like Excel. It's the way to save on Excel with color.
This page will help you.
How to save pandas to excel with different colors


How to define nodes from a Hiera file in Puppet?

Question: I am using puppet and the puppet network device management module and I am trying to build my custom type.
In the built-in type for the routers configuration, you can specify a list of nodes and then the configuration inside that node:
node "c2950.domain.com" {
  Interface { duplex => auto, speed => auto }
  interface { "FastEthernet 0/1":
    description => "--> to end-user workstation",
    mode => access, native_vlan => 1000
  # [...] More configuration
}

What I am trying to do, is to move the manifest declaration of the nodes and the configuration of my custom type to a Hiera file like this one:
nodes:
  - node1
  - node2

config_device:
  node1:
    custom_parameter: "whatever1"
  node2:
    custom_parameter: "whatever2"

And then in the manifest iterate over the hiera file creating the nodes with the configuration of each node with something like (I am taking as reference this question in serverfault):
class my_class {
  $nodes = hiera_array('nodes')

  define hash_extract() {
    $conf_hash = hiera_hash("config_device")
    $custom_paramter = $conf_hash[$name]     ## TRICK lies in $name variable

    node $name {
      my_custom_device { $name:
        custom_parameter   => $device_conf['custom_parameter']
      }
    }
  }
  hash_extract{$pdu_names: }
  }
}

But for this solution I have two problems, I can not define a node inside a define and I can not parameterize a node name. So, is there any way to declare nodes from a Hiera file with their configuration inside?
Answer: Why do you want to describe all nodes in one hiera file? What makes hiera superb is its hierarchical configuration. Use separate configuration files for separate hierarchy layers and finally have separate hiera file for separate node. And all of these layers will be merged together.
Comment: I don't know if you understood me. I am not using puppet in a standard way, I am trying to use {{puppet device}} to configure devices onbehalf. I am looking for a way to place all the device configuration in one hiera file, because I don't want the people that manage the configuration of the devices to edit the manifests.


Why is the overloaded == operator function saying that 2 parameters is too many

Question: The MS Visual c++ 2010 compiler is telling me the operator== has too many parameters, but
let's it pass if I only put one. What's going on here? I got the function right out of Stroustrup's book, I"m pretty sure he knows how to overload an operator in c++.
class Book
{
    public:

    Book(){}

    Book(long long isbn,string  ttl, string  athr, int cpyrght_dt)
    :ISBN(isbn), title(ttl), author(athr), copyright_date(cpyrght_dt) {}
   //...
    const long long & Return_ISBN  () const {return ISBN;           }

    bool operator==(const Book& a, const Book & b)
    {
            return a.Return_ISBN()==b.Return_ISBN();
        }

  private:

    long long  ISBN;
    //....

  };

Answer: You defined operator== as a method (member function), so it has an implicit this argument of type Book*. Either use that or lift the definition outside the class. Since it doesn't use any private members, I'd do the latter.
Comment: @user2904033 You should declare it as a `friend` only if it needs access to non-public data members or member functions. In this case, if `Book::Return_ISBN()` is a public member function, there'd be no need to declare it as a friend
Comment: So you are  saying I have to use the "this" pointer, eg This.Return_ISBN()==a.Return_ISBN()... If I define the function outside the class do I need to declare it as a friend or like any other member function inside the class?
Answer: A two-argument operator overload goes outside of the class definition.
class Book
{
    ...
};

bool operator==(const Book& a, const Book & b)
{
    return a.Return_ISBN()==b.Return_ISBN();
}


How do I call a page within my Chrome Extension without using a dash?

Question: Chrome appears to allow users to call a page from the extension using a format similar to: \
chrome-extension://dckobaoiekjnnheocplcnkhnhhnpjcnl/OAuth/_callback.html
The problem is I am using Salesforce and for whatever reason they consider having a dash in the protocol invalid. The problem I am running into is I have to place a callback URL for the process I am working on. Is there another way to use https and something akin to Localhost or perhaps another protocol that does not contain a - in order to be able to call a page within my Chrome Extension?
Answer: If you are making a call from a background page then relative path OAuth/_callback.html should work.
Comment: The Salesforce APP won't validate a relative path either.
Comment: Assuming you've tried `/OAuth/_callback.html`, which would also work, but maybe you require a URL with FQDN, in which case you could host the page externally to circumvent this strange limitation.


Exposed Filter of Child Terms on Parent Page

Question: I'm looking for a dummy's guide on how to configure the default taxonomy term views so that I can display an exposed filter of child terms on the parent page.
Assuming I have the taxonomy structure below.

Sports

Football
Basketball
Boxing

Entertainment
Politics

I want when I'm on Sports page, there is an exposed filter where I can select either of football, basketball or boxing.
I have followed all tips I could find online but the option to add contextual filter of "Taxonomy Term: Parent term" was not available.
Comment: What do you mean "Sports page"? How many pages have you got? Isn't this just one Views? Is this about the default "Taxonomy term" Views or a custom views of your own? Does it have to be exposed filter or can it be a list of links to the sub-categories (don't assume technological details, simply state your feature description)?
Comment: It's the default "Taxonomy term" view and I meant the page display of this default view. It doesn't have to be an exposed filter, a list would do but I don't want a vertical list, an inline list of child terms would suffice.
Answer: You can create a separate Views of type Taxonomy term (not content!) display Block that is showing taxonomy term names, add the Relationship to the parent term and require it, and a Contextual filter to taxonomy term ID using that relationship.
Test it by entering parent term ID into Preview, you should see the parent's children.
Edit the Format to set the fields to display inline, or use CSS (later) to make them appear horizontally.
Then in your Content (original) Taxonomy Term views add View area into Header and choose the above Block with Inherit contextual filters option ticked.


A question regarding moment generating function

Question: The moment generating function of a real-valued random variable $X$ on a probability space $(\Omega,\mathscr A,P)$ is defined as $G_{X}(t)=E[e^{tx}]$ $(t \in \mathbb{R})$. Prove that $G_{\alpha X+\beta}(t)=e^{\beta t}G_{X}(\alpha t)$ for $\alpha, \beta \in \mathbb{R}$.
Attempt

$G_{X}(t)=E[e^{tx}]$, then
$$G_{\alpha X+\beta}(t)=E[e^{t(\alpha x+\beta)}]=E[e^{\alpha xt}e^{\beta t}]=E[e^{\alpha xt}]E[e^{\beta t}]=e^{\beta t}E[e^{\alpha xt}]=e^{\beta t}G_{X}(\alpha t).$$

Show that $G_{X+Y}=G_{X} \cdot G_{Y}$.
Attempt

$$G_{X+Y}(t)=E[e^{t(x+y)}]=E[e^{xt}e^{yt}]=E[e^{xt}]E[e^{yt}]=G_{X}(t)\cdot G_{Y}(t).$$

Questions

Are my attempts correct?
In general, does $E[XY]=E[X]\cdot E[Y]$? If yes, what conditions do the random variables $X, Y$ have to satisfy for $E[XY]=E[X]\cdot E[Y]$ to be true?
Suppose we have a random variable $X$, and $g$ is not a function of $x$, then does it follow that $E[g]=g$ for all $g$?

Thank you for your time.
Answer:
Yes.
$E[XY]=E[X]E[Y]$ means that $X$ and $Y$ are orthogonal. Independence of $X$ and $Y$ is a sufficient (but not necessary) condition for this equality to be true.
Yes, if the expectation is with respect to $X$.
Answer: Your attempts are correct if you assume that $X$,$Y$ are independent in the proof of $G_{X+Y} = G_XG_Y$. Which btw you may, since that identity doesn't generally hold for non-independent $X$ and $Y$.
In general, if $X$ and $Y$ are independent, you have $\mathbb{E}\left(f(X)g(Y)\right) = \mathbb{E}f(X)\mathbb{E}g(Y)$. You can easily see this by expanding $\mathbb{E}$ into its definition. You get (assuming that the expectation exists, and that $\mu_X$ is the distribution of $X$ and $\mu_Y$ the distribution of $Y$) \begin{align}
  \mathbb{E}\left(f(X)g(Y)\right) &= \int f(x)g(y) \,d(\mu_X\times\mu_Y)(x,y) = \iint f(x)g(y) \,d\mu_X(x) \,d\mu_Y(y)\\
&= \int g(y) \int f\,d\mu_X \,d\mu_Y(y) = \int f\,d\mu_X \int g\,d\mu_Y \\
 &= \mathbb{E}f(X)\mathbb{E}g(Y) \text{.}
\end{align}
Your point (3) is correct too. The expected value of a constant $a$, is, well, $a$.
Comment: Please replace $G_{XY}=G_XG_y$ by $G_{X+Y}=G_XG_Y$, "only if" by "if", and $\mu_x$ and $\mu_y$ by $\mu_X$ and $\mu_Y$.
Comment: @Did Done, but the complaint about $\mu_x$ vs. $\mu_X$ was a bit nitpick-ish ;-)


Como utilizar a referencia Npgsql para versões de framework menores do que 4.5?

Question: Bom, fiz uma aplicação pelo Visual Studio 2015, no Windows 7. Porém, a aplicação será utilizada futuramente, também no Windows XP. O problema, é que há uma referência "Npgsql.EntityFramework", que necessita uma versão do NETFramework maior ou igual a 4.5, que não é aceita pelo Windows XP, alguém teria uma sugestão de como resolver tal problema?
Answer: O suporte ao .NET 4.0 foi derrubado no ano passado (da data desta resposta, no caso, em 2015), na versão 3.0. Portanto, a última versão que pode ser usada é a 2.2.7.
Se usar o NuGet, não esqueça de travar a versão do pacote no arquivo packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
    <package id="Npgsql" version="2.2.7" allowedVersions="[2.2.7]" />
</packages>

Comment: Deu certo viu amigo? Muito obrigado, acabei mexendo só hoje e funcionou, foi só baixar a versão 2.2.7 do Npgsql para NET 4.0, como você disse. Muito obrigado!
Comment: Então, eu coloquei esse código, mas continuou na mesma.
Comment: O aplicativo está escrito em qual versão do *framework* .NET?
Comment: Quando eu fiz, estava na ultima versão disponível(4.6.1), porém , ao mudar para a 4, aparece o erro falando que o Npgsql é de uma versão maior(4.5+) do que o do target framework (4).
Comment: Sim, então você tem que desinstalar esta versão atual do Npgsql e colocar a 2.2.7.
Comment: @JerryMoon [Veja aqui como funciona o site](http://pt.stackoverflow.com/tour). Eu que te agradeço.


How to send firestore timestamps through FCM?

Question: I have a document in firestore which contains a timestamp field and i want to send it as payload of a firebase cloud message. I am using the admin sdk from node.js and i want to receive the message on android.
Is there a way to achieve that?
Answer: A timestamp contains two integer values, seconds and nanoseconds.  If you want to serialize that timestamp to send it to another piece of code, all you have to do is send both of those values to the other code, then reconstitute the timestamp using Timestamp constructor that takes both of those values as input.


Need a recommendation for how to organize SQL result

Question: I'm building a multi-tiered menu. So, for example, each main menu item might have 5-10 submenu items, and each of those might have 5-10 third level items. The menu items, no matter what tier they are from, are kept in a single table. The query I (currently) use to pull the data out looks like this:
SELECT *
FROM menu_items AS m1
LEFT JOIN (SELECT name AS slName, id AS slId, parent_id AS slPid FROM menu_items)
m2 ON m1.id = m2.slPid
LEFT JOIN (SELECT name AS tlName, id AS tlId, parent_id AS tlPid FROM menu_items)
m3 ON m2.slId = m3.tlPid
WHERE parent_id = 0

The result of this query visually looks like the menu I want, but now I'm thinking I may want to try and restructure so that I can stick it cleanly in an object, rather that just leaving it as a DataTable or whatever.
Here's a sample result of the query above:
For reference, sl means second level, tl means third level, etc.
{id=1, name=Industry, level=1, parent_id=0, slname=Equipment & Machinery, slid=4, slpid=1, tlname=null, tlid=null, tlpid=null}
{id=1, name=Industry, level=1, parent_id=0, slname=Food, slid=5, slpid=1, tlname=null, tlid=null, tlpid=null}
{id=1, name=Industry, level=1, parent_id=0, slname=Fabricated Metal Products, slid=8, slpid=1, tlname=null, tlid=null, tlpid=null}
{id=1, name=Industry, level=1, parent_id=0, slname=Automotive, slid=9, slpid=1, tlname=null, tlid=null, tlpid=null}
{id=1, name=Industry, level=1, parent_id=0, slname=Chemicals and Allied Products, slid=10, slpid=1, tlname=null, tlid=null, tlpid=null}
{id=2, name=Application, level=1, parent_id=0, slname=App Stuff 1, slid=11, slpid=2, tlname=null, tlid=null, tlpid=null}
{id=2, name=Application, level=1, parent_id=0, slname=App Stuff 2, slid=12, slpid=2, tlname=null, tlid=null, tlpid=null}
{id=2, name=Application, level=1, parent_id=0, slname=App Stuff 3, slid=13, slpid=2, tlname=null, tlid=null, tlpid=null}
{id=2, name=Application, level=1, parent_id=0, slname=App Stuff 4, slid=14, slpid=2, tlname=null, tlid=null, tlpid=null}
{id=3, name=Product, level=1, parent_id=0, slname=Prod Stuff 1, slid=15, slpid=3, tlname=null, tlid=null, tlpid=null}
{id=3, name=Product, level=1, parent_id=0, slname=Prod Stuff 2, slid=16, slpid=3, tlname=null, tlid=null, tlpid=null}
{id=3, name=Product, level=1, parent_id=0, slname=Prod Stuff 3, slid=17, slpid=3, tlname=null, tlid=null, tlpid=null}

So the problem is now I end up with a bunch of rows which aren't really very nicely formatted to create a Menu object out of. I'm just looking for recommendations on how to restructure. Maybe change up the sql query so get a better base set of data or maybe an idea on how to format my current SQL.
Comment: Perfect use case for a NOSQL backend, isnt it?
Comment: @SajitKunnumkal Probably so. I'm using EBeans for most of everything else -- I just don't think EBeans will support those weird nested joins on the same table. Got a recomendation for a good backend library to work with?
Comment: I will do a stored procedure that goes recursively and returns a xml or json. Depending on RDBMS can be easy or painful :-/
Answer: You could do something like:
ID   NAME            PARENT
 1   Industry        1(or null. either self referencing or null = top level)
 2   Food            1
 3   Burgers         2
 4   Application     4
 5   Software        4
 6   Product         6

In your database. Essentially, the Name loops back and your code can set it up so that it walks up the chain until the parent column is either null or references the ID of that row.
So this menu would end up looking like:
Industry
  Food
    Burgers
Application
  Software
Product

Comment: Oh, then you don't need the joins right? In your code you can walk up the chain to create the menu. You don't need the nulls for what tier it's on because the parent tells you that.
Comment: The nulls aren't for what tier it's on, they're a result of the left joins and represent the case where a menu doesn't have any submenus


Java - connecting to a SQL Server database on Linux

Question: I've downloaded and imported into my project this JDBC driver that supposedly supports Linux (albeit tested only on SUSE Linux).
What I want is to be able to use a .mdf database through Java on Linux. The queries obviously need something to run on, not simply connect to a database - if I am understanding this correctly.
I found a question on SO that seems to have valuable information concerning my issue.
So I was thinking a FreeTDS + JDBC combination. Will queries execute as expected or do I have to go use the database natively, on Windows? The latter basically crushes OS agnosticism that Java provides which I would like avoid, if possible.
The database itself isn't anything fancy, only a few tables - this is merely a school assignment, after all.
I will provide additional information, if needed.
Comment: @Venom I think you should clarify what you exactly want - your question clearly states `What I want is to be able to use a .mdf database through Java on Linux.` yet your answers to kosta's question seem to suggest you actually want to connect to a SQLServer database server.  As these are different problems with different solutions you should clarify which one you actually need...
Comment: if your project is in java and you are using JDBC driver, why would you need the FreeTDS ?
Comment: @kosta Can the JDBC driver alone be used to execute queries? If so, I'll try it that way. But how do I then connect and configure the server - port and such?
Comment: Are you really using SQL Server (on another windows machine) ? If so you could just register driver as :
Class.forName(...);
and construct your jdbc url as:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
Comment: @fvu As I mentioned this is only a school assignment and this is all quite new to me (not programming in general, just Java and its principles). I have a .mdf database (created in SQL Management Studio using T-SQL) and its .ldf log file (I guess it is needed) that are to be used in a Java app using the JDBC driver developed by MS or an alternative one. What I don't know is it is the driver alone enough to executed queries. kosta says it should be but I am bit skeptical about that. I don't even know where to put the aforementioned files because SQL Servers stores them in its own default path.
Comment: @Venom no, you'll need a server to run that database on (and also see my remark, it's pretty unusual to shuttle database files between servers).  Is it your choice to do all of this under Linux, or was that part of the assignment?
Comment: @venom look [here](http://serverfault.com/questions/31105/opening-mdf-files) for some info on using an mdf file by attaching it to an installed SQL server instance.
Comment: @fvu That's what I was afraid of. So, that MS JDBC driver was meant to connect a Java app to an SQL Server instance running on a remote Windows server?. That makes sense, if it's true. That wasn't mentioned in the assignment because it is assumed one should use exclusively Windows, which is quite sad to be honest. It defeats the whole purpose of Java, but there are alternatives like MySQL or PostgreSQL - the only problem being I am unfamiliar with their syntax or principles. Well, back to Windows then...
Comment: @venom see my edit, there may be some useful pointers.  If I were you I'd copy the database into like you already mentioned MySQL or Postgres (easy to do using [Squirrel](http://squirrel-sql.sourceforge.net/)) or a lightweight pure Java embeddable database like [H2](http://www.h2database.com/html/main.html).  95% of the SQL you need will be the same, so don't be too afraid of syntax differences.
Comment: `It defeats the whole purpose of Java`  well, not really.  They (MS) offer a multiplatform ***client*** in Java for their database server, but as besides database servers they also sell operating systems, it's understandable that their server infrastructure runs under their operating systems....
Comment: @fvu I was a bit too harsh there, they did develop the driver for connect-ability but their approach definitely diminishes running things locally as many apps do, I'm sure. Again, assuming I understand the whole process of interoperability regarding these multiple technologies.
Answer: An mdf file can be an old (JET based) Microsoft Access database file, so a JDBC driver for SQL Server, a totally different product, isn't going to help you much.  Here on SO there are a couple of posts that explain how to use the JDBC-ODBC bridge to access Access databases via the ODBC driver detour, but since you specifically mention Linux that's not going to help you.
I see two possible (free) approaches:

use the open source jackcess package that allows Java programs across platforms to open, read and write MS Access database
transfer the content of the MSAccess database file to some database that has native Java drivers (that is, most of them that are not MS Access).

However, an mdf file could also be a SQLServer database, but using that database under Linux is also going to be quite tricky, as you'll need some edition of SQL Server to open it - see here for some details on how to "attach" such an mdf file to an installed instance of SQLServer - but to my knowledge there is no edition of SQL Server that runs under Linux.  So, unless you can find some Windows machine to run SQLServer on, and then connect to it using the JDBC driver you have both options mentioned before may be valid alternatives (ie, option 1 = copy your data into an MSAccess file and access that file with jackcess or option 2, copy the data into some Linux-tolerant database with a decent JDBC driver and use that)
Comment: I beg to differ on the mdf file : it's also the type of file that is "typically" produced and used by SQL Server. See there : http://stackoverflow.com/questions/1175882/what-is-an-mdf-file
Comment: @Nevoris I based my explanation on what OP said, ie that he has an .mdf file and as I think it's pretty uncommon to just give someone the datafile of a SQLServer - you'd rather get a dump file of some sort - I narrowed it down to an MSAccess database. But as of now it's still unclear whether he wants to connect to an SQL server, or wants to use that mdf file he got somewhere - also see my request for clarification from OP below their question.
Comment: True, I was being picky because you seemed quite assertive about the file, and it might have misled Venom. Let's wait for more explanations :)
Comment: @Nevoris see the new comments - I'll leave the answer as-is for now, but I'll edit it to show clearly that I'm talking about the MSAccess variant of mdf files - it may serve a future visitor.
Comment: MDB is Access. MDF is SQL Server.
Answer: Some people have been mislead by my question (I am not a native speaker of English, could be that), the database was meant to be run locally (explicitly not on a remote server) which simply cannot happen with the SQL Server + Linux combination. Wine is a possibility, but that is just too much hassle. So, the solution is either to simply use SQL Server on Windows or use an alternative cross-platform RDBMS like MySQL.
Nevertheless, I'll accept fvu's edited answer and would like to thank other users for the time they've invested in their own answers.