Boundary of compact set $[a_1,b_1] \times [a_2,b_2]$ has measure zero?

Question: Why is the boundary of the compact set
$$[a_1,b_1] \times [a_2,b_2]$$ measure zero?
Answer: The boundary is the union of four line segments.  All line segments in $\mathbb{R}^2$ have measure zero.  They're measurable being closed.  How to prove most easily that their measure is zero depends on your definition of Lebesgue measure, but for example Rudin Real and Complex Analysis 2.19, formulas (4) and (5), let this be shown easily.
In more detail consider the line segment from $(a_1,a_2)$ to $(b_1,a_2)$.  Using formula (4) write it as $\{(x,y):a_1\le x\le b_1, a_2\le y\le a_2\}$; then formula (5) gives its measure as $(b_1-a_1)(a_2-a_2)=0$.
Comment: Bummer, you beat me to it. I posted the same thing 2 min after you. Well done!
Comment: Such things always happen.
Answer: The boundary consists of four line segments. Any line (segment) in $\mathbb R^2$ has measure zero. Indeed, for any $\varepsilon > 0$, the $x$-axis is contained in the sets $$[-n, n,] \times \left [-\tfrac{\varepsilon}{n2^{ n +2}}, \tfrac{\varepsilon}{n2^{ n+2}} \right], \,\,\, n \in \mathbb N$$ so by subadditivity, $$\lambda(x\text{-axis}) \le \sum_{n \in \mathbb N} 2n \cdot \frac{\varepsilon}{n2^{n+1}} = \varepsilon \sum_{n \in \mathbb N} \frac 1 {2^n} = \varepsilon.$$ Since $\varepsilon$ was arbitrary, the $x$-axis has measure zero. By translation and rotation invariance of the Lebesgue measure, any line (and thus by monotonicity, any subset of a line) must also have measure zero. Hence, a union of four line segments also has measure zero.
Comment: Elaborate why you choose the sets. You answer is a bit abstract, IMO.
Comment: I'm not sure what you mean by abstract. On the contrary, my answer is completely constructive. To prove a set $A$ has measure zero, it suffices to prove that for arbitrary $\varepsilon > 0$, we can cover $A$ with a set whose measure is not larger than $\varepsilon$. The reason I chose those sets is because their union covers the $x$-axis and the measure of their union is bounded by $\varepsilon$. This approach seems to me to be the most natural way to prove a set has measure zero.


Different AIC definitions

Question: From Wikipedia there is a definition of Akaike's Information Criterion (AIC) as $ AIC = 2k -2 \log L $, where $k$ is the number of parameters and $\log L$ is the log-likelihood of the model.
However, our Econometrics notes at a well-respected university state that $ AIC = \log (\hat{\sigma}^2) + \frac{2 \cdot k}{T} $. Here $ \hat{\sigma}^2 $ is the estimated variance for the errors in an ARMA model and $ T $ is the number of observations in the time series dataset.
Is the latter definition equivalent to the first, but simply tuned for ARMA models? Or is there some kind of conflict between the two definitions?
Comment: For the record: criterion singular, criteria plural. (Edited accordingly.)
Answer: The formula you quote from your notes is not exactly AIC.
AIC is $-2\log\mathcal{L}+2k$.
Here I'll give an outline of an approximate derivation that makes clear enough what's going on.
If you have a model with independent normal errors with constant variance,
$$\mathcal{L}\propto \sigma^{-n} \: e^{-\frac{1}{2\sigma^2}\sum \varepsilon_i^2}$$
which can be estimated under maximum likelihood as
\begin{eqnarray}
& \propto &(\hat{\sigma}^2)^{-n/2} e^{-\frac12 n\hat{\sigma}^2/\hat{\sigma}^2}\\
& \propto &(\hat{\sigma}^2)^{-n/2} e^{-\frac12 n}\\
& \propto &(\hat{\sigma}^2)^{-n/2}
\end{eqnarray}
(assuming the estimate of $\sigma^2$ is the ML estimate)
So $-2\log\mathcal{L} +2k = n\log{\hat{\sigma}^2} + 2k$ (up to shifting by a constant)
Now in the ARMA model, if $T$ is really large compared to $p$ and $q$, then the likelihood can be approximated by a such a Gaussian framework (e.g. you can write the ARMA approximately as a longer AR and condition on enough terms to write that AR as a regression model), so with $T$ in place of $n$:
$AIC \approx T\log{\hat{\sigma}^2} + 2k$
hence
$AIC/T \approx \log{\hat{\sigma}^2} + 2k/T$
Now if you're simply comparing AICs, that division through by $T$ doesn't matter at all, since it doesn't change the ordering of AIC values.
However, if you're using AIC for some other purpose that relies on the actual value of differences in AIC (such as to do multimodel inference as described by Burnham and Anderson), then it matters.
Numerous econometrics texts seem to use this AIC/T form. Oddly, some books seem to reference Hurvich and Tsai 1989 or Findley 1985 for that form, but Hurvich & Tsai and Findley seem to be discussing the original form (though I only have an indirect indication of what Findley does right now, so perhaps there is something in Findley on it).
Such scaling might be done for a variety of reasons -- for example, time series, especially high frequency time series, can be very long and ordinary AICs might have a tendency to become unwieldy, especially if $\sigma^2$ is very small. (There are some other possible reasons, but since I really don't know the reason this was done I won't start going down a list of all possible reasons.)
You may like to look at Rob Hyndman's list of Facts and fallacies of the AIC, - particularly items 3 to 7. Some of those points might lead you to be at least a little cautious about relying too heavily on the approximation by Gaussian likelihood, but maybe there's a better justification than I offer here.
I'm not sure there's a good reason to use this approximation to the log-likelihood rather than the actual AIC since a lot of time series packages these days tend to calculate (/maximize) the actual log-likelihood for ARMA models. There seems little reason not to use it.
Comment: Sooner or later, every discussion about any *IC turns into "This is the criterion you should use, except that it often gives the wrong answer in such-and-such circumstances". Just being ironic, not at all critical of a typically helpful answer. This is just like real life, where some generic maxim such as "love everybody" is usually to be overridden temporarily by other advice if somebody is trying to beat you up or rip you off.
Comment: @Nick I'm not bothered by the texts that use AIC/$n$ rather than AIC, but what does worry me is that so many of the econometrics books I've looked at just call it "AIC" *without any comment*. To me that's just recklessly irresponsible. Whoever was first to do it but not say so has been copied again and again.
Answer: I believe this is based on the assumption of normal errors. In econometrics, you operate using asymptotics, especially in the time series applications using AIC. As a consequence, the normal assumption should hold asymptotically to justify this (asymptotic) model selection scheme.
Recall that the logarithm of the normal likelihood is
$ln(L) = -(T/2)ln(2\pi) -(T/2)ln(\sigma^2) - (1/2\sigma^2)\sum(x_i - \mu) $,
where we use $\mathbb{E}(X) = \mu$ and $Var(X) = \sigma^2$ if your data is drawn from X. In what follows we neglect the first term, as the observed sample $x_1, ..., x_T$ does not affect it.
Simply use the more general (first) formula and plug in $L$ for the normal likelihood. The first term can be ignored (it is a constant regardless of regressor choice). The second term becomes $Tln(\sigma^2)$. The third term becomes $(1/\sigma^2)(T\hat{\sigma}^2)$, where we have used $\hat{\sigma}^2 = T^{-1} \sum(x_i - \bar{x})$. Again, not using a finite sample correction is justified here because this estimator is only valid asymptotically if the errors are not normal.
Since we do not know $\sigma^2$, we have to estimate the third term as $(1/\sigma^2)(T\hat{\sigma}^2) = (1/\hat{\sigma}^2)(T\hat{\sigma}^2)$ = T.
In summary, this means we get for the normal likelihood that $AIC = 2k + Tln(\sigma^2) + 1$. Needless to say, the minimization is not affected by ignoring the constant $1$. The term is now simply divided by $T$, since it does not change the minimization problem to scale all additive components by $T$. This lands you at the second result, because $AIC$ and $AIC/T$ are identical for the purpose of minimization.

Different AIC definitions


How to get content type data on basis of assigned taxonomy?

Question: I want to get the data of particular content type on the basis of taxonomy assigned to it. How can I get this using query.
$bloglist = db_select('node', 'n')
                    ->fields('n', array('nid'))
                    ->condition('type', 'product_list', '=')
                    ->condition('status', 1, '=')
                    ->orderBy('created', 'DESC')
                    ->execute()
                    ->fetchCol();

        // Get all of the article nodes.
        $bloglists2 = node_load_multiple($bloglist);

I have this query to get the data for product_list content type. Now I want to add one more condition of taxonomy to get data on basis of taxonomy and content type. How can I do that?
Answer: The EntityFieldQuery class was built to do pretty much exactly that:
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product_list')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_foo', 'tid', $term_id)
  ->propertyOrderBy('created', 'DESC')
  ->execute();

