PCA; variance, interpretability, and scaling

Question: I've been going through threads about PCA and the predictive power of various axes, but since I cannot comment, I am opening a new question.
There is a lot of discussion whether PCA components with small variance can be highly predictive and thus we should not 'drop them'? In general the answer is 'yes', since it all depends on the data, but the examples that are typically given are a bit confusing to me.
A typical example goes like this: we have a feature x_1 (e.g. height) that fluctuates a lot and feature x_2 (e.g. temperature) that varies less, but on the other hand somehow effects our label most. Thus, low variance axes can be important.
I have a few questions in regards to the above:
1) the examples refer to features in the non-transformed system (prior to applying PCA) and since these features need to be/can be standarised, the whole idea of their absolute variance looses the point, no?
2) after the PCA transformation there can be a heterogeneity of principal axes variance, but these axes are now linear combinations of the original axes, so when we 'drop' one or more to reduce the dimension, we do preserve partial information from all the original axes (i.e. we do not drop any original axes)
Just to summarise my problem - it would seem that all the examples refer to the degree of variance in the original data and not variance after the transformation (maximisation of which is the objective of PCA) so I am wondering what would be a correct example of a case where low-variance PCA axes can be important?
(the issue being also that after PCA the data looses its interpretability).
Answer: This question appears to focus on two things:

How can principal components regression fail badly?
Could the failure be due to not standardizing the variables?

Let me elaborate on the meanings of these terms.  The setting is where you have $(x_1, x_2, \ldots, x_k, y)$ data.  You view the values of the $y$ as $n$ independent observations of random variables $Y(x_1, \ldots, x_k)$ that depend on the $x$ values. You wish to model the expectation of $Y$ (equivalently, you wish to "predict" $Y$) by means of a linear function of the $x_i,$
$$E[Y] = h(\beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k)$$
for some stipulated function $h$ and unknown parameters $\beta_j.$  (See https://stats.stackexchange.com/a/148713/919 for more about this approach, which when $h$ is the identity underlies the usual ordinary least squares model.)
In many practical cases, especially observational studies, the observed variables (thought of as $k$ $n$-vectors) may be close to linearly dependent, a condition referred to as "multicollinearity."  This creates technical problems for fitting the model and conceptual problems in interpreting the estimated coefficients.
A remedy that is frequently offered is to conduct a preliminary Principal Components Analysis (PCA) of the regressor variables.  PCA replaces those $k$ vectors by $k$ other vectors ("principal components") $z_1, \ldots, z_k$ with the following properties:

For any $i\ne j,$ $z_i$ and $z_j$ are orthogonal.
For $i \lt j,$ the Euclidean length of $z_i$ equals or exceeds that of $z_j.$
For every $i,$ $x_i$ can be reconstructed as a linear combination of a constant and the $z_j.$

The first two properties greatly simplify the model fitting, while the last guarantees that the model has not really changed: the $z_i$ are merely a way of re-expressing the $x_i.$
The Euclidean length in $(2)$ is usually interpreted as something proportional to a variance, because the $z_j$ are almost always constructed so that their components sum to zero.  In this sense, $z_1$ is a "direction of greatest variability" of the $x_i,$ $z_2$ is a direction of second greatest variability, and so on.  Thus, in reconstructing the $x_i$ from the $z_j,$ the first few principal components contribute the most and may be referred to as the "most important" components.  Usually one can safely omit the last few principal components and still very closely reconstruct the original $x_i.$  This further simplifies the modeling by reducing the number of independent variables.
There is a fundamental problem with this "principal component regression" approach: it makes no consideration of the observed responses $y.$  Consequently, it may utterly fail.
I offer an example and then, at the end, show how to construct many others like it with any values of $n$ and $k.$
First, here is a scatterplot matrix showing the relationships among $k=3$ variables and a response $y$ for $n=200$ observations. The red lines are least-squares fits.

The covariance matrix of the $x_i$ shows they already have comparable scales, so it will make little difference whether PCA uses the covariance or the correlation:
     X.1  X.2  X.3
X.1 1.25 1.22 0.10
X.2 1.22 1.20 0.10
X.3 0.10 0.10 0.97

In the following analysis the correlation matrix was used: that is, the $x_i$ were standardized before applying PCA. Using the covariance matrix, the results would be qualitatively the same (I checked).
The strong positive correlation between $x_1$ and $x_2$ creates multicollinearity.  This is evident in the "scree plot" for the PCA, which shows the relative squared Euclidean lengths of the $z_j:$

The tiny third component can be ignored, indicating these three original variables can be accurately reconstructed from just two principal components.  Confirming this, a standard summary reports the Euclidean lengths of the components:
Importance of components:
                         PC1    PC2     PC3
Standard deviation     1.419 0.9910 0.07023
Proportion of Variance 0.671 0.3273 0.00164
Cumulative Proportion  0.671 0.9984 1.00000

Seeing this output, anyone using PCA regression would surely drop the last component $z_3$ or PC3), figuring that "the first two components explain 99.84% (essentially 100%) of the variation among the regressors."
Let's see how $y$ relates to the principal components $z_j.$  Here is the top row of the scatterplot matrix of $(y, z_1, z_2, z_3)$ (the other rows will show perfect zero correlations among the $z_j$ due to property $(1)$ of the PCA):

Therein lies the problem: although $y$ is uncorrelated with the principal components that would be kept, it is strongly correlated with the one that would be dropped.
Let's examine the two ordinary least squares regression models under consideration.  First, the "full" or "base" model that includes all the $x_i:$
             Estimate Std. Error  t value Pr(>|t|)
(Intercept) -0.024359   0.006636   -3.671 0.000312 ***
X.1         -9.053688   0.059840 -151.299  < 2e-16 ***
X.2          9.237486   0.061058  151.289  < 2e-16 ***
X.3         -0.055985   0.006776   -8.263  2.1e-14 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.09354 on 196 degrees of freedom
Multiple R-squared:  0.9915,    Adjusted R-squared:  0.9914
F-statistic:  7651 on 3 and 196 DF,  p-value: < 2.2e-16

