How to check for Grouping field in Views submodule?

Question: I'm developing on the Views Datasource module to enable grouping by field (not field aggregation). I've now got the output format that I want, but I don't know what variable the Grouping Field setting is stored in. I want to check if a grouping field is selected, and then assign the field's name as an array key if it is.
views-views-json-style-simple.tpl.php:
// TODO Enclose everything in an if statement, conditional
//   on a grouping field being selected

$grouped = array();

foreach ($rows["nodes"] as $nodenum => $nodearray) {
  // TODO Replace "building" with variable representing user-
  //   selected field.
  // Variable names will obviously change too.
  $building = $nodearray["node"]["building"];
  foreach ($nodearray["node"] as $cprop => $cvalue) {
    // TODO Replace "building" with grouping field variable
    if ($cprop != "building") { // Ignore grouped field
      $grouped[$building][$cprop][$nodenum] = $cvalue;
    }
  }
}

$rows = $grouped; // Pass back to existing code

The above code takes the $rows output by views, and reformats the array right before it goes to _views_json_json_encode. The idea is to take the default output of Views Datasource:
{
  "nodes" : [
    {
      "node" : {
        "name" : "Energy Services Performance Contract (ESCO)",
        "geometry" : "48.7366, -122.486",
        "description" : "This project was initiated In order to advance Western's sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
        "building" : "BH"
      }
    },
    {
      "node" : {
        "name" : "Energy Services Performance Contract (ESCO)",
        "geometry" : "48.7378, -122.486",
        "description" : "This project was initiated In order to advance Western's sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
        "building" : "WL"
      }
    },
    {
      "node" : {
        "name" : "Wilson Becoming Skyscraper",
        "geometry" : "48.7378, -122.486",
        "description" : "Wilson will have 708 floors added to it, becoming the tallest building ever.",
        "building" : "WL"
      }
    }
  ]
}

and turn it into
{
  "BH" : {
    "name" : [
      "Energy Services Performance Contract (ESCO)"
    ],
    "geometry" : [
      "48.7366, -122.486"
    ],
    "description" : [
      "This project was initiated In order to advance Western's sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus."
    ]
  },
  "WL" : {
    "name" : {
      "1" : "Energy Services Performance Contract (ESCO)",
      "2" : "Wilson Becoming Skyscraper"
    },
    "geometry" : {
      "1" : "48.7378, -122.486",
      "2" : "48.7378, -122.486"
    },
    "description" : {
      "1" : "This project was initiated In order to advance Western's sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
      "2" : "Wilson will have 708 floors added to it, becoming the tallest building ever.\n"
    }
  }
}

Comment: It depends on the stage you want to check for it. For example table descriptions cannot have it at all. Could you show minimal working example of code, with the place you need to know grouping marked with `// TODO`?
Answer: My question assumed that Views Datasource includes parent view format options such as grouping fields, but it does not. Rather than call all of the parent fields from the Views defaults, I copied only the field definition from views_plugin_style.inc to views_plugin_style_json.inc, within the options_form function.
The second part of my question was how to get the value of that field back out. It exists in $options["grouping"][$i]["field"], where $i is the Grouping Field Number, -1.
So, the value entered into "Grouping Field Nr.1" is $options["grouping"][0]["field"].


Difference between containing a cycle of length 3 and containing an element having a cycle of length 3

Question: The whole question is to prove that if $n \geq 5$ and $N$ is a nontrivial normal subgroup of $A_n$ then $N$ = $A_n$.  the problem is broken down into three parts.  (a) is showing that $N$ contains an element having a cycle of length $\geq 3$ and (b) is showing that N contains a cycle of length 3.  What is the difference?  I have been given hints to prove both, but I don't know how to use them.  For a, I was told to use the description of conjugate permutations given in the proposition "If $f$ is an irreducible polynomial over a subfield $F$ of $\mathbb{R}$ and $deg(f) =n \geq 2$ is prime and $f$ has precisely $n-2$ real roots.  Then $Gal_F(f)$ is isomorphic to the full permutation group $S_n$.  For b I was told to consider $f=(123...)(..)..$ take a cycle $g=(12x)$ and compute the commutator $f^{-1}gfg^{-1}$.  Any assistance is appreciated.  I mostly don't really see what the difference between a and b is so if someone could explain that, that would be great.  I've seen elsewhere that $A_n$ is generated by 3 cycles and then $A_n = N$ as a result, but I haven't been able to figure out or find anything related to (a)
Comment: Your first sentence is incomplete.
Comment: @DerekHolt Fixed. Thanks.  Any help is appreciated
Answer: (b) means that $N$ contains an element like $(3~4~5)$.  One cycle of length 3 (and all other cycles of length 1).
(a) means that $N$ contains an element like $(1~2~3)(4~5~6)$ or $(1~2)(3~4~5)$.  At least one cycle of length 3, and the other disjoint cycles can be anything.
Comment: Thanks.  So for b, I think the answer is that since $A_n$ contains all even permutations then $(a b c) = (a b)(b c)$ is in $A_n$.  I still don't get how to show part (a) though.  Could you give me a hint?


Fourier cosine series for $\cos(\pi x)$ on $(0,1)$

Question: My goal is to find the Fourier cosine series for $f(x) =\cos(\pi x)$ on the interval $(0,1).$
Using the formulas
$$A_{0}=\frac{1}{L}\int_{0}^{L}f(x)\ dx \ \ \ \  \text{and} \ \ \ \  A_{n}= \frac{2}{L}\int_{0}^{L}f(x) \cos\left(\frac{n \pi x }{L}\right) \ dx,$$
we can find the coefficients to write the series in the form
$$f(x)\sim \frac{A_{0}}{2} + \sum_{n=1}^{\infty}A_{n}\cos\left(\frac{n \pi x }{L}\right).$$
I won't write out the calculus and the algebra that follows, but both coefficients come out to be $0.$ Does it make sense for the Fourier cosine series of this function to be equal to $0$?  Was it obvious from the beginning?
Thanks in advance!
Answer: $A_1$ is not zero:
$$A_1 = \frac{2}{1} \int\limits_0^1 \cos \pi x \cos \pi x \ dx = 1$$
which makes sense because you are approximating the first term of the cosine series including in the Fourier expansion. You are right with the others, $A_0,A_2,\ldots A_{\infty}$
$$A_0 =  \int\limits_0^1 \cos \pi x \ dx = 0$$
$$A_k =  \frac{2}{1} \int\limits_0^1 \cos \pi x \cos \pi x \ dx = 0 \qquad k \geq 2$$
Comment: Thanks so much.  Do you usually always have to calculate the first term?
Comment: You are welcome. Of course, it is a term like any other.


Access violation when accessing an empty map inside a nested class

Question: I have some code that includes three classes.
The relevant class structure includes the following:

class1 contains a pointer to an instance of class2
class2 contains a private class3 class, and a function to access a reference to class 3
class3 contains a private map class and a function to check if the map is empty

The problem I am having is when I set this up like so I get an access violation:
bool result = class1->class2->GetProperties().CheckEmpty();

But if I set it up like this I don't have any errors:
bool result = class2->GetProperties().CheckEmpty();

Why would adding another class layer suddenly cause this problem?
Here is the code I am using to reproduce the error.
The two lines in the in main do not produce an error but comment those and uncomment the other two and you will get the error.
#include "stdafx.h"
#include <map>

class PropertySet
{
    public:
        PropertySet::PropertySet(){};
        PropertySet::~PropertySet(){};

        bool CheckEmpty() const { return properties.empty(); }

    private:
        std::map< std::string, std::string > properties;
};

class Tile
{
public:
    Tile::Tile() {};
    Tile::~Tile() {};

    // Get a set of properties regarding the tile.
    const PropertySet &GetProperties() const { return properties; }

private:

    PropertySet properties;
};

class Tileset
{
public:
    Tileset::Tileset(){};
    Tileset::~Tileset(){};

    Tile* tile;
};

int main()
{
    bool test = false;

    //NO error-----------------------------
    Tile* t = new Tile();
    test = t->GetProperties().CheckEmpty();
    //-------------------------------------

    //ERROR--------------------------------
    //Tileset* t = new Tileset();
    //test = t->tile->GetProperties().CheckEmpty();
    //-------------------------------------

    delete t;

    return 0;
}

Answer: When you construct a new Tileset, the pointer to Tile is uninitialized.
Tileset::Tileset(){};
Tileset::~Tileset(){};

should be
Tileset::Tileset(){ tile = new Tile(); };
Tileset::~Tileset(){ delete tile; };

Comment: Thanks for the help. I actually have a deeper problem in the library. I was trying to shorten the amount of code and still reproduce the problem but it's just not happening unless I use the library.
Comment: I'm guessing you're using Visual Studio since you have a stdafx.h included. Debugging a library can be annoying but I usually just set a breakpoint before the call that gives an access violation and step through line-by-line to examine each pointer value looking for garbage. Access violation is very likely an uninitialized pointer.


How to find composite functions upto infinity for a given function?

Question: Consider the following function:
$$ f(x) = x + \frac18 \sin (2πx) \\   x  \in [0,1]$$
Define $f_1(x) = f(x)$ , $f_{n+1}(x) = f(f_n(x))$, for $n \geq 1$.
Which of following statements are true ?

There are infinitely many $x \in [0,1]$ for which $\lim_{n\to \infty} f_n (x) = 0$
There are infinitely many $x \in [0,1]$ for which $\lim_{n \to \infty} f_n (x) = 1/2$
There are infinitely many $x \in [0,1]$ for which $\lim_{n \to \infty} f_n (x) = 1$
There are infinitely many $x \in [0,1]$ for which $\lim_{n \to \infty} f_n (x)$ does not exist.

I tried to find a pattern by trying to find composite function many times but failed. I couldn't simplify $f(f(x))$ in terms of simpler function. I also tried drawing graph and finding successive composite functions to find a pattern but failed. Does anyone know of a simpler method?
 Can you please try to do it without using the concept of attractor and repeller ? Please use elemenatry calculus techniques.
Comment: Are you sure that those limits are for $x\to \infty$, and not $n$?
Comment: I think it's $\lim n \rightarrow \infty$. Since $x \in [0,1]$.
Comment: In this case, I think the answer is (2), $\lim_{n \rightarrow \infty} f_n(x) = 1/2$.  I'll see if I can find an nice way to do this.
Comment: No sorry limit is for n
Answer: Note that $f'(x)=1-\frac\pi4\cos(2\pi x)\gt0$. Therefore, $f$ is monotonically increasing.
There are three cases:

$\boldsymbol{x\in\left(0,\frac12\right)}$
$\frac18\sin(2\pi x)\gt0\implies f(x)\gt x$. Furthermore, $f(x)\lt f\!\left(\frac12\right)=\frac12$. Thus, $f_n(x)$ is an increasing sequence bounded above by $\frac12$.
$\boldsymbol{x\in\left(\frac12,1\right)}$
$\frac18\sin(2\pi x)\lt0\implies f(x)\lt x$. Furthermore, $f(x)\gt f\!\left(\frac12\right)=\frac12$. Thus, $f_n(x)$ is a decreasing sequence bounded below by $\frac12$.
$\boldsymbol{x=\frac12}$
$f\!\left(\frac12\right)=\frac12$. Thus, $\lim\limits_{n\to\infty}f_n\!\left(\frac12\right)=\frac12$.

