Is there a PDF version of the Castle Windsor documentation?

Question: The only documentation I've found for the components of the Castle project I've found here in the form of online HTML files.  Does anyone know of anything that is more off-line friendly or printable (e.g. PDF).  I've got quite the long train commute and I'd like to put something on my laptop. :-)
Answer: Decker, I've wondered about the same thing (not only for Castle Windsor) for many Web based resources.  Offline usage.  I wonder whether there's a tool that could create Web Arcive files (MHT) files by crawling the links on a web page.  I'm sure there must be one in the wild...
Update:
I Googled and found
this.
Sure an Open Source version should be available somewhere.  Let me know if you find it :)
Comment: There is, but since I don't use them to pull down porn websites, I have absolutely no idea what they are.  But I'm sure if you search sourceforge you'll find a few of them...
Comment: @Will:  I'm doubt if Castle site has links to Porn ;)
Comment: I've converted some sites for offline reference with httrack (http://www.httrack.com/) and an html to pdf converter.  But that is on Linux, there should be a Windows equivalent for the conversion and HTTrack has a Windows version.
Answer: You can create a mirror of that site for offline browsing using Wget.
http://wget.addictivecode.org/FrequentlyAskedQuestions
Answer: You can download it right from the Castle SVN repository and browse if offline:
http://www.castleproject.org/community/getinvolved.html


Implications of removing session size limit from SMTP Virtual Server

Question: I am running into an issue in one of our applications whereby our SMTP server rejects mail:
System.Net.Mail.SmtpException: Exceeded storage allocation. The server response was: 4.3.1 Session size exceeds fixed maximum session size
   at System.Net.Mail.DataStopCommand.CheckResponse(SmtpStatusCode statusCode, String serverResponse)
   at System.Net.Mail.DataStopCommand.Send(SmtpConnection conn)
   at System.Net.Mail.SmtpConnection.OnClose(Object sender, EventArgs args)
   at System.Net.ClosableStream.Close()
   at System.Net.Mail.MailWriter.Close()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

I've traced this back to the session size limit in SMTP Virtual Server. It's currently set to 10240kb, but before I increase it I'd like to know the implications of raising the limit or removing it entirely. The only clients that send through the server are (should be) under the control of my organisation.
Answer: The implication is that more data will be allowed per session (connection), based on whatever you set the value to. So, in concert with the other limits, this determines how much total data (the sum of all messages sent per session) is allowed per session (connection).
Answer: To add to the previous answer, the SMTP service process will also potentially consume more memory if it allows to have more data sent in the same session. This is especially true if your SMTP server is setup to "store and forward" (receives and stores the message locally, sends a 200 code back to the sending SMTP server and then opens another connection to the destination SMTP server)


Posted 10 messages, with 1 or more starred

Question: I talked with so many people in chat still I am not get any talkative Badges. If there is any bug or this?
Please let me know.
Answer: Did you earn a star for at least one message?
You have to meet both requirements:

10 or more messages;
1 or more starred.
Comment: Yes I achieve both requirement still I am not got.
Comment: @KeyulShah - you did not achieve both requirements. I see no starred chat messages of yours in any Magento chat room.
Comment: http://chat.stackexchange.com/rooms/12611/discussion-between-mohammad-faisal-and-keyul-shah

this is my chat room
Comment: ...and there is no starred message of yours. You would see those listed on the right.
Comment: can you please make photo of your starred message


Assumption of a Random error term in a regression

Question: In one of my recent statistics courses, our teacher introduced the linear regression model. The typical $y=\alpha + \beta X + \epsilon$, where $\epsilon$ is a "random" error term. The teacher then proceeded to explain that this error term is normally distributed and has a mean zero.
The error term is what is confusing me. What exactly does random mean? My back ground in statistics is very low level, but I understand that a random variable is defined as a mapping from a sample space to the real numbers. This definition makes sense, but the assumption of a zero mean is what I get tripped up on. How can we assume this fact?
I've been trying to think about it intuitively, and can only think that in regards to the real numbers, zero is in a sense "the middle ground" and splits up the reals into 2 "equal length" parts. However, I know that the reals are uncountable so this may be a case where my intuition is incorrect.
I apologize in advance if my question is confusing.
Comment: The fact that you're in (what I assume) is an undergrad-level stats course and know what a mapping is *is* quite fascinating, I have to admit. [I tutored statistics for four years in my undergrad.]
Answer: Here's the general idea - someone who has a better background than I do in statistics could probably give a better explanation. So you have this linear regression model:
$$Y = \alpha + \beta X + \epsilon $$
where $\epsilon$ follows a normal distribution with mean $0$.

What exactly does random mean?  My back ground in statistics is very low level, but I understand that a random variable is defined as a mapping from a sample space to the real numbers. This definition makes sense, but the assumption of a zero mean is what I get tripped up on. How can we assume this fact?

Personally, I've always taken the idea that $\epsilon$ follows a normal distribution with mean $0$ as an axiom of sorts for the linear regression model. My understanding is that it's just something nice we would like the linear regression model to have and lends itself well to certain properties. Remember:

Essentially, all models are wrong, but some are useful.

which is attributed to George E.P. Box.
Why would we want such an axiom? Well... on average, it would be nice to have zero error.
In my honest opinion (this is based off the little measure-theoretic probability I have studied), it would be best to approach this idea of "randomness" intuitively, as you would in an undergraduate probability course.
The idea about anything that is random is that you will never know the value of it. So, in an undergraduate probability class, what you do is you assign probabilities to the values your quality of interest can take by creating a probabilistic model. Your model, 99% of the time, won't be perfect, but that doesn't stop anyone from not trying.
The normal distribution with mean 0 is just an example of a probabilistic model that statisticians feel is a suitable model for the error term. It isn't perfect, but it's suitable for most purposes. I worked with a professor whose focus is on assuming a skew-normal error term, which complicates things, but is usually more realistic, since, in reality, not everything looks like a bell curve.
My two cents. Hopefully I've helped somewhat.
Comment: If there are two observations, and therefore two error terms, and the first error is -5, and the second is 5, then the mean would be zero - would this be an example of "having a mean zero"? Thank you.
Answer: Basically, the errors represent everything that the model does not have into account. And why is that? Because it would be extremely unlikely for a model to perfectly predict a variable, as it is impossible to control every possible condition that may interfere with the response variable. The errors may also include reading or measuring inaccuracies. Considering the regression line of best fit, the errors are based on the distance from each point to that line.
The Central Limit Theorem is behind the assumption of the errors following a normal distribution. It states that the distribution of the sum of a large number of random variables will tend towards a normal distribution. And actually, in the real world, the majority of the observable errors appear to be distributed that way; which helps us to extrapolate to the unobservable errors.
Another assumption made is that each data point has its own independent associated error, i.e., the errors are independent from one another, which helps us assume they occur randomly.
And because the errors occur randomly, it is expected each data point has equal probability of appearing above or bellow the line of best fit created by the regression (positive error values for the data points with a higher value than the one predicted by the line, and negative error values for the data points with a smaller value predicted by the line), meaning if you summed up every error it would result in a value very close to zero.
Hope to have helped.
Answer: The assumption of mean 0 is a normalization that must be made because you already have a constant term in the regression. It relates to the issue of identification - that you as the researcher cannot tell the difference between the constant term in the regression and the mean of the error term.
Proof: Suppose that $\epsilon$ is not mean 0
Let $\bar{\epsilon}$ denote the mean of $\epsilon$. Then I can re-write your model as
$Y = (\alpha + \bar{\epsilon}) + \beta X + (\epsilon - \bar{\epsilon})$.
let $\tilde{\alpha} = \alpha + \bar{\epsilon} $ and $\tilde{\epsilon} = \alpha + \bar{\epsilon}$
-->$Y = \tilde{\alpha}+ \beta X + \tilde{\epsilon} $.
This model is identical to yours except it now has a mean-zero error term and the new constant combines the old constant and the mean of the original error term.
Answer: Marcus Dupree,
    I was reading the book "Introduction to Statistics" by Trevor Hastie and Robert Tibshirani. The second chapter in that book deals with regression models. Authors, when explaining the relationship between Y and Xs, they mentioned about existence of "Random error". They further quoted that the "random error is independent of X and has mean zero". I had the question you had.
Why random error and why it's mean should be 0? Then I tried to understand it by some logic, also google searches. what I found is this,
Ideally, we are trying to represent an one to one relationship between Target Variable and Independent Variables. Assuming that we have collected all of the independent variables that are required to explain Y, then the relationship can be represented in a form of a function Y = f(X) ( f(X) will exactly explain Y ).
What are the chances that our assumptions are right with anyone observation is picked at random and apply the function?
if 'i is the n'th observation, applying Yi = f(Xi), you will see the difference between Actual Yi and f(Xi), against our assumption Yi = f(Xi). This difference is called error. Backing our initial assumption, 'Y is completely explained by all Xs we have', we assume this error as a random or Noise and still stick strongly to our initial assumption.
Applying the function f(X) to specific observation may result in Random Error but on the whole, according to our initial assumption, there will not be any error. How is that possible? Specific Observations error, on the whole, no error!
if I have 10 observations, I may have the maximum of 10 errors and they are random. if y is target and 'e' is error, then,
y1 = f(x1) + e1 {e1 may be a random number, may be 0 also}
y2 = f(x2) + e2 {e2 may be a random number, may be 0 also}
y3 = f(x3) + e3 {e3 may be a random number, may be 0 also}
y4 = f(x4) + e4 {e4 may be a random number, may be 0 also}
y5 = f(x5) + e5 {e5 may be a random number, may be 0 also}
y6 = f(x6) + e6 {e6 may be a random number, may be 0 also}
y7 = f(x7) + e7 {e7 may be a random number, may be 0 also}
y8 = f(x8) + e8 {e8 may be a random number, may be 0 also}
y9 = f(x9) + e9 {e9 may be a random number, may be 0 also}
y10 = f(x10) + e10 {e10 may be a random number, may be 0 also}
Y = f(X) + E [based on our initial assumpotions, E is 0]
where, E = e1+e2+e3+e4+e5+e6+e7+e8+e9+10
This can be true only when E is random and Normally distributed and standardized. Where we have a non zero value for individual errors but mean of E will give 0. That's is the reason we are assuming errors are random and normally distributed.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: I think the other answers have done a pretty good job of explaining what the assumption means, but I just want to add why this is such an important assumption for any future readers. This implies that outside of the covariates we include in our model, the rest of the variance is completely independent and normally distributed across the observations. However there are actually a lot of times in the real world that this isn't true. Let's say you want to find the relationship between a person's income and their BMI from a dataset of thousands of people from all 50 states in US. Intuitively, we may suspect that people from the same area of the country are probably more similar to each other in both weight and income than people from random parts of the country. Therefore, we can't assume the error is a zero-mean normally independently distributed term.
However, we also probably don't want to add 50 state coefficients or hundreds of county coefficients into our model. Instead we can use random effects hierarchical model where we assume that the states or counties also have their own error distribution and that component of the error term is separated from the individual error term. By doing this we reduce the risk of identifying a spurious relationship between BMI and income which really is due to regional differences in income and BMI. Similar approaches are done when modeling spatial phenomena (i.e. we expect neighboring ZIP codes or counties to be more similar to each other than farther apart ones) and longitudinal analysis (observations within one patient are going to be related to each other).
Comment: It may not be a direct answer to the question, but it's better than that...It puts the question in context.  Big picture is not taught enough in courses.  MathSE can help with that!