This demonstrates that $y$ can be predicted with high precision from these three variables (and an intercept term), with relatively little error.  (It is possible to construct examples in which this full regression has an arbitrary high p-value: in other words, it looks "insignificant."  Because such examples typically have higher values of $k,$ I won't encumber this post with the lengthy output.)
Here are results for the PCA regression in which every principal component but the last is included in the model:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.006847   0.071687   0.096    0.924
PC1         -0.002607   0.050653  -0.051    0.959
PC2         -0.015818   0.072521  -0.218    0.828

Residual standard error: 1.014 on 197 degrees of freedom
Multiple R-squared:  0.0002549, Adjusted R-squared:  -0.009895
F-statistic: 0.02511 on 2 and 197 DF,  p-value: 0.9752

This model is worthless: the adjusted $R^2$ is essentially zero all p-values are large, and all estimated coefficients are indistinguishable from zero.  As such, it reflects a dramatic failure of PCA regression.
It should be clear why the failure occurred: $y$ is very nearly a linear function of the smallest principal component.  Indeed, when we include only the last principal component $z_3$ we obtain a great model:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.006847   0.006679   1.025    0.307
PC3         14.302384   0.095341 150.013   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.09445 on 198 degrees of freedom
Multiple R-squared:  0.9913,    Adjusted R-squared:  0.9912
F-statistic: 2.25e+04 on 1 and 198 DF,  p-value: < 2.2e-16

Herein lies a key insight: when the full model fits the response $y$ well but principal components regression does not, that means the response is related to information present in the smaller principal components.  This suggests several effective courses of action.  For instance, you might fit a sequence of models in which you introduce each principal component in order (from largest to smallest) until obtaining one that comes sufficiently close to the full model.  I will omit the details because there are many considerations and they are well discussed in other threads on variable selection and model building.

The R code to create such examples reveals their method of construction: simply create the response $y$ from the smallest principal components of the $x_i.$  It's that easy.  Of course things don't work this way in the "real world."  The point is that it's possible for your response in your problem to behave like this, so you should be aware of that, know how to detect it, and have methods to fix it.
n <- 200        # Sample size
k <- 3          # Independent variable count
sigma <- 0.1    # Error SD for `y`
tau <- 0.1      # Controls multicollinearity of `X`; 0 is collinear
# set.seed(17)  # Uncomment to reproduce the figures exactly
#
# Create multicollinear explanatory variables.
#
X <- matrix(rnorm(n*(k-1)), nrow=n)
X <- cbind(X[, 1] + rnorm(n, 0, tau), X)
colnames(X) <- paste("X", 1:k, sep=".")
round(cov(X), 2)               # Display their covariance matrix
#
# Conduct PCA and keep the largest PCs.
# Set `scale.=FALSE` to do PCA on the covariances.
#
PCA <- prcomp(X, scale.=TRUE)
plot(PCA)
summary(PCA)
k.keep <- sum(PCA$sdev > 0.5) # Some people retain only those exceeding 1
#
# Construct a response that is related primarily to a small PC.
#
y <- c(scale(PCA$x[, k])) + rnorm(n, 0, sigma)
#
# Compare the full regression to (a) PC regression and
# (b) regression on the last PC only.
#
summary(lm(y ~ ., as.data.frame(X)))                             # Full regression
summary(lm(y ~ ., as.data.frame(PCA$x[, 1:k.keep, drop=FALSE]))) # PC regression
summary(lm(y ~ ., as.data.frame(PCA$x[, k, drop=FALSE])))


How to access url of Remote Video, Document and Image inside twig template?

Question: I have a field called Media (machine name: field_media) inside of a content type. This field Media takes the media types of Remote video, Image, and Documents. I am currently trying to render this media inside my twig template as a link to whatever media type it is. For example, if it's a remote youtube video, the link would take you to the video or if it's a pdf document, the link would take you to the internal page to display that document.
Examples:
Document:

Remote video:

So inside my field twig template, grab the above values and for each item, place it inside an href attribute like so:

{{ item.content }}

Inside the href value I've tried values such as node.field_media.entity.field_media_oembed_video.value (for remote video) but that didn't work.
My twig template is displaying like this:

Which looks how I want but I can't get the link to take me to the remote vid or internal pdf.
Side note:
In the Manage Display menu of my content type, I have this configuration for the field.
Comment: Have you tried `node.field_media.entity.field_media_oembed_video.0`?
Comment: @shelane yea that didn't work :/ came back as null
Answer: After quite an extensive search and with help of https://www.drupal.org/project/twig_vardumper this worked for me in a Paragraphs Twig template, to print out the remote URL of a youtube video; managed in the Drupal core Media module.
{{ paragraph.field_media_1.entity.field_media_oembed_video.entity.field_media_oembed_video.value }}

Replace field_media_1  with the system name of your defined field.
Comment: awesome thanks! Crazy how long some of those variables are lol
Answer: The name of our field is field_images and we have this to display a thumbnail of our video. That if statement may be the key.
{% if content.field_images[0]["#media"].field_media_video_embed_field.0.value %}
  {{ drupal_image(content.field_images[0]["#media"].thumbnail.entity.uri.value, 'ourimagestyle') }}
{% else %}
  {{ content.field_images[0] }}
{% endif %}

Comment: I am just looking to display a link to the video not the thumbnail but that is good to know for future use
Comment: Something in this though `content.field_images[0]["#media"].field_media_video_embed_field.0.value`. If I could ever get the xdebug to work with twig, it would be easy to try to dissect what that variable breakdown looks like.
Comment: yea seems you have to flush cache everytime you want xdebug to run and even then doesn't always seem to work. I'm trying the https://www.drupal.org/project/twig_vardumper module but not much help either. Thank you though I'll look into something like that!


Hessian of profile likelihood used for standard error estimation

Question: This question is motivated by this one. I looked up two sources and this is what I found.
A. van der Vaart, Assymptotic Statistics:

It is rarely possible to compute a profile likelihood explicitly, but
  its numerical evaluation is often feasible. Then the profile
  likelihood may serve to reduce the dimension of the likelihood
  function. Profile likelihood functions are often used in the same way
  as (ordinary) likelihood functions of parametric models. Apart from
  taking their points of maximum as estimators $\hat\theta$, the second
  derivative at $\hat\theta$ is used as an estimate of minus the inverse
  of the asymptotic covariance matrix of e. Recent research appears to
  validate this practice.

J. Wooldridge, Econometric Analysis of Cross Section and Panel Data (the same in both editions):

As a device for studying asymptotic properties, the concentrated
  objective function is of limited value because $g(W,\beta)$ generally
  depends on all of $W$, in which case the objective function cannot be
  written as the sum of independent, identically distributed summands.
  One setting where equation (12.89) is a sum of i.i.d. functions occurs
  when we concentrate out individual-specific effects from certain
  nonlinear panel data models. In addition, the concentrated objective
  function can be useful for establishing the equivalence of seemingly
  different estimation approaches.

Wooldridge discusses the problem in wider context of M-estimators, so it applies to maximum likelihood estimators also.
So we get two different answers for the same question. The devil in my opinion is in the details. For some models we can use hessian of profile likelihood safely for some models not. Are there any general results which give conditions when can we do that (or cannot)?
Comment: See *On Profile Likelihood* (S. A. Murphy and A. W. van der Vaart), http://www.jstor.org/pss/2669386
Comment: These passages do not seem to address the same question at all: the first concerns numerical calculation for a given dataset whereas the second concerns "studying asymptotic properties."  Use of the Hessian is typically a purely mathematical consideration with typically straightforward answers: see our [related discussion](http://stats.stackexchange.com/q/7308/919).
Comment: van der Vaart says that Hessian is used for calculation of **asymptotic** covariance matrix. Since Wooldridge talks that concentrated objective function cannot be used for study of asymptotic properties, this implies that its hessian (numerical) cannot be used for estimating standard errors. I did not forget our discussion, so I take this passage with the grain of salt. However neither van der Vaart nor Wooldridge given any references. Before doing the extensive research I just wanted to check maybe this is something well known.
Comment: Excellent point: somehow I overlooked the "asymptotic" in the van der Vaart quotation.  There still may be no contradiction, however: Wooldridge merely says that the obvious simple justification (iid summands) is not available for demonstrating that van der Vaart's approach works; Wooldridge does not say it doesn't work ;-).
Comment: @whuber, yes but he doesn't say that it work either :) I am aware that there might be no contradiction, I only want to know whether there are some definite results.
Answer:
For some models we can use hessian of profile likelihood safely for
  some models not

Unfortunately, that is true for now and unlikley to change.
The clearest discussion that I am aware of is The rules of conditional inference: Is there a universal definition of nonformation? B Jørgensen - Statistical Methods & Applications, 1994.
And for some of the issues specific to adressing failures of profile likelhood Stafford, J. E. (1996). A robust adjustment of the profile likelihood, Annals of Statistics, 24, 336-52.

Answer: A fast answer: This is discussed in chapter three of O E Barndorff-Nielsen & D R Cox: Inference and asymptotics, Chapman & Hall, page 90, equation 3.31, which they ascribe to Patefield. They conclude that for a scalar parameter this is valid (they do not analyse other cases).


While using spring form am getting "equal symbol expected " issuse in jsp page

Question: Actually while mapping the path in input field iam getting this exception,
here i will add the jsp page in which am getting exepetion
<form:label path="firstName">
                First Name*
              </form:label>
              <form:input type="text" path="firstName" required autocomplete="off" />
Comment: use required="required" instead of only required.
Comment: the exception is org.apache.jasper.JasperException: /WEB-INF/jsp/login.jsp (line: 35, column: 64) equal symbol expected
Comment: input tagis my 35th line
Answer: The issue is with your input
This is your input
<form:input type="text" path="firstName" required autocomplete="off" />

This is the expected input:
<form:input type="text" path="firstName" required="required" autocomplete="off" />


Are clubs' Champions League Final tickets nominative?

Question: Are the CL Final tickets sold by the clubs (as opposed to those UEFA sells) nominative? Like, do they ask you at the counter for an ID card or a name?
Answer: Yes they are.
From https://championsleague-faq.tickets.uefa.com/ :

Why must I bring my ID card or passport with me to the Final?
  You need to have your ID card or passport with you on the day of the Final so that your identity can be checked against the details provided with your application. Should a ticket holder not be in possession of a valid ID card or passport, they will not be allowed into the stadium.

And from the ticketing terms and conditions:

3.7. In the Application Form, for all Applicants and Guests: (i) all Applicants are required to provide: surname, first name, date of birth, country of birth and Passport or ID number; and (ii) Italian nationals only, additionally, shall also specify province of birth and city of birth.
Comment: But this holds as far as the tickets sold by the UEFA go, while my question was about the questions sold by the finalist clubs.
Comment: Okay. I will research and get back to you.


What are the plugins installed on Joomla script on this site

Question: What are the plugins installed on Joomla script on this site:
http://www.josourmagazine.ae/english/
( style , models , extentions , plug-ins ... etc. )
thanks for any help
zuhair
Answer: Just look at the source code and you'll have some ideas!


Change of order of quantifiers "every$\text{ }t$" and "almost surely": what difference does it make?

Question: Given a certain probability space $(\Omega,\mathcal{A},\mathbb{P})$ and a random variable $X:t\mapsto X(t)$ defined on it, which is the difference between the following statements:
$$\color{blue}{\text{every }t}\text{ is }\color{red}{\text{almost surely}}\text{ a nondifferentiability point for }X(t)\tag{1}$$
$$\color{red}{\text{almost surely }} \color{blue}{\text{every }t}\text{ is a nondifferentiability point for }X(t)\tag{2}$$
?

I would rewrite $(1)$ as:
$$\tag{1.int}\forall t\text{, }\mathbb{P}(t\text{ is a nondifferentiability point for}X(t))=1$$
and $(2)$ as:
$$\tag{2.int}\mathbb{P}(t\text{ is a nondifferentiability point for}X(t), \forall t)=1$$

First, I don't know whether $(1.\text{int})$ and $(2.\text{int})$ are correct "rewritings" of $(1)$ and $(2)$ (resp.). In general, whichever the difference between $(1)$ and $(2)$, which is the gist of such a difference from a mathematical standpoint? I cannot grasp it.

Could you please give an example of a random variable for which $(1)$ holds true, but $(2)$ does NOT hold true? (or viceversa)
Comment: For any fixed $t_0$, note that
the set in (2.int) is a subset of the set in (1.int) at $t=t_0$. So (2.int) implies (1.int) by subadditivity.
Comment: You already know the correct interpretation!
Comment: Good, but I cannot understand what it does mean "practically": could you give me an example of a random variable for which $(1)$ holds true, but $(2)$ does NOT hold true? @KaviRamaMurthy
Answer: On $(0,1)$ with Lebesgue measure let $X_t(\omega)=|t-\omega|$. Then $P(X_t \, \text  {is differentiable at } \, t)=1$ for each $t$ and $P(X_t \, \text  {is differentiable at every point} \, t)=0$.
(2) implies (1) always.
Comment: @Strictly_increasing Because $P$ here is the Lebesgue measure and Lebesgue measure of $(0,1) \setminus \{t\}$ is $1$.
Comment: Why, for $X_t(\omega)=|t-\omega|$, does it hold true that $P(X_t \text{ is differentiable at }t)=1$ for each $t$?


Tokenize a string in KornShell

Question: I need to tokenize in string in KornShell (ksh). I have got the following script for bash; but it does not seem to work in ksh.
The script is below. Please help in making work for ksh.
<code>OLDIFS=$IFS
IFS=","
read -a array <<< "$(printf "%s" "$APPLICATION_NAMES")"
IFS=$OLDIFS
for i in "${array[@]}"
do
   :
   # do whatever on $i
   echo "Checking status of $i"
done
</code>
Comment: `read -a` and `<<<` are bash features, not ksh.
Answer: <code># s=a,b,c
# IFS=,
# set -A arr $s
# for e in "${arr[@]}"; do print -- "$e"; done
a
b
c
</code>
Comment: Hi Dimitre, Thanks a lot, am able to tokenize the string with the provided scritp, Thanks once again

Tokenize a string in KornShell


What property of complex numbers allow us to represent it in the plane?

Question: Why can trigonometry as a geometrically defined concept be used to algebraic operations between complex numbers?  What connects the two things together and how ?
Comment: euler's formula $e^{ix}$= cosx + i sinx
Comment: What is a complex number? I'm not trying to be difficult, but the answer depends on where you're starting.
Answer: There are a couple connections. First of all: you can look at $\mathbb{C}$ as being isomorphic to $\mathbb{R}^2$ with regards to addition (meaning if $z_1 = x_1+iy_1$ and $z_2=x_2+iy_2$ and we associate $z = x + iy$ with the vector $(x,y)$ then with regards to addition, these behave the same - have the "same structure" just with a different name), so it makes sense to look at complex numbers on the plane. The connection with trigonometry is not as obvious but not hard to see either and it comes from Euler's formula:
$$\exp(ix) = \cos x + i\sin x.$$
Making use of the Cartesian representation of a complex number, we can see that if $z = x+iy$, $r = \sqrt{x^2+y^2}$ and $\theta = \arctan\left(\frac{y}{x}\right)$ then we can easily make the association that $x = r\cos\theta$ and $y = r\sin\theta$. By doing this what we are doing is associating the real component of the complex number with the $x$-axis and the imaginary component with the $y$-axis in the Cartesian plane. See the figure below.

This ties into Euler's formula because we now can write our complex number as
$$z = r\cos\theta + ir\sin\theta = r\exp(i\theta).$$
Using this "polar" representation makes a lot of things very nice in the complex plane. It allows us to easily multiply complex numbers, to easily divide them and makes contour integrals fairly simple.
Answer: $e^x=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}...$
$e^{i\theta}=1+{i\theta}+\frac{{(i\theta)}^2}{2!}+\frac{{(i\theta)}^3}{3!}+\frac{{(i\theta)}^4}{4!}...=1+{i\theta}-\frac{{\theta}^2}{2!}-i\frac{{\theta}^3}{3!}+\frac{{\theta}^4}{4!}+i\frac{\theta^5}{5!}...=$
$=[1-\frac{{\theta}^2}{2!}+\frac{{\theta}^4}{4!}-...]+i·[\theta-\frac{{\theta}^3}{3!}+\frac{\theta^5}{5!}-...]=cos(\theta)+i·sin(\theta)$
The temptation to make circles with this is great.
When you fall in the temptation and let the Y-Axis for the imaginary part the magic comes.
It can be shown that when you multiply complex numbers the modulus multiply like in the real line, but the arguments follow the adding rule.
That fact became the algebra of complex numbers in a powerful tool to describe dilations and rotations in the plane.
$z=|z|e^{i\alpha}$
$w=|w|e^{i\beta}$
$z·w=|z||w|e^{i\alpha}e^{i\beta}=|z||w|e^{i(\alpha+\beta)}$
.
.
.
VISUAL COMPLEX ANALYSIS (Tristan Needham)
PREFACE
A Parable.