Thus, for $x\in(0,1)$, $\lim\limits_{n\to\infty}f_n(x)$ exists. Since $f$ is continuous,
$$
\begin{align}
0
&=\lim_{n\to\infty}f_n(x)-\lim_{n\to\infty}f_{n+1}(x)\tag{1}\\
&=\lim_{n\to\infty}f_n(x)-\lim_{n\to\infty}f(f_n(x))\tag{2}\\
&=\lim_{n\to\infty}f_n(x)-f\!\left(\lim_{n\to\infty}f_n(x)\right)\tag{3}
\end{align}
$$
Explanation:
$(1)$: the limit exists
$(2)$: definition of $f_n$
$(3)$: $f$ is continuous
Equation $(3)$ says that $\lim\limits_{n\to\infty}f_n(x)$ is a fixed point of $f$.
Therefore, since there is only one fixed point in $(0,1)$,
$$
\lim_{n\to\infty}f_n(x)=\frac12
$$
Comment: Can you please explain the last step ? Why does it require for f to be continuous and why a fixed point only?
Comment: @RaghavSingal: I have added some explanation to the answer including the content of my previous comment.
Comment: How did equation 3 and the comment come about from the fact that d function f is continuous?
Comment: @RaghavSingal: one form of [the definition of continuity](https://en.wikipedia.org/wiki/Continuous_function#Definition_in_terms_of_limits_of_sequences) is $$\lim_{n\to\infty}f(x_n)=f\left(\lim_{n\to\infty}x_n\right)$$
Answer: The question is equivalent to:
$$ \lim_{n \rightarrow \infty} f_{n+1}(f_n)(x) = \lim_{n \rightarrow \infty} f_n(x)$$
Notice that as $n \rightarrow \infty$, $f_{n \rightarrow \infty} = f_{n+1 \rightarrow \infty} = f(x)$ (assume they converge to some function $f(x)$). Thus the above is equivalent to:
$$ f(f(x)) = f(x) $$
This means:
$$ f(x) + \frac 18 \sin(2 \pi f(x)) = f(x)$$
Simplify to:
$$ \sin( 2 \pi f(x)) = 0$$
Since for $x \in [0,1]$, $f(x) \in [0,1]$, the three ways for this to hold is for $f(x) = 0, \frac 12, 1$. These are fixed points of this system. Taking the derivative of $f(x)$ gives:
$$f'(x) = 1 + \frac {\pi}{4} \cos(2 \pi x)$$
Which gives $|f'(0)| = |f'(1)| = 1 + \frac{\pi}{4} > 1$ and $|f'(\frac 12)| = |1 - \frac{\pi}{4}| < 1$. This implies $\frac 12$ is an attractor, thus (2) is correct.
The intuition behind this is that if $|f'(\frac 12)| < 1$, then if $f(\frac 12) < \frac 12$, then $f(f(\frac 12))$ will increase toward $\frac 12$. And if $f(\frac 12) > \frac 12$, then $f(f(\frac 12))$ will decrease toward $\frac 12$. Also, you can plot $f(x)$ to see this. Thus $\frac 12$ attracts solution around it making it an attractor.
Comment: What is an attractor ?
Comment: And how are first and second cases equivalent ? Can you please elaborate ?
Comment: I made an edit. Hope it is clearer now.
Comment: I dont get it how you put these two equivalent ?
Comment: Your method is either incomplete or incorrect !
Comment: Since we solve for fixed points, we assume a limit of $f_n$ exists as $n$ goes to $\infty$. So $\lim_{n\rightarrow \infty} f_n (x)= f (x)$ and $\lim_{n\rightarrow \infty} f_{n+1} (f_n (x)) = f(f (x))$.
Answer: $f$ has three fixed points: $0$, $1/2$ and $1$. $f'(0)=f'(1)=1+\pi/4$ while $f'(1/2)=1-\pi/4$. This means that $0$ and $1$ are repelling points and $1/2$ is an atractor: if $x$ is close to $1/2$, then $f_n(x)\to1/2$. In fact, it can be shown that if $0<x<1$ the $f_n(x)\to1/2$. For this observe that $x<f(x)<1/2$ if $0<x<1/2$ and $1/2<f(x)<x$ if $1/2<x<1$.
Comment: I am sorry i dont understand reppeler and attractor ?
Comment: If $x$ is close to $0$, then $f_n(x)$ gets away from $0$; this is because $f'(0)>1$ and the mean value theorem. Similarly for $x$ close to $1$. But if $x$ is close to $1/2$, then, since $0x$. If $x$ is close to $1/2$ then $|f(x)-1/2|=|f(x)-f(1/2)|=|f'(c)|\,|x-1/2|<|x-1/2|$.
Comment: How can we conclude from derivative at x = 0 , 1 , 1/2 they are attractor or repeller ? Can you explain in detail or perhaps give a link ?
Comment: If $a$ is a fixed point and $|f'(a)|<1$ then $a$ is an atractor; if $|f'(a)|>1$ It is a repeller.


Slicing array with numpy?

Question: import numpy as np
r = np.arange(36)
r.resize((6, 6))

print(r)
# prints:
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]
#  [12 13 14 15 16 17]
#  [18 19 20 21 22 23]
#  [24 25 26 27 28 29]
#  [30 31 32 33 34 35]]

print(r[:,::7])
# prints:
# [[ 0]
#  [ 6]
#  [12]
#  [18]
#  [24]
#  [30]]

print(r[:,0])
# prints:
# [ 0  6 12 18 24 30]

The r[:,::7] gives me a column, the r[:,0] gives me a row, they both have the same numbers. Would be glad if someone could explain to me why?
Comment: Explain how `r[:,::7]` and `r[:,0]`  `have the same numbers`?
Comment: @Divakar Why shouldn't they contain the same numbers? The `r[:,::7]` is just `r[:, 0:6:7]` for an array of shape `(6, 6)`.
Comment: @MSeifert Ah yes! Just that the first one uses a range of indices, whereas the latter one uses a scalar for indexing. Thanks for pointing out!
Comment: `r[:,[0]]`, `r[:,0:1]` also produce the column array. You get the 1d when indexing with a scalar; the other cases the result is 2d.
Answer: Because the step argument is greater than the corresponding shape so you'll just get the first "row". However these are not identical (even if they contain the same numbers) because the scalar index in [:, 0] flattens the corresponding dimension (so you'll get a 1D array). But [:, ::7] will keep the number of dimensions intact but alters the shape of the step-sliced dimension.

Slicing array with numpy?


Naively estimating the factorial