if (isset($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

Comment: The machine name of the field attached to the node type, you can find it in the Manage Fields admin page
Comment: What should I write instead of `field_foo`? I have the `$term_id` value
Answer: You have to use the Join statement; what you basically need to do is joining your query with another from another table.
Here is an example that you can use.
$query = db_select('file_managed', 'fm');
$query->join('field_data_field_image', 'fi', 'fm.fid = fi.field_image_fid');
$query->groupBy('fm.fid');
$query->fields('fm', array('filename', 'uri'));
$query->fields('fi', array('field_image_width', 'field_image_height'));
$query->condition('fi.bundle','image_for_slider','=');
$result = $query->execute()->fetchAssoc();

In this example, the file_managed table is joined with field_data_field_image;
you have to switch those with node and field_tags.


Asymptotic notation: Once $j$ is $\Theta(\log \log n)$

Question: In the paper Wherefor Art Thou R3579X? they state at the end of page 5, while proving theorem 2.2, that "Once $j$ is $\Theta(\log \log n)$, each term in the sum is $O(1)$".
My question is now what does "Once $j$ is $\Theta(\log \log n)$" mean? Does this have a proper definition or is it just more abuse of asymptotic notation?
Answer: My take on this is that there are real positive constants $a$ and $b$
such that
$$a \log \log n < j < b\log \log n $$
Evidently (since I have not read the original reference),
this will allow you to deduce
that the terms referred to are $O(1)$.
(Added a bit later)
If you want to keep this completely in terms of $O(...)$ notation,
both $j = O(\log \log n)$
and $\log \log n = O(j)$
hold.


Varnish Does not work

Question: I installed varnish as well on my server , but the performance did not change , The http://www.webpagetest.org/ says caching system does not enable on your server , i'm using default configuration of varnish , it's my header :
status: HTTP/1.1 200 OK
Server: Apache
X-Powered-By:   PHP/5.3.29
P3P:    CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Expires:    Mon, 1 Jan 2001 00:00:00 GMT
Cache-Control:  no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: 73ab794b527721e09d2124da5815cf79=2f8ca1fed15724e75f5bf3824a26a9cd; path=/; HttpOnly
Last-Modified:  Thu, 25 Sep 2014 08:28:53 GMT
Content-Type:   text/html; charset=utf-8
Content-Length: 77965
Accept-Ranges:  bytes
Date:   Thu, 25 Sep 2014 08:28:53 GMT
X-Varnish:  1531877383
Age:    0
Via:    1.1 varnish
Connection: close

Answer: I will see if i can help for any future views of this issue, There are a number of things that will cause Varnish not to cache content. You will need to work through all of them and hopefully have a good logging / metrics setup so you can identify which pages / resources are not responding from cache.
Your cache control headers were:
status: HTTP/1.1 200 OK
Server: Apache
X-Powered-By:   PHP/5.3.29
P3P:    CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Expires:    Mon, 1 Jan 2001 00:00:00 GMT
Cache-Control:  no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: 73ab794b527721e09d2124da5815cf79=2f8ca1fed15724e75f5bf3824a26a9cd; path=/; HttpOnly
Last-Modified:  Thu, 25 Sep 2014 08:28:53 GMT
Content-Type:   text/html; charset=utf-8
Content-Length: 77965
Accept-Ranges:  bytes
Date:   Thu, 25 Sep 2014 08:28:53 GMT
X-Varnish:  1531877383
Age:    0
Via:    1.1 varnish
Connection: close

To have this particular request cachable you need to fix:

Expires:    Mon, 1 Jan 2001 00:00:00 GMT
This tells Varnish not to cache
Cache-Control:  no-store, no-cache, must-revalidate, post-check=0,
pre-check=0
This tells Varnish not to cache (Varnish 4+, Varnish 3 will still cache this)
Set-Cookie: 73ab794b527721e09d2124da5815cf79=2f8ca1fed15724e75f5bf3824a26a9cd; path=/; HttpOnly
Varnish will not cache any response with Set-Cookie

In order to tackle metrics / logging so that you can get visibility of all requests i have written about Varnish setup options: https://www.section.io/varnish-install-quick-and-detailed/
Answer: Your problem is here:

Cache-Control:  no-store, no-cache ...

Basically:

next lookup fails (Varnish will not store the response in cache)
browsers will not cache the response so any F5 will request the resource again from your server.

Use the below in your VCL
sub vcl_fetch {

remove beresp.http.Cache-Control;

  set beresp.http.Cache-Control = "public";

}

Comment: I added this code to my config , but my website performance did not changed and webpagetest.org still showing the level F of caching
Comment: The response that your application is returning specifies that it should not be cached. Make sure that you return the public cache headers.
Comment: yes,i see publish cache in my headers after applying your code :) , but my performance did not changed yet
Comment: i think i need to  adding another configuration , but i don't know what should i do
Comment: You need to discard backend set-cookie as well. Check https://www.varnish-cache.org/docs/3.0/tutorial/cookies.html
Comment: how can i testing varnish working as well?
Comment: Check here http://www.isvarnishworking.com/
Answer: I had this problem on ubuntu server with PHP-FPM:
Expires:    Mon, 1 Jan 2001 00:00:00 GMT
Cache-Control:  no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

Problem was session.cache_limiter in /etc/php/7.1/fpm/php.ini (PHP-FPM)
sed -i "s/session.cache_limiter = nocache/session.cache_limiter = ''/" /etc/php/7.1/fpm/php.ini

Other problem to resolve was "SetCookie" for testing use this:
vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "8181";
}

sub vcl_recv {
    unset req.http.cookie;
    return(hash);
}

sub vcl_backend_response {
    unset beresp.http.set-cookie;
    set beresp.ttl = 30m;
}

sub vcl_deliver {
}

One more thing that I was missing was "a2enmod proxy_http" for ProxyPass in Apache2

Varnish Does not work


Can I add an 'environment variable' in CMake GUI Wizard?

Question: A CMake script I am using expects an environment variable XXX_HOME to be set, but I don't have this and don't want to add it.
Is there a way to trick CMake into thinking this variable exists, with a value I set, in the CMake cache - ideally using the CMake GUI - so I don't have to edit the CMake scripts? I tried adding a setting in the GUI XXX_HOME = ... but it didn't work.
Comment: Can't you run cmake-gui from an environment with the environment variable set. I do this all the time on windows so that I can build for different compilers / different bit depths in totally different build trees with the same source. In linux you also should be able to set the variable on the same line as cmake-gui. Like this XXX_HOME="/usr/src/xxx" cmake-gui
Comment: hmm, perhaps I can. Worth a try.
Comment: @drescherjm if you want the green tick move that to an answer...
Answer: Can't you run cmake-gui from an environment with the environment variable set? I do this all the time on windows using batch files and shortcuts to the visual studio command prompt so that I can build for different compilers / different bit depths in totally different build trees with the same source.
In linux you also should be able to set the variable on the same line as cmake-gui. Like this XXX_HOME="/usr/src/xxx" cmake-gui
Comment: This answer isn't aligned with the spirit of a GUI. But anyway @Mr. Boy where's that tick you promsed!?


Rails omniauth and regular login, giving an undefined method error