Imagine a society in which the citizens are encouraged, indeed compelled up to a certain age, to read (and sometimes write) musical scores. All quite admirable. However, this society also has a very curious-few remember how it all started- and disturbing law: Music must never be listened to or performed!
Thought its importance is universally acknowledged, for some reason music is not widely appreciated in this society. To be sure, professors still excitedly pore over the great works of Bach, Wagner, end the rest, and they do their utmost to communicate to their students the beautiful meaning of what they find there, but they still become tongue-tied when brashly asked the question, "What's the point of all this?!"
In this parable, it was patently unfair and irrational to have a law forbidding would-be music students from experiencing and understanding the subject directly through "sonic intuition". But in our society of mathematicians we have such a law. It is nor written law, and those who flout it may yet prosper, but it says, Mathematics must not be visualized!
....
...
..
.


abstracting c++ enums to reduce compilation

Question: In my code I have a central data storage that is referenced into via enumerated symbols. This allows me to see all the places in my code where the enum'd symbol is referenced for setting/getting a value. The problem comes in whenever I want to add a new symbol it requires that all of the code that might access the data storage be recompiled because all of it touches the enum header file.
Is there some abstract that would reduce recompiles? Maybe a design pattern?
Answer: That's the problem you have with a "central data storage" as you called it. That sounds like an excuse for putting all of the enums you don't know what to do with in a single header file.
If an enum is related to a class and used only when that class is used, put it in the same header file as the class. If your enums are really all stand alone, you can still divide that header file into multiple header files that have more specific categories of enums in them.
Answer: Only thing you can do is to use strongly typed enums, if you have access to c++11 features. Then you can forward declare the enum, and you do not have to include that header in other headers needing the enum.
For pre-c++11, nothing can be done to prevent the recompilation.


Unable to fix the error "getToolkit() is undefined"

Question: I'm doing Login Page using Eclipse 2022-09 & jdk-19 and I have done coding to display the frame on the middle of the screen. Below is my coding.
import java.awt.Toolkit;
import java.awt.Dimension;

    public LoginS() {
        initialize();

    Toolkit toolkit = getToolkit();
        Dimension size = toolkit.getScreenSize();
        setLocation(size.width/2 - getWidth()/2, size.height/2 - getHeight()/2);

    }