Question: A naive way to estimate the factorial is $n! \geq (a+1) (a+2) \dots n \geq a^{n-a}$ for any $a$. For example, it gives $n! \geq (n/2)^{n/2}$ and slightly better $n! \geq (n/3)^{2n/3}$. I am interested in how strong this naive estimation it can be. For which $a$ we get the best estimate?
If my calculations are correct, this happens when $a = \frac{n}{W(e n)}$ where $W$ is Lambert W. Can the expression $\left(\frac{n}{W(e n)}\right)^{n-\frac{n}{W(e n)}}$ be simplified, or sensibly estimated by elementary functions?
Comment: I found that $W(n) = \ln n + \ln \ln n + O(1)$ (http://math.stackexchange.com/questions/27355).
Answer: Using Stirling's approximation we have $n! \approx (\frac ne)^n$.  If we take your $a$ to be a fixed fraction of $n$, say $\frac nb$, your gives $(\frac nb)^{n(1-\frac 1b)}$.  Stirling divided by yours is then $ \dfrac {(\frac ne)^n}{(\frac nb)^{n(1-\frac 1b)}}=\dfrac {b^{n(1-\frac 1b)}}{n^{\frac nb}}\lt \left(\dfrac b{n^\frac 1b}\right)^n$ which goes to zero with large $n$ for any $b$, quickly when $n \gt b^b$
Comment: You have some kind of typo; when $b=e$ it is clear that $\frac{(n/e)^n}{(n/e)^{n(1-1/e)}}$ goes to infinity (i.e. Stirling is better). In any case, I understand that Stirling is the proper way to estimate factorial, I am interested in how strong the naive approximation can be.
Comment: The quotient is $\left(\frac{n}{b}\right)^{n/b}\left(\frac{b}{e}\right)^n$.
Answer: I will only try to reproduce your computation. We are trying to maximize $f(a):=a^{n-a}$ for $a\in[0,n-1]$. The derivative is $$f'(a)=a^{n-a}[-\ln(a)+\frac{n-a}{a}].$$
We equate to zero
$$\ln(a)=\frac{n-a}{a}=\frac{n}{a}-1,$$
i.e. $$\ln(ea)=\frac{n}{a}.$$
Taking exponential $ea=e^{n/a}$, i.e. $\frac{n}{a}e^{\frac{n}{a}}=en$. From this $n/a=W(en)$ and $a=n/W(en)$. It doesn't mean much by I got the same.
Now, to estimate your expression involving $W$ one can use asymptotic expansions of $W$.
We have that $$\left(\frac{W(z)}{z}\right)^r=\sum_{n=0}^\infty \frac{r(k+r)^{k-1}}{k!}\ (-z)^k.$$
Let us put this in $H(n):=e^{(n-n/W(en))\ln(n/W(en))}$ for $r=-1$.
No, this one is not good. It holds for $|z|<e^{-1}$. We need asymptotics to infinity. Here they have some (Equation 4.20). Then those are the ones we need to put in the formula for $H$.

Naively estimating the factorial


Deferred non-critical caused high CLS

Question: I've deferred non-critical CSS/JS and preloaded base CSS of the website.
Every lab data on PageSpeed Insights have become better. Except "Largest Contentful Paint" and "Cumulative Layout Shift".
Especially, the CLS increases from 0.002 to 1.148!
The images on the website are set as background-image which I think there won't be "Images without dimensions" problem. I also tried to fix the font by using font-display, but the CLS is still the same.
Are there any other techniques I can use to optimize the CLS?
Comment: there is not a single thing in this question about SEO, they just added the tag in error. This is all about page speed and layout shift, perfectly acceptable questions for SO. I have removed the erroneous SEO tag. Please don't mark questions for closure without reading them just based on a tag.
Comment: This question appears to be off-topic because it is about SEO which is off-topic at Stack Overflow. Please read "[Which SEO questions should be closed as non-programming/non-admin?](//meta.stackoverflow.com/a/382618)" to better understand when SEO questions are acceptable to ask here (most are not). General SEO questions may be asked on [Webmasters.SE](//webmasters.stackexchange.com/).
Answer: CLS Optimization
My answer addresses the second part of your question, regarding techniques that can be used to optimize CLS.
In broad terms, my solution hides the problematic elements in CSS, and makes them visible again in javascript. Layout shift is a problem - and contributes to the CLS score - only if if it is visible to the user; when it is invisible, it does not contribute to the CLS score. The detailed implementation is as follows.
First, create a class "antiCls" and add it to your custom CSS (in the HEAD element) as follows:
.antiCls {
    visibility: hidden;
}

Next, add the following code to the end of your custom JS file (at the bottom of the BODY element). First, the JQUERY version:
$(document).ready(function(){

...
existing jquery code
...

    $(window).on("load", function()

        $('.antiCls').css("visibility", "visible");

    });
});

Here is the vanilla javascript version, without jquery:
var cls = document.getElementsByClassName('antiCls'),
    i = cls.length;

for (i = 0; i < cls.length; i++) {
    cls[i].style.visibility = "visible";
    }

Next, you need to identify the elements to which you will apply your new "antiCls" class. Under the Google "PageSpeed Insights" for the page, look under the section "Diagnostics", and expand the sub-heading "Avoid large layout shifts". There, you will find the offending (non-zero) DOM elements listed: these will probably be images, but other elements (including whole divs) may be listed there as well.
For images, apply the new antiCls class to the parent div, not to the image itself. For elements grouped together under one parent div, apply the new antiCls class to the parent div. Some experimentation will be required, but a CLS score of zero can usually be achieved easily using this technique.
Whether a CLS score of zero should be achieved is another question. To be effective, the antiCls class needs to be applied "above the fold" - that is, to elements that appear in the viewport without scrolling. It is important that at least some elements remain at the top to the page to which the antiCls class has not been applied: these elements will usually include a logo, and possibly some navigation. That way, the speed with which the user is presented with some critical content ("First Contentful Paint") won't be negatively effected.
In my own tests I have discovered that this CLS optimization technique makes no perceptible difference to the speed with which the page is displayed; meaning that a low or zero CLS score can be achieved at nearly zero performance cost.
Answer: You need to inline your critical CSS.
Basically when the page loads it has to wait for all of your CSS to render the "above the fold" (everything immediately viewable without scrolling) content.
When you deferred all of your CSS you made that happen later so the HTML loads and then as your CSS loads the styles are applied, causing things to shift around on the page.
The key part of what it says is "defer non-critical CSS" needs deferring, "critical CSS" needs to load as early as possible.
What is critical CSS?
Critical CSS is all of the CSS required for the "above the fold" content.
What you do is add a

Deferred non-critical caused high CLS


Usage recursive hierarchy tree structure in Linq query with multible tables and return some Json Value

Question: I have a complex hierarchy and I have used RecursiveJoin Extension method and it returned to me a tree structure with parents nodes, children nodes and depth.So it's ok but I need to calculate  total score point from ScoreItem table from database. As well as I had wrote this simple calculation method in t-sql at below,
Begin
    Select
        sp.Name,
        u.FirstName + ' ' + u.LastName as NameAndSurname,
        rgc.Name as ScoreCard,
        si.TotalPoint
    from Score s
        inner join ScoreItem si on si.ScoreId = s.Id
        inner join ProjectResearchGroup prg on si.ProjectResearchGroupId = prg.Id
        inner join RgClone rgc on prg.RgCloneId = rgc.Id
        inner join Salespoint sp on s.SalesPointId = sp.Id
        inner join SalesHierarchySalesPoint shsp on sp.Id = shsp.SalesPointId
        inner join SalesHierarchy sh on shsp.SalesHierarchyId = sh.Id
        inner join [User] u on u.Id = sh.CompanyResponsibleId
    where sh.Id in
        (Select Id
        from SalesHierarchy
        where ParentId in
            (Select Id
            from SalesHierarchy
            where ParentId in
                (Select Id
                from SalesHierarchy
                where ParentId in
                    (Select Id
                    from SalesHierarchy
                    where CompanyId = 2
                        and ParentId is null))))
        and si.IsValidForSalesPoint = 1
End

Also this my back end code for try to implement to linq query from above t-sql queries.
IEnumerable<FlatData> _SalesHierarchy = db.SalesHierarchy
                                         .Select(sh =>
                                         new FlatData()
                                         {
                                         Id = sh.Id,
                                         ParentId = sh.ParentId ?? 0,
                                         Text = sh.Name
                                         })
                                        .ToList();

IEnumerable<DeepNodeData> nodes = _SalesHierarchy.RecursiveJoin(e => e.Id, e => e.ParentId,
(FlatData sh, int index, int depth, IEnumerable<DeepNodeData> children) =>
  {
    return new DeepNodeData
        {
          Id = sh.Id,
          ParentId = sh.ParentId,
          Text = sh.Text,
          Children = children,
          Depth = depth
        };

As a result these above codes return me, this result,
So I would like to return Json output for my web api,such as these
"data": [
        {
            "level1": "XXXX,XXXX,XXXX",
            "level2": "XXXX,XXXX,XXX",
            "level3": "XXXX,XXXX,XX",
            "level4": "XXXX,XXXX,X",
            "val": 2
        },
    ]
};

How can I implement hierarchy query with my other linq queries and return above  Json format. if you have any suggestion and sample application about it, please may you share with me,
Answer: The RecursiveJoin Extension looks pretty nice, but I don't think you need the full power of that code to accomplish your objective.  If I understand your question correctly, you need to enumerate over all lists of nodes from root to leaf, dumping each list into a JSON object.  To do that, first create the following extension methods:
public static class RecursiveExtensions
{
    public static IEnumerable<TValue> SelfAndParents<TKey, TValue>(this TValue value, IDictionary<TKey, TValue> dictionary, Func<TValue, TKey> getParentKey)
    {
        HashSet<TValue> returned = new HashSet<TValue>();
        do
        {
            yield return value;
            if (!dictionary.TryGetValue(getParentKey(value), out value))
                yield break;
            if (returned.Contains(value))
                throw new InvalidOperationException("Circular reference");
            returned.Add(value);
        }
        while (true);
    }

    public static IEnumerable<List<TValue>> FlattenTree<TKey, TValue>(this IEnumerable<TValue> nodes, Func<TValue, TKey> getKey, Func<TValue, TKey> getParentKey)
    {
        var list = nodes.ToList();                                                          // Don't iterate through the node list more than once.
        var parentKeys = new HashSet<TKey>(list.Select(getParentKey));                      // Built a set of parent keys.
        var dict = list.ToDictionary(getKey);                                               // Build a dictionary of key to value
        var results = list
            .Where(node => !parentKeys.Contains(getKey(node)))                              // Filter out non-leaf nodes
            .Select(node => node.SelfAndParents(dict, getParentKey).Reverse().ToList());    // For each leaf return a list going from root to leaf.
        return results;
    }
}

Then use them as follows:
public static class TestFlatten
{
    public static IEnumerable<FlatData> GetFlatData()
    {
        // Get sample data for testing purposes.
        var list = new List<FlatData>
        {
            new FlatData { Id = 1, ParentId = 0, Text = "Some Root Node" },
            new FlatData { Id = 2, ParentId = 0, Text = "Anadolu Satış Merkezi" },
            new FlatData { Id = 3, ParentId = 2, Text = "Emrullah Çelik" },
            new FlatData { Id = 4, ParentId = 3, Text = "Ahmet İşler" },
            new FlatData { Id = 5, ParentId = 4, Text = "Elpa Pazarlama Nazmi Appak" },
            new FlatData { Id = 6, ParentId = 4, Text = "Elpa Pazarlama Nazmi Appak Redux" },
            new FlatData { Id = 11, ParentId = 1, Text = "Some Child of Some Root Node" },
        };
        return list;
    }

    public static void Test()
    {
        var nodes = GetFlatData();
        var flatNodes = nodes.FlattenTree(d => d.Id, d => d.ParentId);
        var results = flatNodes.Select(
            list => list
                .Select((d, i) => new KeyValuePair<int, FlatData>(i, d))
                .ToDictionary(pair => string.Format("level{0}", pair.Key + 1), pair => pair.Value.Text))
            .ToList();
        var json = JsonConvert.SerializeObject(new { data = results }, Formatting.Indented);
        Debug.WriteLine(json);
    }
}

This produces the JSON output:

{
  "data": [
    {
      "level1": "Anadolu Satış Merkezi",
      "level2": "Emrullah Çelik",
      "level3": "Ahmet İşler",
      "level4": "Elpa Pazarlama Nazmi Appak"
    },
    {
      "level1": "Anadolu Satış Merkezi",
      "level2": "Emrullah Çelik",
      "level3": "Ahmet İşler",
      "level4": "Elpa Pazarlama Nazmi Appak Redux"
    },
    {
      "level1": "Some Root Node",
      "level2": "Some Child of Some Root Node"
    }
  ]
}

Is this what you want?  Here I am taking advantage of the fact that Json.NET serializes a dictionary as a JSON object to dynamically create the "levelI" properties as dictionary keys.  Also, as you did not define the "val" value, I didn't include it in the dictionary.
Comment: val, means, **total point** it's come from _ScoreItem_ on DbContext and it has to show end of last level,
Comment: @Ozkan - there's nothing corresponding to `ScoreItem` on your `FlatData`.  Can the data be added there?
Comment: actually I have to make join with _Score_, _ScoreItem_, _Salespoint_,  and _SalesHierarchy_ for prepare to calculate **Score Card TotalPoint** for each SalesPoint, for example, Alamut Kırtasiye but Who is the Alamut Kırtasiye, who is the its parents?? So that firstly I have to get hierarchy that involved with Alamut K. so "level1": "Anadolu Satış Merkezi",
"level2": "Emrullah Çelik",  / "level3": "Ahmet İşler" / "level4:" "Alamut K" "Val:" " 45.66", Val is showing final TotalPoint that calculated for instance, please take a look [link](http://prntscr.com/6ltk8d) here,


Trying to use variable to pass a view argument/parameter

Question: I'm currently in the middle of trying to figure out a way to pass the value from a variable to be used as parameter/argument for my drupal view.
I have a contextual filter that currently configured on my drupal view to output only nodes based on the taxonomy term/ID. Instead of explicitly manually setting the parameters below.
{{drupal_view('view_one', 'block_1', 212, 210)}}

Is there a way I could use a variable to pass the parameters to my drupal view
 % for tags in node.field_filter_tags %}

    {% set tagid = tags.entity.id %}

{% endfor %}

{{drupal_view('view_one', 'block_1', tagid)}}

I tried it but it seems to show duplicates.
Answer: the first you install module Twig Tweak
In file yourtheme.theme
/**
 * Implements hook_preprocess_HOOK()
 */
function yourtheme_preprocess_node(&$variables) {
  $terms=[];
  foreach($variables['node']->field_tags->getValue() as $term){
    $terms[] = $term['target_id'];
  }
  $variables['node_terms'] = implode(',',$terms);
}

In file node.html.twig
{{ drupal_view('custom_view','article_block',node_terms) }}

Config Views CONTEXTUAL FILTERS in your views
Comment: Thanks for this, the only issue I'm currently experiencing that it seems to be rendering duplicates. I have already enable `Distinct` in the `Query Settings`


Error when using hook_form_comment_form_alter()

Question: I am using the following function in template.php to modify the comment form to remove the form title and add a default value inside the form:
<code>/**
* Implements hook_form_comment_form_alter().
*/
function mytheme_form_comment_form_alter(&$form, &$form_state, $form_id) {

    $form['subject'] = array(
      '#type' => 'textfield',
      '#maxlength' => 255,
      '#attributes' =>array('placeholder' => t('subject')),
      '#required' => FALSE,
    );

    $form['comment_body'] = array(
      '#type' => 'textarea',
      '#maxlength' => 255,
      '#attributes' =>array('placeholder' => t('comment')),
      '#required' => TRUE,
    );

}
</code>
It does the desired task but it causes an error where the form will submit but the contents entered into the body are not submitted and will not display. The following error gets generated:
<code>Notice: Undefined property: stdClass::$comment_body in comment_submit()
</code>
Am I missing something within the function so the text inputed is actually submitted when saving the form?
Comment: You need to debug your   $form['comment_body'] as I do not believe that is the correct array
Answer: Turns out the correct way to add the placeholder was:
<code>$form['comment_body'][LANGUAGE_NONE][0]['#attributes']['placeholder'] = t( 'comment' );
</code>


Who is this commentator to many international badminton events?

Question: Over the past few years, I've watched many badminton games on YouTube. At first, video-ed ASTRA broadcasts, but, nowadays, the BWF is hosting many of the international badminton events.
I would like to know the name of the female commentator who provided the commentary to many events. She appears in the final on the Yonex Japan Open 2013.
Answer: Gill Clark
Most likely, this is Gillian Clark ("OSIM BWF World Superseries TV Commentator"). See a recent video with her here (from 1:42).

Gill Clark can also be found on the website for the Yonex Japan Open 2013: "YONEX OPEN JAPAN – memories of a commentator by Gill Clark".


Fazer um else cascateado dentro de um for

Question: Veja abaixo o meu for. Dentro desse for existe alguns IF's. Não quero um outro for para percorrer a mesma lista. Há um if que valida se IcObrigatorio == 1 e abaixo dele valida se vlstDados[i].DsPathDocumento não é vazio e nem nulo. O que eu quero se possível no mesmo for para não ter que percorrer outra vez a mesma lista, fazer essa validação ao contrário, ou seja, caso IcObrigatorio == 0 e vlstDados[i].DsPathDocumento igual a nulo ou vazio, aí eu seto uma variável booleana. Pessoal estou apanhando nessa lógiga devido a como eu coloco um else cascateado, se é o caso. Abaixo meu for.
for (int i = 0; i < vlstDados.Count; i++)
                {
                    vstrNmPessoa = vlstDados[i].NmPessoa;

                    if (vlstDados[i].IcObrigatorio == 1)
                    {
                        if (string.IsNullOrEmpty(vlstDados[i].DsPathDocumento))
                        {
                            if (vlstDados[i].CdTipoDocumentoSubstitui == 0)
                            {
                                vbolErro = true;
                            }
                            else
                            {
                                for (int v = 0; v < vlstDados.Count; v++)
                                {
                                    if (vlstDados[i].CdTipoDocumentoSubstitui == vlstDados[v].CdTipoDocumento)
                                    {
                                        if (string.IsNullOrEmpty(vlstDados[v].DsPathDocumento))
                                        {
                                            vbolErro = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

Acabei fazendo da forma abaixo. Não gostei, pois tive que repeti o mesmo comando acima do else. A intensão minha seria ver se há uma espécie de else em cascata, tipo:
else
else

e não sei se isso seria o melhor também. Assim fiz
for (int i = 0; i < vlstDados.Count; i++)
                {
                    vstrNmPessoa = vlstDados[i].NmPessoa;

                    if (vlstDados[i].IcObrigatorio == 1)
                    {
                        if (string.IsNullOrEmpty(vlstDados[i].DsPathDocumento))
                        {
                            if (vlstDados[i].CdTipoDocumentoSubstitui == 0)
                            {
                                vbolErro = true;
                            }
                            else
                            {
                                for (int v = 0; v < vlstDados.Count; v++)
                                {
                                    if (vlstDados[i].CdTipoDocumentoSubstitui == vlstDados[v].CdTipoDocumento)
                                    {
                                        if (string.IsNullOrEmpty(vlstDados[v].DsPathDocumento))
                                        {
                                            vbolErro = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                        if (vlstDados[i].IcObrigatorio == 0 && string.IsNullOrEmpty(vlstDados[i].DsPathDocumento))
                        {
                            vbolErroDocTorObrigatorio = true;
                        }
                }

Comment: .IcObrigatorio pode assumir valores diferentes de 0 e 1?
Answer: Então você não gostou do código que teve que usar para resolver o problema.
Eis um passo-a-passo para você gostar do seu código e a partir daí conseguir implementar uma lógica melhor:
Não use nomes que não sejam significativos ao negócio
Procure dar nomes mais próximos à regra de negócio do que às características técnicas do código. Assim:
Não identifique o tipo do artefato no seu nome
Você está usando um "v" como prefixo. Parece ser para indicar "variável". Isso é desnecessário. Nunca mais faça isso e, como resultado, além de não sentir nenhuma falta desta prática você ainda vai ter um código mais expressivo.
Não identifique o tipo do dado no nome do artefato
Você está usando "lst" para indicar que é uma lista. Não faça isso. Apenas colocar o nome no plural deixa claro o bastante que se trata de uma lista: "dado" contém 1 dado e "dados" contém N dados.
Você também está usando "bol" para indicar um booleano. Não faça isso. Ao invés, dê um nome que deixe claro que a variável contém true se ela afirma uma verdade ou false caso contrário. Por exemplo, em vez vbolErro use estaErrado ou deuErro ou pathDocumentoNaoInformado.
Eventualmente até simplesmente erro já serve, já que o código que vai ler a variável ficaria assim if (erro) e isso faz todo sentido; ao contrário de if (vbolErro).
É possível que você esteja tão acostumado com o "vbol" no nome da variável que você só leia "erro" em vez de ler "vê ból erro". E isto prova o quanto este prefixo é desnecessário, além de atrapalhar a leitura de outros não tão acostumados quanto você.
O mesmo vale para o "str" indicando que é uma string. Este tipo de informação em uma linguagem de alto nível como a que você usa, além de não ajudar, atrapalha.
Indicar no nome o tipo de dado é uma prática arcaica.
Não use termos genéricos como nomes de artefatos
Evite chamar seus artefatos de "dado" e "info", por exemplo, pois em um sistema quase tudo é dado ou informação. Ao invés, escolha nomes significativos para o negócio como "documento"; ou, no caso de uma lista, "documentos".
Não use IF encadeado ou aninhado
O que são IFs aninhados:
if (condicao)
{
    if (outraCondicao)
    {
        ...
    }
}

Cada IF no código é um caminho possível à mais. Cada caminho alternativo, é uma complexidade à mais. E complexidade é um mal necessário mas indesejável, deve ser reduzida ao mínimo. Assim, quanto menos IF, melhor.
Um bloco de código bonito não possui nenhum if - ele conta uma história de maneira fluída.
De modo que:

Zero ifs é bom.

Um if é um mal necessário.

Um if dentro de outro ("encadeado" ou "aninhado") é um mal necessário com potencial para ser eliminado.

Dois ou mais ifs aninhados é um mal que pode e precisa ser eliminado agora mesmo.

Então, sempre duvide da sua lógica cada vez que você precisar aninhar ifs.
De saída, prefira a repetição em vez da complexidade
A repetição ou duplicação de código não é a primeira coisa a ser eliminada durante o refactoring (processo de melhoria do seu código sem mudar o comportamento).
Primeiro escreva um código simples que faça o que precisa ser feito, mesmo que com duplicações. Depois elimine as duplicações mas sem o ônus de adicionar complexidade. Usar ifs aninhados aumenta a complexidade.
Conclusão:
A melhor maneira de você melhorar o seu código a partir de onde você está é:

Renomeie suas variáveis conforme o que descrevi aqui.

Traga a repetição de volta. Faça quantos loops forem necessários, ou seja, percorra a lista uma vez para cada problema a ser resolvido.

Talvez aí você já esteja satisfeito. Um código expressivo pode ser mais importante do que ganhar um bilionésimo de segundo por percorrer uma lista menos vezes, por exemplo. Se não estiver satisfeito:

Elimine a duplicação de código sem usar ifs aninhados. Usar if aninhado não simplifica nada.

Se não estiver satisfeito, poste uma nova pergunta com o código que você tiver em mãos. Ele estará claro o bastante para que alguém possa ajudá-lo com a sua lógica (embora eu não tenha certeza de que isso não seja code review ou algum outro tipo de pergunta off-topic para o SOpt).
Update: Ah, sim, claro! Dê uma estudada em LINQ, que pode ser uma maneira expressiva e de pouco código para soluçao deste tipo de problema.
Comment: Usei lambda e resolveu minha questão de código limpo.
Answer: Pelo que entendi o que você precisa é isso, dentro de cada bloco você coloca o restante de seu código.
for (int i = 0; i < vlstDados.Count; i++)
{
    vstrNmPessoa = vlstDados[i].NmPessoa;

    if (vlstDados[i].IcObrigatorio == 1 && string.IsNullOrEmpty(vlstDados[i].DsPathDocumento))
    {
        /* ... */
    }
    else if (vlstDados[i].IcObrigatorio == 0 && !string.IsNullOrEmpty(vlstDados[i].DsPathDocumento))
    {
        /* ... */
    }
}

Comment: Isso foi o que eu fiz, mas tive que repetir os camandos.
Comment: @pnet De fato não entendi o que você quer então.
Comment: Acho que a pergunta foi mal elaborada, só isso. Desculpas à comunidade. Não vou remover que pode ajudar outras pessoas.
Answer: tentei reescrever o seu for para que o mesmo fique mais legivel, poderia conferir se a logica está correta?
for (int i = 0; i < vlstDados.Count; i++)
{
    var isObrigatorio = vlstDados[i].IcObrigatorio == 1;
    var hasPathDocumento = !string.IsNullOrEmpty(vlstDados[i].DsPathDocumento);
    var isTipoDocSubstui = !vlstDados[i].CdTipoDocumentoSubstitui == 0;

    if (!isObrigatorio) {
        vbolErroDocTorObrigatorio = !hasPathDocumento;
        continue;
    }

    if (!hasPathDocumento) {
        continue;
    }

    if (!isTipoDocSubstui) {
        vbolErro = true;
        continue;
    }

    for (int v = 0; v < vlstDados.Count; v++)
    {
        var documentoFound = vlstDados[i].CdTipoDocumentoSubstitui == vlstDados[v].CdTipoDocumento;
        hasPathDocumento = !string.IsNullOrEmpty(vlstDados[v].DsPathDocumento);
        if (documentoFound && !hasPathDocumento)
        {
            vbolErro = true;
            break;
        }
    }
}

Comment: Eu utilizei uma lambda e ficou mais claro. A questão toda é referente a código limpo, exigência patronal, por isso o post para saber se há como um else cascateado para não ficar repetindo as mesmas coisas.


Android listview prevent sideways (left-right) swiping when scrolling

Question: I'm using this library https://github.com/romannurik/android-swipetodismiss to implement swipe to delete in my listview. However the problem is that when my fling or up-down swipe is too slanted, it turns into a sideway swipe to remove row gesture and then the listview stops scrolling. I think the ideal behavior should be if the gesture is a up-down scrolling gesture, then the x component of the gesture should be ignored and vice versa for the sideways swipe to delete gesture. Is there a way to achieve this?
Thanks
Comment: AFAIK it isn't a library, just some sample code for people to implement. With that said, your problem is taken care of within the sample with the `SwipeDismissListViewTouchListener` and `SwipeDismissListViewTouchListener.makeScrollListener()`
Answer: Turns out the ideal behavior is the default behavior of the library. The problem was I set my own onScrollListener which I think overrode the library's listener.
Comment: Oops...didn't see this when I posted my comment, but either way, glad you found a solution.


How do I check a DOM value is not empty and then copy it in another place in DOM tree

Question: I have a structure like this:

--here needs to copy the value of destination--

 $ 300

I just want to check if
 ...
 is not empty and then copy the value into

...How do I achieve that?
I expect is something like
if (!jQuery(".content:empty")) {
...logic here...
}

Thanks
Answer: var content = $.trim($('.content').text());
if(content) {
    $('.destination').text(content);
}

If you want to move DOM nodes, you can use:
var $nodes = $('.content').children();
if($nodes.length) {
    $('.destination').empty().append($nodes);
}

If you want to copy nodes, use .append($nodes.clone(true, true)).
Information about these methods can be found in the documentation.
Comment: Use contents() instead of children()?
Comment: @Jleagle: Yes, if the element contains text nodes and element nodes. Good thinking.
Answer: var text = jQuery(".content").text();
if (text) { jQuery(".destination").text(text); }

Comment: weird..your solution work in console but not inside the code :)
Answer: To access the inner HTML of a div use .html().
var value = $('.content').html();

Then you can check the value using a regex to check for whitespace and if its empty. See the link below.
How to check if a text is all white space characters in client side?
Then you can set destination div to the content in value.
$('.destination').html(value);

Answer: if(!($.trim($('.content').val())))
{

$('.destination').val($('.content').val());

}

Comment: val() I think is working for forms only..otherwise is undefined.


Domain and subdomain - using same ip and ssl certificate with san for both domans?

Question: I have a site with a SSL certificate. Now I need to add another site, also using HTTPS.
It seems it is possible to do by creating the binding for the new site using another port for the HTTP and HTTPS traffic. This I'd like to avoid, as adding exceptions in the firewalls is a lengthy process due to security policies.
The way I thought was possible to get around adding new ports was to add the site as a subdomain, and then change the SSL certificate to have an additional SAN name that matches the new subdomain.
I tried testing this on my local machine, but after adding the 443 port with the certificate on both sites, editing the host file to contain the subdomain, and then adding the subdomain as a hostname to the new iis website. Only one of the sites can be started, the other one complains that another site may be using the same port.
Questions:

I feel it should be possible to use the same certificate on a domain and a subdomain at the same time without jumping through hoops?
If the above is not possible, should I then add two new ports one for http and one for https, and then use those ports for the new site. The certificate should then be able to work for the new site correctly? - right?

EDIT:
Do I need another IP address for the new subdomain?
Answer: You can use a wildcard certificate for *.domain.com. There are some security issues with this (since anyone with a copy can create a new site and it will show as valid - for instance if you want company.com and store.company.com and someone gets your private key they can be store1.company.com and it will show as a valid site.
Answer: On IIS7.5, two SSL-protected websites require a unique combination of ip address and port. So, you can share IP adress and use different ports, or you can use the same ports but then each site would need a separate ip address. You need to choose.
(btw, there is not problem assigning multiple ip address to a windows server box in order to accomplish this)
Answer: On IIS 7.5, you would need unique IP addresses. SNI is not supported before IIS 8.


Can you reproduce this chi-squared test result?

Question: Over at Skeptics.StackExchange, an answer cites a study into electro-magnetic hypersensitivity:

McCarty, Carrubba, Chesson, Frilot, Gonzalez-Toledo & Marino, Electromagnetic Hypersensitivity: Evidence for a Novel Neurological Syndrome International Journal of Neuroscience, 00, 1–7, 2011, DOI: 10.3109/00207454.2011.608139.

I am dubious about some of the statistics used, and would appreciate some expertise in double-checking that they are used appropriately.
Figure 5a shows the results of a subject attempting to detect when an electromagnetic field generator was turned on.
Here is a simplified version:
<code> Actual:   Yes  No
Detected:
  Yes       32  19
  No       261 274
</code>
They claim to have used a chi-squared test, and found significance (p < 0.05, without stating what p is.)

The frequencies of the somatic and behavioral responses in the presence and absence of the field were evaluated using the chi-square test (2 × 2 tables) or the Freeman–Halton extension of the Fisher exact probability test (2 × 3 tables; Freeman & Halton,
  1951).

I see several problems.

They excluded some of the data - see Table 5b - where they left the device off for long periods. I cannot see the justification in separating that data.
They seem to be claiming the result is statistically significant when the actual device was on, but not when it wasn't. (I may be misreading this; it isn't clear.) That's not a result that the chi-squared test can give, is it?
When I have tried to reproduce this test with an on-line calculator I have found it to be statistically insignificant.

This is my real question: Am I right in saying this?: A two-tailed, chi-squared test using Fisher's Exact Test is the right way to analyze this data AND it is NOT statistically significant.
Comment: For the record: There was a [Letter to the Editor](http://informahealthcare.com/doi/full/10.3109/00207454.2011.648763) regarding this paper. It challenged some of the (post-hoc?) classifications of severity used in Table 3a (Experiment 1 and 2), warned of publication bias risks and the need to replicate. It didn't complain about the data in Table 5.
Comment: It might also be worth noting that this table is right on the margin of appearing "significant": had only a *single* detection been misclassified, the Fisher test (which is the appropriate one to use) would return a p-value of 10.9%. If the claim is extraordinary or controversial, one would require *much* stronger evidence than this to accept a conclusion of positive association.
Comment: Are the "detected" and "actual" variables observed at the same unit? If so then I'd say this is a symmetry problem.
Comment: @Momo: I think the answer is Yes. There were 600 trials. In 300, the device was actually on, and in the other 300 the device was actually off. The subject was asked if she could detect the electromagnetic radiation, and answered Yes or No. In 14 cases, she failed to answer and they have been excluded. In 535 cases she said No, which means her sensitivity was low (if it existed at all). Not sure how that makes a symmetry problem - any links I could read to learn more?
Comment: Ok, thanks. I just realized that symmetry problem seems to be an expression that is not used in English, so sorry for that. What I mean by it is that the cross classifications are not derived from independent units but that the same unit was repeatedly asked and it therefore is a paired or repeated measurement set up.
Answer: It seems to me that there are three things wrong with the conclusion.
First, as @caracal said: They are reporting "significance" using a one-tailed test, without saying that they are doing so. Most people, I think, recommend using two-tailed tests almost always. Certainly it is not ok to use a one-tail test without saying so.
Second, the effect is tiny. When there was a signal, the subject (there was only one) detected it 11% of the time (32/293). When there was no signal, she detected a signal 6.5% of the time. That difference seems pretty small. And the subject was not able to detect the signal 89% of the time!
Third, as @oddthinking pointed out, there were some selective data reporting that were not properly explained or justified (I didn't read the paper carefully, so am simply repeating what was in the original post).
Answer: A Fisher exact test on the given table gives, per this code
<code>actual <- c(rep("Y", 32), rep("N", 19), rep("Y", 261), rep("N", 274))
det <- c(rep("Y", 51), rep("N", 535))
table(det,actual)
fisher.test(det,actual)
</code>
a p = 0.08
Comment: would you say that a Fisher test is appropriate for this contingency table?
Comment: But that's the two-sided p-value. I guess the hypothesis was one-sided ($p(\text{"yes"} | \text{yes}) > p(\text{"yes"} | \text{no})$, giving a p-value of 0.039.
Comment: @caracal: Do you want to elaborate your reasoning and turn this into an answer?
Comment: @Oddthinking Sorry, I currently don't have the time to skim the paper and think about the issues of sampling / experimental design relevant to the question.


Question About Ito's Chain Rule and SDE's

Question: I'm having a little trouble understanding the setup for Ito's chain rule, and how to expand it to finding SDE's. In class, I was taught that an example of Ito's chain rule was the following:
$$
df = (f_t+1/2f_{BB})\,dt + f_B\,dB
$$
where $f$ is a function of $t$ and the random variable $B$, typically governed by a Brownian Motion. Now, I have this problem, where I'm asked to solve the SDE for $Z = e^{B(t)^2}$ where the hint to the question is to let a random variable $X = (B(t))^2$ and apply the Ito chain rule to $f(x) = e^x$. I interpreted this as asking to substitute in this equation to let $Z = e^X$, where $(B(t))^2$ is written as the random variable $X$ in the original equation. But now, I'm confused on how to take the SDE. I'm unclear how to separate $Z$ into having a drift and diffusion term, but more importantly I'm unclear on how to use Ito's chain rule in this situation, as I don't see a function f which doesn't have the parameters of $t$(time) and $B$(random variable), I only see $Z$ as having these traits, and so I'm not sure how the chain rule would apply. I'm not looking for an answer, I just want to understand how to set up my problem, so I can understand how to solve it. Thanks.
Comment: If $B$ is not a Brownian motion, then its quadratic variation is usually not $dt$. It is also not clear what advantage the separation of operations gives. Using $f(t,x)=e^{x^2}$ should be easy enough.
Comment: You get $$Z_{t+dt}=e^{(B_t+dB_t)^2}=e^{B_t^2}e^{2B_tdB_t}e^{dB_t^2}=Z_t(1+2B_tdB_t+2B_t^2dB_t^2)(1+dB_t^2)\simeq Z_t(1+(1+2B_t^2)dt+2B_tdB_t).$$ Using correctly computed $f_x$ and $f_{xx}$ will of course give the same in an "official" way.
Comment: @LutzLehmann Can you explain why f(t, x) = e^x^2 works in terms of solving for the SDE of Z? I'm just not sure how Z relates to the function f(t, x)
Answer: Ito's formula is valid for semi-martingales. In this case we have $X_t = B_t^2$, which is a semi-martingale as may be observed by applying Ito's formula,
$$
dX_t = 2B_t dB_t + 2 dt
$$
So since $Z_t = \exp(X_t)$ we should have
$$
Z_t = Z_t dX_t + 1/2 Z_t d[X]_t
$$
where $[.]$ stands for the quadratic variation. Now the quadratic variation of $X_t$ can be read directly off of the differential form. It is just the square of the $2B_t dB_t$ bit where we use the algebraic rule that $dB_tdB_t = dt$. (The justification for this is that the quadratic variation of the Ito integral is known to be $[\mathcal{I}_{B_t}(\Phi)] = \int \Phi_t^2d t$ when the latter is finite). That is, $d[X]_t = 4B_t^2 dt$.
So we have
$$
Z_t = Z_t dX_t + 2 B_t^2 Z_t dt = 2Z_t B_t dB_t + 2(1+B_t^2)Z_t dt
$$
As Lutz mentioned, you can also just apply Ito's formula directly without any substitutions,
$$
dZ_t = 2B_t Z_t dB_t + 1/2(2Z_t + 4B_t^2 Z_t)dt
$$
It clearly comes to the same thing and in this case is probably simpler. Still, convincing yourself of each step in the other approach is a valuable exercise.


Can a unique index be created in MySQL if the table has repeating values?

Question: For an existing table, is it permissible to create a unique on a column that might have repeating values?
Answer: No, it is not permissible.
The following SQL:
ALTER TABLE `table`
ADD UNIQUE (`column`)

Will generate the following error:

#1062 - Duplicate entry 'data' for key 'column'

You can identify duplicates using:
SELECT * FROM `table`
GROUP BY `column`
HAVING COUNT(`column`) > 1

After removing all of the duplicates, you can add the UNIQUE constraint.
Comment: Note - This will remove all records having that particular value. You just might want to delete all but one.
Answer: Actually it is possible, at least in MySQL 5.1+.  You can use:
ALTER IGNORE TABLE `table` ADD UNIQUE INDEX (`column`);

If your table is InnoDB you will need to run this first:
set session old_alter_table=1

reference http://www.mikeperham.com/2012/03/02/deleting-duplicate-rows-in-mysql/
EDIT: As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and its use produces an error.  Thanks to @EdwardvanKuik for Pointing it out in the comments
Comment: As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and its use produces an error.
Answer: It is not possible:
Mysql2::Error: Duplicate entry 'foo' for key 'index_clubs_on_url': CREATE UNIQUE INDEX `index_clubs_on_url` ON `clubs` (`url`)

Answer: It is possible where any of the indexed columns in all repeat rows contain NULL because NULL is neither equal to nor not equal to NULL and hence the index values are not considered to be equal and are allowed to go ahead.
MariaDB [mydb]> select case when NULL = NULL OR NULL <> NULL then 'true' else 'false' end as 'test';
+-------+
| test  |
+-------+
| false |
+-------+

see here for example and (possible) workaround (where you are trying to enforce unique rows).
mysql  Ver 15.1 Distrib 10.3.35-MariaDB, for Linux (x86_64) using readline 5.1


How do you derive, the "naive form" of the Lippmann-Schwinger Equation?

Question: I was looking for a derivation of the 'Lippmann-Schwinger Equation'.
The wikipedia material at
http://en.wikipedia.org/wiki/Lippmann%E2%80%93Schwinger_equation#Derivation
does not (23rd Jan 2024), as I understand matters, actually contain a derivation of the equation! As part of the "derivation", it gives what it calls a "naive solution", without actually showing how to get to it. Let's call this naive solution, the 'Naive Form' of the Lippmann-Schwinger equation, this is shown below

\begin{equation*}
     |\psi\rangle= |\phi \rangle+\frac{ 1  }{ E-H_0   }V|\psi\rangle
\end{equation*}

The only version of Sakurai's$^1$ Modern Quantum Mechanics that I currently have, does not contain a derivation of this naive solution either.
My question is: How do you derive, the "naive form" of the Lippmann-Schwinger Equation?
Reference:
1, J.J.Sakurai, Ed San Fu Tuan, Modern Quantum Mechanics Revised Edition, Addison-Wesley Publishing Company (1994).
Comment: Are you not satisfied with the derivation you presented in your answer?
Comment: @Goncalo I just deleted an answer I posted on physics stack exchange, did you mean that answer? I also posted at https://physics.stackexchange.com/a/797895/175502 the same answer, as part of something larger.
Comment: @Gonçalo I have just deleted the "other" answer I referred to in my previous comment.
Comment: No, I mean the answer you wrote below. It presents what you call **A proof**.
Answer: Sakurai$^1$ gives, Section 7.1, 'The Lippmann-Schwinger Equation'

\begin{equation*}
      H_0|\phi\rangle=E|\phi\rangle \tag{7.1.3} \end{equation*}

\begin{equation*}
      ( H_0+V)|\psi\rangle=E|\psi\rangle \tag{7.1.4} ~~~~~~~~~~~ \end{equation*}

Sakurai$^1$ say's, about the solution to ($\mathbf{7.1.4}$)

It may be argued that the desired solution is \begin{equation*}
     |\psi\rangle= |\phi \rangle+\frac{ 1  }{ E-H_0   }V|\psi\rangle \tag{7.1.5} \end{equation*}

but does not give any proof.
A proof.
Re-write ($\mathbf{7.1.3}$), and ($\mathbf{7.1.4}$) as
\begin{equation*}
     (E-H_0)|\phi \rangle =0~~~~~~  \tag{1}
\end{equation*}
\begin{equation*}
     (E-H_0)|\psi \rangle =V|\psi \rangle \tag{2}
\end{equation*}
subtract ($\mathbf{1}$) from ($\mathbf{2}$), note that $(E-H_0)$ is a linear operator, giving
\begin{equation*}
    (E-H_0) \left[ |\psi \rangle - |\phi \rangle \right] =V|\psi \rangle
\end{equation*}
Hence,
\begin{align*}
    |\psi \rangle - |\phi \rangle&= \frac{ 1 }{ E-H_0 }V|\psi\rangle\\
    |\psi \rangle &=|\phi \rangle+\frac{ 1 }{ E-H_0 }V|\psi\rangle \tag{3}
\end{align*}
Other Information
Sakurai$^1$ discusses ($\mathbf{7.1.5}$) (which is the same as ($\mathbf{3}$) ), and say's that on it's own it has no meaning, but that this may be addressed by making $E$ slightly complex. He then gives the
Lippmann-Schwinger equation in the form

\begin{equation*}
      |\psi^{(\pm )} \rangle =|\phi \rangle+\frac{ 1 }{ E-H_0\pm i\epsilon    }V|\psi^{(\pm )}\rangle \tag{7.1.6} \end{equation*}

Reference:
1, J.J.Sakurai, Ed San Fu Tuan, Modern Quantum Mechanics Revised Edition, Addison-Wesley Publishing Company (1994).

How do you derive, the “naive form” of the Lippmann-Schwinger Equation?


NSString Memory Warning in objective c

Question:     NSString * str1 = nil;
    NSString * str2 = nil;
    str1 = @"";
    str2 = @"";

I got memory warning "Value stored to 'str1' is never read" on above statement.
 Is there any other way to do the same?
Comment: What kind of warning? Can you put the warning message in your question?
Comment: Value stored to 'str1' is never read
Answer: The warning:
Value stored to 'str1' is never read

is simply telling you that you have a variable which you set and never use. You'll see the same sort of thing with:
static void xyzzy (void) {
    int plugh = 7;
}

where clearly the plugh variable is not being used.
That's not a serious problem (otherwise it would be an error rather than a warning) but it does notify you that either:

you're wasting space (and possibly time if you're setting it); or
it may be indicative of another problem.

One example of the latter is if you are accidentally using str2 somewhere where you intended to use str1 (possibly due to a cut-and-paste where you forgot to change the pasted code).
As to how to fix it:

If you're really not using it (and have no intention of using it), just get rid of it.
If you are going to use it, commenting it out temporarily will get rid of the warning until you do.
If you think you should be using it, then you have a problem elsewhere and you should track that down.

NSString Memory Warning in objective c


Mostrar input quando o usuário selecionar option

Question: Como faço para mostrar o label nome e o input nome somente quando o usuário selecionar o option inativo?

  Status
  <select name="status">
  <option value="Ativo">Ativo</option>
  <option value="Inativo">Inativo</option>
  </select>

  Nome
  <input type="text" name="nome">

Comment: O que você já fez até o momento?
Answer: Segue exemplo de uma das possíveis formas de ocultar/exibir o label e o input de acordo com a opção selecionada pelo usuário:

$('#status').change(function(){
  var valor = $('#status').val();
  if (valor == "Inativo"){
    $('#nome').show();
  }
  else {
    $('#nome').hide();
  }
});

Status
  <select id="status" name="status">
  <option value="Ativo">Ativo</option>
  <option value="Inativo">Inativo</option>
  </select>

  Nome
  <input id="nome" type="text" name="nome" >

Answer:

  Status
  <select id="status" name="status">
  <option value="Ativo">Ativo</option>
  <option value="Inativo">Inativo</option>
  </select>

  Nome
  <input type="text" name="nome">

Comment: se caso o inativo fosse a primeira opção do option somente clicando em ativo e depois voltando pra inativo que irá aparecer o label?
Comment: Se quiser fazer isso, basta remover o display:NONE a div de id="nome"
Comment: Cara valeu mesmo, agora ficou top
Answer: Se você está procurando dar reatividade a sua aplicação, te aconselho aprender sobre Vue.JS, veja um exemplo do que você procura:

Vue.component('my-form', {
  data: function () {
    return {
      form: {
        status: 'inativo',
        nome: 'Vue.js Rules!!'
      }
    }
  }
});

new Vue({
  el: "#app"
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.1/css/bulma.min.css" rel="stylesheet"/>

  <my-form inline-template>

        Status
        <select name="status" class="control" v-model="form.status">
          <option value="ativo">Ativo</option>
          <option value="inativo">Inativo</option>
        </select>

        Nome
        <input type="text" name="nome" class="control" v-model="form.nome">

  </my-form>


Binary classification when many binary features are missing

Question: I'm working on a binary classification problem, with about 1000 binary features in total. The problem is that for each datapoint, I only know the values of a small subset of the features (around 10-50), and the features in this subset are pretty much random.
What's a good way to deal with the problem of the missing features? Is there a particular classification algorithm that handles missing features well? (Naive Bayes should work, but is there anything else?) I'm guessing I don't want to do some kind of variable imputation, since I have so many missing features.
Comment: Some questions: How many datapoints do you have (I smell a prototypical overfitting problem) ? What do you mean when you say "the features in this subset are pretty much random" ?
Comment: Are the features missing *truly* at random?  What is the mechanism of missingness?
Comment: I have about 40,000 datapoints, so each feature appears in about 1000 rows. (Seems large enough not to be overfitting?) I meant that there aren't groups of features that often appear together (whether feature X is missing or not is independent of what other features are missing or not).
Comment: Have you tried treating the value "missing" as just another label?
Answer: Assuming data are considered missing completely at random (cf. @whuber's comment), using an ensemble learning technique as described in the following paper might be interesting to try:

Polikar, R. et al. (2010).
  Learn++.MF: A random subspace
  approach for the missing feature
  problem. Pattern Recognition,
  43(11), 3817-3832.

The general idea is to train multiple classifiers on a subset of the variables that compose your dataset (like in Random Forests), but to use only the classifiers trained with the non-missing features for building the classification rule. Be sure to check what the authors call the "distributed redundancy" assumption (p. 3 in the preprint linked above), that is there must be some equally balanced redundancy in your features set.
Answer: If the features in the subset are random you can still impute values. However, if you have that much missing data, I would think twice about whether or not you really have enough valid data to do any kind of analysis.
The multiple imputation FAQ page ---->
http://www.stat.psu.edu/~jls/mifaq.html
Comment: The paper I cited in my response discussed the issue of imputation. In short, the training set should be dense enough and there's still the issue of bias that increases with the no. missing features.
Comment: @chl Thanks - Did not know about that one.
Comment: Also, the possibility of imputing data depends on the way missing patterns arose (as pointed by @whuber, indirectly).


Approximate $Y_{1,m}$ spherical harmonic with $Y_{00}$.

Question: Given I have the most primitive spherical harmonic, $Y_{00}(\theta, \phi)=\frac{1}{2} \frac{1}{\sqrt{\pi}}$ and I look at one of the three second most primitive ones, e.g. $Y_{11}(\theta, \phi)=-\frac{1}{2} \sqrt{\frac{3}{2 \pi}} \sin \theta e^{i \phi}$, it seems to me that when I look at their plot that I did with Mathematica,

that I would be able to approximate $Y_{11}$ with $Y_{00}$ by putting two of them next to each other.
How can I find an (analytical?) solution that lets me express the higher order spherical harmonic in terms of two lower order spherical harmonics?
Answer: Slightly too long for an answer: it definitely depends on the norm you are using for your functions. If you are using the $L^2$ norm induced by round metric on the sphere, I have very bad news: the approximation is going to be very bad in general. This is because spherical harmonics are orthogonal with respect to this norm. Let us see a baby example, for instance approximate $Y_{10}$ by $Y_{00}$, and
$$\|Y_{10}-\lambda Y_{00}\|^2= \|Y_{10}\|^2+\|Y_{00}\|\lambda^2 + \lambda \langle Y_{10},Y_{00}\rangle =
\|Y_{10}\|^2+\|Y_{00}\|\lambda^2$$
Minimizing with respect to $\lambda$ gives that the best approximation is... $0\times Y_{00}$.
For your general case of approximating $Y_{11}$ it will be the same, because the set $\{Y_{lm}\}$ is orthonormal!
Comment: Note that shifting $Y_{00}$ in particular does not change too much the picture: $Y_{00}$ is *already a constant*! $Y_{00} + c = Y_{00} (1+c/Y_{00})$. In general, if "the constants function" are not in your linearly approximating set, then you need to be more careful, definitely. This definitely depends a lot on the context, the fact that this is a Hilbert space of functions, etc..
Comment: Well, you should be minimizing the integral of the square of the absolute value of this difference! Otherwise Mathematica is just minimizing w.r.t. $l$ so that **the values of the functions** at the particular (generic) point  these values are as close as possible: that is a different problem! Can you see why?

Definitely the $l$ should *not* be a function if you are approximating by linear combination (constant coefficients!) of functions. Otherwise you could approximate $Y_{11}$ by $Y_{00}$ by the "naive" $\frac{Y_{11}}{Y{00}} Y_{11}$!
Comment: Thanks for the answer! The orthogonality argument makes sense. But I wonder: Isn't it different when the $Y_{00}$ is shifted? That they have no overlap when they have the same origin makes sense, but as far as I understand it, $\lambda$ only scales it but doesn't translate it, so maybe $Y_{00}$ could be made to approximate it better by shifting it away from the origin?
Comment: At the danger of sounding silly, I have to ask another bit: I just asked Mathematica to `Minimize[(SphericalHarmonicY[1, 0, t, p] - l * SphericalHarmonicY[0, 0, t, p])^2, l ∈ Reals]` which yielded as optimal result $l=\sqrt{3} \cos \theta$, which let's the term go to $0$. From how I misunderstand this, $l \neq 0$.


How to dynamically generate iptables rule?

Question: Good day.
I have a following issue - i have plenty of the computers in my local network(probably, about 40, and this amount could increase), and i want to give remote access to all of them from the internet. All those machines are connected to internal network through one gateway/firewall/whateverelse with debian 6.0.7 on board.  I can do something like this with iptables on my debian gateway:
<code>iptables -t nat -A PREROUTING -p tcp --dst %ip% -- dport 43001 -j DNAT --to-destination 192.168.0.1:%remotedesktopport%
iptables -t nat -A PREROUTING -p tcp --dst %ip% -- dport 43255 -j DNAT --to-destination 192.168.0.255:%remotedesktopport%
</code>
So, then the owner of 192.168.0.1 machine will want to work from home, he will do it easily, and same for 192.168.0.255 etc.
But how can i make same rules for all my local network? May be there is a way to do it just more elegant way then typing manually 255 iptables rules? May be there is some trick to dynamically resolve redirection, something like
<code>-A PREROUTING -d %ip% -p tcp --dport 43%three-digits-number-var% -j DNAT --to-destination 192.168.0.%three-digits-number-var%
</code>
where %three-digits-number-var% is a variable from 0 to 255?
I hope that somebody could help me or show me my mistakes, because i'm quite a new to networking and linux.
Upd. The main idea of my current configuration is that number of port matches local ip. E. g.  port 43001 for 192.168.0.1, 43005 for 192.168.0.5 and so on. So just specifying port range won't work. Or it would due to some voodoo?..
Answer: With iptables you can specify a port range using
<code>--dport 43000:43255
</code>
What I think you really need to do here is set up a VPN server so that your remote workers use that to connect to your office network.
Comment: I know nearly nothing about VPN. Am i able to setup it when, for example, my computer at home have "grey" ip?
Comment: One more thing. The DNAT target is only valid in the PREROUTING and  OUTPUT chains.
Comment: Yeah, thanks. Edited that. That's really PREROUTING, i've mistakened.


Can it be shown that a set X is infinite if and only if there exists some $F:X\to X$ that is an injection but not a surjection?

Question: If the function is not surjective, then at least one element of the codomain has no pre-image.  However, because F is a function, every element in the domain is mapped to something in the codomain.  But since we know that F is injective, then we can't use an element in the codomain more than once in our mapping.  That must mean that there is an infinite set of elements in the codomain if we can "skip" one and still be injective.  I'm having trouble, however, translating my thoughts into a proof format.
The Axiom of Choice is not available to me for the purposes of this proof.
Infinite for this question would be that it as has a countably infinite subset.
Thank you to all who addressed my question, both for your help and patience.
Answer: The definition of infinite can vary. It follows from the fact that we have many definitions of finite, and without the axiom of choice they are not necessarily equivalent.
If you have defined "infinite" as "having a countably infinite subset", then there is no need to use the axiom of choice. Use the fact that $n\mapsto n+1$ is an injection which is not a surjection, and conclude the existence of such map; in the other direction let $f$ be a non-surjective injection and let $a$ be an element not in its range, show that $f^n(a)$ is a countably infinite subset of $A$, and conclude that $A$ is infinite. This sort of definition is called Dedekind-infinite.
If you have defined "infinite" as "not equipotent with a finite initial segment of the natural numbers", then you cannot prove this results without the axiom of choice. But the proofs that you can't are difficult and technical. In modern terms, by the way, the definition of infinite is this one, and when not allowing the axiom of choice it is important to be precise about which definition you are using.
Answer: Not without some part of the axiom of choice. It's consistent with $\mathsf{ZF}$ that there be infinite, Dedekind-finite sets, i.e., sets that are not finite but that do not admit an injection to a proper subset.
Every Dedekind-infinite set is easily seen to be infinite. The converse follows from the axiom of countable choice, though I believe that it's actually strictly weaker.
Comment: Your belief is correct. It is weaker than countable choice.


Where the members/methods of inner class, static nested class and local inner class are stored.

Question: Is there any difference in how JVM is allocating space to inner class members and methods.
Please provide what is the difference in this context to all the available kinds of nested classes(static,local,non-static,anonymous).
I searched from various other sources but could not get the clear idea.
Comment: What do you mean by stored ?
Comment: resides or allocated inside main memory not related to perm. storage
Comment: Why do you want to know that? It's most likely up to the JVM you use (oracle, open jdk, .. version 5, 6, 7..). For the purpose of programming Java it should be safe to assume that there is no difference.
Comment: just for any mad interviewer. just in brief of heap and stack will be enough.
Comment: THe classes definition are stored in PermGen, as the nested class (inner static) are treated as normal class then they should be stored there too. The inner class and local class that are part of class they belong is would be not natural store in different space. I can not provide for you a prove but Permament generation could be the right place. This apply to Java <= 7 as inn 8 htere is not permgen
Answer: The static data members of a class are stored with the class, and the non-static data members in each instance. It doesn't make any difference whether the class itself is static, nested, inner, or anonymous.
The methods, whether static or non-static, are stored with the class, again regardless of whether the class itself is static, nested, inner, or anonymous.
Comment: It means non-static are stored in heap area whether or not enclosed class has non static members?
Comment: It doesn't make any difference either whether the class has enclosed classes that are static, inner, or anonymous. I don't understand why you're even asking, or how you think it could possibly make a difference. It's simple. Don't complicate things that aren't complicated. All you need to know is the first sentence of my answer. Forget everything else.


Ubuntu /boot full

Question: On an old server that still runs Ubuntu 16.04 the /boot partition is full, not with old kernels but with kernels that are all newer than the one that is running.
I'm running 4.4.0-176-generic, and the listing is like this (same with initrd.img* files):
-rw------- 1 root root 7220256 Dec  1 19:58 vmlinuz-4.4.0-198-generic
-rw------- 1 root root 7217792 Nov 27 14:03 vmlinuz-4.4.0-197-generic
-rw------- 1 root root 7220608 Nov 10 19:34 vmlinuz-4.4.0-194-generic
-rw------- 1 root root 7221056 Oct 14  2020 vmlinuz-4.4.0-193-generic
-rw------- 1 root root 7220448 Aug 31  2020 vmlinuz-4.4.0-190-generic
-rw------- 1 root root 7217792 Aug 14  2020 vmlinuz-4.4.0-189-generic
-rw------- 1 root root 7219360 Jul 22  2020 vmlinuz-4.4.0-187-generic
-rw------- 1 root root 7209656 Mar 16  2020 vmlinuz-4.4.0-177-generic
-rw------- 1 root root 7209560 Feb 28  2020 vmlinuz-4.4.0-176-generic

How can I safely clean things up?
I currently cannot install anything with apt-get, I get errors such as:
root@dev-server1:/boot# apt-get  install  postfix
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 linux-image-generic : Depends: linux-image-4.4.0-200-generic but it is not going to be installed or
                                linux-image-unsigned-4.4.0-200-generic but it is not going to be installed
                       Recommends: thermald but it is not going to be installed
 linux-modules-extra-4.4.0-200-generic : Depends: linux-image-4.4.0-200-generic but it is not going to be installed or
                                                  linux-image-unsigned-4.4.0-200-generic but it is not going to be installed
 postfix : Depends: ssl-cert but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

...which looks strange as it is referring to a kernel that is not even there.
Thanks,
George
Answer: First, Ubuntu 16.04 LTS has reached its end-of-life in last month, so you need to update to latest Ubuntu ASAP, otherwise you are running outdated software and exposing your system to all kinds of compromises.
You can try to remove the old kernel packages as follows:
Get a list of all kernel installed kernel packages:
dpkg -l | grep linux-image

Purge each package from the system:
apt purge linux-image-4.4.0-176-generic

where you run the command for each but two latest kernel packages you have installed.
After purging old packages, you can try running apt-get -f install to complete installation of missing dependencies.
Comment: +1 but you may also want to avoid deleting  the kernel package that matches the  exact version that you are currently running (check with `uname -a`).
Comment: Let me reiterate that /boot contains no old kernels, only kernels that are NEWER than the one I'm running. Which ones should I delete? A couple that are in-between what I'm running and the newest one?
Comment: Yes, you can start from the in-between. You should make sure that you use the most recent kernel though.
Comment: I just tried purging an in-between kernel and ran into the same problem as before (unmet dependencies with kernel version 200). It seems using apt to purge is futile, how about brute-force "rm" command and then let "apt-get -f install" clean things up?
Comment: What does `apt install linux-image-4.4.0-200-generic` say?

Ubuntu /boot full


In javascript replace single quote from string generated using serverside function

Question: In my Asp.Net site I have third party library in C# which has Method "LocalizeString" to generate local translation for text for controls.
var lblFriendName = '<%=LocalizeString("lblFriendName")%>';

This is causing issue for some string. In this case function returns string  : Friend's name
Where single quote is creating issue.
I cant modify server side code. So is there anyway to make this code line working in JavaScript ?
Answer: Use the HttpUtility.JavaScriptStringEncode method. This will escape any kinds of special JS characters for you. You should ALWAYS use this method when you want to output a string into JS, you can even have security issues with it! Eg. if the string is x'; alert('pwn!'); 'y, you will output this to your browser:
var lblFriendName = 'x'; alert('pwn!'); 'y';

Comment: you mean something like '<%=HttpUtility.JavaScriptStringEncode(LocalizeString("lblFriendName"))%>'; ??
Comment: Worked like charm. and feels me stupid to forget such important function


Random variable and independence on unit interval

Question: I have a simple probability question that has been confusing me.
Lets say I generate a random variable $X$ drawn from the uniform distribution on $[0,1]$. Now, lets define two real (nonrandom) numbers $p,q\in[0,1]$.
Define event $A$ to be the event that $X\leq p$.
Define event $B$ to be the event that $X \geq (1-q)$.
My question is, for what values of p and q are A and B independent?
My idea is that these two events will be dependent when there is a nonempty intersection between $X\leq p$ and $X \geq (1-q)$ and independent if this intersection is empty. So my answer is that $A$ and $B$ are independent when $p-(1-q)\leq 0$. I was hoping someone could help me know if I am correct and if this equality in my inequality answer relating $p$ and $q$ should be strictly less than? My confusion with this arises because of this boundary when $p=1-q$.
Comment: If the intersection between $X \leq p$ and $X \geq 1-q$ is empty, then knowing that $X \leq p$ means that $X \geq 1-q$ is not the case. Mutually exclusive events are always dependent.
Answer: By definition, $A$ and $B$ are independent if and only if $\mathbb P(A \cap B) = \mathbb P(A) \mathbb P(B)$.  In this case, $\mathbb P(A) = p$, $\mathbb P(B) = q$, $\mathbb P(A \cap B) = p - (1-q) = p+q-1$ if $p \ge 1-q$, $0$ otherwise.  So for independence you need $p q = p+q-1$ or $p q = 0$.  But $pq - (p+q-1) = (p-1)(q-1)$.  Thus the condition is that $p=0$ or $p=1$ or $q=0$ or $q=1$.
Comment: No.  When $p \le 1-q$ the intervals don't overlap and $\mathbb P(A \cap B) = 0$.  In that case, in order for the events to be independent we need either $\mathbb P(A)=0$ or $\mathbb P(B)=0$.
Comment: You said that independence only occurs here if $p\geq 1-q$, but shouldn't this be when $p\leq 1-q$?


How to install imagemagick on centos 8?

Question: I tried with :
dnf install GraphcsMagick

yum install ImageMagick

Got always: Unable to find a match
Any idea ?
Answer: This worked for me
dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y
dnf install GraphicsMagick

@yarek
you have a typo (GraphcsMagick) it should be GraphicsMagick.
Answer: ImageMagick is in EPEL repository[1].
You have to enable EPEL repository in order to install it[2].
[1] https://dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/i/ImageMagick-18.104.22.168-1.el8.x86_64.rpm
[2] https://www.linuxtechi.com/enable-epel-repo-centos8-rhel8-server/

How to install imagemagick on centos 8?


Executar PHP dentro da Função JavaScript

Question: Pessoal tenho a seguinte função sendo chamada por onclick, o problema é que não consigo usar variável JavaScript no php, alguém tem uma ideia de como faço essa função?
function fila(id){
var idBanco = id;
console.log(variaveljs);

<?php
    $sql = "UPDATE `tabelaclientespos` SET `empresa` = '2' WHERE
     `tabelaclientespos`.`Id` = idBanco";
    mysqli_query($conn,$sqlTempo);
?>

}
Comment: Outra: [Passar variável php para javascript](https://pt.stackoverflow.com/q/58958/5878)
Comment: [Como passar variáveis entre páginas PHP via JavaScript?](https://pt.stackoverflow.com/q/12241/5878)
Comment: [Atualizar uma variável PHP dentro do JavaScript num intervalo de tempo](https://pt.stackoverflow.com/q/312504/5878)
Comment: Se nenhuma dessas lhe atender, por favor, edite sua pergunta e esclareça melhor o problema.
Answer: Não é melhor fazer ao contrário? Coloque a função javascript dentro das tags  e chame-a ou não usando o PHP.
<?php
echo "";
?>


How do you efficiently search across a group of lists in Python?

Question: In Python I have a group of lists that track information about some users:
user_id = [1,2,3,4,5]
user_name = ['bob', 'alice', 'jerry', 'lisa', 'tom']
user_email = ['email@example.com', 'email@example.com', 'firstname.lastname@example.com', 'firstname.lastname@example.com', 'firstname.lastname@example.com']
...

where the i'th element in each list correspond to each other.
I want to get user info "x" given info "y". In most cases I'd use a dictionary for this for the constant lookup time, but I don't want to build and maintain dozens of dictionaries.
If I maintain a dictionary for every pair of lists shown above I'd have
name:email
email:name
name:id
id:name
email:id
id:email

which already starts getting unmanageable - and grows very quickly with the number of attributes.
I could have everything map to user_id, and then have only 2n dictionaries, but happy to learn of a more appropriate data structure for this use case.
To illustrate how the code is currently implemented:
def get_email_by_user_id(user_id):
   return [email for email, uid in zip(user_email, user_id) if uid == user_id][0]

As you can imagine, very slow :P
Comment: Databases have this same issue and they solve it by creating indices for commonly searched fields. This is analogous to your lookup dictionaries. If you want constant time lookups on a field, you need the index; the alternative is to scan the data in linear time. You probably don't need so many though. If you stored the users as single objects, you could have a single `name -> object` lookup rather than `name -> id` `name -> email `etc.
Comment: Just make a list of dictionaries and have a "query" function where you pass the key and the value you want.  Unless you have millions of users, that will work fine.  If not, then use a database (sqlite3?), which will do exactly the same thing.
Comment: Alternatively, store the records in a dictionary with `id` as the key, and have dictionaries that map username to id, or email to id.
Comment: List comprehensions don't return early. Don't use a list comprehension for this (among other things).
Answer: In the end I took the only option that gave the the performance I needed
I decided the contents of user_id are the canonical identifier.
I then created the following dictionaries:
def make_dictionaries(user_id, other_lists=[('user_name', user_name), ('user_email', user_email)]):
   to_id_dictionary = {}
   from_id_dictionary = {}

   for list_name, list_content in other_lists:
      from_id_dictionary[list_name] = {uid:cont for uid,cont in zip(user_id, list_content)}
      to_id_dictionary[list_name] = {cont:uid for uid,cont in zip(user_id, list_content)}

   return to_id_dictionary, from_id_dictionary

I can then do:
def get_email_by_user_name(user_name):

   uid = to_id_dictionary['user_name'][user_name] # Get UID from name
   return from_id_dictionary[user_email][uid] # Get email from UID

Answer: # Dict for holding your data
data = dict()

# Put all your stuff into data
for id, name, email in zip( user_id, user_name , user_email):
    data[ id ] = { "id": id , "username" : name , "email" : email }

# Function for lookup up by key and value
def lookup_info( key_name , lookup_value , data ):
    '''
    Takes a key name, a lookup value and a dictionary of data.

    Returns the dictionary item
    '''
    for k,v in data.items():

        if v[ key_name ] == lookup_value:
            return( data[ k ] )

Comment: This still would run in O(n)
Comment: True but more organised than previous code. Could otherwise do binary/DFS?
Comment: I don't think binary searches are much help if the data is not sorted.
Comment: Could sort the dicts in "data" array by the lookup key and do it, depends if sort+search would be faster than just a simple loop through - at this point would recommend a database.
Answer: Since the data is related they can be organized into a single list of tuples of the related columns.
DATA = [
    (1, 'bob', 'email@example.com'),
    (2, 'alice', 'firstname.lastname@example.com'),
    (3, 'jerry', 'firstname.lastname@example.com'),
    (4, 'lisa', 'firstname.lastname@example.com'),
    (5, 'tom', 'email@example.com'),
]

Then, a general function can be made that considers only the column you are interested in.
def find_user(user_id=None, user_name=None, user_email=None):
    """Find first user matching given criteria.

    A None value means "don't care".

    Returns tuple of (id, name, email) if found, otherwise None.
    """
    # Collect desired criteria into mapping of record index to desired index value.
    criteria_cols = {i: c for (i, c) in enumerate((user_id, user_name, user_email)) if c is not None}
    for rec in DATA:
        if all(rec[idx] == criteria for (idx, criteria) in criteria_cols.items()):
            return rec  # return early if found.

This function considers any non-None value, and returns the matching record. If no records match, fall through and return the default None value.
print(find_user(user_id=1))
print(find_user(user_id=2))
print(find_user(user_name="alice"))
print(find_user(user_email="firstname.lastname@example.com"))
print(find_user(user_id=3, user_email="email@example.com"))
print(find_user(user_id=2, user_email="firstname.lastname@example.com"))
print(find_user(user_id=3, user_name="jerry"))

Results in
(1, 'bob', 'email@example.com')
(2, 'alice', 'firstname.lastname@example.com')
(2, 'alice', 'firstname.lastname@example.com')
(3, 'jerry', 'email@example.com')
(3, 'jerry', 'firstname.lastname@example.com')
None
(3, 'jerry', 'firstname.lastname@example.com')


Search keyword with selectable exposed filters

Question: I'm trying to make a search view with one textfields and two checkbox filters (body, tags). The search text would only search the selected fields and would show results as summaries.
I've tried combined fields filters in Views, but the filters selected are all enabled. Is there was a way to toggle the filters via checkbox?
Answer: I think this is the module that you are looking for....
Better Exposed Filters

The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.
Views Filters is a powerful tool to refine the results returned by a
  given view. When you expose a filter, you allow the user to interact
  with the view making it easy to build a customized, advanced search.
  For example, exposing the node type field as a filter lets your site
  visitor limit their search queries to just blog entries. Better
  Exposed Filters gives you greater control over the rendering of
  exposed filters.
Why use this module? Because it provides a better user experience than
  the default option. Try telling a client that they should click on an
  option, then scroll to the next option and ctrl+click on it. Don't
  just click 'cause you'll lose your first selection. Oh, and ctrl+click
  again to unselect an option... Yeah, not user friendly.
Comment: Sadly BEF cannot, to my knowledge, give me the option of searching by either Article tags, body or title.


How to link LuaJIT with a C++ program?

Question: I'm trying to simply use the following C++ code
lua_State *state = luaL_newstate();

luaL_openlibs(state);

lua_getglobal(state, "_G");
lua_pushstring(state, "print");
lua_pushnumber(state, 4.5);
lua_call(state, 2, 1);

lua_close(state);

And I'm getting linker errors.  All of the aforementioned function calls generate linker errors:
1>main.obj : error LNK2001: unresolved external symbol _luaL_newstate
1>main.obj : error LNK2001: unresolved external symbol _lua_pushnumber
1>main.obj : error LNK2001: unresolved external symbol _lua_call
1>main.obj : error LNK2001: unresolved external symbol _lua_pushstring
1>main.obj : error LNK2001: unresolved external symbol _luaL_openlibs
1>main.obj : error LNK2001: unresolved external symbol _lua_getfield
1>main.obj : error LNK2001: unresolved external symbol _lua_close

The header inclusion is done with this code :
extern "C" {
    #include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"
}

I "installed" LuaJIT using MinGW, mingw32-make BUILDMODE=static.  It gave me a nice "Successfully built LuaJIT".
I'm compiling the code with VS2012.  I've set up the linker like this :
Additional Library Directiories : D:\Programming\LuaJIT Source\LuaJIT-2.0.1\src
Additional Include Directiories : D:\Programming\LuaJIT Source\LuaJIT-2.0.1\src
I'm on a windows7 machine and I'm using the latest LuaJIT from their github page.
Answer: In general, you should compile all your libraries using the same compiler as your application. MinGW produces a .a library archive whereas MSVC typically outputs a .lib archive.
So: Recompile LuaJIT using MSVC, add the path where luajit.lib resides to your linker path and add luajit.lib to the list of libraries to be linked into your application.
Comment: Thank you, this worked, I had to add this : #pragma comment(lib, "lua51.lib")
Comment: hi. i tryed to compile luajit using msvc as it says in installation instruction. but i always fail. i just can't start msvcbuild command from .net command prompt. does anyone know what i'm doing wrong?
Answer: You should set the path to LuaJIT library ,see the pic below

How to link LuaJIT with a C++ program?