Comparing Nginx+PHP-FPM to Apache-mod_php

Question: I'm running Drupal and trying to figure out the best stack to serve it. Apache + mod_php or Nginx + PHP-FPM
I used ApacheBench (ab) and Siege to test both setups and I'm seeing Apache performing better. This surprises me a little bit since I've heard a lot of good things about Nginx + PHP-FPM. My current Nginx setup is something that is a bit out of the box, and the same goes for PHP-FPM
What optimizations I can make to speed up the Nginx + PHP-FPM combo over Apache and mo_php ? In my tests using ab, Apache is outperforming Nginx significantly (higher requets/second and finishing tests much faster)
I've googled around a bit, but since I've never using Nginx, PHP-FPM or FastCGI, I don't exactly know where to start
PHP v5.2.13, Drupal v6, latest PHP-FPM and Nginx compiled from source. Apache v2.0.63
ApacheBench Nginx + PHP-FPM
Server Software:        nginx/0.7.67
Server Hostname:        test2.com
Server Port:            80

Concurrency Level:      25
---> Time taken for tests:   158.510008 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
---> Requests per second:    6.31 [#/sec] (mean)
Time per request:       3962.750 [ms] (mean)
Time per request:       158.510 [ms] (mean, across all concurrent requests)
Transfer rate:          181.38 [Kbytes/sec] received

ApacheBench Apache using mod_php
Server Software:        Apache/2.0.63
Server Hostname:        test1.com
Server Port:            80

Concurrency Level:      25
--> Time taken for tests:   63.556663 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
--> Requests per second:    15.73 [#/sec] (mean)
Time per request:       1588.917 [ms] (mean)
Time per request:       63.557 [ms] (mean, across all concurrent requests)
Transfer rate:          103.94 [Kbytes/sec] received

Comment: In all honesty, it really would help if you provided some additional details regarding how you currently have things configured. Such configurations such as amount of listening processes, maximum requests per process, whether you have keepalives enabled, etc... all impact server performace. With your configuration files, we'd atleast have a good starting point to work from ;)
Comment: Wow, I never thought that Apache might be faster than nginx.

Thanks for showing this. :)
Comment: Number of worker threads in both cases would certainly make a difference… how many were them?
Answer: Here are some possibilities for this:

You have enabled some kind of opcode cache with mod_php
You have turned on mod_cache in apache
You are using TCP connection method in php-fpm.

Post back with these details.
Also, try apache + mod_fastcgi + apc + php-fpm.
And, if you are using the if condition in nginx for rewrite rules, switch to try_files instead. if sometimes has performance issues.
Answer: Is it possible that you have APC or another accelerator enabled with apache? I agree with the poster above that more information about your configuration is needed.
Comment: This would be better as a comment


Fourier series of arbitrary polynomial

Question: I am working through the following problem:
Let $P(x)$ be some arbitrary polynomial over the interval $[-1, +1]$. Then define
$$A_n(P) = \int_{-1}^{+1} P(x)\cos{(n\pi x)}\,\mathrm{d}x$$
I am require to show that this coefficient (for $n > 0$) is in fact a polynomial in the variable $\frac{1}{n}$. My attempts so far have simply involved computing the integral using by parts, where the $u\cdot v$ term conveniently vanishes, and I am left with
$$A_n(P) = -\frac{1}{n\pi} \int_{-1}^{+1} P'(x)\sin{(n\pi x)} \, \mathrm{d}x$$
I am getting closer to the solution, or have I approached the problem in the wrong manner?
Answer: This is the correct technique. Persevere! One more integration by parts gives you
$$ A_n(P) = \frac{1}{n^2\pi^2} \left[ P'(x)\cos{n\pi x} \right]_{-1}^1-\frac{1}{n^2\pi^2}\int_{-1}^1  P''(x) \cos{n\pi x} \, dx \\
= \frac{(-1)^n}{n^2\pi^2} (P'(1)-P'(-1))-\frac{1}{n^2\pi^2}\int_{-1}^1  P''(x) \cos{n\pi x} \, dx. $$
Now you can use induction, because $P''(x)$ has lower degree than $P(x)$. Because the degree jumps by two, you also have to check both degree one and degree zero to get both of the basis cases, however.
Comment: Thanks for the motivation - did you assume that n made the cosines equal to +1.
Comment: Oh, whoops, brain fart. $\cos{n\pi}=(-1)^n$, of course... thanks.
Comment: So, let me make sure  understand the process - we can always find an expression for $A_n(P)$ that involves integrating a constant multiplied by a sine or a cosine, is that how you would do it? For example, if $P(x)$ is of degree 2, we can use the above expression in order to evaluate the coefficient?
Comment: If $P$ has degree $k$, I have shown that it is equal to a (simple) polynomial in $1/n$, added to the Fourier transform of a polynomial of degree $k-2$. Therefore, provided that $k=0$ and $k=1$ give polynomials in $1/n$, I can use induction to show that every polynomial has Fourier transform a polynomial in $1/n$: suppose it is true for $k-2$, then the integration by parts shows it is true for $k$.
Comment: Awesome answer! fr fr

Fourier series of arbitrary polynomial


Using Process.StartInfo.UserName

Question: I have a website that has a linkbutton that opens a game :
<code>Process game= new Process();
    game.StartInfo.FileName = HttpContext.Current.Request.MapPath("~/iFarkle.exe");
    game.StartInfo.UserName = Session["Username"].ToString();
    game.StartInfo.UseShellExecute = false;
    game.Start();
</code>
How do I use the StartInfo.UserName?
(it doesn't work right now, it stays I entered bad data)(works without the StartInfo.UserName
Comment: Um, that looks like server side code, which is going to launch iFarkle on the *server*. Is that really what you're trying to do?
Comment: Oh right... I want it to run on the user's computer. Nevermind
Answer: If you want the exe to run on the users computer, you can either:
Provide a direct link to the exe file (and make sure your server is configured to serve .exe files), or,
Stream the contents of the file back in the response (having made sure to set the Response ContentType to a suitable type (I think application/x-msdownload would work)).
I'd only do the second if I was going to, for example, perform some additional checks before allowing the download. Of course, as soon as the user has downloaded the exe, they'll be free to do with it whatever they please.
Also note that this will only work if the exe doesn't have any other DLLs it relies on (except DLLs which are safe to assume will already be accessible on the client machine).

Using Process.StartInfo.UserName


Different ring structures on the product of rings

Question: Let $(R_1, +_1, \circ_1)$ and $(R_2, +_2, \circ_2) $ be two rings. Let us consider the set $R = R_1 \times R_2$. We know it has a ring structure given by the following:
$$(x,y) + (x^\prime, y^\prime) = (x+_1 x^\prime, y +_2 y^\prime)$$ and $$(x,y)\circ(x^\prime, y^\prime) = (x\circ_1 x^\prime, y \circ_2 y^\prime)$$
Question: I am looking for different ring structures on $R.$ Any help will be appreciated.
Answer: In general if you have a bijective map $f$ of a ring $S$ to itself  then you can define two new operations
$x+_fy:=f^{-1}(f(x)+f(y))$
$x*_fy:=f^{-1}(f(x)f(y))$
In this case $(S,+_f, *_f)$ is a ring, where the neutral element with respect to $+_f$ is $f^{-1}(0)$ and the neutral element with respect to $*_f$ is $f^{-1}(1)$
Example:
If you choose $f: S\to S$ such that
$f(x):=-x+1$
you have that the inverse is $g(x)=-x+1=f(x)$ and in this case we have
$g(0)=1$ and $g(1)=-1+1=0$
So $1$ is the new neutral element with respect to $+_f$ and $0$ is neutral element with respect to $*_f$ on the new ring $(S,+_f,*_f)$. The new operations are
$x+_fy=f(-x-y+2)=x+y-1$
$x*_fy=f((-x+1)(-y+1))=$
$f(xy-x-y+1)=x+y-xy$
The problem is that  $f: (S,+_f,*_f)\to (S,+,*)$ is an isomorphism of rings, so the two structures are equal.
In your case if you want a new structure on $R$, equal to the initial structure up to isomorphism,
you can consider two bijective maps $f:R_1\to R_1$ and $g:R_2\to R_2$, and in this case you have that
$(R, +_{(f,g)}, *_{(f,g)})$ is a new ring but it is isomorphic to the initial ring $(R,+,*)$
If you want a different structure you can consider a generalization of semi-direct products for Rings:
If you have a morphism
$\psi: R_2\to Aut((R_1,+,*))$
then you have that
$(a,b)+^\sim(c,d)=(a+\psi(b)(c), b+d)$
and
$(a,b)*^\sim(c,d)=(a\psi(b)(c), bd)$
are two operation on $R_1\times R_2$ such that
$(R_1\times R_2, +^\sim,*^\sim)$ is a ring different from $(R,+,*)$
Comment: For so your particular example $f(x) = -x+1$ we get the ring structure on $S$ given by $x+_f y = x+y-1$ and $x \ast_f y = x+y-xy.$ Also, we know that any map $S \times S \to S$ can be thought as a map $S \to Hom(S, S)$. So, I would like know is this function $f$ induces any ring homomorphism from $S \to S.$
Comment: @Surojit it is not true, the map $S\times S \to S$ must be bilinear to get that it can be thought as a map S\to hom(S,S).
Comment: So, if $ f: S \to S$ is a bijection such that $f \circ f= id$, then the map $f : (S, +, \ast) \to (S, +_f, \ast_f)$ is a ring homomorphism.
Comment: Also, this map $f$ is a ring isomorphism too. Thus, it implies that the rings $(S, +, \ast)$ and $(S, +_f, \ast_f)$ are isomorphic rings. But I need to construct some ring $(S, +^\prime, \ast^\prime)$ such that it is not isomorphic to $(S, +, \ast).$
Comment: @Surojit This is known as [**transport of structure**](https://math.stackexchange.com/search?tab=active&q=user%3a242%20transport%20structure)
Comment: @Surojit I hope that I answered to your questions
Comment: @FedericoFallucca: I have one small doubt. Your function $f(x)= -x+1$ is not a ring isomorphism from $(S, +, \ast) \to (S, +, \ast) $.  But if we define the same map $f : (S, +, \ast) \to (S, +_f, \ast_f)$ then it is an ring isomorphism.
Comment: @Surojit Yes,you're right. In general $f: (S,+_f,*_f)\to (S,+,*)$ will be an isomorphism, so you have te same structure. I'm sorry


Model Schema support in Azure API Management

Question: In the Swagger UI, the model/model schema are documented in the Parameters section. When I import the same documentation into the Azure API Management portal, parameters with .NET data types are documented but the complex object/model/model schema in the request body loses its documentation.
I saw an update for Model Schema support Azure API Management adds support for Swagger model schemas.
But it did not work when I tried it in the API Portal.

Do anyone know how to import the Model Schema Documentation into the Azure API Management Portal?
Is this update available in New Portal only? And if so when will API management be available in New Portal?

Note: I am using Swagger 2.0 documentation from Swashbuckle in Visual Studio 2013.
Answer: Model schemas are imported if they are in the Swagger file. If that's not the case your saw, can you please send your Swagger file to apimgmt at microsoft dotcom so that we can take a look at the file.
Answer: I was able to repro this issue and have fixed it.  Hopefully, I will be able to get the fix in the next release.
Comment: Could you give us an update about when to expect the next release? We're desparately waiting for this update
Comment: @standardModel Testing the release build right now, it should start rolling out next week.


Angular material multiselect check box current value not able to get

Question: when i check the checkbox i am getting undefined when i uncheck getting the value of what i previously checked. how to fix this issue?

                <mat-form-field appearance="outline" >

                  <mat-label>{{field.placeHolder}}</mat-label>
                  <mat-select [formControlName]="field.controlName"  multiple  [(ngModel)]="countrySelected" >
                    <mat-option *ngFor="let option of field.options" [value]="option"

                    (onSelectionChange)="countriesUpdate($event)">
                      {{option.label}}
                    </mat-option>
                  </mat-select>
                </mat-form-field>

 console.log(this.countrySelected); undefined on check
how to get current value?
Answer: onSelectionChange is triggered before the form value is set, so you will get the last set value, there are two ways you can resolve this problem

Listen to selectionChange on mat-select instead of onSelectionChange on mat-option
Subscribe to the form control value changes event

<mat-select
  [formControlName]="field.controlName"
  multiple
  [(ngModel)]="countrySelected"
  (selectionChange)="countriesUpdate($event)"
>
  <mat-option *ngFor="let option of field.options" [value]="option.label">
    {{ option.label }}
  </mat-option>
</mat-select>

ngOnInit() {
  this.formGroup
    .get('formControlName')
    .valueChanges.subscribe((selectValue) => console.log(selectValue));
}


Two similar programs both have errors on final line

Question: I have written two similar programs for my programming class.  I have shared the code for both programs due to them being similar in nature and both have compiler issues on the final line with     return0; For the first string of code the error I receive is "expected a declaration" and "syntax error: 'return'". For the second code I receive the errors "return value type does not match the function type" and " 'display': 'void' function returning a value.  I have deleted and added {} at different parts of both codes and tried to rearrange the code. Thanks for help in advance.
Code 1
#include "stdafx.h"
#define nums 7

void display(int *);

int main()

{

    int channels[nums] = { 2,4,5,7,9,11,14 };
    printf("Channels: ");
    display(channels);
}

void display(int *channels)

{

    int i;
    for (i = 0; i < nums; i++);

    {
        printf("%d", *(channels + i));
    }
}

return 0;

code 2
#include "stdafx.h"
#define nums 7

void display(int *);

int main()
{

    int channels[nums] = { 2,4,5,7,9,11,13 };
    printf("channels: ");
    display(channels);
}

void display(int *channels)

{
    int i;
    for (i = 0; i < nums; i++)
    {
        printf("%d", *channels);
        *channels++;
    }

    return 0;
}

Comment: A good C book might prove helpfull.
Comment: unrelated note: `for (i = 0; i < nums; i++);` remove last `;`
Comment: you aren't returning an integer value in either of your `main` functions as your function signature says it should be. also notice how in the second example you have the function
`void display(int *channels)`
Yet you return an integer value inside of it.
Comment: To paraphrase Inigo Montoya, "That code - `*channels++`. I do na think it means what you think it means". What are you attempting to do with `*channels++`?
Comment: 1) You do not write the executable statement outside of the function. So remove `return 0;` 2) Do not return value when the return type of function is `void`. So remove `return 0;`
Comment: Learning C straight from a book I am finding rather difficult so I appreciate all the help I have received to better understand this language,
Answer: Return value is always associated to functions. For example, if a function sums up 2 integers and returns the sum of the integers, it will look something like:
int sum( int a, int b ){
    return a + b;
}

See here, the return type of the function is int, and what it returns is also an int, since addition of two integers gives you an integer. It's like 2 horses + 3 horses = 5 horses. You cannot do 2 horses + 3 lions = 5 mangoes. I hope you get the point of return value and type.
Now in code 1, the error is you put your return 0; statement out of the main() function. The program cannot detect which function is this return statement associated to. To correct this, move your return statement in the next line after you call the display() function, INSIDE main() function.
Similarly, in code 2, move the return statement from the display() function to the main() function, just as you did in the previous case. This is because void expects nothing to be returned, but you are returning an integer. This is the same like giving a millionaire a loaf of break when he says he doesn't need one, he will surely get frustrated!
Hope that helps.
Comment: Thank you for your help.  That makes a lot of sense.  I did what you said and it worked. I guess I never put two and two together that the return statement has always gone in main().  Thanks again for the help.


Mouse cursor on vps win server 2012 R2 not working

Question: i have server with hyper-v manager on network (Windows server 2012).
But after installing i can't click nowhere, the keyboard works but the mouse is not.
Google did not tell me anything.
The mouse cursor looks like dot, not a classic mouse cursor.
I have many vps servers, on win server 2008, or 2012, but problem is only with 2012 R2.
https://i.stack.imgur.com/n8dSi.png
thank you for answering.
Comment: I don't understand. Is this a virtual machine or a physical machine? If this is a virtual machine then what virtualization platform is it running on? If this is a virtual machine have you installed the virtual machine tools or integration services?
Comment: Hello. I have one physical server. I'm on it via remote desktop. And there i have the Hyper-V VPS with Windows Server 2012 R2. I can not get in the order of remote desktop-hyper-v console. On this vps over remote desktop-hyper-v console is not mouse cursor, but dot cursor withou click option and other.
Comment: I still don't understand. Is the machine that has the "dot" mouse cursor a physical machine or a virtual machine?
Comment: Has no cursor on the virtual machine.
Comment: OK, still not directly answering my question but I'll surmise that the problem machine is a virtual machine hosted on Hyper-V on Windows Server 2012. Have you installed the Hyper-V Integration Services in the virtual machine? If not, then you need to and that will probably resolve the problem. Also, in Hyper-V Manager go to Hyper-V Settings, go to the "Reset Check Boxes" settings and click the Reset button. Then click the mouse inside of the virtual machine console/window and tell me if you get any message.
Comment: I have installed integration services. You mean this ? http://d.pr/i/FfSn, after reset button. This is message http://d.pr/i/TIZL I do not understand :(
Comment: because i can't install integration services to vm. :( mouse not working.
Comment: Sure you can. You don't need the mouse for that. Open the Virtual Machine Connection window for the VM, select "Action... Insert Integration Services Setup Disk" and use the keyboard to tab to the buttons, etc. that you need to run the installation. Once the Integration Services are installed you should be able to use the mouse.
Comment: ok, after install and reboot i have this message. http://d.pr/i/49fO mouse stil does't work.
Answer: Assuming this is the same issue I just had:
I downloaded the VMs from Microsoft to let me test IE. They were Virtual PC images which I used as HyperV disks, creating a new Virtual Machine for them.
After booting, my mouse cursor was a small dot (not a cursor I'm familiar with), and clicking didn't seem to do anything. The keyboard worked.
After getting to desktop, I could click - the mouse pointer was not movable on the guest, but I could toggle desktop items (because Win7 has that 'show desktop' button in the bottom-right corner). So clicking worked but the pointer was trapped.
The fix was to go to Programs and Features (using the keyboard) and uninstall the VM guest additions (in this case they were VirtualPC additions that didn't completely work with Hyper-V).
After uninstalling them, mount the Integration Services Pack DVD (Hyper-V Action menu) and it will let you install it. After a reboot the mouse is working again.


Using Contextual Filters to Filter "Content: Published"

Question: Is there any solution to filter "Content: Published" with Contextual Filters?
Comment: Does this make sense? What is your goal?
Comment: Not out of the box and not even with Views Arguments in Filters. As asked above, what is your goal so maybe you can find a workaround.
Answer: Out of the box I don't believe this is available. I have a similar use case however I am also using Workbench Moderation. I'm using the moderation state as the contextual filter and using setting a standard filter of current revision as true. This allows you to target a specific moderation state in your view, published being one of them. It could get irritating if you end up with a lot of moderation states and have to target each of them specifically but my use case requires me to get either just published, or all content regardless of published or not.


How to define a Java Map in graphql?

Question: I have a filterModel which is a Map Map<String, ColumnFilter> filterModel in order to filter my Actor data. I get an filterModel Object from the client when I try to filter my data. How do I define this Java Map in my graphql Query?
filterModel Object from client:
filterModel: {
               firstname: {filterType: 'text', type: 'contains', filter: 'Tom'}, ...
              }

schema:
type Actor {
    actorId: ID!,
    firstName: String,
    lastName: String,
}

type Query {
    rows(
        filterModel: [filterModel]
    ): [Actor]
}

input filterModel {
    key: String,
    value: ColumnFilter
}

input ColumnFilter {
    filterType: String,
    type: String,
    filter: String
}

Answer: There is no map type in GraphQL. Because maps are basically containing dynamic keys and, they do not play well into the static types that GraphQL is expecting.
If you are really unsure of what type the data is going to be in that map, you can always store that dynamic information as a String. This is something I personally would do.
So your filterModel would become
filterModel:String and that string would be a JSON representation of the object. You can do the JSON parsing in the code to convert it back to a Map
Answer: 0 input
mutation{ xxxx(employeeBean:{ xxxxx , attributes: {\"key\":\"value\"}" }) {
xxxxxxx attributes }}

1.schema file
scalar JSON
type Employee {

   ........
   attributes: JSON
}

1.configuration
@Bean
public RuntimeWiringConfigurer runtimeWiringConfigurer() {
    return wiringBuilder -> wiringBuilder
            .scalar(jsonScalar());
}

public GraphQLScalarType jsonScalar() {
    ObjectMapper objectMapper = new ObjectMapper();
    return GraphQLScalarType.newScalar()
            .name("JSON") //graphql type define in the schema file
            .description("Java MAP as scalar.")
            .coercing(new Coercing<Map<String, String>, String>() {
                @Override
                public String serialize(final Object dataFetcherResult) {
                    if (dataFetcherResult instanceof Map) {
                        try {
                            return objectMapper.writeValueAsString(dataFetcherResult);
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        throw new CoercingSerializeException("Expected a Map object.");
                    }
                }

                @Override
                public Map<String, String> parseValue(final Object input) {

                    if (input instanceof StringValue) {
                        try {
                            return objectMapper.readValue(input.toString()
                                    , new TypeReference<Map<String, String>>() {
                                    });

                        } catch (JsonProcessingException e) {
                            throw new CoercingParseLiteralException(e);
                        }
                    } else {
                        throw new CoercingParseValueException("Expected a String");
                    }
                }

                @Override
                public Map<String, String> parseLiteral(final Object input) {
                    if (input instanceof StringValue) {
                        try {
                            return objectMapper.readValue(((StringValue) input).getValue()
                                    , new TypeReference<Map<String, String>>() {
                                    });
                        } catch (JsonProcessingException e) {
                            throw new CoercingParseLiteralException(e);
                        }
                    } else {
                        throw new CoercingParseLiteralException("Expected a StringValue.");
                    }
                }
            }).build();

}

3 bean
public class EmployeeBean {

private Map<String,String> attributes;
}

Note
GraphQlArgumentBinder-> public Object bind(
DataFetchingEnvironment environment, @Nullable String argumentName, ResolvableType targetType)
throws BindException {}
not able to bind the value to the map object because its using map name define in the schema and then put dot and then the first key name and searching of that name in the bean to find the map and its not working as of now

How to define a Java Map in graphql?


Flex4.6: Avoid moving to next cell in spark DataGrid

Question: I 'm using an editable spark DataGrid in Flex 4.6. How can I avoid TAB or ENTER key in a cell to move to next cell?
Answer: You should look at the focus manager Every component has this. I dont know what you would like to do when the user hits a tab. But, look for the following methods/properties, they might help you.
datagrid.focusManager.getNextFocusManagerComponent()

showFocusIndicator

I think you can do  datagrid.focusManager.getNextFocusManagerComponent().getFocusManager().showFocusIndicator = false;
Just a guess. But, try to get the focusManager of the DataGrid and play around with it.


what is the replacement for htaccess files for Azure Web App with PHP>= 8 which now uses nginx?

Question: We are using azure web apps to host a few static HTML pages, which cannot be hosted in Azure Static Web Apps because Azure static Web apps do not support uploading your own certificate.
Now we have our html pages on azure web apps, we need to create rewrite rules, so that depending on the domain, or headers etc, we can route to the right page.
How can this be done without the equivalent of htaccess files?
I have been told that the only solution is to downgrade to web apps with php 7 or below. This is not an issue, as we have no php on the site, but might be an issue because MS are planning to remove this hosting.
It seems odd if there is no way to do any kind of rewrite rules or modify the web server config with azure web app hosting.
Answer: .haccess is solely Apache HTTPD feature, not connected to PHP in any way. With Apache and absolutely any version of PHP (or whatever you have) you'd be able to use .htaccess; without Apache you won't be able to use it.
Apache's documentation never recommended to use this feature, leaving only a single valid use case for it — a shared hosting where the tenant is unable to change httpd.conf file. If you have VPS or any other form of a personal server you should never use .htaccess even with Apache HTTPD, putting everything into httpd.conf instead (or into files explicitly included from there).

You should avoid using .htaccess files completely if you have access to httpd main server config file. Using .htaccess files slows down your Apache http server. Any directive that you can include in a .htaccess file is better set in a Directory block, as it will have the same effect with better performance.

Most probably you should have gotten rid of this bad habit of using .htaccess files a long, long time ago.
Nginx is another HTTP server, and there is no analogous feature comparable to .htaccess. You always configure everything into the server configuration file, nginx.conf and into files explicitly included from it.
It is possible to translate Apache's rewrite rules into Nginx's rules. We can help you with that, but you need to show these rules.
Comment: Thanks for the reply. I am fairly fluent in apache and nginx conf.  The big win for htaccess is that I can code the rules in files in git along side the html, so that the deployment pipelines deploy the rules and pages at the same time, and no matter what apache server you use locally or for testing the rules will be there, its like a yaml build file.  The issues is that there is no where to put the nginx rules, as they are not part of our html, and the azure piplines which come with the azure web app only deploy to wwwroot.   Azure manages the nginx config, I dont know how it could be hacked
Comment: As nginx is an azure managed resource, e.g. if you add a new custom domain or certificate, it must be editing the webserver config internally, so any attempt to hack or modify the nginx config would get overwritten best case.  The crux is without something like htaccess files, the nginx config cant be extended we assume
Comment: Well, in that case your question simply happens to be off topic here. Questions involving web hosting control panels are off-topic because they [customize their systems so that standard system administration methods no longer apply](https://meta.serverfault.com/questions/8055). (Standard administration methods include installing appropriate software, directly editing its configuration files, building structures involving reverse proxies, application servers and so on, which is precisely what you are unable to do.)
Answer:
It seems odd if there is no way to do any kind of rewrite rules or modify the web server config with azure web app hosting.

This isn't true, although the UX of it all is atrocious. However, the following process is straightforward and much preferred over your Cloudflare solution.
I'll give you an answer using a solution that I just put in place for my PHP 8.2 project.

I added a default.conf file to the root of our source control.
a. This default.conf was created using the default nginx configuration file that is installed on the App Service. This default configuration file is found at /etc/nginx/sites-enabled/default.
b. I edited the default.conf file in source control to include my nginx rewrite rules.

Deployment copies our source control repository to the Azure App Service's wwwroot directory including this default.conf file.

In the App Service > Configurations > General Settings, you need to add this small startup script to copy the default.conf file onto the one used by nginx

cp /home/site/wwwroot/default.conf /etc/nginx/sites-enabled/default; service nginx restart

Our default.conf file looks like this as a reference:
server {
    #proxy_cache cache;
    #proxy_cache_valid 200 1s;
    listen 8080;
    listen [::]:8080;
    root /home/site/wwwroot;
    index  index.php index.html index.htm;
    server_name  example.com www.example.com;
    port_in_redirect off;

    location / {
        index  index.php index.html index.htm hostingstart.html;
        try_files $uri $uri/ /index.php?$args; #### this specifically was the rewrite rule we needed for our project
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /html/;
    }

    # deny access to .env files
    location = /.env {
        deny all;
        return 404;
    }

    location = /.env.example {
        deny all;
        return 404;
    }

    # Disable .git directory
    location ~ /\.git {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Add locations of phpmyadmin here.
    location ~* [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.[Pp][Hh][Pp])(|/.*)$;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_connect_timeout         300;
        fastcgi_send_timeout           3600;
        fastcgi_read_timeout           3600;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

Answer: Well, I found a solution to the issue that you cant add rewrite rules on Azure Web Service (without hacking startup scripts, hacking files and potentially breaking azure control panel functionality like adding new domains and certs)
That solution is to do put the free version of Cloudflare infront of Azure web apps, and use cloud flare rewrite rules (10 for free).  This solved our problems, although we would have preferred to have the rules in git deployed with our web app (which can be done with azure static web apps and azure web apps with php < 8).


How to get type of object's attribute in python

Question: assume I have the following class:
class myClass():
    def __init__(self, number):
        self.myStr = "bla"
        self.myInt = number * 3

how do I get the the attributes types? I mean I want to get the following list: ['str','int']?
I also want it to work on derived classes.
Thanks a lot :)
Comment: Why not `['int', 'str']`?
Comment: A Pythonic way is [here](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) :-)
Answer: RHP almost has it. You want to combine the dir, type, and getattr functions. A comprehension like this should be what you want:
o = myClass(1)
[type(getattr(o, name)).__name__ for name in dir(o) if name[:2] != '__' and name[-2:] != '__']

This will give you ['int', 'str'] (because myInt sorts before myStr in alpha-order).
Breaking it down:

getattr looks up the name of an attribute on an object
type gets the type of an object
__name__ on a type gives the string name of the type
dir lists all attributes on an object (including __dunder__ attributes)
the if test in the comprehension filters out the __dunder__ attributes
Comment: is there any easy way to check if a certain class has attribute of some derived object?
Comment: `dir` lists _all_ attributes on an object; if the object's class inherits from another class, an instance of that object will have all the attributes on both.
Comment: I have a tiny problem with your solution: in some cases I get inside the list - "'instancemethod'".
Comment: That would be from an object having methods as attributes. Methods are members of an object, too. You can filter these out by splitting up the list comprehension, and removing items if the result of `type` has a `__call__` attribute.
Comment: sorry, but I maybe wasn't clear enough. I want to know the type of objects that show up as 'instance' and 'instancemethod'. I guess these are the attributes that were inherited. that was my first problem.
Comment: Those _are_ the types of objects. `instancemethod` is the type of a method attribute, it is a function with `self` bound to the first argument.
Comment: I think I should reopen another question
Answer: Use the type() function. You can even use it to print out the variable type like this:
print(type(variable_name))

Comment: Suppose you find out this information. How do you expect it to *help you*? You should explain more about what you are *really trying to do*.


Who first proved that a fraction writable with coprime denominators is an integer?

Question:
Let $a$ and $b$ be two coprime integers and $q \in \mathbb{Q}^*$. If $qa,\ qb \in \mathbb{Z}$ then $q \in \mathbb{Z}.$

From which historical mathematician does this lemma come? Any references?
Comment: Euclid?${{{}}}$
Comment: Well... I never heard of this *lemma* as stated as a specific result worth remembering and referring. If I ever needed the results I'd figure they'd be easy to derive or even to just dismiss as "a clear immediate corollary to Euclid's Lemma".  There's lots of lemmas I never heard of.  I've never heard of the Lemma that all positive integers may be written as $3^k*M$ where $M$ is an integer not divisible by $3$ and I dare say you've never heard it either (odd that I can quote it despite never having heard it....)
Comment: Denominators for $q$ are closed under subtraction so also under gcd, thus if $\,a,b\,$ are deominators for $q$ so too is $\,\gcd(a,b) = 1,\,$ i,e, $\,q\in\Bbb Z.\,$ Proofs like this became obvious once ideals were known. See [here](https://math.stackexchange.com/a/1197025/242) for further discussion of such denominator (and order) ideals. It is probably difficult to date the first time this *precise* statement is known (before ideal theory).
Comment: Not all lemma's are historically traceible.  I've never heard of this lemma but it fairly clear and easy to prove.  I doubt there is any history to it.  Euclid may or may not have proven it.
Comment: @Maman FYI, in case you didn't know about it, you may wish to consider in the future if these types of questions may be better suited for the [History of Science and Mathematics](https://hsm.stackexchange.com/) site.
Comment: fyi: it's [easy to show](https://math.stackexchange.com/a/3295370/242) that this is equivalent to Euclid's Lemma and closely related results. @fleablood Surprised to hear that you've never seen it since I explicitly highlight it frequently here when discussing denominator (and order) ideals (e.g. the link in my prior comment) Maybe I should use brighter colors!
Comment: @fleablood Not only have I heard it, but I've also proved it here at least a handful of times (e.g. the analog for the prime $2$ when discussing proofs of irrationality of $\sqrt 2$).
Comment: @Gone Thanks for your suggestion !
Comment: Special case $(a,b)= 1$ of the [Lemma](https://math.stackexchange.com/a/1165413/242) in the linked dupe.
Answer: Setting $q=r/s$, this is equivalent to: if $(a,b)=1$ and $s\mid ra$ and $s\mid rb$, then $s\mid r$.
I doubt there is a specific significant first appearance of this lemma, but indeed it could have been proved by Euclid: write $1=ax+by$ for integers $x,y$, and then
$$
r=1r=(ax+by)r = (ra)x+(rb)y
$$
is a multiple of $s$.
While this proof uses the "Bezout identity" $(a,b)=ax+by$, which was apparently due to Bachet in the early 17th century, the Euclidean algorithm leads naturally to that statement, and thus one could algorithmically compute $r/s$ and know from Euclidean principles that the answer will be an integer.
Comment: Almost everything in elementary divisibility theory is equivalent to results on gcds and lcms. But that doesn't mean they were all discovered at the same time. Many things that are easily seen  to be equivalent nowadays were very difficult to see in older times due to lack of modern theory.


When to prefer the moment generating function to the characteristic function?

Question: Let $(\Omega, \mathcal{F}, P)$ be a probability space, and let $X : \Omega \to \mathbb{R}^n$ be a random vector. Let $P_X = X_* P$ be the distribution of $X$, a Borel measure on $\mathbb{R}^n$.

The characteristic function of $X$ is the function
$$
\varphi_X(t) = E[e^{i t \cdot X}] = \int_\Omega e^{i t \cdot X} \, dP,
$$
defined for $t \in \mathbb{R}^n$ (the random variable $e^{i t \cdot X}$ is bounded hence in $L^1(P)$ for all $t$). This is the Fourier transform of $P_X$.
The moment generating function (m.g.f.) of $X$ is the function
$$
M_X(t)
= E[e^{t \cdot X}] = \int_\Omega e^{t \cdot X} \, dP,
$$
defined for all $t \in \mathbb{R}^n$ for which the integral above exists. This is the Laplace transform of $P_X$.

Already, we can see that the characteristic function is defined everywhere on $\mathbb{R}^n$, but the m.g.f. has a domain that depends on $X$, and this domain might be just $\{0\}$ (this happens, for example, for a Cauchy-distributed random variable).
Despite this, characteristic functions and m.g.f.'s share many properties, for example:

If $X_1, \ldots, X_n$ are independent, then
$$
\varphi_{X_1 + \cdots + X_n}(t) = \varphi_{X_1}(t) \cdots \varphi_{X_n}(t)
$$
for all $t$, and
$$
M_{X_1 + \cdots + X_n}(t) = M_{X_1}(t) \cdots M_{X_n}(t)
$$
for all $t$ for which the m.g.f.'s exist.
Two random vectors $X$ and $Y$ have the same distribution if and only if $\varphi_X(t) = \varphi_Y(t)$ for all $t$. The m.g.f. analog of this result is that if $M_X(t) = M_Y(t)$ for all $t$ in some neighborhood of $0$, then $X$ and $Y$ have the same distribution.
Characteristic functions and m.g.f.'s of common distributions often have similar forms. For example, if $X \sim N_n(\mu, \Sigma)$ ($n$-dimensional normal with mean $\mu$ and covariance matrix $\Sigma$), then
$$
\varphi_X(t) = \exp\left(i \mu\cdot t - \frac{1}{2} t \cdot (\Sigma t)\right)
$$
and
$$
M_X(t) = \exp\left(\mu\cdot t - \frac{1}{2} t \cdot (\Sigma t)\right).
$$
When some mild assumptions hold, both the characteristic function and the m.g.f. can be differentiated to compute moments.
Lévy's continuity theorem gives a criterion for determining when a sequence of random variables converges in distribution to another random variable using the convergence of the corresponding characteristic functions. There is a corresponding theorem for m.g.f.'s (Curtiss 1942, Theorem 3).

Given that characteristic functions and m.g.f.'s are often used for the same purpose and the fact that a characteristic function always exists whereas a m.g.f. doesn't always exist, it seems to me that one should often prefer to work with characteristic functions over m.g.f.'s.

Questions.

What are some examples where m.g.f.'s are more useful than characteristic functions?
What can one do with an m.g.f. that one cannot do with a characteristic function?
Comment: Isn't the key to this question the word "introductory" near the very end?  Would it make any pedagogical sense to introduce anything involving the analysis of complex numbers into a course that presumes only minimal exposure to (and no comfort with) elementary Calculus and often even not that?
Comment: @whuber That was something I thought about as well, but I don't want my question to be about pedagogy, so maybe I should remove the last paragraph
Comment: A partial answer is here:  https://stats.stackexchange.com/questions/304066/real-life-uses-of-moment-generating-functions/304069#304069
Answer: That's a good question, but a broad one, so I can't promise I'll say everything about it that should be said. The short answer is that rival techniques differ not in what they can do, but in how neatly they can do it.
Characteristic functions require extra caution because of the role of complex numbers. It's not even that the student needs to know about complex numbers; it's that the calculus involved has subtle pitfalls. For example, I can get a Normal distribution's MGF just by completing the square in a variable-shifting substitution, but a lot of sources carelessly pretend the approach using characteristic functions is just as easy. It isn't, because the famous normalisation of the Gaussian integral says nothing about integration on $ic+\mathbb{R}$ with $c\in\mathbb{R}\backslash\{ 0\}$. Oh, we can still evaluate the integral if we're careful with contours, and in fact there's an even easier approach, in which we show by integrating by parts that an $N(0,\,1)$ distribution's characteristic function $\phi (t)$ satisfies $\dot{\phi}=-t\phi$. But the MGF approach is even simpler, and most of the distributions students need early on have a convergent MGF on either a line segment (e.g. Laplace) or half-line (e.g. Gamma, geometric, negative binomial), or the whole of $\mathbb{R}$ (e.g. Beta, binomial, Poisson, Normal). Either way, that's enough to study moments.
I don't think there's anything you can do only with the MGF, but you use what's easiest for the task at hand. Here's one for you: what's the easiest way to compute the moments of a Poisson distribution? I'd argue it's to use a different technique again, the probability-generating function $G(t)=\mathbb{E}t^X=\exp \lambda (t-1)$. Then the falling Pochhammer symbol $(X)_k$ gives $\mathbb{E}(X)_k=G^{(k)}(1)=\lambda^k$. In general it's usually worth using the PGF for discrete distributions, the MGF for continuous distributions that either are bounded or have superexponential decay in the PDF's tails, and the characteristic function when you really need it.
And depending on the question you're asking, you may instead find it prudent to use the cumulant generating function, be it defined as the logarithm of the MGF or CF. For example, I'll leave it as an exercise that the log-MGF definition of cumulants for the maximum of $n$ $\operatorname{Exp}(1)$ iids gives $\kappa_m=(m-1)!\sum_{k=1}^n k^{-m}$, which provides a much easier computation of the mean and variance (respectively $\kappa_1$ and $\kappa_2$) than if you'd written them in terms of moments.
Comment: I don't understand your remark about "integration on $ic+\mathbb R,$" because afaik the cf is defined as an integral of a complex-valued function on $\mathbb R.$  It doesn't have to be viewed as a contour integral.  For those uncomfortable with complex numbers it can viewed as a pair of real integrals anyway.  It's unclear how the mgf is "simpler" in any respect.  Indeed, the cf is simpler in the sense that one doesn't have to worry about convergence.
Comment: @whuber What i mean is $\int_{\Bbb R}\frac{1}{\sqrt{2\pi}}\exp (-\frac{x^2}{2}+itx)dx=\int_{-it+\Bbb R}\frac{1}{\sqrt{2\pi}}\exp (-\frac{y^2}{2}-\frac{t^2}{2})dt$.
Comment: Would you mind elaborating a little on why it does not?  I see nothing problematic in this particular case; and in general, because the original integral over $\mathbb R$ is convergent, one would not expect any problems with substitutions of this sort.
Comment: I suspected as much.  But isn't that just an artifact of how one might choose to evaluate the integral, rather than being any inherent feature of the cf itself?
Comment: @whuber The trouble is a lot of sources pretend the substitution works as straightforwardly as in the MGF case, which it doesn't.
Comment: @whuber The problem comes when people state, without justification, that the integral is $\int_{\Bbb R}\frac{1}{\sqrt{2\pi}}\exp(-\frac{y^2}{2}-\frac{t^2}{2})dt$. Some sources don't even show the integral over a line in $\Bbb C$ as an intermediate in the equation, giving a false impression - to which many students can succumb, often on their own - that this substitution, like the usual one for the MGF, preserves the integration range or might as well do.
Comment: Thank you.  Although I haven't encountered that error before, I can see how it can occur.  Your point seems to be that people might more easily make mistakes in working with complex numbers than with real numbers, suggesting the issue you are addressing is primarily psychological rather than mathematical.  If that's not the impression you intended to leave, then you might consider clarifying the argument.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/84709/discussion-between-j-g-and-whuber).
Answer: If your random variable has all of its moments, then the MGF exists, and is generally at least as useful as the characteristic function for proofs.
To answer your question, when the MGF exists, it provides the basis for many extreme-value calculations related to $X$. The simplest of which is (for $t\geq 0$),
$$P(X>r)=P(e^{tX}>e^{tr})\leq M_X(t)/e^{tr}.$$
Here, the r.h.s. can now be minimized over $t$. Strangely, this bound is one of the few simple ways we know of to get estimates on rare events. The general area of this is Large Deviations Theory, where one must do a ton of work to obtain better (tighter) bounds. A common example of this is looking at $S_n=X_1+\cdots + X_n$, so that when the MGF of $X_1$ exists,
then one can show $P(|S_n-E[X]|>nr)$ decays exponentially in $n$. This is more generally known as Cramer's Theorem.
Here are some compact notes on this.
Comment: Everything in your first paragraph is already mentioned in the question except the last sentence, which I think is false. For example, all moments of the log-normal distribution exist, but its m.g.f. is undefined for any positive real number. The second part of your answer is very useful because it highlights an application of m.g.f.'s that apparently has no characteristic function analog


How to put values from ArrayList in certain ranges?

Question: Is it possible to put values from my ArrayList into a specific ranges?
My ArrayList contains doubles:
0.4987873968412172
0.49949149542775684
0.4995227496071881
0.4999386804321369
0.500520813392628
0.5005912302221284
0.5006590304457654
0.5009476185730563
0.5013192031470984

And I want to divide them into (for example) two ranges to get an output:
Numbers from 0.498 to 0.499
0.4987873968412172
0.49949149542775684
0.4995227496071881
0.4999386804321369

Numbers from 0.500 to 0.501
0.500520813392628
0.5005912302221284
0.5006590304457654
0.5009476185730563
0.5013192031470984

Comment: What problem, use HashMap or List and divide to two ranges in for?
Answer: List<Integer> range1 = new ArrayList<>();
List<Integer> range2 = new ArrayList<>();
for(Integer i: myArrayList)
  if(i < 0.5) range1.add(i);
  else range2.add(i);

Comment: Thank You, that solved my problem.
Answer: Yes, use if and else
if (number > 0.498 && number < 0.499) {
    firstArrayList.add(number);
}
else
{
    secondArrayList.add(number);
}

And if you have 3 (or more) ranges use else if
if (number > 0.498 && number < 0.499) {
    firstArrayList.add(number);
}
else if (number > 0.500 && number < 0.501)
{
    secondArrayList.add(number);
}
else
{
    thirdArrayList.add(number);
}


If the equation $2x+2y+z=n$ has $28$ solutions, find the possible values of $n$

Question:
Let $n$ be a positive integer. If the equation $2x+2y+z=n$ has $28$ solutions, find the possible values of $n$.

I tried taking $2x$ as $a$, and then $2y$ as $b$, and then finding the possibilities. However, I am not sure about the approach I've used.
A little hint would be appreciated.
$x$, $ y$ and $z$ belong to whole numbers.
Comment: I believe there are some extra conditions on $x$, $y$ and $z$ also, such as they are positive integers etc.
Comment: haha gotcha @AayushPaurana
Comment: @AayushPaurana First off, I'm not sure why there would be more than one $n$. Second, my approach seems to be generating results that show there are no possible values of *n*...
Comment: @AayushPaurana I got $n=17,18$ if the numbers are positive...
Comment: do you mean $n$ or $n!$ ?
Comment: Are they positive or whole?
Comment: My bad @AhmadBazzi. The exclamatory mark was out of sheer excitement!
Comment: @RushabhMehta, whole numbers
Comment: @RushabhMehta I'm eager to see you solution as well. Could you please post it?
Comment: When you say "whole numbers" what do you mean?
Answer: I assume that the equation $2x+2y+z=n$ has $28$ solutions when $x,y,z$ are positive integers.
Note that this is same as finding the powers of $t$ with coefficient $28$ in the following expansion.
$$(t^2+t^4+t^6+t^8+.......)^2(t+t^2+t^3+t^4+......)$$
$$\left(\dfrac{t^2}{1-t^2}\right)^2\times\dfrac{t}{1-t}=t^5\times\left(\dfrac{1}{1-t}\right)^3=t^5\times(1+t)^3\times\left(\dfrac{1}{1-t^2}\right)^3$$
$$=t^5(1+t)^3\left(\dbinom{2}{2}+\dbinom{3}{2}t^2+\dbinom{4}{2}t^4+\dbinom{5}{2}t^6+..........\right)$$
Note that the last part has the general term of $\dbinom{k}{2}t^{2k-4}$. Since $\dbinom{8}{2}=28$, the last part contains the term $28t^{12}$. So we have $28t^{17}+28t^{18}$
So, the value of $n$ can be either $17$ or $18$
Comment: You lost a square on $(t^2+t^4+t^6+t^8+\ldots)$  It is restored the next line
Answer: Assume $x,y,z$ are required to be positive integers.

Consider two cases . . .

Case $(1)$:$\;n$ is even.

From the equation $2x+2y+z=n$, it follows that $z$ is also even.

Writing $z=2w$, and $n=2m$, for some positive integers $w,m$, we get
\begin{align*}
&2x+2y+z=n\\[4pt]
\iff\;&2x+2y+2w=2m\\[4pt]
\iff\;&x+y+w=m\\[4pt]
\end{align*}
By the Stars-and-Bars formula, the equation
$$x+y+w=m$$
has exactly ${\large{\binom{m-1}{2}}}$ positive integer solution triples $(x,y,w)$, for any given positive integer value of $m$, hence
\begin{align*}
&{\small{\binom{m-1}{2}}}=28\\[4pt]
\implies\;\;&{\small{\frac{(m-1)(m-2)}{2}}}=28\\[4pt]
\implies\;\;&m^2-3m+2=56\\[4pt]
\implies\;\;&m^2-3m-54=0\\[4pt]
\implies\;\;&(m-9)(m+6)=0\\[4pt]
\implies\;\;&m=9\\[4pt]
\implies\;\;&n=18\\[4pt]
\end{align*}

Case $(2)$:$\;n$ is odd.

From the equation $2x+2y+z=n$, it follows that $z$ is also odd.

Writing $z=2w-1$, and $n=2m-1$, for some positive integers $w,m$, we get
\begin{align*}
&2x+2y+z=n\\[4pt]
\iff\;&2x+2y+(2w-1)=2m-1\\[4pt]
\iff\;&x+y+w=m\\[4pt]
\end{align*}
As for case $(1)$, since $m$ is a positive integer such that the equation
$$
x+y+w=m
\qquad\qquad
$$
has exactly $28$ positive integer solution triples $(x,y,w)$, it follows that $m=9$, hence $n=2m-1=17$.

Note:$\;$If $x,y,z$ are only required to be nonnegative integers, then using arguments analogous to the ones given above, we get $n=12$ or $n=11$.


Experiment design - response variable is a sum over a period, low power

Question: I would like to run a statistically rigorous experiment, similar to that of an E-commerce A/B test.
I want to create a checkerboard of time periods where I alternate between treatments A and B. Ultimately I care about increasing revenue.
I believe the treatment could affect any or all of the following:

number of visitors per period
percent of visitors who become customers
the revenue per customer
the types of customers and their spending profiles (e.g. big customers, small customers, customers interested in specific products spend different amounts)

Hence I feel that my ideal response is period revenue, i.e. the total revenue over the period of each treatment being in effect (so if I have 2 treatments with 10 periods each, I have 20 responses).
But since period revenue is really a sum over individual order revenues (which have large variance) and is affected by visitor frequency and customer/visitor ratio etc., I know that the period revenue will be quite noisy (variance of sum >= sum of variances, assume not negatively correlated). Therefore I'm worried about the power of my experiment and whether I will actually be able to find significance.
To address this, I see the following options:

Shorten the periods? If I want the whole experiment to take a fixed amount of time, like 2 weeks, I think this would give me more data points while reducing the variance of the response. But I'm not certain how to determine the ideal period length and determine how short is too short.
Replace period revenue as the response with one of the metrics from the list above with a reasonable variance / historical distribution. Downside e.g.: if we pick # of visitors as the response and find a significant effect, that may not mean revenue increased, maybe customer to visitor ratio decreased.
Run an analysis for each of the metrics above separately. Since running more comparisons and p-values, would need to correct the p-values with Bonferroni or similar. Downside e.g.: if revenue per customer increases but customers go down, it's not clear my revenue actually increased.
Build some sort of composite response variable. I feel like the revenue is already effectively a composite variable. Similarly, I'd expect summing/differencing these variables will result in more variance, not less variance, so I'm not sure my power would increase.

Which of the following approaches seem most reasonable? Am I missing some possible solutions? What  additional exploratory work should I do to determine my approach? Are there research papers involving similar types of experiments that I can reference (I'm struggling to find the right keywords to form an effective search)?
Thanks! Let me know if I can add any detail.
Answer: OK, here is my two cents based on your framing.
Variance is a factor, yes, but so is underdetermination of the effect.  You mention this in your second point (e.g. two metrics could change in such a way that they cancel one another out).
To combat this, here is some general advice:

Try to explain away as much variance as you can.  If your unit of randomization is the user, it makes sense to use features about the user which are related to their spend. One way to do this is to use CUPED/ANCOVA and create a variable for their spend prior to the experiment starting.

Your metric should be determined by the unit of randomization.  I don't think it makes sense to randomize users and then make revenue per day your metric of interest.  Your metric can be partly decided based on what the intervention is designed to do.  For example, do I think that a change on the landing page is going to effect behaviour at checkout?  Depends on how far down the funnel checkout is.

Revenue is a KPI that can be factored in a bunch of ways.  For example, revenue could be Revenue per converted user x conversion rate x number of users landing per day x number of days.  It is fine to Pick a primary metric in according to point two and then make all of the other metrics secondary metrics.  This can give you insight into what is driving the change, but can be hard to interpret in the language of frequentist inference because most people operate on a reject/fail to reject basis (e.g. why did revenue decrease, all my other metrics show no change p>0.05).  There is likely no need to adjust the p value here unless you think the number of users converting at one stage effects the conversion rate at the next stage.  E.g. Does conversion rate effect revenue per converted user?  No, those are likely independent.  People do not likely spend more just because more people are choosing to spend (except in some pathological cases like we saw with Covid and toilet paper, I think this probably doesn't apply to e-commerce but you can make that decision for yourself).
Comment: Thanks! I will look at CUPED/ANCOVA, looks very relevant. I am technically not working with E-Commerce but using it as an example. Thus I don't have the ability to randomize users, I think the only thing I can reliably randomize is blocks of time. Does that change your answer?
Comment: @wahsmail only slightly.  Techniques like "Randomized Block Designs" will be relevant. Your main metric might now be Revenue per day, and the block design will allow you to adjust for "Day of Week" type effects. You might be able to use "Last Week's revenue" as a possible tool for ANCOVA.


NSPersistentCloudKitContainer: Share a single database with App Extension

Question: I know this is a common question, maybe it is so many time asked before. Also I know how to share a single database with App Extensions using Core Data by enabling App Groups. I am now using the NSPersistentCloudKitContainer to sync the data (across iCloud devices), and works very well.
But I want to share my database with my App Extensions (Today Extension), at this time App Groups won't help anymore, because they are different technologies as Apple described. So I am simply enabled iCloud for both the container app and the app extension from Signing and Capabilities pane. Then I can access my single database from both app container/extension as shown below:
// MARK: - Core Data stack, Shared database
lazy var persistentContainer: NSPersistentCloudKitContainer = {
    let container = NSPersistentCloudKitContainer(name: "MyApp")

    // Spotlight search support and history tracking
    container.persistentStoreDescriptions.forEach {
        $0.setOption(CoreDataSpotlightSearchDelegate.init(forStoreWith: $0, model: container.managedObjectModel), forKey: NSCoreDataCoreSpotlightExporter)
        $0.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
    }

    // Load persistent store
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })

    container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    container.viewContext.automaticallyMergesChangesFromParent = true

    return container
}()

However it is only works when the device is online (which is expected behavior), so my question is:
Is it possible to share my database between app and extension while the device is offline using NSPersistentCloudKitContainer? Some workarounds?
EDIT
This is a non-working version, I can access the same database but without cloud-syncing (Not appears on the CloudKit Dashboard):
 // MARK: - Core Data stack, Shared database
lazy var persistentContainer: NSPersistentCloudKitContainer = {
    let container = NSPersistentCloudKitContainer(name: "MyApp")

    // Shared container support
    if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.company.MyApp")?.appendingPathComponent("MyApp.sqlite") {
        let persistentStoreDescription = NSPersistentStoreDescription.init(url: url)
        container.persistentStoreDescriptions = [persistentStoreDescription]
    }

    // Spotlight search support and history tracking
    container.persistentStoreDescriptions.forEach {
        $0.setOption(CoreDataSpotlightSearchDelegate.init(forStoreWith: $0, model: container.managedObjectModel), forKey: NSCoreDataCoreSpotlightExporter)
    }

    // Load persistent store
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })

    container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    container.viewContext.automaticallyMergesChangesFromParent = true

    return container
}()

Comment: Please clarify what you mean by offline. Obviously an offline device cannot sync with the cloud because that requires an internet connection.
Comment: @malhal Yes of course, won't sync as I mentioned above. So what I want to get? If the user made some changes from the container app while device is offline, I need to update the app extension (they're shows the same data). Unfortunately it is not working. 2) Shared database with App Groups: Works great without a cloud syncing. 3) ?
Comment: Sync means the device syncing with the cloud. It sounds to me like you are talking about the app and the extension sharing the same database?
Comment: @malhal Exactly! I need to share my database with the app extension.
Answer: To share a database between an app and extension you need to fully implement Persistent History Tracking; it is not as simple as enabling the store option. For an introduction to the feature see WWDC 2017 What's New in Core Data at 20:49 and also see the documentation Consuming Relevant Store Changes in particular "Merge Relevant Transactions into a Context".
My theory on why you weren't noticing a problem when using the NSPersistentCloudKitContainer is when your store was online and syncing with the cloud is you were benefiting of a side effect of the cloud sync  running in your app process and editing the store upon resuming which in turn caused your context to get updated.
And by the way, the NSPersistentHistoryTrackingKey option is set by default for NSPersistentCloudKitContainer's store descriptions that have cloudKitContainerOptions like the default first store description has.
Comment: Did anyone get this working without NSPersistentCloudKitContainer creating duplicates when two processes are trying to sync a common store?
Comment: Did you mean the `NSPersistentContainer`?
Comment: Sorry I meant subclass NSPersistentCloudKitContainer
Comment: I have edited the question, and what I have tried so far.
Comment: Ok I have a new idea but first I'd like to know if you are using the history tracking feature that is necessary to share between app and extension.
Comment: Yeah! History Tracking is set to `true`
Comment: Ok but are you fetching history and merging it in?
Comment: But I can't, how to implement? So I need to fetch a history and merge it with the context (from app extension)? Can you show some example? Thank you very much!
Comment: sample is here https://developer.apple.com/documentation/coredata/consuming_relevant_store_changes
Comment: Yes, I did. You have to deduplicate them before you merge the object back to the main context. Here's an example: https://developer.apple.com/documentation/coredata/synchronizing_a_local_store_to_the_cloud take a look at `CoreDataStack.swift`


MySQL getting stuck, eating up disk i/o

Question: Using mySQL 5.0.51 on Solaris .
At intermittent times it looks like MySQL is getting 'stuck' . The disk usage on the server spikes to 98% busy from reads. I used dtrace (specifically DTrace toolkit - iosnoop)  to track down what processes was using all the reads. Mysql was calling tablename.TDM hundreds of times per second. There was no more than average load on the webserver that could account for this. There were no cronjobs running, and no other utilities like mysqldump or anything. It is a master / slave replication setup.
As a jury-rigged fix, I altered the mysql table from 'tablename' to 'tablename2' and then back to 'tablename'
This fixed the problem temporarily, and "unsticks" mysql. The disk usage goes back down and dtrace is no longer showing hundreds of reads to 'tablename.TDM' / second.
A couple ideas I had are:
1. MySQL version bug
2. Infinite loop somewhere in my application (which i'm not sure how likely this is)
3. ??

Has anybody seen this before or have any insight?
Thanks
Comment: Have you checked your slow query log?  Is it enabled?
Comment: Didn't have it enabled, will enable it tonight during slow hours
Answer: Uh, renaming tables randomly is a horrible idea.
Look at the MySQL process list to determine what processes are loading the system. Use:
show full processlist;
There's also utilities like mytop and mtop that are handy.
Edit 1
Isolating is going to depend on your environment.  Where are the connections from?
If localhost can it only be a system script or do you have an application being served from your DB?
If remote host, what function does that remote host serve?  Is it different from others?  Does it have scripts or is it only an application?
It should be fairly quick and simple to isolate the source but not necessarily the cause.
Comment: def. agree with not renaming tables, but had to do something.

will get mytop. Thanks
Comment: Connecting from DB server so essential localhost, i also have to webservers attached to the db server, which are running mysql connections and apache.

but i'm doing my debugging right from the db server itself. as a side note the table in question has 600,000 records, which i think mysql should be able to handle, but maybe this is an issue
Comment: That makes it more difficult to isolate from a connection perspective.  If you're running unoptimized queries against an improperly indexed table, it's definitely plausible that is the source of the problem.  Zoredache provided a good recommendation as well.

MySQL getting stuck, eating up disk i/o


when using event.target it works on website but on code has error

Question: With javascript I check if the user clicks inside 2 divs with event.target, it works but in code it gives this error message:
Argument of type 'EventTarget | null' is not assignable to parameter of type 'Node | null'.
  Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 44 more.Vetur(2345)
cogsClose() {
    if (
      !document.querySelector(".cogs-window")!.contains(event.target)! &&
      !document.querySelector(".fa-cogs")!.contains(event.target)
    ) {
      document.getElementById("cogs-user")!.classList.add("cogs-hide");
      document.getElementById("cogs-tabs")!.classList.add("cogs-hide");
    }
  }

The error shows on both of the event.target.
Comment: Why put '!' anywhere ???
Answer: Let's check what lib.dom.d.ts says abut that. So the contains functions signature looks like this:
contains(other: Node | null): boolean;

and typing for mouseEvent's property target is
readonly target: EventTarget | null;

EventTarget is not compatible type with Node. This is because target don't have to be always Node type as is mention in doc.
But if you are sure about the typing then u can just cast that right to Node or HTMLElement or something like that.
.contains(<Node>(event!.target))

But be careful about that.. Types are here to protect us so signature looks like this for some reason. Same for using ! everywhere..
Answer: It worked for me
.contains(event.target as Node)


Nina Simone "Love me or Leave me" and Bach

Question: When listening to Nina Simone's version of "Love me or Leave me" (this version), I have a feeling that she incorporates some classical music into her solo (around 1 minute to 2:20) - googling I found some references claiming she put Bach parts in it. E.g., this source claims she puts Bach's Fugue in C Major (on the version given there). I was wondering if there are actually parts of Bach music or its just "in the style of Bach". If there is a part of Bach, can someone refer me to the exact piece and to what part of the piece? Thanks in advance.
Answer: She's certainly channelling Bach (until the final cadence when she slips in a bit of Beethoven!)   I'm hearing generic passage work in Bach's style rather than any specific quotes.  It's not fully worked-out counterpoint, but there's plenty of interesting melodic conntent in the left hand.
I wonder if she had the musical resources to actually work a fugue on 'Love me or leave me?'   Not that I'm suggesting one would have improved this wonderful performance!


Correlation coefficient for a uniform distribution on an ellipse

Question: I am currently reading a paper that claims that the correlation coefficient for a uniform distribution on the interior of an ellipse
$$f_{X,Y} (x,y) = \begin{cases}\text{constant} & \text{if} \ (x,y) \ \text{inside the ellipse} \\  0 & \text{otherwise}  \end{cases}$$
is given by
$$\rho = \sqrt{1- \left(\frac{h}{H}\right)^2 }$$
where $h$ and $H$ are the vertical heights at the center and at the extremes respectively.

The author does not reveal how he reaches that and instead only says that we need to change scales, rotate, translate and of course integrate. I would very much like to retrace his steps but I am a bit lost with all that. I would therefore be grateful for some hints.
Thank you in advance.
Oh and for the record

Châtillon, Guy. "The balloon rules for a rough estimate of the correlation coefficient." The American Statistician 38.1 (1984): 58-60

It's quite amusing.
Comment: Could you write down an expression for the ellipse? The _"height at the extreme"_ doesn't make sense for a standard ellipse: $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ since it has height $0$ at the extremes. Indeed, if $(X,Y)$ is uniformly distributed on the interior of the standard ellipse, then $\rho = 0$.
Comment: The entire operation appears fundamentally mistaken.  The "change scales" part destroys the uniformity.  A truly uniform distribution is achieved either as the limiting distribution within narrow (Euclidean) buffers of the curve or is uniform by arclength. In either case the normalizing constant is a complete elliptic function and won't possibly simplify to the expression given here. I'm not sure what $h$ and $H$ mean, but--as an example--the correlation coefficient for an ellipse with a major axis twice the minor axis, tilted at an angle of $\pi/6$, will be $0.78004$.
Comment: If you would like a full, complete answer, then you will find it in my post at http://stats.stackexchange.com/a/71303/919.  After all, when the ellipse is a circle the uniform is (obviously) circularly symmetric, so just about everything in that answer applies directly.  In particular, by viewing the ellipse not as a rotation of a horizontal ellipse, but as a *skew transformation,* the formula for $\rho$ becomes obvious, because $\sqrt{1-\rho^2}=\lambda = h/H$ (using the notation in the section on "How to Create Ellipses").
Comment: @DilipSarwate Yeah, I tried the standard case and computed $\rho = 0$, no problems there. What about the other cases though, where you need to scale, rotate etc?
Comment: @whuber I have included a figure from the paper that explains what $h$ and $H$ stand for, I hope that this makes it clearer.
Comment: The picture helps immensely: not only does it show what $h$ and $H$ are, it shows that the distribution is *not* over the ellipse, but over its *interior*!  (The ellipse, by definition, is the curve.)
Comment: @whuber I apologise for the misunderstanding.
Comment: @whuber Wow! I wish I had read your answer to the other question before spending so much time on my own answer to this question. Thanks for the learning experience.
Answer: Let $(X,Y)$ be uniformly distributed on the interior of the ellipse
$$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ where $a$ and $b$ are the
semi-axes of the ellipse.  Then, $X$ and $Y$ have marginal densities
\begin{align}
f_X(x) &= \frac{2}{\pi a^2}\sqrt{a^2-x^2}\,\,\mathbf 1_{-a,a}(x),\\
f_X(x) &= \frac{2}{\pi b^2}\sqrt{b^2-y^2}\,\,\mathbf 1_{-b,b}(y),
\end{align}
and it is easy to see that $E[X] = E[Y] = 0$.  Also,
\begin{align}
\sigma_X^2 = E[X^2] &= \frac{2}{\pi a^2}\int_a^a x^2\sqrt{a^2-x^2}\,\mathrm dx\\
&= \frac{4}{\pi a^2}\int_0^a x^2\sqrt{a^2-x^2}\,\mathrm dx\\
&= \frac{4}{\pi a^2}\times a^4 \frac 12\frac{\Gamma(3/2)\Gamma(3/2)}{\Gamma(3)}\\
&= \frac{a^2}{4},
\end{align}
and similarly, $\sigma_Y^2 = \frac{b^2}{4}$. Finally,
$X$ and $Y$ are uncorrelated random variables.
Let \begin{align}
U &= X\cos \theta - Y \sin \theta\\
V &= X\sin \theta + Y \cos \theta
\end{align}
which is a rotation transformation applied to $(X,Y)$. Then,
$(U,V)$ are uniformly distributed on the interior of an
ellipse whose axes do not coincide with the $u$ and $v$ axes.
But, it is easy to verify that $U$ and $V$ are zero-mean
random variables and that their variances are
\begin{align}
\sigma_U^2 &= \frac{a^2\cos^2\theta + b^2\sin^2\theta}{4}\\
\sigma_V^2 &= \frac{a^2\sin^2\theta + b^2\cos^2\theta}{4}
\end{align}
Furthermore,
$$\operatorname{cov}(U,V) = (\sigma_X^2-\sigma_Y^2)\sin\theta\cos\theta
= \frac{a^2-b^2}{8}\sin 2\theta$$
from which we can get the value of $\rho_{U,V}$.
Now, the ellipse on whose interior $(U,V)$ is uniformly distributed
has equation
$$\frac{(u \cos\theta + v\sin \theta)^2}{a^2}
+ \frac{(-u \sin\theta + v\cos \theta)^2}{b^2} = 1,$$
that is,
$$\left(\frac{\cos^2\theta}{a^2} + \frac{\sin^2\theta}{b^2}\right) u^2  + \left(\frac{\sin^2\theta}{a^2} + \frac{\cos^2\theta}{b^2}\right) v^2
+ \left(\left(\frac{1}{a^2} - \frac{1}{b^2}\right)\sin 2\theta \right)uv = 1,$$
which can also be expressed as
$$\sigma_V^2\cdot u^2 + \sigma_U^2\cdot v^2
-2\rho_{U,V}\sigma_U\sigma_V\cdot uv = \frac{a^2b^2}{4}\tag{1}$$
Setting $u = 0$ in $(1)$ gives
$\displaystyle h  = \frac{ab}{\sigma_U}$.
while implicit differentiation of $(1)$ with respect to $u$ gives
$$\sigma_V^2\cdot 2u + \sigma_U^2\cdot 2v\frac{\mathrm dv}{\mathrm du}
-2\rho_{U,V}\sigma_U\sigma_V\cdot
\left(v + u\frac{\mathrm dv}{\mathrm du}\right) = 0,$$
that is, the tangent to the ellipse $(1)$ is horizontal at
the two points $(u,v)$ on the ellipse for which
$$\rho_{U,V}\sigma_U\cdot v = \sigma_v\cdot u.$$
The value of $H$ can be figured out from this, and will (in the
unlikely event that I have made no mistakes in doing the
above calculations) lead to the desired result.
Comment: That is a proper orthogonal rotation matrix, thank you.


WinPE diskpart can't attach vdisk

Question: I created WinPE 3.0 and didn't modify it in any way. I want to attach a vdisk (.vhd file) while running WinPE but I can't attach it, no error is shown, no indication that diskpart didn't attach it, it just doesn't happen.
These are the steps that I followed:

WinPE booted
(i typed the following)
diskpart
select vdisk file=e:\myfile.vhd
attach vdisk

The only thing that happens is the help is shown.
The file is in place, I checked a couple of times, diskpart doesn't give anything useful.
Comment: Does `list vol` inside `diskpart` show the virtual disk?
Answer: You need to assign as well in diskpart otherwise it will be mounted but not have a drive letter.
http://blogs.msdn.com/b/7/archive/2009/10/08/diskpart-exe-and-managing-virtual-hard-disks-vhds-in-windows-7.aspx
Comment: i know that i need to assign it, but when i type "select vdisk" it doesn't say an error or drive selected it prints out the help for select (like i typed "select /?"), when i type attach vdisk the same typing it prints out the help without any error...
Comment: I was able to succesfully do it with the commands listed above.

However, I had to move the VHD to a local fixed disk otherwise I was getting "requested operation could not be completed due to a file system limitation"

Try moving the vhd to a fixed disk location and if it works there, start trying other places.
Comment: Did you get it to work?
Answer: It looks like you have forgotten the quotes on both sides of the filename try that and see if that works for you should look like this
SELECT VDISK FILE="C:\Example\Exam22.vhd". Do not forget to use quotes on both sides of the complete path.  And when you attach it using the [attach
 Vdisk file name=<"xxxxx">]

WinPE diskpart can't attach vdisk


How to check NSXmlParser finished parsing?

Question: In my project I am consuming web services and parsing data from web services in another class and showing this data in a tableView it works absolutely fine in synchronously but
I have tried to implement it a asynchronously and it is not showing data although data has been received as it is showing on Console when I restart the app on simulator it will show if I wait it until to show on console is there any way to check data is available to show on tableView so as I can reload tableview to display data
Comment: R u using NSXMLParserDelegate in your class??
Comment: You should accept some of your questions as answers if you want folks to continue to help ...
Answer: If you use the NSXMLParserDelegate in your class you can find it out through the following delegate method
<code>//Called when the XML document has been finished parsing
    - (void)parserDidEndDocument:(NSXMLParser *)parser
    {

    }
</code>


List Proper Primitive Groups of a certain degree by GAP

Question: As J.D.Dixon noted in his great books, there are just 5 proper primitive groups of degree 8, $P(8)=5$. I wanted to examine it with GAP, so wrote the following small program:

> G:=[];;
> for k in [1..7] do G[k]:=PrimitiveGroup( 8,k ); od;
> G[1]; G[2]; G[3]; G[4];  G[5];  G[6];  G[7];

Clearly, since $S_8$ and $A_8$ are not proper, so it works as we want. My question is how to "List all groups", for example as I called them above without writing the third line of the program? I examined some List commend line in the GAP, and could't list the groups not in the form I did above ( G[1]; G[2]; G[3]; G[4];  G[5];  G[6];  G[7]; ). Thanks for any help.
Comment: I'm not sure I understand your question... do you ask for a GAP command to display a list?
If that is the case: As far as I know, there is no possibility to display arbitrary lists in a readable format. In your case, however, the following should work fine:

`n := 8;; List( [1..NrPrimitiveGroups(n)], i -> PrimitiveGroup(n,i) );`
Comment: Also, I just noticed that `AllPrimitiveGroups(NrMovedPoints,[8])` yields identical output. Moreover, to use GAP libraries efficiently, you may want to learn about [selection functions](http://www.gap-system.org/Manuals/doc/htm/ref/CHAP048.htm#SECT005).
Comment: @BabakS.: yes, GAP will easily handle computations described at http://math.stackexchange.com/questions/370476/let-g-gl2-mathbbz-5-mathbbz-the-general-linear-group-of-2-times-2. It is also easy to guess the names of functions to use.
Comment: @m_l: Thanks for the help. You kindly gave me what I should to know. Thanks again.
Comment: @AlexanderKonovalov: Thanks for the edit. May I ask you a question about GAP?
Comment: @BabakS.: yes, sure - just here or by email, please.
Comment: @AlexanderKonovalov: How can I command GAP to write a*b as ab while I am working on a free group. In fact this makes my output so easy to study. Thanks.
Comment: What about `Print(ReplacedString(String(a*b),"*",""),"\n")` ? Note, however, that `a*b` **IS** the output which may be correctly parsed back by GAP, while `ab` is not - for example, what if `ab` is already a name of another global variable?
Comment: @m_l: Thanks for sharing the link about selection functions, but  it points to the old GAP 4.4.12 manual and does not work any more. Apparently the new link should point [here](http://www.gap-system.org/Manuals/doc/ref/chap50.html#X81B00B667D2BD022). This is why it's more reliable to advice to type in GAP e.g. `?SmallGroup` to invoke the documentation from the GAP command line (`SetHelpViewer` may be configured to open the HTML version of the manual in a browser instead of showing the text version directly in the GAP session).
Comment: @AlexanderKonovalov: Are you online?
Comment: @AlexanderKonovalov: What about using GAP for this one? http://math.stackexchange.com/q/370476/8581. Thanks for your time. You are very Welcome to me, friend.
Comment: @AlexanderKonovalov: Thanks friend for the edit.
Answer: Thanks to m_l, this has been answered in the comments. I'm posting a formal answer in order to clean up unanswered questions with the gap tag in view of "http://meta.math.stackexchange.com/questions/1559/dealing-with-answers-in-comments?" discussion on Meta.
I will try to cover a bit wider topic for a reader who will discover this page in a search for an answer on a similar question. GAP contains several Data Libraries listed on this page. In GAP 4.6, Group Libraries are covered in Chapter 50 of the Reference Manual (chapter numbering may change in future versions), and this includes the Small Groups Library, Primitive and Transtive Permutation Groups libraries, and more. From the GAP command line this chapter may be viewed by entering ?Group Libraries. Look there for functions like AllLibraryGroups and OneLibraryGroup, where "Library" denotes the appropriate library.


is Cov(X) and Var(X) same? when X is random vector

Question: i'm studying with hogg. introduction to mathematical statistics.
and i learned about random vector
but i wonder whether Cov(X) and Var(X) is same or not.
as intuitive thinking , if X is a random vector , say, X = (X$_1$, X$_2$, X$_3$, $...$ , X$_n$)$^t$
i just thought Cov(X) ( written as in text book) can be written as Var(X)
Is writing Var(X) wrong when X is a random vector or is there another meaning different from Cov(X)?
Comment: How does the text box write it?  We do not all have a copy.
Answer: Both "Cov" and "Var" are used to represent the covariance matrix of the vector $\bf X$. See for example this Wikipedia remark:

Nomenclatures differ. Some statisticians, following the probabilist William Feller, call the matrix $\Sigma$ the variance of the random vector X, because it is the natural generalization to higher dimensions of the 1-dimensional variance. Others call it the covariance matrix, because it is the matrix of covariances between the scalar components of the vector X.