I'm unable to compile the coding due subjected error. Same error for getWidth(), getHight() and setLocation() as well. when I use the same coding on NetBeans, it works fine. Only on Eclipse it's giving error. Need help please...
Is there any difference between eclipse java.awt.Toolkit and NetBeans java.awt.Toolkit?
Comment: no, there is no difference (regarding IDE) - How is the class declared? Is it a `Component` or a `Window`? (always better to include a [mre] for such questions - also recommended to take the [tour] and check [ask]) || BTW `setLocationRelativeTo(null)` can be used to center a `Window` (e.g. `JFrame`) - [doc](https://docs.oracle.com/en/java/javase/19/docs/api/java.desktop/java/awt/Window.html#setLocationRelativeTo(java.awt.Component))
Comment: No, I didn't do any special declaration. Just a normal class statement. Below is the code...

public class LoginS {

 private JFrame frmLoginSystem;
 private JTextField txtUsername;
 private JPasswordField txtPassword;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     LoginS window = new LoginS();
     window.frmLoginSystem.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
Answer: I use this code to center....
   `int frW=frame.getWidth();
    int frH=frame.getHeight();
    int width = Toolkit.getDefaultToolkit().getScreenSize().width;
    int height = Toolkit.getDefaultToolkit().getScreenSize().height;
    int x=(width-frW)/2;
    int y=(height-frH)/2;
    frame.setBounds(x, y, frW, frH);`

Comment: Yes, using your code, it works. Thanks. Also just wanted to know how to solve such errors? like said above is there any special declaration required?


Nested jar: URI

Question: The format of the jar: URI scheme is simply defined to be jar:<url>!/[<entry>].
Is it possible to "nest" two such URIs together and refer to a file inside an archive inside an archive this way? Something like:
jar:jar:http://example.com/!/archive!/file

This should designate /file inside an archive jar:http://example.com/!/archive, that is /archive found in a file provided by http://example.com/. However, URL.openConnection throws an exception:

java.net.MalformedURLException: no !/ in spec

I also cannot replace ! with %21 since that makes the jar: URI invalid, and I am not aware of any escaping that could be performed. Is this somehow possible? Or, as a more generic question, is it possible to store a URI with !/ inside <url> so that it is preserved?
Answer: As it is stated in the source code java.net.JarURLConnection does not handle nested Jar URIs.
Your example jar:jar:http://example.com/!/archive!/fileis parsed as entry archive!/file in the archive jar:http://example.com/. The latter is not a valid jar URI. You can not either escape the !/ sequences, because the text after jar: and before !/ must be a valid URI without any translation.
You can of course provide your own URLConnection implementation that supports nested Jar URIs.
Answer: While the other answer is indeed correct in the case of JarURLConnection, the use of jar: and similar URIs is not restricted to it. Such is the case of the Apache Commons VFS:

jar:// arch-file-uri[! absolute-path]
Where arch-file-uri refers to a file of any supported type, including other zip files. Note: if you would like to use the ! as normal character it must be escaped using %21.

"Normal character" means usage of the character in path to the file inside the archive, not in the inner URI. This makes jar:jar:http://example.com/!/archive!/file valid, as it is the last occurence of ! that should be used as a delimiter.
Note that the inner URI should probably still remain unescaped, thus it is impossible to use # there.

Nested jar: URI


Vue-resource with browserify

Question: I am trying to use vue-resource with browserify. But I always get the following error. Cannot read property 'get' of undefined. I tried search around the web but the solution is not working.
var Vue = require('vue');
Vue.use(require('vue-resource'));

import UploadImage from './components/UploadImage.vue'

new Vue({
    el: '#app',

    components: { UploadImage },

    ready() {
        console.log('Vue is ready.');
        this.$http.get('/api', function(data){
            console.log(data);
        });
    }
});

I install vueand vue-resource by using npm install.
package.json
{
  "private": true,
   "devDependencies": {
    "clipboard-js": "^0.1.0",
    "gulp": "^3.8.8",
    "gulp-batch-replace": "0.0.0",
    "gulp-phpunit": "^0.14.0",
    "laravel-elixir-vueify": "^1.0.3",
    "vue": "^1.0.24",
    "laravel-elixir-browserify": "^0.8.1",
    "vue-resource": "^0.7.0",
    "vueify": "^8.4.1"
  },
  "dependencies": {
    "babel-runtime": "^6.0.0",
    "bootstrap-sass": "^3.0.0",
    "laravel-elixir": "^5.0.0"
  }
}

Comment: I'd start by updating vue-resource to `v1.x`. Can you do `Vue.http.get(...)`?
Answer: Try this:
ready() {
    Vue.http.get('/api').then((response) => {
        console.log(response.data);
    });
}

Answer: Here are my suggestion:
1: Using webpack replace browserify.
2: Using axios replace vue-resource.

Vue-resource with browserify


What is the most extreme set 4 or 5 nontransitive n-sided dice?

Question: A set of nontransitive dice is a set of dice whose face numbers are such that the relation "is more likely to roll a higher number than" is not transitive. (See  wikipedia)
For some sets, the deviation from transitivity is small in the sense that A beats B beats C beats A with probabilities $p_{ij}$ only slightly greater than $0.5$ .  Efron's dice (there are 4 of them) beat each other nontransitively with probability $2/3$.
Can we make a strictly better set of 4 six-sided dice? That is, a set of 4 six-sided dice such that they beat each other nontransitively with all probabilities $> 2/3$ ?
Can we make a strictly better set of 4 $n$-sided dice for some small $n$ which one can conveniently make a die out of, e.g. $n = 4, 8, 12, 20 $ ?
Can we make a strictly better set of 5 $n$-sided dice for some small $n$ which one can conveniently make a die out of, e.g. $n = 4, 6, 8, 12, 20 $ ?
Can we make a strictly better set of 3, 4 or 5 dice, each having potentially a different number of sides ($4, 6, 8, 12$ or $20$) ?
Ideally I would like to find a fairly small set of fairly easy-to-make, preferably platonic-solid dice which beat each other nontransitively with probabilities > 80%. They would make an excellent teaching aid and magic trick. There is another answer on math.stackexchange which claims that the best you can do with 3 dice is $p = 0.58$, which is disappointingly close to $0.5$; for a teaching aid you need to be able to beat students almost every time for them to spot the pattern quickly. Efron's dice are substantially better at $2/3$, but is that really the best we can do?
EDIT: I missed this answer which argues that the probability cannot be > than 0.75 irrespective of the details of the dice. Still, it would be nice to know what the "simplest"/smallest set of "simple" dice is that gets you above, say, 70%, 72%, etc.
Also, assuming that the other player doesn't yet understand what's going on, a uniform nontransitive probability of $75%$ - $\epsilon$ can still be improved by making some dice lose with probability > $75$%, so that if the other player chooses randomly from the dice, the will get beaten on average much more than $75$% of the time. The "worse" choices can be encouraged by making the highest number on them very high. As far as I understand the proof in this answer, this possibility is not excluded.
Comment: If there is a nontransitive 3-chain in a set of 4 dice, then the 4th dice is superfluous, and there is another answer here on math.stackexchange which claims that the best you can do with 3 dice is $p = 0.58$
Comment: You're not going to get $p > 80$% no matter what you do. As [this question](http://math.stackexchange.com/questions/57338/how-far-can-probability-intransitivity-be-stretched) notes, there's a strict upper bound of $p<3/4$ for any intransitive set of random variables, and for 6-sided dice considerations of discreteness reduce that to $p<2/3$ (so Efron's dice are optimal for a set of 6-sided dice).
Comment: With 4 dice, I suppose you would like to forbid A > B > C > A; D > A, D > B, D > C, and insist A > B > C > D > A?  Or what, exactly?
Comment: Thanks, Micah, I just caught that. Presumably there might be a set of 3 20-sided dice which achieve the bound for n=20 sides, 72.5%. This would still be fairly impressive; although the constructed solution in the answer we linked to uses n n-sided dice, Efron shows that you can hit the bound with less than n dice. How good does it get?
Comment: Note that the question for which I determined the optimum $p=21/36\approx0.58$ required the win probability to be independent of which die you pick. The code I posted there is easily modified not to impose that requirement, and then it finds this set of three dice: $(0,3,3,3,3,3)$, $(2,2,2,2,2,5)$, $(1,1,1,4,4,4)$, with win probabilities $25/36$, $21/36$, $21/36$, for which the expected win probability upon uniformly randomly choosing a die is $67/108\approx0.62$, and the worst choice has the highest number. I hope to be posting an answer with more results when I find the time.
Comment: I think to turn the part of your question where you allow the dice to win with different probabilities into a well-defined mathematical question you'll need to somehow quantify whether the set of dice has an acceptably "fair" appearance. Without any such restriction, you can get an expected win probability of $(k-1)/k$ upon uniformly randomly choosing a die from $k$ dice, simply by making all faces of a die show the same number, and assigning all but one of the dice a number higher than its predecessor.
Comment: Joriki, thanks for pointing that out. I would certainly want the dice to be nontransitive. But even then there might be some tradeoff between the minimum win probability and the average win probability. What does that tradeoff look like?
Comment: Also, Joriki, I am having some trouble understanding your answer here: http://math.stackexchange.com/questions/57338/how-far-can-probability-intransitivity-be-stretched?rq=1

Specifically, I don't quite understand "so for the median to increase" - why can't we have a constant median for all dice? Of course a constant median would still impose p <= 0.75.
Comment: Actually it is the set, not the dice themselves, which is called nontransitive.
Comment: @joriki: To make the game seem fair, we can let the student choose which die they want, saying that you are giving them the advantage of picking first. If they think (wrongly) that there is always a best die, they would not find anything wrong with that. So we want the worst-case to have the highest possible probability of us winning. Anyway there is an answer on MO that states that 2/3 is the best for any 4 dice (http://mathoverflow.net/a/119885).
Answer: A great visual aid for developing a set of four transitive dice is this one:

In the left image, each quadrant shows the probability diagram of each of the four duels. In the right image you see that these diagrams form a spiral.
See also: https://www.quora.com/What-are-some-mathematical-paradoxes/answer/Job-Bouwman


Why am I getting this error for the schema I define in my module?

Question: I'm building a module for Drupal 7, but I have troubles with my schema, and I don't understand why.
This is my schema.
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'unique keys' => array('id')
    );

I get this error.

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
  You have an error in your SQL syntax; check the manual that
  corresponds to  your MySQL server version for the right syntax to use
  near 'NULL DEFAULT NULL,  end_time NULL DEFAULT NULL, duration INT
  unsigned NOT ' at line 5: CREATE  TABLE {table_name} ( id INT
  unsigned NOT NULL auto_increment, nid INT  unsigned NOT NULL, oid
  INT unsigned NOT NULL, start_time NULL DEFAULT  NULL, end_time
  NULL DEFAULT NULL, duration INT unsigned NOT NULL, PRIMARY  KEY
  (id), UNIQUE KEY 0 () ) ENGINE = InnoDB DEFAULT CHARACTER SET
  utf8;  Array ( ) in db_create_table() (line 2717 of
  /Applications/MAMP/htdocs/project/www/includes/database/database.inc).

How can I fix this error?
Comment: I've found out Drupal 7 no longer supports the `datetime` type and to use this type you must use the key 'mysql_type', however I'm still getting an error.
Answer: I've managed to fix it. I've altered 2 things from my original schema, the first issue was that Drupal 7 no longer supports 'type' => 'datetime', instead use 'mysql_type' => 'datetime'. The second was 'unique keys' => array('id'), I removed this and everything works correctly.
Solution...
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'mysql_engine' => 'InnoDB'
    );

Comment: `unique keys` takes a nested array, so `'unique keys' => array('idx_id_uniq' => array('id'));`. But it doesn't make sense to have the primary and unique keys set for the same single column, as primary keys already have a unique constraint
Answer: Try this for Drupal7,
'pubblish_date' => array(
  'description' => t('The pubblish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),
'unpublish_date' => array(
  'description' => t('The unpublish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

Comment: Thanks @shrish, similar solution to what I've just posted. An issue here maybe that whilst using the Type Varchar you may also need to include a Length value.
Comment: Some elaboration on the problem and why this solution works rather than 'here is a fix for your specific code' would be much more appreciated.
Comment: This is also a word-for-word copy paste from a similar issue.
http://drupal.stackexchange.com/questions/69737/how-to-implement-a-mysql-date-or-datetime-field-correctly-in-hook-schema


Panes' Title translation

Question: I need to translate the Label of the panes in a page. For example, Title and Body are not translated in my pages.
Note: I do not mean the content of panes! I only mean their label! Which is generally called TITLE.
Comment: Have you tried to use Panels translation (i18n_panels)? See also: [How to translate a panel page title and a pane title](http://drupal.stackexchange.com/q/9007/1908)
Comment: Thank you for your comment. I have already activated this module. The issue is that, consider there is an edit node form, and no field caption is translated! such as: Title*, Body, ...
Answer: Sounds like i18n_panels would be overkill. You can do it like this:
<code>/**
 * Preprocess panels panes to translate their title.
 */
function MY_THEME_preprocess_panels_pane(&$variables) {
  $pane_config = $variables['pane']->configuration;
  if (!empty($pane_config['override_title'])) {
    // Translate pane title via t().
    $variables['title'] = t($pane_config['override_title_text']);
  }
}
</code>
Or, if appropriate, just:
<code>/**
 * Preprocess panels panes to translate their title.
 */
function MY_MODULE_preprocess_panels_pane(&$variables) {
  $variables['title'] = t($variables['title']);
}
</code>
The first will process the title only if defined in the pane settings as a title override. The second will translate the title regardless of whether it's the override title or original title from elsewhere.
Tested under Drupal 7, the same or similar approach would probably work for Drupal 8.

Panes' Title translation


What is the best Framework to use for developing a skinned application?

Question: I need to develop an application for windows, and it needs to support skins.  I am looking for a framework to use.  I would much prefer to not use QT, because of it's licensing - GPL is not an option for me, and it is otherwise to expensive (and I can't put off developing this application till March, when QT is supposed to go LGPL).
Does anyone have any suggestions as to what I should use?  Language options for me are C/C++, C# (preferably .Net 2.0 or lower), or Visual Basic.  Something that used quasi-CSS for skinning, like QT does, would be a bonus.  Open Source licensing (LGPL, MIT, etc) would be a bonus as well.
Thanks!
Answer: I would have thought that "WPF" is the (obvious) best answer - unless your preference for .Net 2 or lower is unbreakable. To use WPF, you would be writing in either C#/VB/F# in .Net3-3.5 (or perhaps even IronRuby/IronPython that are coming out for .Net shortly).
Google for 'skins' and 'WPF' and you will get loads of matches. There is implicit but very good support for skinning in WPF.
For example: http://www.wpfdev.com/2008/04/09/creating-skins-for-wpf-controls/
Comment: WPF is unattractive because it requires .Net 3.0/3.5 - which most people have not installed yet.
Comment: But is there any reason not to install it? It is not a particularly onerous prerequisite for an end user, and coming direct from MS the average user is not going to be too put off by installing it. Also, many machines with auto-update enabled may have acquired it automatically.
Answer: If you are speaking about C++ then you can have a look at Ultimate++ which according to the docs offers skinning (never tried this feature). Unlike some other widget toolkits it attempts to make some use of the modern C++ features. And it is rather lightweight. As for the license - the "best" of all - BSD.
Comment: Do you happen to have any other insightful comments?
Comment: I have to say that is a pretty stupid thing to say. Why would you bother even developing in C++ if you didn't want to use the best it has to offer?
Comment: 1800, replace modern with best and you're half the way there
Comment: It's skinning support is totally undocumented, and very, very complex
Comment: Thanks for the info, I haven't looked into skinning, only seen that it appeared in some release notes.
Answer: Take a look at the DevExpress DXperience .NET WinForms Controls (especially "DefaultLookAndFeel" and "StyleController" cannot remember which of them it was). They are really powerful and there is the ability to to easily write own skins for your application.
At the moment there is a special offer where you can get 60 DevExpress Controls free of charge.
http://devexpress.com/Products/Free/WebRegistration60/
Answer: Gtk support themes, this link provide more info to compile a theme http://dt.in.th/2008-08-25.gtk-compile-windows.html. Also you will find a lots of themes for Gtk , see here for example http://art.gnome.org/themes/gtk2.
If you want a commercial solution, for MFC/C++ there's BCGSoft, Codejock, for C#/.Net Infragistics. If you plan to do something very simple any of them can be enough, but if you want to do more complex UI they may start getting too much in the way.
Answer: Another vote for DevExpress if you're doing C# development, and you're prepared to use a commercial product.
Have a look at their ExpressApp Framework product (XAF). This ships with a number of skins. The demo is reasonably good. The framework will generate applications for both Win and Web deployment.
It's not cheap, but depending on the application which you're trying to produce, it could save you a fortune.
Answer: I've ended up writing my own custom skinning support, specific to my application.
Using a wxNO_BORDER with wxWidgets, and writing lots of controls from scratch, has given me the abilities I need.
In the future, I'll probably use QT, when it is under LGPL, or else WPF, when and if DotNet 3 is an option for me.
Thanks for all the responses.
Answer: I think XAF is the best choice now to rapidly develop a skinned application, and it supports both Windows and Web UI with a single code base. On the other side, if performance is what you concern seriously, you'd better try it yourself hardly before making final decision.
Answer: I will try Qt Designer and try the integrated CSS editor before taking a decission.
Anyway I will bet on Qt4


Testing ITelephony endCall on AVD throws java.lang.NoSuchMethodError

Question: I have no problem executing call blocking codes when the OS is Marshmallow and above but testing it on Kitkat in AVD throws java.lang.NoSuchMethodError: com.android.internal.telephony.ITelephony.endCall
public interface ITelephony {

     void endCall();
     void silenceRinger();

}

These are the permissions used:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />

This is being executed in a BroadcastReceiver:
Class<?> c = Class.forName(tm.getClass().getName());

Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);

ITelephony telephonyService = (ITelephony) m.invoke(tm);

telephonyService.silenceRinger();
telephonyService.endCall();

This is my gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.app.testapp"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.googlecode.libphonenumber:libphonenumber:8.8.3'
    implementation 'com.google.android.gms:play-services-ads:11.8.0'
}

Comment: can you post your build.gradle ?
Comment: @AlexandreGombert posted already.
Answer: This method is no longer available in this class as of API 29. There is also no replacement. I've checked all methods available from this class. It's probably connected to the fact that it was also removed from TelecomManager https://developer.android.com/reference/android/telecom/TelecomManager.html#endCall(). Handling calls with a custom dialler would still work.


Show/Hide portfolio items with jQuery

Question: Thanks for your answers and sorry forgot to post HTML of categories I want to display! -
It's in Wordpress, so clicking the ul li#digi shows the digital categories - just think the jquery could be simplified..

Ogilvie Homes

BBC News

etc etc
So to confirm clicking  the li# would show the corresponding divs as above..

All

Digital

Social Media

Print

Audio

PR

Content Marketing

//jQuery
$(document).ready(function() {
$("#all").click(function() {
$(".category-digital").show("fast", "linear");
$(".category-social-media").show("fast", "linear");
$(".category-print").show("fast", "linear");
$(".category-audio").show("fast", "linear");
$(".category-pr").show("fast", "linear");
$(".category-content-marketing").show("fast", "linear");
}),

$("#digi").click(function() {
$(".category-digital").show("fast", "linear");
$(".category-social-media").hide("fast", "linear");
$(".category-print").hide("fast", "linear");
$(".category-audio").hide("fast", "linear");
$(".category-pr").hide("fast", "linear");
$(".category-content-marketing").hide("fast", "linear");
})

$("#social").click(function() {
$(".category-social-media").show("fast", "linear");
$(".category-audio").hide("fast", "linear");
$(".category-print").hide("fast", "linear");
$(".category-digital").hide("fast", "linear");
$(".category-pr").hide("fast", "linear");
$(".category-content-marketing").hide("fast", "linear");
})

$("#print").click(function() {
$(".category-print").show("fast", "linear");
$(".category-social-media").hide("fast", "linear");
$(".category-audio").hide("fast", "linear");
$(".category-digital").hide("fast", "linear");
$(".category-pr").hide("fast", "linear");
$(".category-content-marketing").hide("fast", "linear");
})

$("#aud").click(function() {
$(".category-audio").show("fast", "linear");
$(".category-social-media").hide("fast", "linear");
$(".category-print").hide("fast", "linear");
$(".category-digital").hide("fast", "linear");
$(".category-pr").hide("fast", "linear");
$(".category-content-marketing").hide("fast", "linear");
})

$("#pub").click(function() {
$(".category-pr").show("fast", "linear");
$(".category-social-media").hide("fast", "linear");
$(".category-print").hide("fast", "linear");
$(".category-digital").hide("fast", "linear");
$(".category-audio").hide("fast", "linear");
$(".category-content-marketing").hide("fast", "linear");
})

$("#cm").click(function() {
$(".category-content-marketing").show("fast", "linear");
$(".category-social-media").hide("fast", "linear");
$(".category-print").hide("fast", "linear");
$(".category-digital").hide("fast", "linear");
$(".category-pr").hide("fast", "linear");
$(".category-audio").hide("fast", "linear");

})
});

Comment: html of `category-*` ?
Answer: Try it like this: I've changed the ids so they fit to the -category titles.

All

Digital

Social Media

Print

Audio

PR

Content Marketing

and than use the following js script:
$(document).ready(function () {
    $('.li').click(function () {
        $('[class^=category-]').hide('fast','linear');
        var id = $(this).attr('id');
        if(id == 'all') {
             $('[class^=category-]').show('fast','linear');
        } else {
             $('.category-'+id).show('fast','linear');
        }
    });
});

Comment: Edited my post above.
Comment: I think you misread the question, it's not about hiding of showing the filter li items. It's about using the li items to filter another elements marked with a category class.
Comment: @frikinside : Thanks for the hint! I have edited my code. Should match the question now.
Comment: No problem! And yes, I think it match the question now, unless the mistaken was me the whole time! But, just one thing, in your answer you use the containing substring selector, it would be better if you use the starts with, replacing the $('[class*=category-]') with $('[class^=category-]').
Comment: Ok, cool! Thanks for the tip! I'm always using *= so didn't thought about another one, but you're right, ^= would be better here! - Edited it ;)
Comment: Thanks you so much that worked a treat - just to let you know the class didn't being with "category-" so I ditched $('[class^=category-]'). and used $('[class*=category-]') as it's wordpress and it throws in random classes!
Answer: try
$(".filter ul li").click(function(){
  $(".filter ul li").hide();
  $(this).show("fast", "linear");
 });

Comment: I think you misread the question, it's not about hiding of showing the filter li items. It's about using the li items to filter another elements marked with a category class.
Answer: Just hide all categories and show the one you clicked:
$(document).ready(function() {

 $(".filter ul li").click(function() {
    $(".filter ul li").hide("fast", "linear");
    $(this).show("fast", "linear");
})

});

Comment: I think you misread the question, it's not about hiding of showing the filter li items. It's about using the li items to filter another elements marked with a category class.
Answer: You can first hide everything with hide(); after which you show the clicked element.
$("yourlement").click(function(){
  $("yourelement").hide();
  $(this).show();
 });

Answer: Hey try this as your script.
$(document).ready(function () {
    $('div.filter>ul>li').click(function() {
        $('div.filter>ul>li').hide();
        $(this).show();
    });
});

Comment: I think you misread the question, it's not about hiding of showing the filter li items. It's about using the li items to filter another elements marked with a category class.
Comment: Hi @frikinside **I'm trying to show a specific category when clicked and hide the others e.g. when #digi is clicked it shows digital and hides the rest **
 - is exactly what i've answered... if he wants category classed items shown/hidden he'll need to update the amount of HTML he's provided.
Comment: Hi @JFit you made a point, and you're right, maybe he must provide more HTML including the classed category items, but I think that the jquery code that shows it's clear enought showing what he wants, but maybe I'm the wrong one and the question is not quite clear.
Comment: I assumed that his content was within the LI cos of the html he gave and the description. but if he provides the HTML it will be handy enough to update that.
Answer: You can first hide everything with hide(); after which you show the clicked element.
$("your_element").click(function(){
  $("your_element").hide();
  $(this).show();
 });

Answer: If you make a few changes in the HTML, I think I could provide a simple way to do this in 3 steps.
Step 1)
Change the id of you li items for a complete category (digi would be digital, aud would be audio,...)
Step 2)
Add to every category wrapper another class category-all. So for example, the .category-audio elements now would had another class category-all.
Step 3)
Replace you jquery method by this one:
$("div.filter.group ul li").click(function(){
    $(".category-all").hide("fast", "linear");
    $(".category-" + this.id).show("fast", "linear");
});