Question: I have used Rails Tutorial's instructions to create a working login. And then later to add Google authorization I used the omniauth method.
However, whenever I sign in using the Google account, I get an error in the sessions_controller. Where it says:
NoMethodError (undefined method `[]' for nil:N
ilClass): app/controllers/sessions_controller.rb:6:in `create'

I am adding the sessions_controller
Sessions_controller.rb
    class SessionsController < ApplicationController
  def new
  end

  def create
    @user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      redirect_back_or user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def create_from_omniauth
    @user = User.from_provider_data(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to user
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end

  def google_destory
    session[:user_id] = nil
    redirect_to root_url
  end

end

How do I resolve this, any help would be highly appreciated.
Thank you!
Answer: I think because it's ENV, not env.
@user = User.from_provider_data(env["omniauth.auth"])

to
@user = User.from_provider_data(ENV["omniauth.auth"])

unless env is something defined by you


Quantifying the uncertainty of aggregated model predictions

Question: Say I have a binary response variable, Y, that I model using a logistic model with four predictors, A, B, C and D. To make matters concrete, imagine that Y = 1 designates a respondent registering support for something, and 0 an absence of support.
Having estimated the relevant parameters on some sample, S, I then want to see what proportion of 1s (i.e., support) I likely would have seen, had all observations in S taken on a particular value on A. Assume conditions for causal inference are satisfied for A, so that changing its value can be thought of as a (hypothetical) intervention.
So I create a "new" sample, S*, identical, to S, save for each observation taking on the desired value on A. I then use the fitted model to "predict" the probability of Y = 1 for each observation in that sample. Taking the mean of those predictions I get an estimated proportion of support under the relevant intervention.
My question is: how should I quantify the uncertainty of that estimate? I can think of three ways, but am not sure which one (if any) makes sense:

Resample from the predicted probabilities of the model and bootstrap a confidence interval for the relevant mean that way.
Calculate a confidence interval for the prediction made on each observation (the probability that respondent 1 registers support, etc.) like here, and then create a confidence interval for mean support by taking the means of the upr and lwr values of the individual predictions.
Resample from S* to fit a large number of models, generate predictions on each model, and then bootstrap a confidence interval for the relevant mean from these predictions.

Any advice here would be greatly appreciated.
Answer: If I am understanding you correctly, you want to create a confidence interval around the proportion of observations that would have resulted in $Y = 1$ given $A = a$. Your logistic regression already provides us with $P(Y = 1 | A = a, B = b, C = c, D = d)$. You are justified in taking the mean as a point estimate of $P(Y = 1|A = a)$ by the law of total probability. Because the proportion of observations where $Y = 1$ is logically equivalent to the probability that an observation will yield $Y = 1$ you could use the normal approximation computed on the predicted probabilities themselves to create a confidence interval.
Here is some R code that would do the trick
<code># fake data for demonstration
# 20 samples drawn from a uniform distribution between 0 and 1
predicted_probs <- runif(n = 50, min = 0, max = 1)

# estimate of the average probability
global_prob_est <- mean(predicted_probs)

# standard error of the estimate
global_prob_se <- sd(predicted_probs)/length(predicted_probs)

# 90% CI using the 5th and 95th percentiles of a normal distribution.
qnorm(p = (0.05, 0.95), mean = global_prob_est, sd = global_prob_se)
</code>
Comment: Thanks so much, David! More straightforward than I thought! Just one question: on your proposed way of proceeding, it seems we capture none of the uncertainty in the model estimates (i.e., the individual predictions), as given by the SEs on my proposed (2). For example, say we have two models generating identical vectors of estimates (your `predicted_probs`), but with massively different SEs (on one model, they're all low; on the other, they're all high). On your proposal, the CIs for both vectors would be the same. On proposal (2), they would not be. Or am I way off?
Comment: (1/2) Ah, I see. Yes, my proposal takes the model fit as a plug-in estimator (in the same sense as using a fitted model in a bootstrap). I recognize the challenge as being with respect to the propagation of uncertainty from the standard errors of the logistic regression. This would be straight forward in a Bayesian context because the uncertainty is treated as a random variable versus a non-probabilistic interval.
Comment: (2/2) You could use the predict function to get the se on each interval and then compute a confidence interval for each point as you have proposed in (2); however the means of the lower and upper boundaries would not necessarily have the same coverage as the intervals at each point e.g., the means of the lower and upper boundaries of 90% intervals do not necessarily capture the "true parameter" (in this case, a vector of probabilities) in 90% of repeated uses.
Comment: Thanks again, David. Yes, that was my thinking with (2). It's the *closest* I can think of to what I need, but for the reasons you outline re coverage I'm not sure it's close enough. That said, it does of course capture *something* about the uncertainty involved. If you end up thinking of a better way, I'd be happy to hear!


Laravel : how to create unique tag in tags model

Question: I want create tag for posts . I don't want tags repetitions to be saved,But it is stored repeated
public function store(Request $request)
{
    $data = $request->all();
    $post = Post::create($data);
    if ($post && $post instanceof Post) {
        $tags = $request->input('tags');
        foreach ($tags as $tag){
                $newTag = Tag::create(['name'=>$tag]);
                $tags[] = $newTag->id;
        }
            $post->tags()->sync($tags);
        return redirect()->back();
    }
}

How can it be done?
Answer: updateOrCreate method will help check
It will create data if it not exists and update in case it already in db
Tag::updateOrCreate(['name'=>$tag]);


Covariance between two binomial random variables

Question: Consider a binomial random variable $X$ with parameter $p$ and another binomial random variable $Y$ with parameter $q$. What is the covariance of $X$ and $Y$?
How well does the proof generalize to $n$ such random variables $X_1...X_n$ with respective parameters $p_1...p_n$? Has the covariance matrix been worked out in this case as well?
Comment: Binomial distribution or Bernoulli distribution? If binomial, $n$ is needed. My answer is based on Bernoulli, If you mean Binomial, I will delete my answer.
Answer: If the binomial random variable are independent, then of course the population correlation is $0.$ Samples from the distributions of the two random variables will tend to be near $0.$
set.seed(1234)
x = rbinom(10^5, 10, .3);  y = rbinom(10^5, 10, .7)
cor(x,y)
[1] -0.0006200541

However, one can simulate mixtures of binomial random variables that are correlated.
In the plot below, a small amount of uniform noise keeps points that would
have had exactly integer coordinates from plotting exactly on top of each
other. [This is called 'jittering'.]
set.seed(2019)
p = rbeta(10^4, 2, 2)  # different p's for each (x,y)-pair below
x = rbinom(10^4, 10, p);  y = rbinom(10^4, 10, p)
cor(x, y)
[1] 0.7146091
cov(x,y)
[1] 5.03711
X = x + runif(10^4, -.2, .2)
Y = y + runif(10^4, -.2, .2)
plot(X, Y, pch=".")

Finally, if the success probabilities $p$ are the same in three
independent binomials $U, V,$ and $W,$ each distributed
$\mathsf{Binom}(n=5, p = 0.3),$ then $X = U+V$ and $Y = U+W$ are
correlated random variables, each with distribution
$\mathsf{Binom}(10, 0.3).$ Also,
$$Cov(X,Y) = Cov(U+V, U+W) = Cov(U,U)\\ = Var(U) = 5p(1-p) = 1.05,$$
where the second inequality is due to the mutual independence of $U,V,$ and $W.$
set.seed(713);  m = 30000
u = rbinom(m, 5, .3);  v = rbinom(m, 5, .3);  w = rbinom(m, 5, .3)
x = u + v;  y = u + w
cor(x, y);  cov(x, y)
[1] 0.5082363
[1] 1.065182   # aprx Cov(X,Y) = 1.05

par(mfrow=c(1,3));  cutp = (-1:10)+.5
k = 0:10;  pdf = dbinom(k, 10, .3)
 hist(x, prob=T, br=cutp, col="skyblue2")
  points(k, pdf, col="red", pch=19)
 hist(y, prob=T, br=cutp, col="skyblue2")
  points(k, pdf, col="red", pch=19)
X = x + runif(m, -.2, .2)
Y = y + runif(m, -.2, .2)
 plot(X,Y, pch=".")
par(mfrow=c(1,1))

The first two panels show histograms of simulated marginal distributions
of $X$ and $Y,$ with red dots showing exact PDFs. The simulated marginal distribution is shown (slightly jittered) in the third panel.
Answer: Suppose the values for $X$ and $Y$ following Bernoulli distribution are 0 and 1, and $p$ and $q$ are probabilities of being 1. We know $$Cov(Y,Y) = E(XY)-E(X)E(Y)$$ and $$E(X)E(Y)=pq.$$
Since $E(XY) = P(X\!=\!1,Y\!\!=\!1) = p\mu$, where $\mu\!=\!P(Y\!\!=\!1|X\!=\!1)\!\in\![0,1]$, we have
$$E(XY) \leq min(p,q)$$
and since $P(X\!=\!1,Y\!\!=\!1) = q - \lambda(1-p)$, where $\lambda\!=\!P(Y=1|X=0)$
$$E(XY) \geq max(0,p+q-1).$$
So
$$max(0,p+q-1) - pq \le Cov(X,Y) \le min(p,q) -pq$$
For the situation of more than 2 random variables, it maybe is complicated.
Comment: Do you intend for $X$ and $Y$ to be _Bernoulli_ random variables?
Comment: Yes. May I misunderstand the OP. That no $N$s were given mislead me to bernouli. Maybe I should delete it.
Comment: No, please don't delete on account of my comment. Your interpretation is reasonable. But it is customary to say 'Bernoulli' when $n = 1,$ so I tried to make what sense I could of general Binomials with $n > 1.$ At least your interpretation led to an interesting answer (+1), I'm not sure I can say the same for mine.
Comment: If OP means binomial, my answer really does not answer the question.
Comment: It you wait for questions to be perfectly clear, there will be many fewer questions to answer. // Just browsed a few of your other answers. Some really nice ones there.
Comment: @BruceET Thank you. Here is something for you to kill the time.  a-statistician.github.io
Comment: May have a chance to check into that.


Fastest way to get XAMPP or WAMP up on Win7 64-bit?

Question: I recently upgraded to a 64-bit machine, (I know I'm behind but everything was running and I'm cheap). I use XAMPP on my older machines to stand up local web dev and want to do the same on my new machine. However I'm having significant trouble getting XAMPP or WAMP to run properly under the 64-bit install. WAMP simply won't install saying that the setup files are corrupted and XAMPP installs but throws an error about running from the XAMPP directory on control panel launch and Apache will not stay running.
In my reading it seems that neither XAMPP or WAMP have been ported to 64-bit yet (not sure if this information is the most recent).
What is the quickest way to get one of these stacks up on a 64-bit Win 7 install, I don't really care if it has to run in 32-bit mode or not. Thanks in advance for your help.
EDIT: Of course after posting I found the 64-bit download of WAMP, posting here for others who are search challenged like myself. I had been getting the sourceforge download links rather than the wampserver ones. Apparently the direct search engine links were defaulting to 32-bit or something.
Both versions here : http://www.wampserver.com/en/download.php
Comment: App installation is not programming related - voting to move to [serverfault](http://serverfault.com/)
Comment: Ok, new to StackExchange though, how do I go about doing the move?
Comment: Click the flag link (to the left of your username/avatar image) to contact a moderator if others haven't already voted.  Takes 5 votes...
Comment: @Fredrik, I meant moving the question to ServerFault, but yes installing WAMP was a breeze once I found the right download.
Answer: download xampp from here
extract to someplace u like. then launch setup_xampp.bat from the extracted directory, follow instructions
double click on xampp_Start.exe to start, xampp_stop.exe to stop.
u can even extract this in a USB drive and when u change compus just launch the setup.bat once again. and u are good to go


Variables updating issues using $digest() with angularjs & jasmine

Question: I'm having issues with the use of scope.$digest() when testing an angular directive.
When we see the angularjs tests, each time we compile an html piece of code to tests in it,               .$digest() is called to perform a scope life cycle.
My problem is that if I execute this function, the argument value of the widget is taken into account at the end of this method instead of using the parsed one.
If I don't execute the function, everything works right.
Can someone explain why this is happening?
I have created a codepen example: Codepen example
var Widgets =  angular.module('myWidgets', ['ng']);
Widgets
.directive('widgetb', function() {
    return {
        restrict: 'E',
        scope : {
            a: "@",
        },

        replace: true,
        template: "
" +
                        "{{a}}" +
                    "
",
        controller : function($scope) {
            $scope.action = function(action) {
                console.log("Action received");
                console.log(action);
            };
            $scope.a = parseInt($scope.a);
        }
    };
});

describe("Test", function() {
    var $compile, scope;

    beforeEach(function() {
        module('myWidgets');
    });
    beforeEach(inject(function(_$compile_, $rootScope) {
        $compile = _$compile_;
        scope = $rootScope.$new();
    }));

    it('Compile', function() {
          var element = $compile('<widgetb a="3xx" />')(scope);
          var widget_scope = element.isolateScope();

          /* test ok if digest command is not executed, error otherwise */
          widget_scope.$digest();
          expect(widget_scope.a).toBe(3);
    });
});

Answer: Directive controllers are not run once per $digest cycle, but template interpolation is. What you would want is a watcher in the controller to make sure that $scope.a is always kept an integer.
Basically what's going on is, when widgetb is being compiled into the scope, the controller runs. When there's no scope.$digest, the latest value of $scope.a comes from the controller. Once you call scope.$digest(), the template gets interpolated based on what was originally passed in. Since @ is not two-way bound, as it's a primitive, it was not changed from when you called parseInt in the controller beforehand, so it gets "reset" to 3xx.
Here's an updated codepen with the watcher installed. Tests pass:
http://codepen.io/anon/pen/ocKrF
Comment: I was afraid the watcher takes a lot of resources but it may be the only way to do this. Moreover, I've realized that we can modify the variable inside the watch function but a new watcher won't be fired, avoiding unnecessary watcher executions. Thanks!
Comment: Yeah I was dealing with a similar issue a few weeks ago. Unfortunately it is difficult to keep a scope variable in integer form if it's passed in as a string, and I believe a watcher is the only way to preserve the change. An alternative would be to declare the integer as a variable in a parent scope and pass it as a 2-way `=` binding, but I felt that was out of the scope of your question.
Comment: Doing that we reduce the widget coupling making it parent dependent.  Returning into classic development, we can create a private variable in the controller accessible by public getter & setter and initialized with the input variable the first time. This may reduce the load performed by the watchers. In the other hand, I think this breaks in some way the declarative programming way of working with angular....
Comment: Yeah, this is true. If you're not expecting it to change after initialization you can also unbind the watcher by calling it inside of itself, but I'm unsure how that would behave in a test environment.
Comment: I meant augment coupling, sorry


Java variables inside Javascript

Question: I have a variable declared outside my javascript function which gets its value from session.
<code>   String elementID = session.getAttribute("elementID");
   <SCRIPT>
        var a = "123"
        elementID = a;
   </SCRIPT>
</code>
Will this work out? i need to assign the value "123" to the string variable elementID.
Comment: JSP is server side. Javascript is client side. **That's the first thing you need to understand.**
Comment: In other words, **no** it will not work.
Comment: It is will just fine if you serialize the value. But you definitely need to understand the difference between those two languages and why that wouldn't fundamentally work.
Comment: It's quite unfortunate that JavaScript has "Java" in its name. You wouldn't expect C++ to share its variables with JavaScript, would you?
Comment: If you are generating the Javascript as part of a page that is being generated by Java (such as in a JSP), then you can certainly embed values from Java into the Javascript -- at that point, you are merely assembling some text which is going to be sent down to the browser -- but this is not the right syntax for that.
Answer: This is not simply possible, since Java runs server-side and JavaScript client-side.
You can't assume that the JavaScript (that won't be evaluated until it's on the client) knowns anything about Java. It doesn't.
Comment: Actually, [it is possible to invoke Java functions from JavaScript in the browser](http://stackoverflow.com/questions/11536455/calling-java-method-in-javascript). Of course, the JavaScript and Java code will need to be written in separate files.

Java variables inside Javascript


Can't update user model in express?

Question: I'm trying to do a put request to update a user model but instead my router just sends another get request.
Here's my router
router.get('/update', isLoggedIn, function(req, res) {
  res.render('update.ejs', {
      user : req.user // get the user out of session and pass to template
    });
});

router.put('/update', function(req, res) {
  var username = req.body.username;
  var profile_type = req.body.prof_type;
  var pic = req.body.profile_pic;
  var aboutme = req.body.whoami;
  console.log(req.body.whoami);
  User.findById(req.params.id,function(err, userup){
    if (!userup)
      return next(new Error("Couldn't load user"));
    else {
      userup.username = username;
      userup.prof_type = profile_type;
      userup.profile_pic = pic;
      userup.whoami = aboutme;
      userup.save(function(err) {
        if (err)
          console.log('error on update');
        else
          console.log('successful update');
      });
    }
  });
    res.redirect('/profile');

});

Here's my html input form
<form action="/update" method="put">

                    Username
                    <input type="text" class="form-control" name="username">

 Pick a type of profile

                    <input type="radio" class="form-control" name="prof_type" value="true">Tutor

                    <input type="radio" class="form-control" name="prof_type" value="false">Student

                    Link to profile picture
                    <input type="text" class="form-control" name="profilepic">

                    About me
                    <textarea name="whoami" class="form-control">Enter text here </textarea>

                <button type="submit" class="btn btn-warning btn-lg">Update</button>
            </form>

I've also tried changing them to be /update/:username, however, after I click the update button with the fields, I GET this address
http://localhost:3000/update?username=bob&prof_type=false&profilepic=bob&whoami=bob

Not sure why I'm not updating the model or even why it's not putting. Any help is much appreciated, thanks!
Answer: HTML only supports GET and POST requests. See the specification for details:

The method and formmethod content attributes are enumerated attributes
  with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET
  method. The keyword post, mapping to the state POST, indicating the
  HTTP POST method. The invalid value default for these attributes is
  the GET state. The missing value default for the method attribute is
  also the GET state. (There is no missing value default for the
  formmethod attribute.)

You can use the PUT method only with an ajax request. For example in jQuery:
$.ajax({
    url: '/update',
    type: 'PUT',
    success: function(result) {
        // Do something with the result
    }
});

Can't update user model in express?


How to save a graph that is generated by GNU Radio?

Question: I have generated the spectrogram with GNU Radio and want to save the output graph but have no idea how to do it.
Comment: Save it how? To the disk? Is it pickleable? The documentation should say whether or not it is.
Comment: just save it on my desktop. There is no "save as" when the graph is generated and the gnuradio toolbar only saves the blocks diagram.
Answer: The "QT GUI Frequency Sink" block will display the frequency domain representation of a signal.  You can save a static image of the spectrum by accessing the control panel using center-click and choosing "Save".


Why isn't the property conditional working?

Question: I've been programming for a short time, so I apologize if this is the wrong way to ask a question.. or if I'm using terminology incorrectly.
I am working with classes and their components, and can't seem to get a property conditional to work. It is the MonthlySalary property within the Employee Class. It is supposed to prevent a value less than 0 from returning, but it's not working and allowing a negative value to be displayed.
I've also included the main method which utilizes the class, as I'm not sure if that is part of the problem.
Thanks for your time, and any advice would be greatly appreciated.
<code> class Employee
   {
      private decimal _monthlySalary; //// private field

      public string FirstName { get; set; }   //public field  using auto constructor
      public string LastName { get; set; }    // public field using auto constructor

      public Employee(string firstName, string lastName, decimal monthlySalary)  // Constructor
      {
         FirstName = firstName;
         LastName = lastName;
         _monthlySalary = monthlySalary;
      }

      public decimal MonthlySalary //property
      {
         get { return _monthlySalary; }

         set
         {
            if (value > 0.0m)
            {
               _monthlySalary = value;
            }

            else
            {
               _monthlySalary = 0.0m;
            }
         }
      }

      public decimal YearlySalary() //method
      {
       return MonthlySalary * 12;
      }

      public decimal Raise() //method
      {
         return YearlySalary() * 1.10m;
      }

   }
}
   class EmployeeTest
   {
      static void Main(string[] args)
      {

         string firstName, lastName;
         decimal monthlySalary;

         Console.WriteLine("Enter Employee's first name: ");
         firstName = Console.ReadLine();

         Console.WriteLine("Enter Employee's last name: ");
         lastName = Console.ReadLine();

         Console.WriteLine($"Enter monthly salary for employee {firstName} {lastName}");
         monthlySalary = decimal.Parse(Console.ReadLine());

         Employee one = new Employee(firstName, lastName, monthlySalary);

         Console.WriteLine("Employee Name: {0} {1}", one.FirstName, one.LastName);
         Console.WriteLine("Employee monthly salary: {0:C}", one.MonthlySalary);
         Console.WriteLine("Employee annual salary: {0:C}", one.YearlySalary());
         Console.WriteLine("Yearly Salary after raise: {0:C}", one.Raise());

         Console.WriteLine("Enter Employee's first name: ");
         firstName = Console.ReadLine();

         Console.WriteLine("Enter Employee's last name: ");
         lastName = Console.ReadLine();

         Console.WriteLine($"Enter monthly salary for employee {firstName} {lastName}");
         monthlySalary = decimal.Parse(Console.ReadLine());

         Employee two = new Employee(firstName, lastName, monthlySalary);

         Console.WriteLine("Employee Name: {0} {1}", two.FirstName, two.LastName);
         Console.WriteLine("Employee monthly salary: {0:C}", two.MonthlySalary);
         Console.WriteLine("Employee annual salary: {0:C}", two.YearlySalary());
         Console.WriteLine("Yearly salary after raise: {0:C}", two.Raise());
      }
   }
}
</code>
Comment: You need to write `MonthlySalary = monthlySalary;` in the constructor else the setter is not called, so the field is directly assigned without any control/validation when you create a new instance by passing parameters here: `new Employee(firstName, lastName, --> monthlySalary <--); `
Comment: Change: _monthlySalary = monthlySalary; to MonthlySalary = monthlySalary;
Answer: You do not perform any validation logic in the constructor of Employee. You probably want
<code>public Employee(string firstName, string lastName, decimal monthlySalary)  // Constructor
  {
     FirstName = firstName;
     LastName = lastName;
     MonthlySalary = monthlySalary;
  }
</code>
Another tips is that you can use
<code>_monthlySalary = Math.Max(0.0m, value);
</code>
This is just a more compact way to ensure the salary is always positive.


What methods of forecasting should I be looking at to forecast sales?

Question: I am wanting to forecast sales of different products within a business.
I have a good background in mathematics (but mainly focused on analysis, group theory, algebra etc. as opposed to statistics).
I also have some experience in Python + related libraries (pandas, numpy, tf, keras) so anything that could use that would be nice.
The information I have is like:

Previous sales (including when and how much)
number of customers that  are eligible to buy the product
how big the customer is
etc...

I do have access to a lot of potentially related information that could be used but I don't know what to choose.
I have considered doing maybe some kind of seasonal time series (as I suspect there is some seasonality in some products) like ARIMA but I am not sure at all.
Also I want to make it quite simple to begin with I don't want to get carried away with fancy statistical methods that are maybe a) don't understand or b) are not even applicable in my scenario.
I am wanting suggestions of areas/methods/techniques that I could look into that may prove useful.
I don't have terrible amounts of data (on average I would say 3 years of data with 12 points per year [sales in month]) so presumably that would make a difference.
Any advice is appreciated and if clarification is needed let me know.
Thanks.
Answer: 36 months of data can often be useful in forming a model. Initially, you might want to develop arima type model that incorporates trends, level shifts, and memory while dealing with unusual values.
Secondly, you might investigate adding user-suggested causal variables to your model. These models are an extension and are often referred to as Dynamic Regression OR Transfer Functions or SARMAX models .. https://autobox.com/pdfs/SARMAX.pdf  .
Search on SE to find out more about these approaches. You might also post an actual data set and ask for some help.
Comment: `Initially you might want to develop arima type model that incorporate trends , level shifts and memory while dealing with unusual values.` Could you perhaps elaborate on this line, what are these ARIMA type models and where can I learn more about this approach? Are there any tutorials online so I can see how such an approach is implemented?
Comment: I would begin by reading http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series. and search on SE for terms like "level shifts" , "deterministic time trends" , "Intervention Detection"  , "outlier detection" .  "Pulse Detection"  .. There are many posts on this topic ..
Comment: Thank you, the link is broken though.
Comment: http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html . you can also search on  ARIMA or arima
Answer: I would start by looking through the excellent free online book Forecasting: Principles and Practice (2nd ed.) by Athanasopoulos & Hyndman. It leverages the equally excellent forecast package for R, which allows you to automatically build ARIMA or Exponential Smoothing models and forecasts very easily.
With only 36 data points, there is really not much to work with, except for very blatant influences (for which you could look to the xreg parameter for forecast::auto.arima()), so if you want to get more fancy, you would probably have to invest quite some domain knowledge.
Answer: Simple Models
If you are looking for simple models I would test these:

Linear Regression
Exponential Smoothing with seasonality
Seasonal ARIMA models
Rule of thumb methods: seasonal naive method, seasonal mean, simple mean.

These models should help you in assessing a baseline for the model performance. I believe models 1-2-3 are already implemented in the statsmodels library. Depending on how granular your forecast needs to be, you might want to perform a hierarchical forecast. I've used a top-down hierarchical approach for a client (Fashion Retail) that needed forecasts for both product categories and single skus inside the category.
Moreover, these models have the advantage of being more transparent and interpretable compared to machine learning models. If your model produces crazy non-sensical predictions, it's much easier to debug them.
Machine Learning Algorithms
If you don't have constraints for model transparency/interpretability, you can employ some Machine Learning algorithms, such as:

Gradient Boosted Tree Methods (lightgbm, catboost, xgboost, sklearn libraries): these methods don't need a ton of data to be effective, so they should work with monthly observations. It took me a while to study the math behind them, but you don't really need to know how they work to get predictions from them. These libraries are also well documented and there are a ton of examples online.
Neural networks: they have been employed succesfully both in literature and in online competitions. They usually need a lot of data to shine, though. If you never used them before, I'd try the other models first. However if you are not doing this stuff for work, I suggest you check them out because in my opinion they make use of very interesting concepts and ideas.
Ensemble models: they combine the predictions of different models, for example by using the average or the median of your models' predictions. This can usually improve your forecast, especially if there is low correlation between the prediction errors of the different models. Of course, it is more time consuming to maintain more than one model in production.

Data

You should avoid including data features that can't be predicted with a reasonable amount of accuracy. For example, if you have information about daily temperature/weather, you can easily see its effect on past sales, but you can't really use weather forecasts for predicting far into the future, because weather forecasts become unreliable after 3 days in the future.
Promotional activities heavily impact sales. They can also be planned in advance, so if you can get your hands on this data, try to assess if it can be beneficial to your model.
Inventory/Stock out information: sometimes it can happen that your product is so in demand, that you run out. If you don't have any information about stock-outs, your demand data is "censored", and you have no way of knowing if you didn't sell because people didn't want to buy or because the product wasn't available. Note that there is a distinction between predicting Sales and Demand. Predicting sales is useful for forecasting financial performance, while predicting demand is useful for optimally allocating inventory.
Holidays and special events. This information is probably not so useful if you have to generate a monthly forecast. It still might be useful if you have important festivities that sometimes fall in one month, and sometimes in the other (e.g. forecasting sales of Easter eggs and colomba cakes in Italy).
Outlier removal techniques can be useful for improving the staibility (and sometimes error metrics) of your forecast

Additional sources that I found useful (I wrote a thesis on demand forecasting 2 years)

https://otexts.com/fpp2/ My favorite book on forecasting (code implementations are in R, but I found equivalent Python tutorials/examples for most models)
kaggle.com has a lot of great notebooks written by really smart and skilled people.
https://www.youtube.com/watch?v=68ABAU_V8qI Great video that explains the tradeoffs between complexity and predictive power of a model. It also has some neat "tricks" that can be used in forecasting (although not all are applicable for monthly time series).

Tips:

Make sure that your model/feature engineering choices are aligned with the granularity and forecasting horizon of the problem at hand.
if you use Python and pandas to handle your data, the resample function is a great tool. It allows you to quickly aggregate data in periods of specified length (for example, weekly, monthly, quarterly) with just one line of code.
Transforming the target variable before fitting the model can be useful. For example, if you try to estimate the variable y = log(Sales) and then do an inverse transformation, you can ensure that your predictions are positive.


Prove the distributive law $a(b+c)=ab+ac$ for real numbers?

Question: I have always taken these kinds of things for granted. Well of course $a(b+c)=ab+ac$! But why? The thought randomly popped in my head, and I realized that I could not prove it.
Perhaps we should take some time to prove these "obvious" things. I feel like if I cannot prove it, then I do not fully understand it. I would really like a proof of this most basic law, because I have been pondering over it for quite a while. Thanks!
Edit: This proof is for real numbers.
Comment: For what kind of objects $a$, $b$, $c$ do you want to prove this?
Comment: There are two common approaches to defining the real numbers I know of. One of them is as a totally-ordered, Dedekind-complete field, and distributivity is one of the field axioms, so you just get that distributivity holds by definition. (Proving the real numbers exist with this definition is then a more interesting task.) The other approach constructs the reals from the rationals, in which case distributivity can be proven using the techniques of analysis and the distributivity of the rationals. The distributivity of the rationals can then be proven from the distributivity of the integers,
Comment: For an intuition using geometry, I'd found [this](https://www.youtube.com/watch?v=aNReoaONJdg) video useful.
Comment: which can then be proven from the definition of the integers.
Comment: I always have a problem when trying to answer this kind of question. (─‿‿─)
Comment: @JChau: Can you tell in detail what things you are taking as axioms ? I ask this because for example if you say that you take the 'axioms'  of Real Numbers as presented in the Apostol's Calculus as granted, an answer may be provided. Otherwise, I think that Christian Blatter's answer is the most precise answer to your question.
Comment: @WilliamHilbert I do not want / need to prove that real numbers exist, if that is what you are asking. So yes, I am taking the 'axioms of real numbers' for granted
Comment: @Anant Thank you so much! If you want, post that as an answer so I can accept it
Answer: (This is to @JChau who "simply want[s] a full proof from someone why the property $a(b+c)=ab+ac$ is true for real numbers".)
A full proof involves a construction of the reals from the Peano axioms. Landau's classic Grundlagen der Analysis from 1930 takes 90 pages to do this. If you are willing to accept the distributive law for integers you can bring this down to a dozen pages or so. There are many constructions of the reals around; and all of them require about the same amount of work. A comparatively short version can be found in chapter 1 of Baby Rudin.
Answer: For natural numbers, the "proof" would look like this.
Since $m\cdot n$ is just $n+n+\dots+n$, repeated $m$ times, this means that $$(p+q)\cdot n = n+n+\cdots+n,$$ repeated $p+q$ times, but it is also equal to $$\underbrace{(n+n+\cdots n)}_{p}+\underbrace{(n+n+\cdots +n)}_{q}$$
which is $p\cdot n + q\cdot n$.
For rational numbers, the expression follows from the definition $$\frac pq\cdot \frac rs = \frac{pr}{qs}.$$
For the real numbers, you have to follow the construction of real numbers from rational ones using Dedekind cuts, for example.
Comment: "You can't really prove te law for reals" - of course you can! Why not?
Comment: @user2357112 Yes, poorly expressed. I fixed my answer.
Answer: Henry Reich - creator of minutephysics - gave a geometrical intuition for the distributive law in this video. I've pasted a snapshot from that below.

For a formal proof, I defer to Christian Blatter's answer :)


tem como obter o valor numerico de uma tag sem ser por id, no caso uma class e depois dividir por outro número e mostrar dentro do site

Question: Quero fazer uma extensão para o chrome, a ideia é pegar um valor numerico de dentro de um site, em sua página e fazer contar somando, subtraindo, dividindo e etc e então mostrar o resultado ao lado do valor como uma calculadorinha eu tentei algumas coisas e consegui por Id, mas quando na tag é uma class não estou conseguindo:
aqui o manifest
{
    "manifest_version": 2,
    "version": "0.0.1",
    "name": "test calc",
    "description": "calc",
    "author": "LA",
    "browser_action": {
     "default_title": "Alterando valor",
     "default_popup": "index.html",
     "default_icon": "icon.png"

 },
 "content_scripts":[
 {
 "js": [
 "captura.js"
 ],
 "matches": [

 "https://sitequalquer/*"
 ]

 }

 ]

}

e aqui o javascript
var url = document.getElementById('Idtal').text;
alert(url);

var url = document.getElementsByClassName('classetal').innerText;
alert(url);

var url_ = document.getElementsByClassName('classetal')[0].innerHTML;
alert(url_);

var url_ = document.getElementsByClassName('classetal')[0].value + ",";
alert(url_);

outra duvida é: depois eu preciso usar um operador com as var e enviar por alert, correto?
Answer: O getElementsByClassName retorna um array e o objeto que contem seu texto é o textContent, veja este exemplo.
var url = document.getElementById('this-id').textContent
alert(url);

var url = document.getElementsByClassName('class-name')[0].textContent
alert(url);

Quanto sua outra duvida: você pode fazer isso:
var a = 5;
alert(a + 45); //output: 50

Comment: nossa, muito obrigada Felipe Chagas
funcionou direitinho
era isso mesmo
obrigada mesmo =D
Comment: De nada! Se matou a duvida, pode marcar como solução, para fechar a questão, por favor.


Force capitalization of terms on entry with Autocomplete Deluxe module

Question: I would like to force the capitalization of taxonomy term entries, or alternatively make them case insensitive so that 'book' and 'BOOK' are not different taxonomy terms. Is there a way to enable this. The context is this form http://www.wequest.co.uk/user/register on the 'skills' and 'resources' field... I need these to be standardised because they represent catalogues of skills and resources and I don't want duplicates either: of terms or due to different cases.
Answer: The Taxonomy dupecheck module would probably help for most of that (I'm not entirely sure about the case-sensitivity issue but give it a try; MySQL queries for term names will be case-insensitive so my gut instinct is this would work)

Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.

To force title-case on the term you could implement hook_taxonomy_term_presave() in a custom module and force it like so:
function MYMODULE_taxonomy_term_presave($term) {
  if (some_condition_applies_to($term)) {
    $term->name = ucwords($term->name); // Or ucfirst() depending on your requirement
  }
}

Comment: I have already installed this module, but I also would like to standardise, for cleanliness, the input to capitalisation. I have tried adding the css text-transform:capitalization to the form field, which looks like it works, but then the entries don't actually get saved with capitalization which is pretty weird...
Comment: The css method will only work on the client side, it won't change anything that's sent to the server. I've added some code to the answer that might help, it's untested but in theory it should do the trick
Comment: Hi clive, I don't this that hook_taxonomy_term_presave exists, but hook_taxonomy_term_save does would this still achieve the same result?
Comment: @Andrew It definitely exists, there's a link to it in the answer :) It's invoked from [`taxonomy_save()`](http://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_term_save/7)


Uncaught TypeError: Cannot read property 'ajax' of undefined

Question: I tried deleting an item from a table with AJAX via a POST call.
///// DELETE INDIVIDUAL ROW IN A TABLE /////
jQuery('.stdtable .delete').live('click', function (e) {
//var newsId1 = $(this).attr("title");

e.preventDefault();

var p = jQuery(this).parents('tr');

if (p.next().hasClass('togglerow'))
   p.next().remove();

p.fadeOut(function () {
    jQuery(this).remove();
});

$.ajax({
  URL: "/AdminPanel/News/DeleteNews",
  data: { "newsId": 1 },
  dataType: "json",
  type: "POST",
  success: function (msg) {
  alert(msg);
}
});

In this code I get Uncaught TypeError: Cannot read property 'ajax' of undefined.
Comment: Note that live() is deprecated and removed from later versions of jQuery
Answer: Did you try doing what the rest of the code is doing, using jQuery
jQuery.ajax({
  URL: "/AdminPanel/News/DeleteNews",
  data: { "newsId": 1 },
  dataType: "json",
  type: "POST",
  success: function (msg) {
  alert(msg);
}

You can wrap your code in a DOM ready function that sets the value of $ locally in the function scope, that way you can always use $
jQuery(function($) {
    // code goes here
});

Comment: Thanks o lot, @adeneo. I knew this, but didn't think as you)
Comment: This is the answer. Thank you @adeneo!
Answer: I can't solve the problem using jQuery instead of $.
In my case, I add the source jQuery.js and solve the problem, like

Comment: buddy, try to use js labriraies and frameworks,, I asked this question 6 years ago)))
Comment: Thanks for your comment. In my handling project, it connects js labriraies failed so I use this method.


recv() function do not get message back in python

Question: I am new to TCP/IP connection using python
I have this simple code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("www.google.com",80))
s.send("GET /\n")
while 1:
 received = s.recv(1024)
 if received:
  print received

but when I run it it just runs forever and does not give me any result!!!
Could you please help me. Thanks
Answer: Follow HTTP Protocol
s.send("GET /\n")

This is not correct. You should send http data in a proper way. Use this
s.send("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n");

In fact you are to send standard http request headers.
GET / HTTP/1.0
Host: www.google.com

Note: As David says in the comment you must be able to decode chunked transfer coding. So its better you state HTTP/1.0 in the header.
Comment: Since I really don't think he wants to deal with chunked encoding, claiming 1.1 compliance is probably not a good idea.
Comment: yes I replaced "s.send("GET /\n")" with "s.send("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n");" one and it works now, Thanks
Comment: @David I never had problem with that header.
Comment: @shiplu.mokadd.im: Then you got lucky. The [standard](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1) says: "All HTTP/1.1 applications MUST be able to receive and decode the "chunked" transfer-coding ..."
Comment: Another reason is that HTTP 1.1 defaults to keeping connections alive. Likely his code is going to keep reading until the connection closes, so specifying HTTP 1.1 would make his code hang.
Comment: OK I changed it to HTTP 1.0 Thanks for help
Comment: @DavidSchwartz connection can be closed just by adding "Connection: close" header.


Meraki wireless access point disconnects clients

Question: We have a Meraki MR16 Cloud Managed AP and it disconnects certain clients.  The clients with Intel wireless cards work without any disconnects.  The Meraki reports the follow in its event log:
<code>Sep 4 09:55:47   WPA authentication
Sep 4 09:55:47   802.11 association      channel: 11, rssi: 64
Sep 4 09:55:38   802.11 disassociation      client has left AP
Sep 4 09:55:38   WPA deauthentication      vap: 0, radio: 0, aid: 1633956416
</code>
An example wireless network card which the Meraki disconnects is Realtek RTL8191SE 802.11b/g/n WiFi Adapter.  The realtek laptop is sat 2 meters away from the AP and has a lot of signal and the Meraki reports minimal interference.
Any ideas why it disconnects non-intel wireless network cards?
Comment: It is fixed now.  I think firmware updates has solved the issue.
Comment: You really need to discuss this with Meraki.  Their product is a bit of a black box at the best of times, and it *is* a Managed service.
Answer: I have run into similar problems with our MR12 access point we got as a demo unit. Specifically it seems to be newer Intel WiFi Cards that have this problem. If these Intel WiFi  laptops attempt to connect to an SSID using encryption like WEP or WPA2, they will appear to connect and then immediately disconnect and repeat that pattern forever. Only when using an open SSID (eliminating security all together) could those laptops connect.
Obviously, this presented a real problem for us. :) As we refresh computers we are getting more laptops with the affected Intel WiFi cards in them. I opened a ticket with Meraki and they blamed it on Intel drivers. Like in your situation they did a firmware update that gave us an extra option to specify 'WPA encryption mode' but that did nothing to help.
Here are the cards I found in our environment that were affected:
Card 1: Intel Centrino Advanced N 6235
Card 2: Intel Centrino Advanced N 6205
Card 3: Intel Centrino Ulitmate N 6300 AGN
This put a serious reservation in my mind about deploying Meraki WAPs in our environment as this is a pretty big problem. So far they have shown little motivation to actually fix the problem. We have $50 WAPs that seem to handle these WiFi cards just fine.
So anyway, they know about the problem but are doing nothing to fix it. :(
Comment: Meraki's updated the firmware on our devices and we don't get any problems now but we are thinking about adding new Wireless Access Points so its good to know Meraki are still having issues.  You thought being part of cisco now they would have the knowledge to solve these issues.
Comment: Cool! I am glad to hear you are not having problems at least. We are still fiddling around to see if we can improve things on our end. The issues to me are not such a big deal but what scares me is the 24-hour response time for trouble tickets, even those of high severity. What do you do if you have a network down issue? Its not like you can just fix it yourself.
Answer: I am having exactly the same issue.  Cisco Meraki is simply wasted my 3 months in blaming my network end that enforced me to change the switches, cabling, nodes positions etc etc etc.  After three months I requested them to downgrade the firmware and all my clients started to authenticate without any issue.  Today one of the nodes showed the same behavior of dis-association.  I am again at the mercy of Meraki.  :(
I was told that Meraki Cisco engineering team is aware of this issue with Intel Cards.  When it will be fixed? who knows.
Update:  Its been more than one year.  MR16, MR24 keeps on disconnecting our clients with Intel(R) Centrino 6200 series cards.  You can imagine how much loads of tech support would have been performed to find the core issue.  No one at Meraki able to understand this.  I am seriously looking into other options. :(
Save yourself and buy a cheaper node, I am sure it will outperform meraki.
Comment: Its good to know other people are (still) having problems.  I think the message for me is to stay away from Meraki.
Answer: A little update on this: I think the MR12 AP we have been using over the past year is the culprit. In the last 24 hours I managed to get my hands on an MR18 and found that laptops with the affected WiFi cards are able to access the network with encryption.
Anyway, there may be other APs in Meraki's lineup that have problems but at least we know one to avoid.


How can I get a ComponentManger object in JIRA

Question: Directly import com.atlassian.jira.ComponentManager in java file does  not work.
atlassian-create-jira-plugin-module then choosing Component Import and specifying com.atlassian.jira.ComponentManager does not, either.
I have looked into some tutorial and just does not get the approach.
Answer: Use ComponentAccessor class.
The answer for Jira 5.0 is here: https://answers.atlassian.com/questions/73426/how-do-i-import-com-atlassian-jira-componentmanager.


Assumptions on the underlying function for a binary classification problem

Question: Consider the binary classification problem, and let the feature space be denoted as $S$. What we are assuming is that there is an underlying function $F$, mapping from feature space S to the set containing two elements -1 and 1, that is $F:S\to\{-1,1\}$. Can we make only additional assumption that this underlying function $F$ is also a piece-wise constant function and no further assumptions.  That is the function $F$ maps feature space to the two element set containing 1 and -1, and additionally it is a  piece-wise constant function. How safe is this assumption? I hope to design a learning algorithm and lets say the algorithm learns a function $f_n$ for a certain data set of size $n$, then the learning algorithm is such that, as $n\to \infty$, $f_n \to F$ pointwise in all points of $S$ except at points of discontinuity of $F$.
With this assumption, the generalization ability of such an algorithm would be infinite?
Comment: your question doesn't make much sense. generalization ability is not a number, and has nothing to do with asymptotic properties of the algorithm. there is plenty of algorithms that respect those properties, and they may have different generalization performance (you defined your model on deterministic terms, I assume that that is a p convergence).
Comment: @carlo : Thanks for the comment. I just wanted to keep things simple, t get to the main point I am asking (thats why deterministic). My main question is exactly that. Why do methods that pointwise converge to the underlying binary step functions are not the best classifiers. For example take spline interpolation or RBF, they fit any training data exactly (universal approximants) and as data points go to infinity, they converge pointwise to the underlying step function. What mre can be expected is my question? Why are they not the best candidates! Why should we go for SVM or anything?
Comment: spline interpolation is not generally an universal approximant, SVM with RBF kernel is. in some cases however, you may prefer a less powerful approximant which has useful inductive bias. this depends on your problem, but most famous case is CNNs, which are not universal approximants.
Comment: @corlo : When I am saying universal approximation, I mean can approximate (not all continuous functions as the case in neural nets), but can approximate all step functions. (sorry for using the wrong word). A Linear spline does that for step functions. SVM cant do that. When you cant separate using SVM, we need to change to a different kernel and try. But How can we say SVM is better generalization. All these questions I have is due to my lack of understanding of difference between generalization and pointwise convergence to underlying step function. Any good reference for this?
Comment: @ArtemMavrin : For a counter example consider $S$ as $(0,1)$ and define $F$ as $F(x) = 1$ if $x$ is rational and $F(x) = -1$, if $x$ is irrational.
Comment: @ArtemMavrin : But then, my example was a pathological. So you mean to say albeit the only way, but its still a safe thing to proceed and design an algorithm like the one I mentioned? (converging pointwise as data size grows)
Comment: With this assumption, the generalization ability of such an algorithm would be infinite?
Answer: Your assumption is not enough to conclude infinite generalisability unless $S$ is finite.
In the case where $S$ is finite (and each element of $S$ has nonzero measure) then your argument works; with a large enough data set you expect more and more observations at each $x \in S$, and the chance of covering $S$ completely tends to 1.
In the case where $S$ isn't finite, the only way you can hope to generalise to $x \in S$ that you haven't "seen" yet is to make a continuity assumption on $F$. Obviously you can't assume $F$ is continuous because it can't take values between 0 and 1, but you can fix this by assuming that $F$ is the sign of an underlying continuous function $G$.
If you don't make such an assumption then you can never hope to generalise functions with dense discontinuities (such as your example of classifying rationals)


An upper bound for the number of divisors

Question: I've come across this problem in Murty & Carmen, exercise 1.5.3: show that there is a constant $c$ such that
$d(n)=O(\exp(\frac{c\log n}{\log\log n})))$ where $d(n)$ is the number of divisors of $n$
I've gotten most of the way through and have also looked through this article https://terrytao.wordpress.com/2008/09/23/the-divisor-bound/, but I don't understand this one step in their explanation:
$(6)\le O(1/\varepsilon)^{\exp(1/\varepsilon)} = \exp\exp(O(1/\varepsilon))$
Could anyone provide some justification as to why this would be true? I've tried playing around with the equality, but I've been having no luck. Thanks in advance!
Comment: Write $N = \frac{1}{\epsilon}$ for ease of notation and then try rewriting the exponential. Remember that $A^B = \exp(B \log A)$.
Comment: see  https://math.stackexchange.com/questions/3953080/what-are-some-upper-bounds-for-the-number-of-factors-of-a-number-a-proof-would/3953231#3953231
Answer: By unique factorization theorem, we can write $n$ into
$$
n=p_1^{r_1}p_2^{r_2}\cdots p_k^{r_k}q_1^{s_1}q_2^{s_2}\cdots q_m^{s_m}
$$
where $p_i$ denotes some prime $\le t$, and $q_j$ denote some prime $>t$. Thus, we have
$$
d(n)=\prod_i(r_i+1)\prod_j(s_j+1)
$$
By definition, we know that $k\le t$ and $r_i<\log_2 n$, so we have
\begin{aligned}
d(n)
&\le\left(1+\log_2n\right)^k\prod_j(s_j+1)\le(1+\log_2n)^t\prod_j2^{s_j} \\
&=(1+\log_2n)^t\prod_j q_j^{s_j\log2/\log q_j}<(1+\log_2n)^t\prod_jq_j^{s_j\log2/\log t} \\
&\le(1+\log_2n)^tn^{\log2/\log t}=\exp\{t\log(1+\log_2n)+\log2\log n/\log t\} \\
&\le2^{\log n/\log t+O(t\log\log n)}
\end{aligned}
Finally, setting $t=\log n/(\log\log n)^3$ gives $d(n)<2^{(1+\varepsilon)\log n/\log\log n}$ for large $n$.
For OP's question on the specific inequality, let $A_1,A_2,\dots$ denote the O constants then
\begin{aligned}
(A_1\varepsilon^{-1})^{\exp(\varepsilon^{-1})}
&=\exp[\exp(\varepsilon^{-1})\log(A_1\varepsilon^{-1})] \\
&<\exp[\exp(\varepsilon^{-1})\exp(A_2\varepsilon^{-1})] \\
&=\exp\{\exp[(1+A_2)\varepsilon^{-1}]\}=\exp\exp O(\varepsilon^{-1})
\end{aligned}


Does $|\langle x,Ax\rangle |=\langle x,|A|x\rangle$ for bounded operators on Hilbert space?

Question: If $A$ is a bounded linear operator on a Hilbert space $H$ is it true that $|\langle x,Ax\rangle |=\langle x,|A|x\rangle$ for all $x\in H$? If not, can we at least establish inequality in one direction? Here $|A|$ is the unique positive square root of the positive operator $A^*A$. Hints or references are always appreciated.
Answer: You cannot expect equality to hold in general. Let $\{ e_n \}_{n \in \mathbb Z}$  be an orthonormal basis of your Hilbert space. Consider the shift operator $Se_n = e_{n+1}$. Then $S^*S=1$ and $|S|=1$ (the identity operator. We then have
$$
0= |\langle e_1 , Se_1 \rangle | \neq \langle e_1, |S|e_1 \rangle =1.
$$
This also rules out one possible direction of  the inequality. To see that we cannot have an inequality in the other direction, let's look at some $2\times 2$-matrices.
Let $A=
\left(
\begin{array}{cc}
0 & 1 \\
5 & 0
\end{array}
\right)
$
and then $|A|=
\left(
\begin{array}{cc}
5 & 0 \\
0 & 1
\end{array}
\right)
$.
Let $x=
\left(
\begin{array}{c}
1 \\
 2
\end{array}
\right)
$.
Then $| \langle x , Ax \rangle | = 12$ but $ \langle x, |A| x \rangle=9$.
Thus not only are the values not equal, there is no inequality between them (in either direction) that always holds.
What is the issue here? Take the polar decomposition of $A= U|A|$. Here $U$ is a partial isometry. Then we are comparing
$ | \langle x, A x \rangle | = |\langle U^* x, |A| x \rangle |$ with
$ \langle x, |A| x \rangle$.
Should there be an inequality between these two sides? Think of what happens if we fix $|A|$ and allow the partial isometry $U^*$ to be ANY partial isometry. We are then looking at the values obtained by taking the inner product of $|A|x$ with the elements of the (possibly quite large) set $\{U^*x \}$. Depending on $U^*$, this could be either larger or smaller than $\langle x, |A|x \rangle$.


huge Oracle Redo Logs

Question: At 10PM each Tuesday all of a sudden oracle is generating huge REDO logs until the disk runs out of space.  My application is not running any huge queries or anything during this time according to the logs.
The only thing I can find is that the dba_scheduler_job_run_details table started an oracle job right at that time.  I can't find any info on google about this job, so am desperate for any ideas.
Info from dba_scheduler_job_run_details:
JOB_NAME: ORA$AT_SA_SPC_SY_254
STATUS:   STOPPED
ACTUAL_START_DATE: 11-03-22 22:00:02.125060000 CST6CDT
RUN_DURATION 9:4:19.0
Comment: I think this is on-topic for either ServerFault or dba.stackexchange.com
Answer: 10PM is usually the time that automatic statistics gathering starts.  Although it normally runs every day.  In 11g stats gathering uses auto tasks instead of the scheduler, try looking for the stats job with a query like this:  select * from dba_autotask_job_history order by window_start_time desc;
But even if the problem is caused by statistics, it seems odd that it would cause too much REDO.  Usually gathering statistics is a lot of reading and a very small amount of writing.  Unless you've got many small tables that change all the time; in that case the amount of statistics information could be much larger than the actual data.  If that's the case you may need to gather the stats more often, or maybe lock the stats.
Or possibly the statistics process is blowing up on a specific table.  This will show you what table was last analyzed, maybe it will give you a clue: select last_analyzed, dba_tables.* from dba_tables order by 1 desc nulls last;
Answer: I something generates huge REDOLOG, then you must have huge DML activity. For examaple cleanup script which tries to purge some data, but fails, rollbacks, and then tries to do the same task again and again and again...
The best way how to prove/disprove your doubts is the "Log miner tool". It's not trivial to use, but it will tell you which statements (and against which table) generated most of the redo and that time.

huge Oracle Redo Logs


Uniform convergence in complex domain

Question: I know how to prove $(1+x/n)^n \to e^x$ uniformly if $x \in [a,b] \subset \mathbb{R}$  by finding a uniform bound $e^x - (1 +x/n)^n < K/n$ for a bounded interval.
My question is how to prove the $(1 + z/n)^n \to e^z$ on any compact set $S \subset \mathbb{C}$.  I am not sure how to extend from the real case in the proof.
Comment: If you have defined $e^{z} $ via the series $\sum z^n/n! $ then the proof for the real case applies to the complex case also.
Answer: Let Log denote the principal branch of logarithm. Then $\frac {Log (1+z)} z \to 1$ as $z \to 0$. Let $\epsilon >0$. There exists $\delta >0$ such that $|\frac {Log (1+z)} z -1| < \epsilon$ if $|z| <\delta$. Let K be a compact set in $\mathbb  C$. Then $|n \frac {Log (1+z/n)} z -1| <\epsilon$ for all $z \in K$ provided n is sufficiently large. [ Because $|\frac z n|<\delta$ if $z \in K$ and n is sufficiently large]. Hence $ |{Log \{(1+z/n)^{n}\}} -z| <\epsilon |z|$ By continuity of the exponential function at 0 this proves that$(1+z/n)^{n} e^{-z} \to 1$ uniformly on K. Finally, $|(1+z/n)^{n}-e^{z}| \leq |(1+z/n)^{n} e^{-z}-1| e^{|z|} \to 0$ uniformly on K.
Comment: Thank you. I suppose the missing details can be filled with (1) the first limit is $1$ using power series and (2) sufficiently large $n$ is independent of $z$ since $|z| < B$ for all $z \in K$.
Comment: You are right. Sorry that I left out some easy steps.

Uniform convergence in complex domain


Interesting problem from symmetric group:

Question: Interesting problem from symmetric group:
For $ \ n \geq 3 \ $ , if $ \ \alpha \in S_n \ \ define \ \ \alpha' \in S_{n+2} \ $ by $  \begin{Bmatrix} \alpha'(i)=\alpha(i) \ \ 1 \leq i \leq n \\ \alpha'(n+1)=n+1 \ \ \ \ \ \ \ \ \ \\ \alpha'(n+2)=n+2 \ \ \
\ \ \ \ \  \end{Bmatrix} $
Define $ \phi : S_n \rightarrow S_{n+2} $ by
$ \ \ \phi(\alpha)=\alpha ' \ \ if \ \ \alpha \in A_n \ \ $ and
$ \phi(\alpha)=\alpha' \beta \ \ if \ \ \alpha' \notin A_n \ \ for \ \ \beta= (n+1 \ \ \  n+2) \ cycle $
(a)  Prove that  $ \ \phi \ $ is homomorphism .
(b) Prove that $ \ \ \phi(S_n) \leq A_{n+2} \ $.
My approach :
(a)  Let $ a , \ b \in S_n $ .  If $ a,b \in A_n , then \ \ ab \in A_n , \ \ because \ \ A_n \ \ forms \ a \ group . $
Then $ \ \phi(ab)(i)=(ab)'(i)=(ab)(i)=a(i) b(i)=a'(i) b'(i)=\phi(a) \phi(b)(i) $
or, $ \phi(ab)=\phi(a) \phi(b) $.
Hence $ \phi \ is \ a \ homomorphism . $
I think for the part (b) we have to show that $ \ \phi:S_n \rightarrow A_{n+2} $ is an Injection map  . But I am unable to show.
Am I right ? Any help for the second part ?
Comment: You only proved it for the special case of when $a$ and $b$ are both in $A_n$.
Comment: I can not proceed further . Any help is really appreciating
Comment: What happens if $a\in A_n$ and $b\notin A_n$?
Comment: If $ a \in A_n  \ and \ b \notin A_n $ , then $ ab \notin A_n $.  So $ \phi (ab)=(ab)' \beta=(a' ) (b' \beta)=\phi(a) \phi(b) $
Comment: What if $a\notin A_n$ and $b\in A_n$?
Comment: Yes I now understood .  But what about part (b) ? . How can I do That ? Any idea please.
Answer: To show part (b)(i.e., $\phi(S_n)\subset A_{n+2}$), I think it is enough to show that the image of the function $\phi$ lies in $A_{n+2}$ i.e., to show that $\phi(\alpha)\in A_{n+2}$ for all $\alpha \in S_n$.
Take any $\alpha \in S_n$. Then either $\alpha \in A_n$ or not. Observe that, by the definition of $\phi$ and $\alpha^{\prime}$ in either case the image is an even permutation in $S_{n+2}.$ Can you see that?
Answer: a-)
To show that $\phi$ is an homomorphism, let $\alpha_1, \alpha_2 \in S_n$.
If $\alpha_1, \alpha_2 \in A_n$.Then since $\alpha_1 \circ \alpha_2 \in A_n$,
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1 \circ \alpha_2)^{'} = (\alpha_1)^{'} (\alpha_2)^{'}$$
If, without lost of generality, $\alpha_1 \not \in A_n$ and $\alpha_2 \in A_n$,
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1 \circ \alpha_2)^{'} \circ \beta = (\alpha_1^{'}) (\alpha_2^{'}) \beta$$
since $(n+1)$ and $(n+2)$ are fix in $\alpha_2$,
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1^{'})\beta (\alpha_2^{'}$$
If $\alpha_1, \alpha_2 \not \in A_n$, then
$$\phi (\alpha_1 \circ \alpha_2) = (\alpha_1 \circ \alpha_2)^{'}= \alpha_1^{'} \circ \alpha_2^{'}$$
since $\alpha_1 \circ \alpha_2 \in A_n$.
b-)
Note that in all of the if statements above, $\phi (...) \in A_n$, and for the rest, I think it is clear.


Valid Properties for CheckBox.Name

Question: I'm working on a task that has me populating a window (dynamically) with options for the users to select.  I'm trying to name the Checkbox's and I get an error at runtime when I'm testing:
'cbPS_Steel, Carbon - Schedule 40' is not a valid value for property 'Name'.

The Name Property takes a string value, but it's not taking the values I pass to the property, even though they are strings.  Could this be because of the hyphen or the spaces?
Specifically:
Are there any characters that the Name property for Checkbox's deemed as invalid?  Any information, or articles would be helpful.  Thank you!
Code:
cb.Name = setCheckBoxName(cb, 2);

private string setCheckBoxName(CheckBox cb, int iCase)
{
    string name = "";

    switch (iCase)
    {
       case 0:
           name = "cbAS_" + cb.Content.ToString();
           break;
       case 1:
           name = "cbRV_" + cb.Content.ToString();
           break;
       case 2:
           name = "cbPS_" + cb.Content.ToString();
           break;
       case 3:
           name = "cbMS_" + cb.Content.ToString();
           break;
       default: break;
    }

    return name;
}

Answer: This is described in the documentation on the FrameworkElement.Name property. It says:

The string values used for Name have some restrictions, as imposed by the underlying x:Name Directive defined by the XAML specification. Most notably, a Name must start with a letter or the underscore character (_), and must contain only letters, digits, or underscores. For more information, see WPF XAML Namescopes.

With that said, it would probably be a cleaner solution to subclass Checkbox and add a property that helps you tell your checkboxes apart to that subclass.
Comment: @GeoffOverfield maybe the Tag property may be useful instead of subclassing :)
Comment: Great Idea!  Thanks for the help!
Answer: The Name property allows you to reference the control from code behind (when used in Xaml for example) so it has to be valid with the same restrictions as variable names
And a variable name cannot contain hyphen nor spaces :)
EDIT: Look at the comments, there are less restrictions in the Name property. Thanks @O.R.Mapper
Good luck!
Comment: Well, actually, [you can use some control characters that look like spaces in identifiers](https://lostechies.com/jimmybogard/2009/02/17/spaces-in-identifier-names-in-c/).
Comment: "it has to be valid with the same restrictions as variable names" - that does not seem to be correct. Variable names must not match C# keywords, but the `Name` property can be set to a string matching a C# keyword. At least, unless you count the `@` that you can then use to refer to the variable again as a part of the variable name.
Comment: Thanks @Yitschak.  I figured that's what it was.  A lot of my `Checkbox`'s would have names like this.  I was trying to set them up like this so I can compare things at a later time, but I suppose comparing the `.Content` will be just as effective.
Comment: @GeoffOverfield maybe the Tag property may be useful instead of subclassing :)

Valid Properties for CheckBox.Name


Why do we have $ \sin(x) = x \prod_{n=1}^{\infty} ( 1 - \frac{4}{3} \sin^2 (\frac{x}{3^n})) $

Question: Show that
$$ \sin(x) = x \prod_{n=1}^{\infty} ( 1 - \frac{4}{3} \sin^2 (\frac{x}{3^n})) $$
I know $ 1 - \sin^2x = (1 - \sin x) (1 + \sin x) $ but I'm not sure how to apply it.
Or maybe we need $ 2 \sin^2 (x) = 1 - \cos(2x)$?
Answer: Remember that $$ \sin 3x = 3\sin x-4\sin^3 x \implies \frac{\sin 3x}{3\sin x} = 1- \frac 43 \sin^2 x$$
Now you can see the telescoping product.
Comment: Clear and concise.  (+1)
Comment: a very fine hint !


How to hide the fields in manage display when layout module is installed and display when module is uninstalled programmatically?

Question: In the below config I want to remove the body field from content  and add it in hidden as body: true when I uninstall the layout module.
Basically when I install the layout module the fields in manage display should get disabled/hidden and when I uninstall the module the fields should be displayed. How can I achieve this programatically?
This config code is of entity_view_display.node.article.default
  uuid: eedc35e4-0592-4f1a-bdc6-47dbf60fa929
    langcode: en
    status: true
    dependencies:
      config:
        - field.field.node.article.body
        - field.field.node.article.comment
        - field.field.node.article.field_image
        - field.field.node.article.field_media
        - field.field.node.article.field_sample_text
        - field.field.node.article.field_tags
        - node.type.article
      module:
        - layout_builder
        - text
        - user
    third_party_settings:
      layout_builder:
        enabled: false
        allow_custom: false
    id: node.article.default
    targetEntityType: node
    bundle: article
    mode: default
    content:
      body:
        type: text_default
        label: above
        settings: {  }
        third_party_settings: {  }
        weight: 0
        region: content
    hidden:
      comment: true
      field_image: true
      field_media: true
      field_sample_text: true
      field_tags: true
      langcode: true
      links: true
      search_api_excerpt: true

Comment: Are you looking for a hook like hook_modules_installed/uninstalled or setComponent /removeComponent for the display mode? See https://drupal.stackexchange.com/questions/224686/8-how-do-i-programmatically-enable-a-user-field-under-manage-form-display-and
Comment: in hook_install() I want to hide fields in manage display. Like when I enable/install the layout builder module the fields in manage display should get disabled.
Comment: You mean the core layout builder module? Then you need the hook I've mentioned. hook_install() runs only for the module where the hook is implemented.
Comment: No no, I have created a custom layout module. And I am working on D9. I just want the content to get emptied in above mentioned config and body field in the content should be be hidden:true. And this functionality should be done in hook_install(). Hope I am able to explain it well!
Comment: I want to disable the field in manage display when I install my custom module.
Answer: I have solved the issue. Instead of \Drupal::entityTypeManager() I used
$articleDefaultLayout = LayoutBuilderEntityViewDisplay::load(
    'node.article.default'
);
$articleDefaultLayout->setComponent('body');

Comment: @4uk4 thanks your help.
Comment: This doesn't matter whether you use entityTypeManager() or the static load(). Both have the same result.
Comment: But when I used entityTypeManager(), removeComponent() was giving error. "Method not found"
Comment: Then there is a different error. BTW your code example has the disadvantage that it throws an error when the Layout Builder is not installed. It would be a better idea to load the original class or load the entity by entity type id via the entityTypeManager(). Then you get always the currently installed class for this entity type.
Comment: I have got your point. But why it is showing this error then? I did exactly what you mentioned in the code in hook_install(). It is failing to found the removeComponent() method. !!
Answer: To disable the body field when you install the custom module:
mymodule.install
/**
 * Implements hook_install().
 */
function mymodule_install() {
  \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load('node.article.default')
    ->removeComponent('body')
    ->save();
}

How to enable the field see 8 - How do i programmatically enable a user field under manage form display and manage display?
Comment: I am getting error in removeComponent() method. And If I want to delete the field using field id so instead of 'body' we can write field id, right?
Comment: I am working on Drupal 9


How do I simplify this trig problem?

Question:
Simplify the expression. Use exact values and show all steps. $$8\left[\left(\cos\dfrac{3\pi}4\right)\left(\sin-\dfrac\pi4\right)\right]+\dfrac1{\sin\frac{5\pi}6}-\left(\tan\pi+\cot\dfrac{7\pi}{4}\right)$$

Here is the answer I got: $$\dfrac{\sin\left(\frac{5\pi}6\right)\left(-\cot\left(\frac{7\pi}4\right)+8\cos\left(\frac{3\pi}4\right)\sin\left(-\frac{\pi}4\right)-\tan(\pi)\right)+1}{\sin\left(\frac{5\pi}6\right)}$$
This is supposed to simplify to $7$, but I'm not quite sure how I can do this?
Comment: You can evaluate each of those trig functions explicitly. Do so, and plug in the numbers.
Comment: Do you know the values of these trig functions based on the arguments? Do you know what $\sin(\frac{5 \pi}{6})$ is? Do you know how to write all of these in terms of sines and cosines?
Comment: Use the angle addition formulas, the double and half angle formulas, and known trig angles (like 30, 45, and 60 degrees) together to evaluate the exact value of the functions in your equation.
Answer: There are explicit values inside the trig functions, so you can evaluate the trig functions explicitly as well. $$\cos\left(\frac{3\pi}{4}\right) = \frac{-\sqrt{2}}{2} \\ \sin\left(\frac{-\pi}{4}\right) = \frac{-\sqrt{2}}{2} \\ \sin\left(\frac{5\pi}{6}\right) = \frac{1}{2} \\ \tan(\pi) = 0 \\ \cot\left(\frac{7\pi}{4}\right) = -1$$ Hence your quantity becomes $$8\left[\frac{-2}{\sqrt{2}}\cdot \frac{-2}{\sqrt{2}}\right]+\frac{1}{\frac{1}{2}}-\left(0+(-1\right))$$ I believe this will simplify to $19$... If you replace the coefficient of $8$ on the brackets with a $2$ you will get $7$

How do I simplify this trig problem?


how to find coefficient c1, c2, c3, c4 of a polynomials of degree 4 from resolvent

Question: if not starting from standard resolvent of each degree
and use (y-x1...)(y-x2...)(y-x3...) and group theory
how to find corresponding c1, c2, c3, c4 of polynomial x^4+c4*x^3+c3*x^2+c2*x+c1 which c1, c2, c3, c4 are in terms of x1, x2, x3, x4  and  x^4+c4*x^3+c3*x^2+c2*x+c1  is separable which means (x-....)(x....)(x....)...?
update1:
x1,x2,x3,x4 may not be symmetric polynomials,
i see x1*x2 + x3*x4 as permutation group [[1,2],[3,4]]
or x1*x2*x3 + x4 as [[1,2,3],[4]]
david a. cox's book only have an example page 358 about working from x^4+c4*x^3+c3*x^2+c2*x+c1 to resolvent and then group, my question is reverse direction, which means from a set of groups and then resolvent and then one polynomial
if physicist start from group to work out a polynomial, how do they do in real practice?
update2
if not start from x1*x2+x3*x4  this permutation group  [[1,2],[3,4]] , and if start from for example, x1*x2*x3 + x4, resolvent is change to something like  (y-(x1*x2*x3 + x4)) * (y-.....etc, how to find back a polynomial for degree 4.
Comment: if possible, use degree 3 as example
Comment: Maybe *you* should show *us* an example, since your question is incomprehensible. Anyway, $c_1$ is just $x_1x_2x_3x_4$, $c_4$ is $-(x_1+x_2+x_3+x_4)$, and so on, if you just multiply out.
Comment: david a. cox's book only have an example page 358 about working from x^4+c4*x^3+c3*x^2+c2*x+c1 to resolvent and then group, my question is reverse direction, which means from a set of groups and then resolvent and then one polynomial
Comment: Sorry, I still have no idea what you are trying to ask.
Comment: if not start from x1*x2+x3*x4  this permutation group  [[1,2],[3,4]] , and if start from for example, x1*x2*x3 + x4, resolvent is change to something like  (y-(x1*x2*x3 + x4)) * (y-.....etc, how to find back a polynomial for degree 4.
Comment: So, are you asking, what are the coefficients of $$(y-(x_1x_2x_3+x_4))(y-(x_1x_2x_4+x_3))(y-(x_1x_3x_4+x_2))(y-(x_2x_3x_4+x_1))$$ And are you asking for the answer in terms of $c_1,c_2,c_3,c_4$? The answer could be very complicated.
Comment: yes , i am asking for c1 , c2, c3, c4 in terms of x1,x2,x3,x4, i guess this is complicated, the important thing is that i would like to learn the method and steps. because there are many groups. moreover, bonus is that i would like to learn how [[1,2,3],[4]], [1,2,4],[3]],....etc in  your suggestion are related and in another words, how to find these set of group. For simple, you can use maple code instead of using Latex to answer.
Comment: Any thoughts on the answer I posted yesterday, hilbert?
Comment: Are you still here?
Answer: I think we have established in the comments that part of the question is, given a function $f(x_1,x_2,\dots,x_n)$ of the roots of a polynomial, for example, $x_1x_2x_3+x_4$, how do we find the conjugates of this expression.
The answer is, the conjugates are the expressions $f(x_{\sigma(1)},x_{\sigma(2)},\dots,x_{\sigma(n)})$, as $\sigma$ runs through all the elements of the group $S_n$.
In the example, and writing elements of $S_n$ in cycle notation, $\sigma=(1\ 4)$ gives us $x_2x_3x_4+x_1$, $\sigma=(2\ 4)$ gives $x_1x_3x_4+x_2$, and $\sigma=(3\ 4)$ yields $x_1x_2x_4+x_3$ (and of course letting $\sigma$ be the identity gets us $x_1x_2x_3+x_4$). There are 20 other elements of $S_4$, but they just give us the same four conjugates over and over.
The other part of the question is how to express $\prod_{\sigma}(y-f(x_{\sigma(1)},x_{\sigma(2)},\dots,x_{\sigma(n)}))$ in terms of the coefficients of the original polynomial. I will leave that to someone more proficient in the use of computer algebra systems than myself.


Expressing an assertion as first-order sentences in ZF Set theory

Question: I want to express the following assertion as first-order sentences in the language of set theory (that is, without abbreviations, in terms of logical symbols and relation symbols $=, \in$ only);
The instance of the Axiom Schema of Separation for the property "$x \subseteq \bigcup$$ x$"
Please can anyone help me out?
Answer: Hint
You have to use the definitions:

$A \subseteq B \leftrightarrow \forall z \ (z \in A \to z \in B)$

and;

$z \in \bigcup C \leftrightarrow  \exists D \ (z \in D \land D \in C)$.

Thus, $A \subseteq \bigcup A$ will be:

$\forall z \ (z \in A \to \exists D \ (z \in D \land D \in A))$.


Why intersection is not an axiom in naive set theory by halmos

Question: Why intersection is not an axiom in naive set theory? though, union was given as an axiom
Answer: $A\cap B=\{x\in A\mid x\in B\}$. So intersection can be deduced from comprehension axiom scheme.
Answer: The existence of intersection follows from the axiom schema of separation which informally tells you that if you start with a set and specify appropriately a way to select certain elements from this set by describing a formula that they satisfy then indeed there exists a subset containing precisely those elements. The construction of intersection fits this pattern (we can describe $A \cap B$ as selecting elements from $A$ that also lie in $B$) and so the existence of intersection follows from this axiom (for a rigorous proof, see Axiom schema of specification - Existence of intersection and set difference). The union construction generates from two sets $A,B$ a new set which is not a subset of either $A$ or $B$ in general and so requires another axiom to justify its existence.


Covariance of random variables with identical distribution.

Question: Let $X_1,...,X_n$  be random variables with identical distribution, and for all $i=1,...,n$ $\mathrm{Var}(X_i)$ exist.
1. Show that the covariance between each two random variables exist.
2. Show that :
$\mathrm{Var} \sum _{i=1}^{n} X_i = n \mathrm{Var} (X_1) + n(n-1)\mathrm{Cov}(X_1,X_2)$
Well, at the first question I tried to split it to two cases: case 1, that $\mathrm{Cov}(X_i,X_j)$ when $i=j$, and in this case it is simply $\mathrm{Var}(X_i)$ which exists.
but then I tried to show the other case, when $i\neq j$, and I dont really know how. Is it correct to use Cauchy-Schwarz inequality $|\mathrm{Cov}(X_i,X_j|^2 \leq \mathrm{Var}(X_i)\mathrm{Var}(X_j)$?
Other then that, I don't know how to show the second question, can someone give me a hint?
Thanks!
Answer: Cauchy Schwarz is fine. For the second equation $\def\Var{\mathop{\rm Var}}\def\Cov{\mathop{\rm Cov}}$(which will hold only if not only the $X_i$, but the pairs $(X_i,X_j)$, $i \ne j$ are identically distributed) recall that
\begin{align*}
  \Var\sum_i X_i &= \Cov\left(\sum_i X_i, \sum_j X_j\right)\\
          &= \sum_{i,j} \Cov(X_i, X_j)\\
          &= \sum_i \Var(X_i) + \sum_{i\ne j} \Cov(X_i, X_j)
\end{align*}
and the fact the the $X_i$ are identical distributed. This gives $\Var(X_i) = \Var(X_1)$ for all $i$. If we have that the pairs are identically distributed, we have $\Cov(X_i, X_j) =\Cov(X_1, X_2)$ for all $i \ne j$, hence
$$ \Var\sum_i X_i = \sum_i \Var(X_1) + \sum_{i\ne j} \Cov(X_1, X_2) = n \Var(X_1) + n(n-1)\Cov(X_1, X_2) $$
Comment: @Buzi You cannot show this from your assumptions, you have to assume it additionally if you want (2) to hold. It will not follow from $X_1, \ldots, X_n$ being identically distributed: Let $X_1, X_2$ be independent and $N(0,1)$ distributed (to be concrete). Let $X_3 := X_1$. Then $X_1, X_2, X_3$ are identically distributed, but: ${\rm Cov}(X_1, X_2) = 0$ and ${\rm Cov}(X_1, X_2) = {\rm Var}(X_1) = 1$.
Comment: Do I need to show that the pairs $(X_i,X_j) i\neq j$ are identically distributed?  How do I do that? It does not follow from the fact that $X_1,...,X_n$ are identically distributed?
Comment: Oh, you are right, I even got this very own counter example in class. Thanks for your help! You helped me a lot!