Show/Hide portfolio items with jQuery


Angular CLI is creating project in my home folder

Question: Whenever I run ng new appName the app is created in /User/name, which is my home directory. Any idea why this is happening?
My ~/.angular-cli.json only has packageManager: 'yarn'
Comment: You likely have a package.json file there and that effects the logic of determining if you're within an existing CLI project. Locate that file and remove it.
Comment: Thanks. That fixed it. I had a `package.json` in my home directory.
Comment: Great to hear, I posted this as an answer for others to find in the future, please accept.
Answer: You likely have a package.json file there and that effects the logic of determining if you're within an existing CLI project. Locate that file and remove it.


Are there any interesting sets of real functions whose cardinality is unknown?

Question: Consider the set, let's call it $R$, of all functions $f:\mathbb{R} \to \mathbb{R}$? Are there any interesting subsets $S \subset R$ whose cardinality is (currently) unknown? By interesting, I mean something "natural" (e.g., continuous real functions, the set of all real functions with a countable number of discontinuities, Darboux functions) which analysts might care about.
The motivation for this question is honestly just curiosity. I find this quite interesting, because there's so many types of real functions we can consider. Surely there's some interesting, nontrivial examples worth discussing.
Answer: How about the space of all real-valued functions which are not continuous? You can actually show that there are some input-output pairs of real numbers which satisfy the definition of continuity. In other words, you can show continuous functions exist without ever writing one down!
Proof
$(1)$ Let $F(\mathbb{R},\mathbb{R})$ denote the set of all possible single variable, real valued functions.
$(2)$ Now let $S\in F(\mathbb{R},\mathbb{R}) $ denote the set of all functions where if the difference between output values is less than $\epsilon$, then we can find a corresponding $\delta$ which will always be greater than the difference between two arbitrary input values. This is possible, we can just make up a rule where the difference between input values $x_1$ and $x_2$ is twice the difference between $f(x_1),f(x_2)$. Play around with some numbers to get the intuition.
$(3)$ Let $f\in S$. Consider two points of the function $f(x_{1})$ and $f(x_{2})$. Remember since $f\in S$, the difference $|f(x_{1})-f(x_{2})|<\epsilon$ and $|x_1-x_2|<2\delta$ by definition. This fits the definition of continuity, and so continuous functions do exist. You can modify to show its possible to have differentiable functions, monotonic etc.
What is the cardinality of $F(\mathbb{R},\mathbb{R})$? What about the set of monotone functions? What about the set of functions which are differentiable, but the derivative is not differentiable anywhere?
To conclude, you could reasonably conjecture (based on cardinality of power sets) that there are probably a $\aleph_{2}$ number of possible subsets of $F(\mathbb{R},\mathbb{R})$ we could ask ourselves what the cardinality of each of those sets are. Consider a set $X$ where each function is bounded by some constant: $|f(x)|<M$. We could choose any $M\in (1,\infty)$ to be the bound, and that means there are $\aleph_1$ such functions in $X$ alone.
Comment: "*What about the set of monotone functions? What about the set of functions which are differentiable, but the derivative is not differentiable anywhere?*" These are all Baire functions (of the simplest types) and there are $c$ many Baire functions, so there are at most $c$ many of each of these types. There are at least $c$ many of each of these types because any nonzero constant added to a specific function belonging one of these types produces a different function of the same type.
Comment: OP asked for an interesting set of functions whose cardinality is unknown. How does this answer address that?
Comment: it was clearly stated. How many monotone functions, how many bounded functions etc.
Comment: What makes you think these are unknown cardinalities?
Comment: well then I learned something as well. You could have spent your time answering the question rather than downvoting mine for no reason other than I was unaware that these are Baire functions.
Comment: I didn't downvote your question, and being at work I didn't have time to compose an appropriate answer. (I felt sure you didn't know about Baire functions. This was mainly to help others eliminate a lot of potential categories of functions.)
Comment: "*I didn't downvote your question*" Ooops, I meant "answer", not "question".


How to add new reference in entity reference field in node edit form keeping old references intact and hidden?

Question: In my project, there is a content type 'song' containing an entity reference field to reference content type 'playlist'. More than one user can edit a 'song' to add it to their own 'playlist's.
Now, when one user updates a 'song' node creating his/her references in the node edit form, the previous references made by another user are deleted. In the node edit form, the field is formatted through an entity reference view showing a list of 'playlist's only created by the current user. The number of values for the entity reference field is set to unlimited.
What would be a good and server-friendly approach to solve this problem keeping in mind that there can be an unlimited number of previous references made by other users?
Answer: Edit the field and set number of values to be unlimited. If you want more control and flexibility you could put the entity reference within a field collection.
Comment: Thanks for your answer, but the number of values is already set to unlimited. I edited the second paragraph of my question to add some more details about it.
Comment: The previously selected items are being removed because drupal sees the the list being produced buy the view as the allowed options for validation. You should be able to get round this you can use hook_form_alter in a custom module but you might be better of putting the reference on the playlist content type or using the flag module
Comment: Thanks a lot again. Actually, the reference is also on playlist content type and I'm using corresponding node reference module to keep them in sync. I needed to add the reference from the song view page and that's why I put the reference in the 'song' content type too. If you can give me some hints about how to get around this using hook_form_alter I can proceed to accept your answer.

Also, I know how to use flag for creating a bookmark like feature. But, is it possible to create new playlists and add songs into them by a user using the flag module?
Answer: In your current setup it's logical to only have entity reference to song from play list content type. Having the reference from song to playlist is redundant. You can always have view showing all the playlists that the song belongs to.


Breathing for singing : stomach only or ribs?

Question: I am taking singing lessons where the teacher taught me to breath by focusing on the movements of the stomach.
However in this video, the teacher indicates I should breath by expanding my rib cage.
These 2 movements seem very different to me. Are both techniques valid, or is one better?
Comment: FWIW, I was taught that the rib cage should be raised and steady, and that breathing should be from the diaphragm (the sheet of muscle below the lungs; movement of the stomach may be a rough consequence of this). I understand that's because moving the rib cage is slow, less well controlled, and has wider effects on voice production, whereas the diaphragm is tuned for exactly this.
Comment: In breathing for clarinet, I've been told my shoulders should not move. I suggest discussing details with your teacher - that's what you pay then for! There should be a lot of tiny details about breathing that are important and it is very helpful to work on fundamentals early rather than fix them later.
Answer: Expand your stomach to lower your diaphragm. You'll take in a lot of air. If you then lift and expand your rib cage you'll take in even more.
So the answer is: both.
Answer: The breathing apparatus are of course connected: this is not as much an anatomically accurate advice as it is one of where to focus control for best results.  A focus on the lower abdomen helps keeping the channels in between pliable for the communication of finely controlled pressure (pressure is force per area and the diaphragm has a large cross section).  Of course there is no air touching the diaphragm.  Maintaining the connection to the abdomen also maintains the resonance paths, giving a sustained quality to the produced sound.
Additionally, the throat should not feel like a constriction: essentially one aims for a feeling of connecting the diaphragm's action with the mask where the sound is emitted, with the throat being relaxed and not the principal source of either sound or air.
Anatomically, of course, this is a load of nonsense, but the visuals of that description help to avoid constricting your airways in places and manners detrimental to sound production and vocal health, and there are centuries of experience that thinking and teaching in those terms produces good results even if X-ray videos of good singers would be more scientifically accurate.


What "things" can you notice on the piano that you can't on the harpsichord, after playing the same piece on both?

Question: Referring to Bach's Prelude and Fugue in C minor BWV 847, Masato Suzuki remarked  at 1:37, as translated from Japanese to English

I also like to play it on the piano. When playing it on the piano I notice things [emphasis mine] I hadn't noticed on the harpsichord.

What are these "things"? What can be noticed on the piano, that even a professional musician couldn't on the harpsichord, for the same piece?
I am asking for any Western classical music piece  that can be played on different keyboards, like the organ, and not simply by Bach. You can generalize this question for other instruments. E.g. what do you notice on one that can't be noticed on the other, for pieces that can be played on both violin and viola? Same question for viola and cello, for cello and double bass, etc.
Answer: A harpsichord uses jacks with plectra that pluck the string as you push the keys. The point at which the string is plucked more or less solely depends on how long and how flexible the plectrum is. This means that the harpsichord does not allow play different dynamics by touch. Harpsichord playing therefore resorts to different approaches. Small harpsichords have two rows of jacks and stops to enable or disable a set. This means you have different tone colors (depending on where the strings are plucked). Big harpsichords even might have two manuals with different stops and might have many more stops with even different sets of strings, such as an 8 foot and a 4 foot register (occasionally even 2 foot or 16 foot registers). A very common thing for two-manual harpsichords would for example be to have three sets of strings, each manual having an 8 foot register and one manual having an additional 4 foot register. There are also stops like the lute stop where felt dampers are put onto the start of the strings to mimic a more finger plucked sound like on a lute.
Thus you see on a harpsichord you differentiate by changing stops and thus tone color, the octave and dynamics. A two manual harpsichord then allows you to play different lines with different stops. But on a harpsichord you cannot put emphasis on specific notes, which makes things like emphasizing phrases against other notes really hard. Harpsichord requires you to use timing for doing such.
Comment: I would insert "use volume to" into the next-to-last sentence since as the last sentence notes it's possible to emphasize notes and phrases with timing.
Answer: Note: This answer was only intended to answer the question focusing on Masato Suzuki's own remark. His remark may or may not be applicable to the general opinion (see also the comment thread).

There was another interview in Japanese with Masato Suzuki on Toppan Hall, touching on the topic of playing Bach's works with harpsichord and piano.
Relevant quotation:

―― 最初に弾いたのはいつですか?
鈴木: [...]。ピアノのレッスンで平均律を習ったときは、家でチェンバロで弾くのと、先生のところでピアノで弾くのとで、葛藤していた時期があったな…。ピアノではどうも、うまく弾けなくて。
―― どういうところがですか?
鈴木: 父がチェンバロで弾くのをずっと聴いていたし、僕自身もチェンバロで一番弾いていて。チェンバロのやり方に慣れていたので、まったく別のアプローチで弾かなければならないことに違和感があったんです。ピアノで弾いてもいい曲には変わりないですし、いまもピアノで弾くことはあります。でもチェンバロという楽器の良さである、音が即興的につながっていく感覚や、フーガみたいに高度な情報処理が必要な曲では、やっぱりチェンバロのために書かれた作品なんだと実感するんですよね。
―― ピアノで弾くと、どういうところが引っかかるのでしょう。
鈴木: ピアノは打鍵によって一音一音、音量の違いがつくれるので、ある声部を際立たせたり、沈ませたりということができますが、そこが逆に障害になるんです。チェンバロはそれができないので、必然的に全部の声部を平等に歌うことになる。すべてをくっきりアーティキュレーションすればするほど、フーガとして立体的になっていきます。そもそもチェンバロは通奏低音を担う即興的な楽器で、当時はソロを弾くほうが例外。バッハも通奏低音としての可能性を追求していただろうし。面白いのは、バッハの譜面は完璧なんですけど、弾き手に想像の余地を残している。たとえば、あるテーマでフーガを即興しようとしたときに、良いものになるよう磨けば磨くほど、彼の譜面に近づいていくような感覚があります。即興演奏のひとつのモデルケースとして、楽譜があるような。書かれている通りに完璧に演奏することも大事ですが、そこには必ず即興的要素がある。だから、チェンバロで弾くと納得がいくのかもしれません。楽譜のリアリゼーションとしては、ピアノでもオルガンでも、アコーディオンだって可能なんですけどね。バッハをピアノで聴いたときに、すごく好きだと感じることは少ないです。むしろ趣味で、ピアノで弾くバッハは楽しいですけど(笑)。

Translated (with the assistance of DeepL, manually reviewed):

―― When did you first play it?
Suzuki: [...]. When I learned the Well-Tempered Clavier1 in piano lessons, there was a time when I was conflicted between playing on the harpsichord at home and playing on the piano at the teacher's place... I couldn't play well on the piano.
―― What do you mean by that?
Suzuki: I had always listened to my father play on the harpsichord, and I myself played the harpsichord the most. I was used to the harpsichord method, so I felt uncomfortable with having to play it in a completely different approach. It is still a good piece to play on the piano, and even now I sometimes play it on the piano. However, the harpsichord has its own advantages, such as the sense of improvisational connection of sounds, and in pieces that require advanced information processing, such as a fugue, I feel that the piece was written for the harpsichord.
―― What aspects does it bother you when played on the piano?
Suzuki: The piano can create a difference in volume with each note by hitting a key, so it is possible to make a certain part of the voice stand out or be subdued, but this also makes a hindrance to the piano. The harpsichord cannot do this, so it is inevitable that all parts of the voice are played equally. The more clearly articulated all the voices are, the more three-dimensional the fugue becomes. In the first place, the harpsichord is an improvisational instrument that serves as a bass continuo, and at that time it was more the exception than the rule to play solo. And Bach would have pursued its potential as a figured bass. What is interesting is that even though Bach's score is perfect, he leaves room for the player's imagination. For example, when I try to improvise a fugue on a certain theme, the more I polish it to make it good, the closer I get to his score. It's like the score is one model case of improvisation. While it is important to play perfectly as written, there is always an element of improvisation. Maybe that is why playing on the harpsichord is so satisfying. As for realizing the score, it is possible on piano, organ, or even accordion. When I hear Bach on the piano, I rarely feel that I like it very much. Rather, as a hobby, I enjoy playing Bach on the piano (laughs).

1 Thanks Brian Chandler for the correction!
Comment: Translation comment: "learned about equal temperament" actually means "learned the WTC". In Japanese this is known as the [Equitempered Clavier], shortened to「平均律」 (lit. equal temperament) because of an early misunderstanding of what "Wohltemperierte" (well-) means.
Comment: Note, there are a few statements about harpsichord here that I think any harpsichordist would disagree with. _The harpsichord cannot [differentiate in volume], so it is inevitable that all parts of the voice are played equally._ But anyone playing a fugue knows that it's _very_ important that the voices _not_ be equal. Harpsichord would do this by differentiating the length that the voice is sustained, giving the theme-voice a few milliseconds more than other voices. If the harpsichord has multiple manuals, then of course that can help. and...
Comment: _... the harpsichord is an improvisational instrument that serves as a bass continuo, and at that time it was more the exception than the rule to play solo._ The intent behind this sentence is accurate, but it overstates it a bit. It's certainly true that the harpsichord was used _more_ for continuo than solo playing, but solo playing was not rare or unusual; it had had been going on for centuries.
Answer: Adding to Lazy's answer: there is little sustain on harpsichord. Once a note is played, it will decay at a certain rate, which is quite different from that on a piano, where using the sustain pedal (or sostenuto pedal) will allow a much longer decay. Regarding organ, a note could sustain for ever, while the key is depressed! Organ, like harpsichord, has little or no jurisdiction over volume, unlike piano, for each setting. One reason why organs developed two or three manuals, which could be set to balance each other.
Another difference is the action - the weighted feel. That on a piano gives the player a lot of feel, whereas harpsichord and organ use effectively 'switches', which turn the notes played on and off, with no effect to their sound.
Comment: The sustain pedal does not really affect sustain time, it prevents dampening after releasing the key. The longer sustain on the piano is a result of lower dampening due to using a cast iron frame (rather than a wooden frame) as well as lower relative loss of energy from the soundboard due to having much heavier strings at much higher tension (thus small movement but much energy). By the way organs can sometimes do dynamics to some extent using shutters. These are literal shutters in front of the pipes that can be opened and closed using a pedal.
Comment: Even without the sostenuto pedal, a piano sustains rather longer than a harpsichord, which I think is a result of the higher tension of the strings and perhaps also their higher mass.
Answer: Other factors not mentioned in the earlier answers:

the lighter/more nasal tone color of the harpsichord causes chords to blend differently (the same is true of early pianos, typically called fortepianos today, which make the left hand chords in early piano music much more enjoyable than the mud that results on a modern piano)
harpsichords are almost invariably tuned in some unequal temperament, which is very rare for pianos; this also gives harmonic sounds a significantly different effect
the different size and weight of the keys and the corresponding difference in playing technique (also due in large part to the fundamental mechanical difference of the action as mentioned in Lazy's answer) will lead most players to make at least some different fingering choices for the different instruments; this could give the player a different sense of the piece.

But the first thing that I'd guess at is probably that mentioned in Tim's answer: with its longer sustain, the piano is more given to a cantabile approach to slower melodic passages, which might make the player more cognizant, for example, of suspensions, or maybe just of melodic shape, tension, and release.  It's not that these are impossible on a harpsichord, but they are probably easier to notice on a piano.
Answer: I think that the answers given are answering the question "How could the piano sound different?" and they are all quite accurate. But the real question is really much more general, and in a sense I think any specific answer sort of misses the point. The questioner suggests (quite reasonably) that a "professional" should surely have noticed everything already, so why need to hear it differently (on a piano). But of course any competent pianist has noticed all of the basic facts; Suzuki is talking about something much more intangible. Hearing a piece differently just gives new insights, relations between voices, rhythmic subtleties, and so on... Bach's music is abstract in an obvious way - (almost) no tempo indications, for example - and leaves everything up to the interpretation of the player. So even without a different instrument, you can play it at wildly different speeds, and different views of the landscape will emerge. The IMSLP page includes all sorts of arrangements (including Clarinet, Trombone, Bass Guitar, Drum Set and Piano!); Suzuki probably doesn't have friends with this combination of instruments, but he can easily play on a piano.
If you say this answer is "vague", I plead guilty. But I think that's how it is.
Comment: This seems like the most likely interpretation to me, as well, it is like changing the font when you proofread a document helps your brain notice things you didn't see before even though the actual content is exactly the same. https://writing.stackexchange.com/a/65983/25794
Answer: An elaboration on Brian's answer: When I have students studying the Bach violin Sonatas and Partitas, I recommend they listen to Chris Thile's recordings on mandolin. Playing any work on a different instrument removes "artifacts" of interpretation that are unique to the instrument and reveals what is universal in the music itself. In this case, what you might "notice" are details of harmony, voice leading, melodic structure, etc—the "skeleton" of the music rather than the "skin" that comes from the particular instrument it's played on.
This re-instrumentation is more appropriate for Bach than for some other composers. Bach himself frequently adapted his own works for other instruments; there are harpsichord versions of violin concertos, and lute versions of violin sonatas/partitas. While he never "abused" or ignored the abilities of an instrument, he made few concessions to it; much of his violin works actually "work better" on a chordal instrument. In contrast, some other composers built their works around the unique way an instrument works as an intentional part of the music. Some of Hindemith's violin works, for example, arrange notes on the basis of how the fingers fall on neighboring strings rather than chord theory.


Drush alias doesn't work

Question: None of my site aliases defined in /home/peter/.drush/aliases.drushrc.php seems to work. When I ran:
drush sa @mysite.dk.local

I got
$aliases['mysite.dk.local'] = array (
 'uri' => 'mysite.dk',
 'root' => '/usr/share/nginx/www/drupal-7.16/sites/',
 'path-aliases' =>
 array (
   '%dump-dir' => '/usr/share/nginx/www/drupal-7.16/sites/drush.dbdumps',
   '%files' => '/usr/share/nginx/www/drupal-7.16/sites/files',
  ),
);

which looks ok, but when I do
drush @mysite.dk.local status

I get
PHP configuration     :  /etc/php5/cli/php.ini
Drush version         :  4.5
Drush configuration   :
Drush alias files     :  /home/peter/.drush/aliases.drushrc.php

So it seems that drush couldn't find  specified path, cause when I run second command in sites directory everything is showing up as expected. Can anybody point out what I'm missing?
Answer: If your settings.php file is at /usr/share/nginx/www/drupal-7.16/sites/default/settings.php, then you should change your 'root' line as follows:
'root' => '/usr/share/nginx/www/drupal-7.16',

The way you have it, Drush is expecting that your Drupal root is at /usr/share/nginx/www/drupal-7.16/sites, which is to say that it is also expecting to find your settings.php file at /usr/share/nginx/www/drupal-7.16/sites/sites/default/settings.php. Take out the extra 'sites' as shown above, and it should work fine.

Drush alias doesn't work


FB.getLoginStatus does not fires callback function

Question: I have a difficult problem. Difficult means I searched through the net and StackOverflow as well the whole FBJS SDK documentation and haven't find answer.
I am building a Page Tab application where I'd like to let fans to rsvp events. So I have to check if the user is logged in and if it doesn't I have to login. That sounds pretty easy, but FB.getLoginStatus doesn't fires callback function. This is the code excerpt:
FB.init({
   appId: window.appID,
   status: true,
   xfbml: true,
   cookie: true,
   oauth: true,
   channelUrl: 'http://example.com/fb/channel.html'
 });

and then I simply - of course after the user clicks on a button - call FB.getLoginStatus, but it seems it doesn't do anything.
I've already checked sandbox mode, FB.init success, URLs in application settings and developing environment. I can call FB.ui, although FB.ui with method: 'oauth' I get an error message saying " The "redirect_uri" parameter cannot be used in conjunction with the "next" parameter, which is deprecated.". Which is very weird because I didn't used "next" parameter. But when I set next to undefined, it works fine, I get the window, but it says "Given URL is not allowed by the Application configuration.". Expect from that, I can login, then I've got the access_token. But in the new window, getLoginStatus still doesn't do anything.
So any advices are welcome.
Thanks,
Tamas
UPDATE:
function onBodyLoad() { //on body onload
    FB.init({
     appId: window.appID,
     status: true,
     xfbml: true,
     cookie: true,
     oauth: true,
     channelUrl: 'http://example.com/fb/channel.html'
    });
   }
...
function getName() { // on button onclick
 FB.getLoginStatus(function(response){
  if (response.authResponse)
   {
    window.loggedIn = true;
    debugString('Logged in');
   } else
   {
    window.loggedIn=false;
    debugString('Not logged in');
   }
}, true);
if (window.loggedIn === undefined)   {
     debugString('getLoginStatus did not exec'); // I always get this message
  }

}
UPDATE 2: I created a new App on a different URL, which is configured as a standalone website. There these codes work perfectly, I can getLoginStatus, I can login, etc. Is there any difference working in the context of FB, and in a standalone website, using FB JavaScript SDK?
Comment: Would you provide some more code?
Answer: FB.getLoginStatus does not fire the callback when you are running the website on a different domain than the one that you registered the app with. I usually find myself in this situation when I am developing locally or on a staging server.
For example, if you registered the site with example.com and your staging server is example.mystagingserver.com, the callback wont fire. In this case, you need to create a second application in Facebook and use the Application ID and Secret for the new app.
Comment: I don't know what happened, but yesterday I checked the App settings again, and the App domain showed as a deletable label, not as a string I used to see, and - voilá - everything is working as a smooth, running machine.
Answer: I just had the same problem, though it only happened to some users.
I finally found out that if your app is sandbox mode, none-developer users can still see your app as a pagetab. But calling getLoginStatus will fail silently (even logging turned on).
Took a while to figure that one out, I hope this can save someone else some time.
Answer: I'm using this code, successfully. I'm not quite sure where the differences are.. but I'm using the ASYNC FB Loader.
 window.fbAsyncInit = function() {
   FB.init({ appId: 'XXXXXX', //change the appId to your appId
             status: true,
             cookie: true,
             xfbml: true,
             oauth: true});

 function authEvent(response) {

   if (response.authResponse) {
          //user is already logged in and connected
           FB.api('/me', function(info) {
              login(response, info);
            });
    } else {
          //user is not connected to your app or logged out
           button.onclick = function() {
            FB.login(function(response) {
            if (response.authResponse) {
               FB.api('/me', function(info) {
                   login(response, info);
              });
                } else {
               //user cancelled login or did not grant authorization
             }
         }, {scope:'email,rsvp_event,status_update,publish_stream,user_about_me'});
                    }
                }
            }

            // run once with current status and whenever the status changes
            FB.getLoginStatus(updateButton);
            FB.Event.subscribe('auth.statusChange', updateButton);
        };
        (function() {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol
                + '//connect.facebook.net/en_US/all.js';
            document.getElementById('fb-root').appendChild(e);
        }());

        function login(response, info){
            if (response.authResponse) {
                accessToken =   response.authResponse.accessToken;
        userid = info.id;

                userInfo.innerHTML  = '' + info.name+"
 Your Access Token: " + accessToken;
            }
        }

Answer: You can use the following code to check if the user is logged in:
FB.getLoginStatus(function(response) {
    if (response.authResponse) {
        // logged in and connected user, someone you know
    } else {
        // no user session available, someone you dont know
    }
});

From FB JS SDK Documentation.
You can wrap the whole code in jQuery ready :
$('document').ready(function(){
    ... above code
})

Also you may want to check this question StackOverflow.
Comment: that is the bad part, because the callback function won't run on getLoginStatus ... as I said in the original question. And I read the question you mentioned, but it didn't help.
Comment: I'm having the same issue, FB.getLoginStatus will only be called if the user is logged in.
Comment: I'm logged in and no such luck :O
Answer: I had the same problem. I was working on the facebook login process of our website. During development the "FB.getLoginStatus" did not return a response. I fixed it in the settings of the app on facebook:
-In facebook go to "manage apps"
-Go to the "facebook login" settings of your app
-Add your development url (for example "https://localhost") to the "Valid OAuth Redirect URIs"
(Don't forget to remove the "https://localhost" from the OAuth Redirect URIs when you are finished with developping.)
Answer: Something common that causes this is that a browser is blocking cookies, this will cause the event not to fire. Also, make sure that if you or your user have and ad blocker that it is not blocking third party cookies.
Example of warning:
Answer: For me after extensive testing can confirm the dialog to log the user will not show unless you use a valid Application ID
These can be found in
https://developers.facebook.com/apps/{{Application__Id}}/settings/

Just make sure you call the api with the correct ID.


fade toggle jquery

Question: Tenho uma div e dentro dela um header (h3) e um button, quero que quando eu pressione esse button, altere o conteúdo do texto e do button, com um novo texto e um novo button com um efeito fadeOut para o texto/button atual e FadeIn pro novo texto/button! como posso fazer isso ?

O texto a ser alternado

<button class="ui button">button</button

Comment: Ao invés de descrever seu html seria melhor incluir no conteúdo da pergunta.
Comment: "Tenho uma div" ok poste para podermos ajudar .
Comment: codigo adicionado
Answer: Você pode usar fadeOut com callback alterando os textos dos elementos e finalizando com fadeIn.
Veja que selecionei o H3 em .find("h3") e em seguida o button com .next(), já que o button é o próximo elemento após o H3:

$(".ui.button").click(function(){
   $(this).closest("div").fadeOut( function(){
      // troca o texto do H3 e o texto do button
      // e faz fadeIn
      $(this)
      .closest("div")
      .fadeIn()
      .find("h3")
      .text("Novo texto no H3")
      .next()
      .text("novo texto do button");
   });
});

O texto a ser alternado

   <button class="ui button">button</button>

Answer: Um exemplo lúdico utilizando Jquery

$(document).ready(function(){
  var contador = 0;
  $("#botao").on('click', function(){
    contador++;
    $(this).val("Yay!");

    $("#texto").fadeOut(function(){
      $("#botao").fadeOut();

      $(this).html(contador + " cliques e contando..").fadeIn(function(){
          $("#botao").val("Clique").fadeIn();
      });

    });

  });
});

Contador de clicks

  <input id="botao" type="button" value="Clique">

fade toggle jquery


multiplying through a maximum function with random variables

Question: Does this hold?
$$
\max(0,\vec{a}) \cdot \max(0,\vec{b})
= \max(0,\vec{a} \cdot \vec{b})
$$
Comment: (-1) I am done with this question. This is at least the **third** time you have changed the question, after an answer was posted to the previous version. (And the second time since you *accepted* the answer!) You can post a new question, or at the very least add an update without deleting the old content (which leaves answers orphaned). If there is some [underlying question](http://meta.stackexchange.com/a/66378/339776), you should just post that.
Comment: Where you say "Beginning with the inside of the expectation", the following line is wrong. Say $gx<0$ and $gy<0$, then your LHS$=0$, but your RHS$>0$.
Answer:
Update: I am putting my old comment here as the answer, since the question has now been changed to just that!

First note that since 1) the dot product produces a scalar result, and 2) the question involves no expectations or probabilities, then your question is really equivalent to:
"Does it hold that $\max[0,a]\max[0,b] = \max[0,ab]$ ?"
That is, the fact that $x,y,g$ are vectors or that $g$ is random are unimportant.
The answer to this simpler question is no. An easy counter-example is $a=b=-1$.

The answer below was to the original question, which asked if it was true that
  $$\mathbb{E}\big[(x^Tg)_+(g^Ty)_+\big] = (x^Ty)_+$$
  where (I believe the intent was) $g\sim\mathrm{N_{0,I}}$

(Note: I am using "positive part" notation here, where $x_+\equiv\max[0,x]$. Similarly, I will use matrix notation for dot products: $x^Ty\equiv\vec{x}\cdot\vec{y}$.)
A simple counter-example to your formula is the following. For $x=y=1$, the right hand side is simply $1$, while the left hand side is
$$\mathbb{E}[(g_+)^2]=\tfrac{1}{2}\mathbb{E}[g^2]+\tfrac{1}{2}\mathbb{E}[0]=\tfrac{1}{2}\neq{1}$$

If you remove the $()_+$ part, the formula works, since $g\sim\mathrm{N_{0,I}}$ by definition implies $\mathbb{E}[gg^T]=I$, so we have
$$\mathbb{E}\big[(x^Tg)(g^Ty)\big]
= x^T\,\mathbb{E}\big[gg^T\big]\,y
= x^TIy = x^Ty
$$

For the scalar case, the formula with the $1/2$ correction-factor holds
$$\mathbb{E}[(gx)_+(gy)_+]=\tfrac{1}{2}(xy)_+$$
where $x,y\in\mathbb{R}$. But this does not hold in the general vector case (i.e. if $x$ and $y$ are not parallel).
Comment: @whuber I was addressing the equation in the question title, which at the time I posted was equivalent to "Is $\mathbb{E}\big[(x^Tg)_+(g^Ty)_+\big] = (x^Ty)_+$ ?"
Comment: How did you carry out this calculation?  In your example the left hand side is $\mathbb{E}((g1)(g1))=\mathbb{E}(g^2)=1$.
Comment: I changed "positive part" notation from $\max(0,g)$ to $g_+$. So for $g\sim\mathrm{N}_{0,1}$ half the time $g_+=0$.
Comment: You seem to have changed the order of operations: if you are computing the last formula in the question, then you need to compute the positive part of $g^2$, not the square of the positive part of $g$.


MySQL Server 8.0 - No bin file

Question: I have been trying to reset my password for MySQL in order to use the DBMS appropriately for an application I am working on. I have looked at numerous threads for resetting your password on MySQL and the only way is to go through the command prompt I have noticed.
Every method I have seen requires being able to access the bin file such as:
C:\> cd "C:\Program Files\MySQL\MySQL Server 5.5\bin"

However, for MySQL Server 8.0 there is no "bin" file following the 'MySQL Server 8.0'.
Does anyone know a way around this so that I can reset my password?
Answer: You tagged your question with mysql-workbench, so I assume you would accept a solution that involves this tool. If you have your old password still, you can simply log in to your server with that password, go to Administration -> Users and Privileges:

There you can enter a new password.
Comment: That sure does look handy, however I do not believe that my workbench version, 8.0, has this 'Administration' feature. I cannot seem to locate it on my workbench.
Comment: It surely has. It just might look a bit different, as some details changed over time. Best is to get the latest version (8.0.17 currently).

MySQL Server 8.0 - No bin file