Multivariable chain rule on quadratic cost function

Question: Consider the quadratic cost function
$$
J(U) = \tfrac{1}{2}U^HAU+U^HBa-2U^HC b,
$$
where $U\in\ \mathbb{C}^{81}$ is the vector of decision variables and the other matrices ($a$, $b$ are vectors) are constant and of appropriate dimension. This is basically a quadratic cost function. I want to optimize this in MATLAB and provide its gradient $\nabla J_U$. So, if i am not mistaken
$$
\nabla J_U=AU+a^HB^H-2b^HC^H,
$$
note that $A$ is an hermitian matrix. The main issue is that $U$ is an intermediate variable, namely
$$
U =  \text{vec}\ \overline{q}q^\top,
$$
where $\overline{(\cdot)}$ denotes the conjugate, $(\cdot)^H$ the conjugate transpose and $(\cdot)^\top$ the non-conjugate transpose. Furthermore, $U\in\mathbb{C}^{9}$. The gradient $\nabla U_{q_1, \dots, q_9}$ is rather cumbersome, but calculable. My question is, how to connect these results with each other? I am not very good at vector calculus but it is obvious that i require the chain-rule here. But i am not certain how to apply it here.
EDIT
Let me give you the origin of the equation. I start with
$$
\begin{bmatrix}q^HE_1q\\ \vdots \\ q^hE_nq\end{bmatrix}=\begin{bmatrix}\text{vec}\ (E_1)^\top\\ \vdots \\ \text{vec}\ (E_n)^\top\ \end{bmatrix}\text{vec}\ (\overline{q}q^\top)=\Gamma u
$$
$E_i$ is hermitian, hence the left term will always be real. In my scenario, you can never arbitrarily multiply $u$ with a complex scalar, because $u$ follows from $q$.
Answer: For convenience, define the vectors
$$\eqalign{
b &= Ba,\qquad c=-2Cb \\
y &= \tfrac{1}{2}Au,\,\quad v = y+b+c \\
}$$
and the matrix
$$\eqalign{
V &= {\rm Reshape}(v,9,9) \quad\implies\quad v = {\rm vec}(V) \\
Y &= {\rm Reshape}(y,9,9) \quad\implies\quad y = {\rm vec}(Y) \\
}$$
Let's use a colon to denote the trace/Frobenius product, i.e.
$$\eqalign{
&A:B = {\rm Tr}(A^TB) = {\rm Tr}(B^TA)=B:A \\
&A:BC = B^TA:C = AC^T:B = etc \\
}$$
Then your cost function can be written as
$$\eqalign{
J &= y^Hu + b^Hu + c^Hu \\
  &= (y+b+c)^*:u \\
  &= v^*:u \\
}$$
Calculate the differential of $J$
$$\eqalign{
dJ &= v^*:du + u:dv^* \\
  &= v^*:du + u:\left(\tfrac{1}{2}A^*du^*\right) \\
  &= v^*:du + y:du^* \\
}$$
Next, utilize the relationship with $q$
$$\eqalign{
u &= {\rm vec}(q^*q^T) \\
du &= {\rm vec}(q^*dq^T+dq^*q^T) \\
du^* &= {\rm vec}(q\,dq^H+dq\,q^H) \\
}$$
Substitute this into the differential expression, then calculate the gradient
$$\eqalign{
dJ &= v^*:du + y:du^* \\
 &= {\rm vec}(V^*):{\rm vec}(q^*dq^T+dq^*q^T)
 + {\rm vec}(Y):{\rm vec}(q\,dq^H+dq\,q^H) \\
 &= V^*:\left(q^*dq^T+dq^*q^T\right) + Y:\left(q\,dq^H+dq\,q^H\right) \\
 &= \left(V^H:dq\,q^H + V^*:dq^*q^T\right)
  + \left(Y^T:dq^*q^T + Y:dq\,q^H\right) \\
&= \left(V^Hq^*:dq + V^*q:dq^*\right) + \left(Y^Tq:dq^* + Yq^*:dq\right)\\
&= \left(V^Hq^*+Yq^*\right):dq + \left(V^*q+Y^Tq\right):dq^* \\
\frac{\partial J}{\partial q} &= V^Hq^* + Yq^*, \qquad
\frac{\partial J}{\partial q^*}= V^*q + Y^Tq \\
}$$
Since $J$ is real, these results implies that $(V,Y)$ are hermitian.
Some comments asked about how the trace/Frobenius product
behaves with vectors.
$$\eqalign{
{\rm Tr}(y^TAx) &= {\rm Tr}((Ax)^Ty)
 &= {\rm Tr}((yx^T)^TA) &= {\rm Tr}(A(yx^T)^T) &= etc \\
y:Ax &= Ax:y &= yx^T:A &= A:yx^T &= etc \\\\
}$$
Update
The Frobenius Inner Product described on Wikipedia is defined as
$$\langle A,B\rangle = {\rm Tr}(A^HB)$$
and is different from the product used in this answer which is
$$A:B={\rm Tr}(A^TB)$$
The colon product has the following extremely useful properties
$$\eqalign{
A:B &= B:A \qquad&\big({\rm commutes\,with\,itself}\big) \\
A:B\odot C &= A\odot B:C \qquad&\big({\rm commutes\,with\,Hadamard}\big) \\
}$$
which hold even when the matrices involved are complex.
The Wikipedia product satisfies neither property.
I find the fact that
$\langle A,B\rangle \ne \langle B,A\rangle$
and trying to remember which matrix gets conjugated to be
a perpetual source of errors.
The only nice property of the Wikipedia product is
$$\|A\|_F^2 = \langle A,A\rangle$$
but this only fractionally more succinct than
$$\|A\|_F^2 = A^*:A$$
Comment: Wow, thanks so much. I have made one mistake though; the matrices $A$ and $B$ are defined as $A=\Gamma^H\Omega\Gamma$ and $B=2\Gamma^H\Omega\Phi$. The multiplication $U\Gamma$ by definition results in a real number; hence the cost function is a real number. On top of that $u$ is defined as $u=\text{vec}(\overline{q}q^\top)$ and not $u=\text{vec}(qq^\top)$. Using $(\cdot)^H$ explicitly instead of $(\cdot)^\top$ is not needed, apologies.
Comment: It doesn't matter what pedigree you give to the $B$ matrix. If you select its value such that $u^HBa$ is real, then I can change the vector **variable** to $u^H=\alpha u^H$ where $\alpha$ is an arbitrary _complex_ scalar. The value $\alpha u^HBa$ will no longer be real.  The quadratic term is fundamentally different, since it contains the product of $\alpha$ with its complex conjugate, so it remains real.
Comment: Ive editted the question to show where the equation comes from and why (i believe) the term is real. Anyways, when $u=\text{vec}\ (\overline{q}q^\top)$, i lose what to do in the last steps. $qdq^\top + dqq^\top$ is just the product rule right? And $d\text{vec}\  X=\text{vec}\ dX$?
Comment: Could you also maybe elaborate on how $d\tfrac{1}{2}Au:u=Au:du$? I am not entirely following that.
Comment: And how do you go from $(V+V^\top):(dq\ q^\top)$ to $(V+V^\top)q:dq$? I cannot find one property of the trace that can be used. Since $dq$ and $q$ are vectors, you cannot use the cyclic property (as it only holds for square matrices). Any property that i try to use, results in $dq^\top$
Comment: Thanks for updating the question. Now I understand that $u$ is not a free vector of parameters but is subject to a complicated constrained. I have updated my answer under the assumption that $J$ is real.
Comment: You sir are amazing, thank you so much !
Comment: @user2501247 Kindly accept his answer as well ;)
Comment: Hm @greg is your derivation entirely correct? With complex matrices, according to Wikipedia $A:B=\text{tr}(A^HB)$, while you claim that $A:B=\text{tr}(A^\top B)$, which would yield different results i believe. Subsequently, i am also not sure that $Y:dq q^H=Yq^*:dq$. Also, i am not sure, while providing the gradient to the optimizer, what to do with $\frac{\partial J}{\partial dq^*}$, but that is a different question.
Comment: I've updated the answer to address the Wikipedia definition. Also your algorithm only needs to update $q$, since that will automatically update $q^*$. Therefore you only need the gradient with respect to $q$. Of course you would work with $q^*$ and its gradient instead, in which case $q$ gets implicitly updated.
Comment: I cannot thank you enough man. Ive checked your derivation and it is indeed correct! Again, thank you sir.


Redirect user based on role and node content

Question: I want to redirect a user when they login based on what role they have and whether they have created a node of a type.
So if the user has administrator role, direct user to admin url
else if
the user has role list_user, check if user has content of type new listing, if they don't, direct them to create node listing if they do have created node of type listing, direct them to profile.
I have this set up in separate rules but I'm sure it will work better and faster by just having one php block of code in the template.php
My only problem is, I don't know php and everything I've tried doesn't work very well or not at all.
Any help would be appreciated.
Answer: Use Rules module to redirect based on user roles.

After Installing Rules module, Go to Admin -> Configuration -> Rules (admin/config/workflow/rules/)
Add new rule
Enter rule name & select User has logged in from React on Event
Add new condition and set User has Role Select the required role and Save
In Action add new action Set it Page Redirect & enter the redirection URL
Answer: You should create basic module instead of heaving it in your theme (template.php file).
Create empty directory called your_module in sites/all/modules and create your_module.info and your_module.module files inside. Here is info what should you put into .info file. For basic implementation you need only name and core properties.
.module file must implement hook_user_login() (this hook will be triggered after user login). Read more here. Here is pseudocode implementation of your problem:
<?php
function your_module_user_login(&$edit, $account) {
  if (something) {
    $edit['redirect'] = 'admin';
  }
  elseif (something_else) {
    $edit['redirect'] = 'admin/content';
  }
  elseif (something_else_2) {
    //
  }
}

Read more how to create drupal module
Answer: This is a fairly vague questions as few different problems need to be solved before you have a complete solution.  I think @zaporylie is right and is a push in the right direction.  My answer here acts as further help; but you will need to find out how to get details of the node type and what content types the user has.  I use a debugger PHPStorm; that when you create a breakpoint you can all the variables that are available to retrieve.
If you want to find a user role you can use ( the elseif is a guess ! )
global $user;

if (in_array('administrator', $user->roles) {
    drupal_goto($youradminurl);
}
elseif (in_array('list_user', $user->roles) && $node->type == $user->contenttype)){
      drupal_goto($differenturl);
}


How to develop a musical idea/lyrics without forcing it?

Question: I have many musical ideas, some instrumental and some are parts of songs with lyrics and melody but in most times I can't get myself to develop the musical ideas or to write more lyrics without feeling I'm forcing it.
What mostly happens is that the first musical idea or song's verse and/or rhyme comes easly and "natural" but then when I try to develop it it becomes "artificial" and I find it hard to develop it and feel I am forcing it just to get more lyrics or more music to get to a full length song.
In other rare cases some songs are just being spelt out of me in whole and so fast.. Those also turn out to be the songs I like best.
What can I do to develop musical ideas/lyrics without feeling I'm forcing it?
Answer: Short version: it doesn't matter what you do-- so long as you do a lot of it, you'll get better at coming up with ideas.
Go ahead and force stuff.  Work it out note by note.  Or just noodle around on a piano or guitar, or hum a bunch of random stuff until something sticks out.
I've had dreams where a whole song just came to me by pure inspiration, and I woke up and wrote the whole thing down.  I've also spent months and months working on a piece, never quite getting it right, chopping huge sections out in total frustration, and finally stumbling on really great material by mistake.
One more thing: an important trick to being a good musician isn't what you make-- it's what you're willing to throw out.  I've had so many good ideas that I just couldn't make work-- learning when to give up and try something different is really important.
Comment: thoughtful post; to the OP its still worth writing your ideas down, or recording them as they may be useful in the future.
Answer: A few suggestions:

narrow down the possibilities: Sometimes writing for a specific goal can help provide shape to a composition. For example, writing a song for a commercial or a musical play. This helps because it provides a clear frame of reference for making musical decisions. You will shift the focus of judging your own writing from your own opinion to what is best for the goal.
ask yourself what is the definition of forced. How do you know when a musical idea is forced?
Play the music to someone else and get some feedback. Maybe they don't think it's forced. The could find it to be connected musically.
Variations of a theme. This is a tried and true technique.
Have patience, sometimes ideas need some time to brew in our brains.
Answer: This might be fairly obvious - and restricting, which is why others may not want to endorse it - but the best way to develop musical ideas without feeling like you're forcing it is to only work on music when inspiration strikes.
This is probably a no-go if you work in the music industry, but if all you are is a music hobbyist (like me), such a schedule is often fine to stick to and maintain.
I must admit that I still tend to force it somewhat often, including when composing for contests and composing inner sections of classical music. Probably like you, my favourite compositions of mine tend to be non-contest entries (or compositions made for very lenient contests such as "anything newer than this post that is 4 minutes long or less is accepted, due date is a month from this post") - most of my contest entries had to follow fairly restrictive rules that I often felt like I had to force music through and use several of my worse musical ideas for.
I have several musical works in progress on my computer, some of which have not been updated in years, and several of my compositions involve a musical form (sometimes considerably detailed) chosen in advance where inspiration for any of its musical themes did not come until several weeks after I chose the form. I even have lengthy melodies (20 seconds or longer each) of my very incomplete Symphony No. 1 in G Minor stored only in my mind and emitted on occasion when I sing them to myself alone. All of these ended up this way because of my basic tendency to only work on music, especially those works, when I get the inspiration to work on them further.
There is a considerable cost to only composing when inspiration strikes, but if you want to feel the best about all your completed music, it might still be worth the cost.
Comment: I feel like this answer and Bennyboy1973's outline the two positions described in [the first chapter of William Zinsser's *On Writing Well*](https://www.google.com/books/edition/On_Writing_Well_30th_Anniversary_Edition/tPkZ3WU1BM8C?hl=en&gbpv=1&dq=zinsser%20on%20writing%20well&pg=PA3&printsec=frontcover). And @Ray, I recommend reading those pages for how they relate to this question.
Answer: I think part of the problem is pitting "natural" and "forcing it" against each other, especially when you then ask "how to develop?"
If "natural" is some kind of intuitive, "without thinking about it" type process, then "developing an idea" seems the very opposite of that. Developing an idea is where method and technique come into play.
If you demand of yourself that everything flow out "naturally" with no effort, revision, method, etc. it seems you set yourself up for frustration. The worst thing, IMO, is you set yourself up for feeling you don't have natural ability and so aren't good enough.
Don't expect everything to be perfect and effortless, and quick.
To pick just one of many, many songwriter anecdotes, if Paul McCartney could used "Scrambled eggs/Oh my baby how I love your legs/Not as much as I love scrambled eggs" as the working lyric for yesterday, I think we can get away with using filler until a better idea develops.

https://en.wikipedia.org/wiki/Yesterday_(Beatles_song)#Origin

As far as specific methods and techniques are concern, there is plenty of stuff to find in song writing books. But I don't think that is the issue. The first thing is to not get hung up on "forcing it" as failure.


Scales name convention

Question: Suppose I take the whole step half step pattern from C major scale. Why can't I just impose this pattern to make C# major, D major, D# major, E major, F major ... this way? How to determine if its okey to write D# major or I'm allowed to write Eb major? what are the conventions behind that?
Comment: Please be aware that choosing a preferred answer very soon will deter others from bothering to proffer any of their own. More than half the world isn't even awake yet!
Comment: "...write D# major ..." write it where, how? If you wrote a D sharp major key signature on staff, how would you write it? what problem do you see? Something makes me think you haven't tried to write it on staff, or else you would immediately see the practical difference between D sharp major and E flat major.
Comment: @Tim thank I didnt realise
Answer: Keys with more than 7 sharps or 7 flats in key signature are avoided. For example, D# major would require two double sharps, i.e., (f# c#) g# d# a# e# b# fx cx. It would be quite inconvenient to read. In turn, Eb major has just 3 flats: bb eb ab.
Comment: Keys with more than _six_ sharps or flats are avoided.  You can find them, but there is a strong preference for B major over C flat major and for D flat major over C sharp major.
Comment: thank you so much and is this the sole reason?
Comment: im failing to upvote you due to a technical glitch
Comment: @Rajarshi_Rit you probably need more "reputation" points to upvote other answers. Anyway, yes, convenience is the main reason. I could imagine some situation when D# major could be justified, but what normally people do is they switch to the enharmonically equivalent key, as needed.
Comment: thank. its hard to get these scores because I ask seldom and frequently asking not so important question may lead to downvote
Comment: Aren't there special cases where you might need >6 accidentals e.g. if the music modulates from another key (with ≤6 accidentals), or in a part written for a transposing instrument (when other instruments are written in a key with ≤6 accidentals)? (But yes, you should stick to ≤6 accidentals when there _isn't_ such a reason.)
Comment: @gidds - don't see the point. If a piece is written in, say key C concert, the Bb trumpet part will be written in D to compensate. I reckon there's no need to go to more than 6 sharps or flats at most, in any key signature. And if, say 7 flats were deemed necessary, write in key C!
Comment: @gidds the more common approach is to use the enharmonically equivalent key, so, for example, if the piece is in B major, the B flat instruments will be in D flat major.  There's such a passage, for example, in Copland's Appalachian Spring (the 13-instrument version, which uses only B flat clarinet; the full orchestra version has the clarinets switching between A and B flat instruments).
Comment: @Tim but a key signature of seven flats isn't enharmonically equivalent to C.  It _is_ of course equivalent to B.  This is a great argument against concert pitch scores.  If the concert key signature is 5 or 6 flats, the conductor is going to have to remember that the B flat instrument parts are transposed by a diminished third instead of a major second when discussing the part with the players.
Comment: @gidds I forgot to address the modulation angle.  Similarly, the rule is usually to use the enharmonic equivalent.  If you're going up a major third from A major to C sharp major, you'll typically make it a diminished fourth from A major to D flat major instead.  You can see this sort of thing in 19th century songs, which were published in different keys for different voice types.  Also consider Beethoven's Moonlight Sonata, which is in C sharp minor, but the middle movement, which is in the parallel major key, is in D flat major rather than C sharp major.
Comment: @phoog - yes, I did mean key B. But even so, 5 sharps is probably easier to read than 7 flats, although horns seem to prefer flats - while guitar seem to prefer sharps. Interesting about Moonlight - I'd have thought parallel keys would have been the preference, but fewer 'accidentals' wins, I guess.
Comment: @Tim for a piece in three sharps at concert pitch, would the B flat trumpets and saxes prefer to be in five sharps or seven flats?
Answer: That's exactly what we do, to transpose scales into different keys.
The idea of writing down any music is to make it the easiest possible to read. So, we end up with as few sharps or flats as possible in any key, thus key signature.
Key C - none. Key G - 1♯. Key D -2♯, key A - 3♯, key E - 4 ♯, key B - 5♯, key F♯ - 6♯.
And flat keys - key F - 1♭, key B flat - 2♭, key E flat - 3♭, key A flat - 4♭, key D flat - 5♭, key G flat - 6♭.
Note that keys F♯ and G♭ are enharmonic - they are effectively the same set of notes (in 12tet). There is no need to have any more sharps or flats in the key signature - that lot cover all eventualities.
Your D♯ key would require way more - and some double sharps as well (x), so key E♭ (enharmonic), with only 3 flats, does the job  far more simply!
Answer: Not too many reasons to write in a nonexistent key of D# actually, unless you are just having an exercise of it for learning purposes. Eb is one of those keys with only one spelling.
Answer: The name of the key signature matches the tonic note in musical notation. So if you are given sheet music, follow what the sheet music says. If it's written in 7 sharps, you call it C# major/a# minor, not Db major/bb minor.
When you are talking about a piece of music you hear without notation, such as pop music, you do not want to name a key that has double sharps/flats, and most people would also avoid naming keys with 7 sharps/flats. For major keys, this means only naming flat keys, except Gb can be F#, and for minor keys, the keys are a, bb, b, c, c#, d, d#/eb, e, f, f#, g, g#.

Scales name convention


identity impersonation in IIS 7

Question: I'm a bit consused by Identity Impersonation in IIS7.5
In the good old days you could just put  in the web.config and call it good. Directories could then be locked down to a specific user, and then IIS would be able to access resources, such as Sql Server stored procedures, that that user had permissions to.
With the new integrated pipleline, this no longer works. I could switch to "classic" pipeline, but that will only work for so long so I want to do things the preferred "modern" way.
I definitely want to keep two tiers of security. The anonymous side of the site will have access to the SPROCs needed to display anonymous data, and the admin portion will have additional access. Without identity impersonation, how can this be done?
Answer: Great question!  I didn't know this was different in IIS 7.5 until I read your post.  (I would upvote you but I don't have enough points).
I found a good post from someone who works on the core IIS team.  Perhaps this will help you a little bit.
http://forums.iis.net/t/1147713.aspx
Answer: Impersonation still works, but to get to sql server (the second hop) you have to use "delegation".  The most important part of getting delegation to work is that you have to use kerberos. It is one thing to have it installed and enabled, it is another to make sure that it is actually used.  Googling "two hop" and "delegation" gets you lots of "how to" information, some better than others.
This one has nice pictures
I recommend testing in IE first.
Once you have it working in ie, move on to chrome where the servers that IIS needs to connect to have to be white listed. The most important key to set is "AuthNegotiateDelegateWhitelist"
This is a post on how to do that

identity impersonation in IIS 7


GDB - Reading 1 words from the stack

Question: I want to print 1 words from the top of stack in the form of hexadecimal. To do so, I typed the following:
(gdb) x/1xw $esp
but GDB keeps popping up:
0xffffffffffffe030:     Cannot access memory at address 0xffffffffffffe030
The program I'm trying to debug has already pushed a value onto stack so just in case if you're wondering that I might be trying to access kernel variables at the very beginning of program, it's not so.
Any idea?
Answer: 0xffffffffffffe030 is a 64-bit constant, so you are running in x64-bit mode. But $esp is a 32-bit register (which GDB sign-extends to 64 bits in this context).  The 64-bit stack pointer is called $rsp.  Try this instead:
(gdb) x/1xw $rsp

Comment: @7_R3X: [What do the E and R prefixes stand for in the names of Intel 32-bit and 64-bit registers?](https://stackoverflow.com/questions/43933379/what-do-the-e-and-r-prefixes-stand-for-in-the-names-of-intel-32-bit-and-64-bit-r)
Comment: Thanks a lot. It worked. Just one little thing I'd like to know. What does 'r' in rax, rsp or any other 64 bit register stands for? 32 bit registers are preceded with an 'e' which stands for 'extended'.
Comment: @ecm: Thanks a lot!

GDB - Reading 1 words from the stack


Power law fitting of data with uncertainties

Question: I need to fit data points on a power law and each one of these carries an uncertainty.
I've been using Python, more precisely scipy.optimize.curve_fit to get the job done but I don't know how to handle the uncertainties with it.
I thought about using a linear fit in log-log scale but it seems less precise compared to fitting directly on a power-law (not taking care of the uncertainties, just testing both on generated data and added noise).
I found that but it's not really helping me.
I wouldn't mind using R to do the job if needed.
Answer: To clarify the answer by user777, there are two packages that I and my collaborators have developed specifically for rigorously fitting power-law distributions. Both can be found here. One is for when your data are integer or real values, while the other (which is the one that user777 linked to) is for binned data, i.e., when you only know the number of the measurements within each of several contiguous ranges.
In each case, the packages have four parts:

fit the power-law model to your data,
estimate the uncertainty in your parameter estimates,
estimate the p-value for your fitted power law, and
compare your power-law model to alternative heavy-tail models.

These methods are described exhaustively in two references, both of which are freely available on the arxiv pre-print server (just search for their titles). The approach they use to fit the model is maximum likelihood, which is far more accurate than classic "curve fitting" approaches on scatter plots.
[integer and continuous quantities] A Clauset, C R Shalizi, and MEJ Newman. "Power-law distributions in empirical data." SIAM Review 51, 661-703 (2009).
[binned quantities] Y Virkar and A Clauset. "Power-law distributions in binned empirical data." Annals of Applied Statistics 8, 89-119 (2014).
In your case, I'm not entirely sure what you mean by each data point carrying an uncertainty. Do you mean a classic measurement uncertainty, like the kind you have when you measure the length or weight of an object (and is thus normally distributed)? If the variance is modest and the number of data points large, then you can get a pretty good estimate of the power-law parameter using our methods even if you ignore the uncertainty (because the estimator takes the logarithm of each value, and normally distributed fluctuations become highly compressed under the log). If you don't have much data, or if the uncertainty is really large, then I would recommend choosing a reasonable binning scheme (powers of 2 or something) and applying the binned-data methods.
Comment: Thank you aaron for the detailed answer. Indeed my uncertainties as I decided to call them are normally distributed as each of my data point comes from a different Monte-Carlo, my problem was/is that they come with very different orders of uncertainties $\sigma_i$ and so I was looking at way of weighting them (as with the $\frac{1}{\sigma_i^2}$ weight in linear fit but tuned for power law fitting. It seems very wrong to me that they have the same influence in the power law coefficient when some are much more reliable than others. I will look into the binning method
Comment: or just brush off the most imprecise values if I can't do more.
Answer: In the paper Power Law Distributions in Empirical Data, the authors exhaustively describe how to rigorously fit a power law and test the quality of the power law fit. Note that the authors explicitly warn that using a linear fit on the log-log scale is undesirable. As far as I can tell, this paper is the canonical resource for power law fits of empirical data.
R code for the paper, among other power-law related computer code, is available on Aaron Clauset's website.
Since the entire paper is concerned solely with estimating and validating this sole procedure, I would not feel comfortable attempting to summarize it in this format.
Clauset, Aaron, Cosma Rohilla Shalizi, and Mark EJ Newman. "Power-law distributions in empirical data." SIAM review 51.4 (2009): 661-703.


Commerce equivalent of Signup, Pay Per Node, etc

Question: I had previously asked for some information about specific e-commerce functions on D6, and was pointed to UberCart, along with Pay Per Node, Signup, and a few other modules. I've just learned that our hosting company has updated their php install so D7 is now supported.
Are there equivalents to those modules for D7? I know Commerce is the big one, but can it do pay-per-node type stuff (to support a print-on-demand fundraiser)?
Answer: Here are a few links that might get you started.  Drupal commerce is a lot more powerful than Ubercart, because everything is fieldable you should be able to make your event signup product include any fields you wish to collect.  I'm not sure what you mean by print-on-demand fundraiser but hopefully this gets you heading in the right direction.
http://vimeo.com/31459435
http://mustardseedmedia.com/podcast/episode51
~Mark
Comment: The print-on-demand fundraiser was explained in the link I included in my OP. We are not dealing with inventory or stock - users can purchase items which are not created until the fundraiser is complete.
Comment: Thanks. I'll look at those. Unfortunately I'm having trouble getting the Commerce Kickstart profile to install...


What is meaning of this symbol / notation in complex analysis

Question: I am trying questions of assignment of an institute in which I don't study.

There is a question in which $\Omega$ is a bounded region and f$\in C(\bar\Omega) \cap H(\Omega)$.

I have no idea on what is meant by $C(\bar\Omega) $ although I know that  $H(\Omega)$ is set of all holomorphic functions on set $\Omega$ .  I tried searching on google but could not found it's meaning although some links going to mathstackexchage has vaguely similar terms ( but only vaguely) .
So, can anyone please tell meaning of this notation?
Thank you.
Comment: It is the space of continuous functions on $\overline {\Omega}$.
Comment: $C(\overline{\Omega})$ is the set of continuous functions on $\overline{\Omega}$, which is the closure of the region $\Omega$. Thus the intersection consists in functions that are contiunous on the boundary and holomorphic on the interior of $\Omega$.
Comment: $C(\bar\Omega)$ are the *continuous* functions on $\bar\Omega$.
Comment: Holomorphic in $\Omega$, and continuous on the closure of $\Omega$.
Answer: Putting a bar over a set often means taking the closure. And the $C$ means the set of continuous (complex-valued) functions on the given set. So what you have is a symbol-heavy way to say that $f$ is continuous on the closure of $\Omega$ and holomorphic on $\Omega$.
Comment: To be pedantic, $C(\bar\Omega)$ and $H(\Omega)$ have no elements in common, as they are sets of functions with different domains. But writing around this issue to get at what we actually mean is going to be cumbersome, so we abuse the notation a bit. It's not really ambiguous, so we can get away with a bit of unpreciseness.


Proof that $\sqrt6 - \sqrt2 - \sqrt3$ is irrational.

Question: I want to prove that: $$\sqrt6 - \sqrt2 - \sqrt3$$ is irrational. I have tried using squares, the $p/q$ definition of rationality and the facts that
1)rational$\times$ irrational=irrational (unless rational=0),
2)rational$+$irrational=irrational.
However, I haven't been able to reach some conclusion. Things seem harder than when you have two square roots. Any help would be appreciated!
Comment: Hint:  Squaring the expression was a good start.  Suppose that the original was rational, what does the squared form tell you?
Comment: The answer below solved my problem but what about the squaring approach? Personally it didn't seem to get me anywhere since I couldnt make the L.H.S. to be irrational.
Comment: Subtraction is not associative. $1-(0-1)=2$ and $(1-0)-1=0$. Of course in either interpretation of your question you get an irrational number. But it's always good to be accurate.
Comment: A more generic answer would be that a linear combination of square roots of integers with integer coefficients is always an algebraic integer. And an algebraic integer is rational if and only if it is an integer. Therefore questions of this type are under [this](http://math.stackexchange.com/q/278935/11619) or [this](http://math.stackexchange.com/q/113689/11619) umbrella question for more. Basically the answers say that you never get rational numbers from such combos except trivially, when all those integers have integer square roots. Questions linked to those two give plenty of examples.
Comment: @Jezulas.  I'll write it out and post it below.  I see that other people have thoroughly answered the question, though some of the answers look a little complex.  I think it's not so hard really...  Anyway, I'll write it up.
Answer: Suppose $\sqrt{6}-\sqrt{2}-\sqrt{3}$ is rational.
Then, $(\sqrt{3}-1)(\sqrt{2}-1)=\sqrt{6}-\sqrt{2}-\sqrt{3}+1$ is a rational number, say $r\in\mathbb{Q}$.
That is, $\sqrt{3}-1=\frac{r}{\sqrt{2}-1}=r(\sqrt{2}+1)$.
Thus, $\sqrt{3}-r\sqrt{2}=r+1\in\mathbb{Q}$.
Clearly, $r\neq -1$, whence $\sqrt{3}-r\sqrt{2}\neq 0$.
Now, $\sqrt{3}+r\sqrt{2}=\frac{3-2r^2}{\sqrt{3}-r\sqrt{2}}=\frac{3-2r^2}{r+1}\in\mathbb{Q}$.
What happens if both $\sqrt{3}-r\sqrt{2}$ and $\sqrt{3}+r\sqrt{2}$ are rational numbers?
This line of reasoning shows that $a\sqrt{pq}+b\sqrt{p}+c\sqrt{q}$ is irrational if $a,b,c\in\mathbb{Q}$ with $a\neq0$ and $p,q\in\mathbb{N}\setminus\{1\}$ are such that $p$ and $q$ are distinct and square-free.
Comment: Well, I was avoiding more advanced stuff.
Comment: Thank you! This one would have probably taken me a lot of time.
Comment: There is another path from $\sqrt{3} - r\sqrt{2} = r+1 \in \mathbb{Q}$, using the fact that $\sqrt{3} \not \in \mathbb{Q}[\sqrt{2}]$.
Answer: I think the direct method is fairly simple, really. Not sure it adds anything to the other answers at this point, but just in case.
NOTE:  a commenter helpfully pointed out an algebraic error in the original version of this solution.  This error had no significant impact on the solution, and it has now been corrected.
Suppose $\sqrt 6 -\sqrt 2 - \sqrt 3$ were rational.  Square to see that
$$6 + 2 + 3- 4\sqrt 3 - 6\sqrt 2 + 2\sqrt 6 \;\; \in \mathbb Q$$
Which implies that:
$$ \sqrt 6 - 2\sqrt 3 - 3\sqrt 2 \;\; \in \mathbb Q$$
Subtracting this from the original expression we see that
$$2 \sqrt 2 + \sqrt3 \;\; \in \mathbb Q$$
Square again and simplify to deduce that $$\sqrt 6 \in \mathbb Q$$
which is false, giving us the contradiction we sought.
Comment: Thank you! This one is fairly simple indeed but I somehow managed to miss it.
Answer: The brute-force method, for when no clever argument such as in the other answer applies, would be something like:

Let $X=\sqrt{6}-\sqrt2-\sqrt3$.
Calculate $1$, $X$, $X^2$, $X^3$, $X^4$ as rational linear combinations of $1$, $\sqrt2$, $\sqrt3$ and $\sqrt 6$.
Because the expressions for these 5 powers of $X$ lie in a 4-dimensional vector space over $\mathbb Q$, they must have a nontrivial linear relation, that is, a degree-4 polynomial with rational coefficients that has $X$ as a root. Find such a polynomial using linear algebra.
Appply the rational root theorem to see if the polynomial has any rational roots. If not, then $X$ cannot be rational.
Comment: In particular, $X$ satisfies $X^4-22X^2-48X-23=0$ (found by asking WolframAlpha for the minimal polynomial of $\sqrt{6}-\sqrt{2}-\sqrt{3}$ after giving up doing it by hand).  Appealing to the rational root theorem, all rational roots must be integer divisors of $23$, but neither $23$, $0$, nor $-23$ are roots (alternatively, put $p/q$ into the polynomial and show it can never be a root).
Comment: @Kyle Miller: Downvote for resorting to Wolfram, upvote for being honest about it.
Comment: @KyleMiller If you know the space is four dimensional then you are already done, really you should say that the space has dimension *less* than or equal to $4$.
Answer: Let us assume that
$$\sqrt6-\sqrt2-\sqrt3=r\in\mathbb Q.$$
From this we get
\begin{align*}
\sqrt6-r&=\sqrt2+\sqrt3\\
(\sqrt6-r)^2&=(\sqrt2+\sqrt3)^2\\
6+r^2-2r\sqrt6&=5+2\sqrt6\\
1+r^2&=2(1+r)\sqrt6
\end{align*}
Since $\sqrt6\notin\mathbb Q$, the last equality can be true only if $1+r=1+r^2=0$
The equality $r+1=0$ is satisfied only for $r=-1$. But for $r=-1$ we get $1+r^2=2\ne0$.
So we get a contradiction.
Answer: Suppose that your expression equals a rational number $r$. Treat this equation as a linear combination, with rational coefficients, in the "unknowns" $\sqrt2,\sqrt3,$ and $\sqrt6$ equating to a rational number. Multiply through by $\sqrt2$ and by $\sqrt3$ to obtain two more such equations. We need to check that this system of equations is nonsingular, say by noting that the determinant $1+2r-r^2$ of the coefficients cannot be zero since $\sqrt2$ is irrational. Solving this system then gives a rational value (in particular) for $\sqrt2$, which we know to be impossible.
Answer: $X=(1-\sqrt{3}-\sqrt{2})^2 = 6 + 2(\sqrt6 - \sqrt2 -\sqrt3)$
We suppose $(1-\sqrt{3}-\sqrt{2})^2$ is rational.
$((1-\sqrt2)-\sqrt3)^2((1-\sqrt2)+\sqrt3)^2 = 8$
$Y=(1-\sqrt2+\sqrt3)^2$
since $X$ is rational according to our assumption
We do have $Y$ is rational also
$X+Y=  12- 4\sqrt2$
We do have contradiction, so $X$ is irrational, the irrationality of $X$ implies the irrationality of $\sqrt6-\sqrt2-\sqrt3$
Answer: Let us assume $\sqrt{6}-\sqrt{3}-\sqrt{2}$ to be a rational number.
Then from the definition of rational no it can be expressed as :
$\sqrt{6}-\sqrt{3}-\sqrt{2}=\frac{p}{q}$, where p and q are co-primes and $q\ne0.$
Squaring both sides we get:
$11-2\sqrt{18}-2\sqrt{12}+2\sqrt{6}=\frac{p^2}{q^2}$
$2\sqrt{6}-6\sqrt{2}-4\sqrt{3}=\frac{p^2-11q^2}{q^2}$
To prove L.H.S is irrational:
According to our assumption,
$ \sqrt{6}-\sqrt{3}-\sqrt{2}$ is a rational no.
$ \implies 2\sqrt{6}-2\sqrt{3}-2\sqrt{2}$ is rational no.
Now, $2\sqrt{6}-6\sqrt{2}-4\sqrt{3}= (2\sqrt{6}-2\sqrt{2}-2\sqrt{3})-(4\sqrt{2}+2\sqrt{3})$
You can easily prove that $(4\sqrt{2}+2\sqrt{3})$ is an irrational no.
So, $2\sqrt{6}-6\sqrt{2}-4\sqrt{3}= (2\sqrt{6}-2\sqrt{2}-2\sqrt{3})-(4\sqrt{2}+2\sqrt{3})$= a rational no.(from assumption)- an irrational no.
Now the L.H.S is an irrational no whereas the R.H.S is a rational no. which clearly is a contradiction.
So this contradicts our assumption that $\sqrt{6}-\sqrt{3}-\sqrt{2}$ is a rational no.
Hence it follows  $\sqrt{6}-\sqrt{3}-\sqrt{2}$ is irrational.
Comment: How do you know the L.H.S. is irrational?  That seems more or less equivalent to the original question.
Comment: That is pretty much the same conclusion I came to after squaring. I could not prove that the L.H.S. was irrational.
Comment: While it's true that the left-hand side is irrational, assuming it is at this point is wishful.  Try squaring it again; you'll probably get a polynomial on the R.H.S. which is very similar to the one I posted under Henning's answer.
Comment: @lulu How do i know the L.H.S. is irrational? I had done my edits. Hope you can agree now that the L.H.S is irrational.


Working with the coupon collector problem

Question: Here is the problem I have:
Say that each box of cereal contains a prize. There are $n$ different prizes in all.
What is the probability that more than $t$ boxes are needed to find all $n$ gifts?
This is what I have worked out so far:
I know this is a variation on the coupon collector problem. I let $X$ be a random variable which is the number of boxes bought before all $n$ gifts are found. Finding $\Bbb E[X]$ is simple enough:
Let$$X=X_1+X_2+...+X_n$$
$$\text{Every $X_i$ is distributed geometrically, with probability of success $\frac{n-i}{n}$}$$
Now because each $X_i$ is independent we use the linearity of expectation: $$\Bbb E[X]=\Bbb E[X_1]+\Bbb E[X_2]+...+\Bbb E[X_n]$$
$$=1+\frac{n}{n-1}+\frac{n}{n-2}+...+n$$
$$=n(1+\frac{1}{2}+\frac{1}{3}+...+\frac{1}{n})$$
$$=n\sum_{i=1}^n \frac{1}{i} $$
Now, how do I apply this to the question above to obtain $\Bbb P[X\geq t]?$ Apologies if this seems obvious.
Edit: Seemingly the expected value will not help to obtain the answer I'm looking for. I suppose what I need is the CDF of the random variable $X$. Any ideas?
Comment: The expectation can't help you get the CDF, it can only provide a bound and not a very good one at that. You might be able to do it by thinking about the more general problem where $m/n$ of all boxes have no gift at all, and then reduce the size of the problem by conditioning on $X_1$. That is, $P(X \geq t)=\sum_{k=1}^\infty P(X \geq t \mid X_1=k) P(X_1=k)$, and now $P(X \geq t \mid X_1=k)$ is the probability that it takes at least $t-k$ draws in order to find $n-1$ gifts when $1/n$ of all boxes have no gift at all.
Comment: I don't think knowing $E[X]$ helps you much to find the probability in this case.  You might consider using the principle of inclusion and exclusion. https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle
Comment: @Ian thanks for the answer, I suppose the expectation won't help me. Could you possibly give a more complete version of the answer you just gave?
Comment: Actually never mind, this way of doing it will ultimately just give you the general form $P(\sum_i X_i \geq t)=\sum_{\mathbf{x} : \sum_{j=1}^n x_j \geq t} \prod_{i=1}^n P(X_i=x_i)$. Which doesn't directly help you to obtain any simple answer, all it does is convert it to $\sum_{\mathbf{x} : \sum_{j=1}^n x_j \geq t} \prod_{i=1}^n \frac{n-i}{n} \left ( \frac{i}{n} \right )^{x_i-1}$.
Answer: Using the principle of inclusion exclusion,
\begin{align}
P(\text{more than $t$ boxes are needed})
&=P\left(\bigcup_{i=1}^n\{\text{prize # $i$ is missing}\}\right )
\\&=\sum_{k=1}^n(-1)^{k+1}\hspace{-.7cm}\sum_{i(1)\le i(2)\le \dots\le i(k)}\hspace{-.7cm}P\Big(\text{prizes $i(1),i(2),\dots,i(k)$ are missing}\Big)
\\&=\boxed{\sum_{k=1}^n(-1)^{k+1}\binom{n}k\left(1-\frac{k}n\right)^t.}
\end{align}
Comment: This could use a little bit of expansion to be clearer, I think.
Comment: @Ian Let $E_i^t$ be the event that after $t$ boxes are opened, prize number $i$ is missing. The second expression is $$P\left(\bigcup_{k=1}^nE_i^t\right),$$ and the third is $$\sum_{k=1}^n(-1)^{k+1}\hspace{-.7cm}\sum_{i(1)\le i(2)\le \dots\le i(k)}\hspace{-.7cm}P\Big(E_{i(1)}^t\cap E_{i(2)}^t\cap \dots \cap E_{i(k)}^t\Big).$$ This is exactly how you apply principle of inclusion exclusion to compute the probability of a union of events. It should now be obvious why this evaluates to the fourth expression; we have fixed a particular set of $k$ prizes, and want the probability none are found.


mdadm Build legacy array with 512-byte chunk

Question: I'm attempting to build an array using mdadm.  The array has 512-byte (not kibibyte) sized stripes.  Because mdadm accepts arguments to chunk in kibibytes, not in bytes, I have been unable to build this array correctly.
mdadm --build -n2 -c512 -lraid0 /dev/md0 /dev/sdb /dev/sdc

Builds the array with chunk size 512 KiB.
mdadm --build -n2 -c.5 -lraid0 /dev/md0 /dev/sdb /dev/sdc

Returns an error.
Any ideas?  I would normally just manually rebuild the RAID.  But this one is 4TB big.  I could rebuild it to an LVM, but I was hoping to avoid this.  Any ideas?
Comment: Glancing through the mdadm source, it's hard to say. Internally, the size is represented as a int counting 512-byte sectors for a little while, but is checked to make sure it's at least 4KiB, then divided by 2 to convert to # KiB.  On the actual `ioctl` side, there's apparently two versions, before md 0.90.0, it used a "chunk size factor" where 0=4KiB, 1=8KiB (2^x*4096) so it cannot be done on older kernels at all.  Newer md uses # of bytes, but you'd have to look at the kernel to see if it supports 512 byte chunks, then patch mdadm to remove the checks and conversions that would stop it.
Comment: Thank you so much for taking the time to sleuth this out.  I checked the kernel source in the md driver and it would indeed be possible, because everything is referenced by number of sectors as far as I can tell. Thank you very much, I'll play with it and see what I come up with.  If you copy this response as an answer I'll gladly accept.
Comment: @DerfK, b (thumb up)
Answer: I had the same problem and I solved it by means of a little Linux FUSE program I wrote. It's named xraid and I put it on Sourceforge.
For assembling your RAID:

Download and compile xraid
Run it:
mkdir mnt
./xraid mnt 512 /dev/sdb /dev/sdc
You now should be able to access your RAID under mnt/xraid.
Comment: Thanks for this.  I eventually broke down and used a handmade python script to access the data and copied it to another RAID with a sane block size, but if I have this issue in the future I'll be sure to take a look at it.
Answer: I had to "de-RAID-0" a raw array from a 2-disk enclosure today. This is the script I used to build a 2TB disk image file from 2x1TB drives with 1K (1024b) stripes. Modify as needed. If you have more than 2 RAID-0 disks, you'll need to duplicate and modify the line that advances output by 1 block for each added disk; the extra counter is included on that line already.
Formatted (can use ksh instead of Bash if preferred):
#!/bin/bash

A=0; C=0; S=0; ERR=0
STRIPE=1024  # Stripe size in bytes (not KiB)
FN=raid_recovery.bin  # Output file name

while [ $ERR -eq 0 ]
  do

  # Copy from first device
  dd if=/dev/sdc of=$FN bs=$STRIPE seek=$C skip=$A count=1 conv=notrunc 2>/dev/null || ERR=1

  # Advance output by 1 block; copy from second device
  # For 3+ disks, copy-paste this line for every added disk and modify 'if=' for each
  [ $ERR -eq 0 ] && C=$((C + 1)) && dd if=/dev/sdk of=$FN bs=$STRIPE seek=$C skip=$A count=1 conv=notrunc 2>/dev/null || ERR=1

  # Update source, dest, and status delay counters
  A=$((A + 1)); C=$((C + 1)); S=$((S + 1))

  # Display current output position periodically
  [ $S -ge 256 ] && S=0 && echo -n $'\r'"$C blocks done"

done

One-liner version:
A=0; C=0; S=0; ERR=0; STRIPE=1024; FN=raid_recovery.bin; while [ $ERR -eq 0 ]; do dd if=/dev/sdc of=$FN bs=$STRIPE seek=$C s
kip=$A count=1 conv=notrunc 2>/dev/null || ERR=1; [ $ERR -eq 0 ] && C=$((C + 1)) && dd if=/dev/sdk of=$FN bs=$STRIPE seek=$C skip=$A count=1 conv=notr
unc 2>/dev/null || ERR=1; A=$((A + 1)); C=$((C + 1)); S=$((S + 1)); [ $S -ge 256 ] && S=0 && echo -n $'\r'"$C blocks done"; done


HtmlAgilityPack - How to get the Value from the tag  into aspx.cs

Question: I have a task to do. I need to get the value from the tag into c#. I need to display the value into Label
This here is my HTML code:

<asp:Label ID="Label2" runat="server" Text="" Font-Size="XX-Large"></asp:Label>

<asp:Label ID="Label3" runat="server" Text="" Font-Size="XX-Large"></asp:Label>

from code behind i use this here to get the value but it does not work:
HtmlDocument page = new HtmlWeb().Load(@"D:\Downloads\wichtig\try\WebApplication1-Kopie-Kopie\MeineWebseite\löschen\WebForm2.aspx");
        var title = page.DocumentNode.SelectSingleNode("//div[@id='para1']");
        Label3.Text = title.ToString();

I only know how to get the tag by Id. This is how it works
 document2.Load(@"D:\Downloads\wichtig\try\WebApplication1-Kopie-Kopie\MeineWebseite\löschen\WebForm2.aspx");

        string tag = document2.GetElementbyId("para1").Name;
        Label2.Text = tag;

That is how it works but I want Label3 should display the current date like

id="para1

it does.This here is the result
enter image description here
Comment: what are you trying to get from the div? whats the value supposed to be for `Label3.Text` ?
Comment: I want Label3 should display the value of para1. It should display the current day. Today It should show Freitag. It means friday
Comment: Does this answer your question? [Running Scripts in HtmlAgilityPack](https://stackoverflow.com/questions/11393075/running-scripts-in-htmlagilitypack)
Comment: You cant execute scripts to find the values... its the browser that executes the scripts and updates the page.
Comment: Is there no way how solve it. I can only get the tag by Id
Comment: the date value is not part of the HTML for Html-Agility-Pack to scrape. It has not been evaluated and thus cant be scraped like how you are thinking. In your example, `div[@id='para1']` has no value or anything in it.
Comment: Thanks for your help but I dont understand "Running Scripts in HtmlAgilityPack " what its about
Comment: @Opijkkk Your browser runs JavaScript code.  HTMLAgilityPack does not.  If JavaScript code manipulates that div in any way, HTMLAgilityPack will not see it, as that manipulation will not have occurred there.
Comment: Thanks for your help. What would you recommend me to do
Comment: @Opijkkk Read the question/answer linked above by Jawad.
Answer: You should use InnerText property:
var title = page.DocumentNode.SelectSingleNode("//div[@id='para1']");
Label3.Text = title.InnerText;

Comment: There is no text in `title.InnerText`.. its blank.


How can I get the data in the adapter and display it in the fragment?

Question: I have trouble getting data from adapter to fragment. I want to display some information through recycler view but the problem is that I have an error in getting the data arraylist in my VaccineAdapter.
This is my patientlogin class once the user login the account. I want to display his/her personal information as well as the his her vaccine history in a recyclerView order.
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_login);

        name = findViewById(R.id.fullName);
        IdNo = findViewById(R.id.idNumber);

    }
    // Validate name
    private Boolean validateName(){
        String val = name.getText().toString();

        if(val.isEmpty()){
            name.setError("Field is Empty");
            return false;
        }else{
            name.setError(null);
            name.setEnabled(false);
            return true;
        }
    }

    // Validate ID number
    private Boolean validateIdNumber(){
        String val = IdNo.getText().toString();

        if(val.isEmpty()){
            IdNo.setError("Field cannot be empty");
            return false;
        }else{
            IdNo.setError(null);
            name.setEnabled(false);
            return true;
        }
    }

        public void loginPatient(View view){

        //validate Login info
        if (!validateName() | !validateIdNumber()) {
            return;
        }else{
            isUser();
        }
    }
    //if validation is correct
    private void isUser() {

        final String userEnteredIdNo = IdNo.getText().toString().trim();
        final String userEnteredName = name.getText().toString().trim();

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Patient List");

        Query checkUser = reference.orderByChild("id").equalTo(userEnteredIdNo);

        checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()){
                    IdNo.setError(null);
                    IdNo.setEnabled(false);

                    String IdNoFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);

                    if(IdNoFromDB.equals(userEnteredName)){
                        IdNo.setError(null);
                        IdNo.setEnabled(false);

                        String imageFromDB = dataSnapshot.child(userEnteredIdNo).child("image").getValue(String.class);
                        String idFromDB = dataSnapshot.child(userEnteredIdNo).child("id").getValue(String.class);
                        String nameFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);
                        String ageFromDB = dataSnapshot.child(userEnteredIdNo).child("age").getValue(String.class);
                        String birthdayFromDB = dataSnapshot.child(userEnteredIdNo).child("birthday").getValue(String.class);
                        String addressFromDB = dataSnapshot.child(userEnteredIdNo).child("address").getValue(String.class);
                        String vaccineNameFromDB= dataSnapshot.child(userEnteredIdNo).child("vaccine_Name").getValue(String.class);
                        String institutionNameFromDB = dataSnapshot.child(userEnteredIdNo).child("institution_Name").getValue(String.class);
                        String vaccineDateFromDB = dataSnapshot.child(userEnteredIdNo).child("vaccine_Date").getValue(String.class);

                        PatientInfoHelperClass helperClass = new PatientInfoHelperClass(imageFromDB , idFromDB , nameFromDB , ageFromDB , birthdayFromDB ,addressFromDB ,vaccineNameFromDB , vaccineDateFromDB , institutionNameFromDB);

                        Intent intent = new Intent( patientLogin.this , patientProfile.class);
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("helperClass", Parcels.wrap(helperClass));
                        intent.putExtras(bundle);

                        startActivity(intent);

                    }
                    else{
                        name.setError("No such name exists");
                        name.requestFocus();
                    }
                }
                else{
                    IdNo.setError("Wrong Id Number");
                    IdNo.requestFocus();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

This is my VaccineAdapter this is the adapter
 public VaccineAdapter(Context context, List<PatientInfoHelperClass> mList) {
        this.mList = mList;
        this.context = context;
    }

    @NonNull
    @Override
    public VaccineAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.vaccine_list,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VaccineAdapter.MyViewHolder holder, int position) {
        //get data
        String vName = mList.get(position).getVaccine_Name();
        String iName = mList.get(position).getInstitution_Name();
        String vDate = mList.get(position).getVaccine_Date();

        //set data
        holder.vaccine_Name.setText(vName);
        holder.institution_Name.setText(iName);
        holder.vaccine_Date.setText(vDate);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

class MyViewHolder extends RecyclerView.ViewHolder{
    TextView vaccine_Name, institution_Name, vaccine_Date;
    public MyViewHolder(View itemView){
        super(itemView);

        vaccine_Name = itemView.findViewById(R.id.vaccineName);
        institution_Name = itemView.findViewById(R.id.institutionName);
        vaccine_Date = itemView.findViewById(R.id.vaccineDate);
    }
}

This is my HistoryFragment connected to vaccine adapter where I want to display vaccine history in a recyclerview order.
RecyclerView recyclerView;
List<PatientInfoHelperClass> mList;
VaccineAdapter adapter;

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public HistoryFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment HistoryFragment.
 */
// TODO: Rename and change types and number of parameters
public static HistoryFragment newInstance(String param1, String param2) {

    HistoryFragment fragment = new HistoryFragment();
    Bundle bundle = new Bundle();
    bundle.putString(ARG_PARAM1, param1);
    bundle.putString(ARG_PARAM2, param2);
    fragment.setArguments(bundle);
    return fragment;

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    Bundle args = getActivity().getIntent().getExtras();
    View v = inflater.inflate(R.layout.fragment_history, container, false);
    recyclerView = v.findViewById(R.id.historyRecyclerView);
    mList = args.getParcelable("helperClass");
    adapter = new VaccineAdapter (getActivity(), mList);
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return v;
}

This is my PatientInfoHelperClass
   @Parcel
public class PatientInfoHelperClass {
    String image, name, id, age, birthday, address, institution_Name, vaccine_Name, vaccine_Date;

    public PatientInfoHelperClass() {
    }

    public PatientInfoHelperClass(String image, String name, String id, String age, String birthday, String address, String institution_Name, String vaccine_Name, String vaccine_Date) {
        this.image = image;
        this.name = name;
        this.id = id;
        this.age = age;
        this.birthday = birthday;
        this.address = address;
        this.institution_Name = institution_Name;
        this.vaccine_Name = vaccine_Name;
        this.vaccine_Date = vaccine_Date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getInstitution_Name() {
        return institution_Name;
    }

    public void setInstitution_Name(String institution_Name) {
        this.institution_Name = institution_Name;
    }

    public String getVaccine_Name() {
        return vaccine_Name;
    }

    public void setVaccine_Name(String vaccine_Name) {
        this.vaccine_Name = vaccine_Name;
    }

    public String getVaccine_Date() {
        return vaccine_Date;
    }

    public void setVaccine_Date(String vaccine_Date) {
        this.vaccine_Date = vaccine_Date;
    }
}

I want to display the vaccine_Name, institution_Name, and vaccine_Date that I call in my adapter. but  don't know how to get the data from my vaccineAdapter to the HistoryFragment.
This is the error I get.
This is the design of the app. Once I clicked the history in the bottomNavigation the error will appear.
Comment: What error you are getting?
Comment: I'm getting  `Process: com.example.phaxtrack, PID: 6030
    java.lang.ClassCastException: android.content.Intent cannot be cast to java.util.List`
Answer: The error is in your fragment in the line mList = getActivity().getIntent();
The getIntent() method essentially returns intent not a list so you can't equate your mList to getActivity().getIntent()! getIntent() is used to pass data from activity to activity/fragment to activity. It returns the intent that started the activity.
Example of getIntent(),
If you start an Activity with some data,
String someData = "StackOverflow is awesome";
Intent intent = new Intent(context, SomeActivity.class);
intent.putExtra("someKey", someData);

you can retrieve this data using getIntent in the receiver activity:
 Intent intent = getIntent();
 if (intent != null)
     String gotBackSomeKey = intent.getExtra("someKey");

Now for passing data between fragments or from an activity to a fragment, we use Bundle.(Your case)
Example of Bundle,
 Bundle bundle = new Bundle();
 bundle.putParceableArrayList("YourListTag",mList);
 FragmentClass fragInfo = new FragmentClass();
 fragInfo.setArguments(bundle);
 transaction.replace(R.id.fragment_single, fragInfo);
 transaction.commit();

Make sure, unlike String or Int, you cannot pass List to your Bundle/Intent directly if you have a customized list. You will have to make your object of the list Parcelable or Serializable and then pass it like above example. You can read how to implement Parcelable/Serializable here
https://developer.android.com/reference/android/os/Parcelable
https://developer.android.com/reference/java/io/Serializable
Comment: this is the error I get: `java.lang.ClassCastException: com.example.phaxtrack.utils.PatientInfoHelperClass cannot be cast to java.util.List`
Comment: this is how I received the data `mList = Parcels.unwrap(getActivity().getIntent().getParcelableExtra("helperClass"));`
Comment: Please add the full stacktrace of the error so we can determine which file has the error
Comment: Also mList = getActivity().getIntent() why us this statement there? If it is not used, can you remove it?
Comment: Please review the updated question. The picture of the error is at the bottom.
Comment: Where are you calling HistoryFragment from?


How to show a video player on aspx page dynamically

Question: I have an application and In my home page I want to show a video, and the URL of this video I want to set dynamically. Can someone tell me How Can I do this.
I have tried YoutubePlayer control from codeplex but it work fine with youtube not with the URL that I want it to work.
I have tried ASP-Net-Video control as well but it shows a tooltip
Can any one tell me how I can create object to play video and how can I set the path of the video dynamically
Answer: You could try Flowplayer. It's one of the most popular and widely-used players available.
Flowplayer provides rich JavaScript and Flash APIs to allow for easy customization and rapid integration. Check out the documentation for specific details.
Comment: yes but I want to assign the video url dynamically from the page can I do that
Comment: Nathan If u can probably show me a demo how to use it can save my time in the mean while I m trying my best to do it
Comment: Nathan everything is fine but u know what it supports limited media format. suggest me something else
Answer: Check out the HTML5 video player.  You can then change the path to the video easily both server or client side.


State does not update React Hook

Question: So I'm doing a rpg trait randomizer, where I have the traits in a array, and I can choose to random or add based on a select, but , whenever I click any of those buttons, the state on the select that should  show the array, doesn't get update, only if I open the add trait select.
In short, the problem is the array after a add is not showed in the display.
 return (

                    <text style={{ fontWeight: 'bold' }}>Traits</text>

<button>Delete</button>

                    <select className="Traits-List"
                        multiple

                    >
                        {traitsList && (
                            traitsList.map((trait) => (
                                <option key={trait.label} value={trait.value}>{trait.label}</option>
                            )))}
                    </select>

                    <button onClick={(e) => { handleTraits() }}>Random</button>

                    <Select
                        placeholder={"traits"}
                        options={Traits}
                        menuPlacement="top"
                        styles={selectStyle}
                        onChange={handleTraitAddTemp} //?
                    ></Select>
                    <button onClick={() => { handleAddTrait(tempTrait) }}>Add</button>

)

the handle functions
const [traitsList, setTraitsList] = useState([]);
    const [tempTrait, setTempTrait] = useState({});

     const handleTraitAddTemp = (e) => {
        console.log(e)
        setTempTrait(e);
    }

     function addTrait(Trait) {
        const tempTraits = traitsList;
        console.log(traitsList)
        if (tempTraits && tempTraits.includes(Trait))
            return;

        tempTraits.push(Trait)
        console.log(tempTraits)
        return tempTraits
    }

 function handleAddTrait(Trait) {
        let res = addTrait(Trait)
        setTraitsList(res);
    }

 function handleTraits() {
        let res = randomTraits()
        setTraitsList(res)
    }

function randomTraits() {
        const tempTraits = traitsList;
        let rng = randomNumber(1, 38)
        console.log(rng)
        console.log(tempTraits)
        console.log(traitsList)
        while ((tempTraits.length !== 0) && (tempTraits.includes(Traits[rng]))) {
            rng = randomNumber(1, 38)
            console.log(rng)
        }
        tempTraits.push(Traits[rng])
        console.log(tempTraits)
        return tempTraits
    }

The left part i click the random button, the second i choose a trait in the menu then the random trait that i got is showed
Comment: This exact question was asked earlier today https://stackoverflow.com/questions/67864282/react-update-array-in-setstate-hook
Comment: I guess so, I will try, thanks!
Answer: Whenever you do this const tempTraits = traitsList; replace with following.
const tempTraits = [...traitsList];

Comment: should i change in
`setTraitsList(res)`

as well?
Comment: I don't think so.
Comment: i changed, and worked, thanks for the help!!

State does not update React Hook


Create a separate view for each primary menu based on URL aliases in drupal 7

Question: I have created a taxonomy menu in drupal 7. Let say the main menu has technology and market data.

Let say Technology has sub menu as security and security has test1 and hello as sub menus and so on.
-Technology       URl: http://localhost/drupal/taxonomy/term/1
     -- Security    URL: http://localhost/drupal/taxonomy/term/2
         --Test     URL: http://localhost/drupal/taxonomy/term/3
         --Hello    URL: http://localhost/drupal/taxonomy/term/4

Market data also has the same hierarchy.
These are the values I have set while creating the view
    Format:

      Unformatted list | Settings

      Show:Content | Teaser

    FILTER CRITERIA
      Content: Published (Yes)

      Content: Type (= Article)

      Content: Has taxonomy terms (with depth) (or Technology, ...) | Settings

    PAGE SETTINGS

      Path:/taxonomy/term/%

      Menu:No menu

      Access:Permission | View published content

    CONTEXTUAL FILTERS
      Content: Has taxonomy term ID (with depth)

After creating this view I am able to see the view in all pages (Technology,Security,test1,Hello) I am able to display article as mention in point 1.
Now I replaced the url with automaic url aliases and the url it generate the following URL.
        -Technology       URl: http://localhost/drupal/technology
             -- Security    URL: http://localhost/drupal/technology/security
                  --Test     URL: http://localhost/drupal/security/test
                  --Hello    URL: http://localhost/drupal/security/Hello

Now I replaced the view with following settings
     Format:

   Unformatted list | Settings

   Show:Content | Teaser

FILTER CRITERIA
   Content: Published (Yes)

   Content: Type (= Article)

   Content: Has taxonomy terms (with depth) (or Technology, ...) | Settings

 PAGE SETTINGS

   Path:/technology/%

   Menu:No menu

   Access:Permission | View published content

 CONTEXTUAL FILTERS
   Content: Has taxonomy term ID (with depth)

Within  Has taxonomy term ID (with depth) has the following settings:

     WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED
       Override title:    %1
     Specify validation criteria

      Validator

         Taxonomy Term

      Vocabularies

         Home Page Main Menu

      Filter value type

         Term name converted into ID

   I have selected the Transform dashes in URL to spaces in term name filter values also.

But the problem is I am not able to overwrite the taxonomy pages.
Can anyone help me what I have missed while creating the view.
Answer: The reason for this problem has to do with how path aliases are handled. When the url is set to a page alias, Drupal translates the url into its actual url taxonomy/term/tid before it seeks the content that is to be displayed, such as your view definition whose path is still an alias.  Since the view path doesn't match the URL, it is not selected to generate content.  If you want a descriptive URL to work with the view path, you cannot use the path aliases.
I have a similar problem where I have converted hundreds of hierarchical taxonomy terms into a menu system with aliases using taxonomy menu. The aliases show up fine when I select a menu item, and set the View definition to Taxonomy/term/% but the views, of course, display the base URL instead of the alias.  I have not explored a work-around yet.  If you find anything, please post it here on your question.


c++ creating a static like array with "new" or another way of creating a dynamic array

Question: I know that the common technique of creating a dynamic array using new in C++ is:
int * arr = new int[5];

A book also says:
short tell[10]; // tell is an array of 20 bytes
cout << tell << endl; // displays &tell[0]
cout << &tell << endl; // displays address of the whole array
short (*p)[10] = &tell; // p points to an array of 20 shorts

Now I wonder if there is a way to allocate memory for an array using new, so it can be then assigned to a pointer to the whole array. It might look like this:
int (*p)[5] = new int[5];

The above example doesn't work. The left side looks correct to me. But I don't know what should be on the right.
My intention is to understand if it's possible. And I know that there are std::vector and std::array.
Update:
Here is what I actually wanted to check:
int (*p1)[5] = (int (*)[5]) new int[5];
// size of the whole array
cout << "sizeof(*p1) = " << sizeof(*p1) << endl;

int * p2 = new int[5];
// size of the first element
cout << "sizeof(*p2) = " << sizeof(*p2) << endl;

And here is how to access these arrays:
memset(*p1, 0, sizeof(*p1));
cout << "p1[0] = " << (*p1)[0] << endl;

memset(p2, 0, sizeof(*p2) * 5);
cout << "p2[0] = " << p2[0] << endl;

Answer:
know that the common technique of creating a dynamic array

In C++ that was written 20 years ago, maybe.
These days you should use std::vector for dynamic arrays and std::array for fixed size array.
If your framework or platform supplies additional array classes (like QT's QVector), they are fine too, as long as you don't mess with C-pointers directly, and you have RAII-based array class.
and as for concrete answer, new T[size] always returns T* , so you cannot catch a pointer returned by new[] with T(*)[size].
Comment: you can forcefully cast it with c-cast `(int(*)[5])new int[5]`, but please, don't do it in real code.
Comment: So, that means that it is not possible to allocate memory for this construction `int (*p)[5] =`. Right?
Comment: I am just playing around it and trying to get dipper understanding. BTW, why are you saying not to do it in real code?
Comment: because we don't use C pointers and C-casts unless we really have to. and I guess you don't really have to.
Comment: That is a good point =) . Many thanks. I've got what I want. Now I will supplement my question, because I cannot put a bloc of code here.
Answer: The problem is that left and right sights have different types.
The type of:
new int[5]

is
int*.

The type of:
int (*p)[5]

is
int (*)[5].

And compiler cannot assign one to another.
Generally speaking it is impossible to assign T* to T (*)[N]. That is why you need to use the syntax mentioned in the beginning of your question.


combining two rows in R (appending one row to the end of the other)

Question: I have the following dataset
df <- structure(list(
X1 = c("A1", "1", "A2", "2", "A3", "3"),
X2 = c("B1", NA, "B2", NA, "B3", NA),
X3 = c("C1", NA, "C2", NA, "C3", NA),
X4 = c("D", "D", "D", "D", "D", "D")),
class = "data.frame", row.names = c(NA, -6L))

What I am trying to do is get to the following dataset
df <- structure(list(
X1 = c("A1", "A2", "A3"),
X2 = c("B1", "B2", "B3"),
X3 = c("C1", "C2", "C3"),
X4 = c("D", "D", "D"),
X5 = c("1", "2", "3")),
class = "data.frame", row.names = c(NA, -3L))

In short, what I need to do is take the even rows with the NAs and append that to the end of the odd rows.
Any help would be appreciated.
Answer: Create a 'grp' based on the occurrence of NA in 'X2', then create the 'X5' as the last value from 'X1', ungroup and remove the NA rows with na.omit
library(dplyr)
df %>%
  group_by(grp =  cumsum(lag(is.na(X2), default = TRUE))) %>%
  mutate(X5 = last(X1)) %>%
  ungroup %>%
  select(-grp) %>%
  na.omit

-output
# A tibble: 3 x 5
#  X1    X2    X3    X4    X5
#  <chr> <chr> <chr> <chr> <chr>
#1 A1    B1    C1    D     1
#2 A2    B2    C2    D     2
#3 A3    B3    C3    D     3

Or another option is to make use of the even condition
library(tidyr)
df %>%
    mutate(X5 = case_when(row_number() %%2 == 0  ~X1)) %>%
    fill(X5, .direction = 'updown') %>%
    na.omit
#  X1 X2 X3 X4 X5
#1 A1 B1 C1  D  1
#3 A2 B2 C2  D  2
#5 A3 B3 C3  D  3

Or with base R
df$X5 <- NA
df$X5[c(TRUE, FALSE)] <- df$X1[c(FALSE, TRUE)]
out <- na.omit(df)

Comment: @JWH2006 can you test with the second solution.
Comment: Base R works, thank you so much. Second solution with Base r worked
Comment: I tried using this with lapply in this function lapply (df, function(x) {
x %>%
  group_by(grp =  cumsum(lag(is.na(X2), default = TRUE))) %>%
  mutate(Information = last(X1)) %>%
  ungroup %>%
  select(-grp) %>%
  na.omit
}) And got this error Error: Problem adding computed columns in `group_by()`.
x Can't transform a data frame with duplicate names.
Comment: @JWH2006 that is a different error.  Can you check if any of the datasets have duplicate column names
Comment: They do. This was from an earlier dataset that was ungrouped using group_split (). So all the dataframes in the list have the same column names.
Comment: @JWH2006 i meant if one of the datasets have duplicate column names or not.  data.frame doesn't allow duplicate column. names and tidyverse may show error if there are duplicate


Solve the equation $\sqrt{45x^2-30x+1}=7+6x-9x^2$

Question: Solve the equation $$\sqrt{45x^2-30x+1}=7+6x-9x^2.$$
So we have $\sqrt{45x^2-30x+1}=7+6x-9x^2\iff \begin{cases}7+6x-9x^2\ge0\\45x^2-30x+1=(7+6x-9x^2)^2\end{cases}.$ The inequality gives $x\in\left[\dfrac{1-2\sqrt{2}}{3};\dfrac{1+2\sqrt{2}}{3}\right].$ I am not sure how to deal with the equation. Thank you in advance!
Comment: Simlify the equation into the form $\sqrt{5(3x-1)^2-4}=8-(3x-1)^2$ and set a substitution $y=(3x-1)^2$.
Answer: Denote $t:=\sqrt{45x^2-30x+1}$. Then we observe that
$$t^2=45x^2-30x+1=-5(7+6x-9x^2)+36.$$
As a result, it follows that $$t=-\frac{t^2-36}{5}\implies t^2+5t-36=0\implies(t+9)(t-4)=0.$$
Since $t\geq 0$, it follows that $t=4$. Therefore, $$45x^2-30x+1=16\implies45x^2-30x-15=0\implies 3x^2-2x-1=0.$$
Hence $(3x+1)(x-1)=0$. Either $x=1$ or $x=-1/3$.
Comment: Thank you for the response! I don't see how $t=-\dfrac{t^2-36}{5}.$
Comment: This follows from my first observation $t^2=-5(7+6x-9x^2)+36$, which entails $7+6x-9x^2=-\dfrac{t^2-36}{5}$. I just substitute it and $t=\sqrt{45x^2-30x+1}$ back to the original formula.
Answer: Let $u=9x^2-6x$ and rewrite the equation as
$$\sqrt{5u+1}=7-u$$
Squaring both sides gives $5u+1=49-14u+u^2$, or
$$u^2-19u+48=(u-16)(u-3)=0$$
We see that $u=16$ is not a solution, since $\sqrt{81}\not=-9$. This leaves us with $u=3$, which is a valid solution, since $\sqrt{16}=4$, and from this we have
$$9x^2-6x=3\implies3x^2-2x-1=(x-1)(3x+1)=0$$
which gives $x=1$ and $x=-1/3$ as the complete solution set.
Remark: What makes this work so nicely is that $45:30=9:6$. If the coefficients of $x^2$ and $x$ on the two sides hadn't been in proportion, the solution would have been much more involved.
Answer: $$45x^2-30x+1=(-9x^2+6x+7)^2$$
$$-5(-9x^2+6x+7)+36=(-9x^2+6x+7)^2$$
Substitute $u=-9x^2+6x+7$ and solve the quadratic equation.
Answer: From $45x^2-30x+1=(7+6x-9x^2)^2$, you have that $$81x^{4}-108x^{3}-135x^{2}+114x+48 = 0$$
This factors as $$3(x-1)(3x+1)(9x^2-6x-16) = 0$$
So the roots of that polynomial are $x = 1, -\frac{1}{3}, \frac{1\pm\sqrt{17}}{3}$. Out of these, the only ones in the range $\left[\frac{1-2\sqrt{2}}{3} ,\frac{1+2\sqrt{2}}{3} \right]$ are $x = 1$ and $x = -\frac{1}{3}$.


How to compute covariance of joint distribution?

Question: Let $z$ be an $m$ dimensional vector distributed as $z \sim N(0,D)$ where $D$ is some diagonal covariance matrix.
And let $x$ be some $n$ dimensional vector whose conditional distribution with $z$ is given as $p(x|z) \sim N(Az, 0)$ where $A$ is some $n \times m$ matrix. This might seem a little weird to have no covariance; originally the covariance was $k \mathbb{I}$ ($k$=const and $\mathbb{I}$ is identity matrix) but this specific questions concerns the limit $k \rightarrow 0$.
Is it possible to calculate the mean and covariance of the conditional distribution $p(z|x)$?
I believe there is a result on p111 of the book by Kevin Murphy that can help with this. However I am having trouble applying it. Denoting covariance matrices by $C$, it tells me that the desired covariance should be
$C_{(z|x)} =C_z - C_{(z,x)}  C_x^{-1} C_{(x,z)}$
It is clear that $C_z=0$ but how can I calculate the other two terms, namely the covariance of the joint distribution and the covariance of $x$?
Comment: You may rephrase the title of your question to be more specific. Something like "How to compute covariance of joint distribution?" would be better and more helpful when navigating through the question list.
Answer: If we start from $\mu_{x|z}=\mu_x+C_{xz}C_z^{-1}(z-\mu_z)=Az$, and $\mu_z=0$, we get $\mu_x=0,C_{xz}=AD$. Then, we can use this in $C_{x|z}=kI=C_x-C_{xz}C_z^{-1}C_{zx}$ to get that $C_x=kI+ADA^T$ (also, use the fact that $C_{zx}=C_{xz}^T$). Now, we know all we need to calculate $C_{z|x}$:
$$C_{z|x}=C_z-C_{xz}^TC_x^{-1}C_{xz}=D-DA^T(kI+ADA^T)^{-1}AD$$
From here you can take the limit of $k$ to whatever value you want. Clearly $C_z\neq 0$, and $C_{xz}$ is just a portion of the joint distribution's covariance matrix, where $C_{xz}^{ij}=\operatorname{cov}(X_i,Z_j)$.
Comment: Thanks. Aren't you missing a transpose in the answer though: $D-D^TA^T(ADA^T)^{-1}AD = D-D^TA^T(A^T)^{-1}D^{-1}A^{-1}AD =D-D^TD^{-1}D=D-D^T$.
Comment: And, in fact, if D is diagonal, $D-D^T=0$. Right?
Comment: That's because $D=D^T$, and you can't inverse $A$; it's not square.
Comment: Ah right, of course. Thanks a lot! So in the $k \rightarrow 0$ limit, I can't simplify beyond dropping the $kI$ term in your original answer?
Comment: I'm afraid not. You can use matrix inversion lemma, but still it's not in an easy form.


Zeroth homotopy group of the space $O(3)/H$

Question: Short version of the question:
Is $\pi_0(O(3)/C2) = Z_2$ as $\pi_0(O(3)) = Z_2$? Here $C_2$ is a cyclic group of order 2.
Long version or the question:
The zeroth homotopy group describes the connectness of a space. Take the space $O(3)/H$ as an example, where $H$ is a subgroup of the Lie group $O(3)$. If $H = \{1\}$, then $O(3)/H = O(3)$ containing two disjoint copies of $SO(3)$. Therefore, $\pi_0(O(3)/H) = Z_2$ in this case.
Then a question occurred to me: does $\pi_O$ in general given by the number of disjoint copies of a space. If I consider a situation $H=C_2$ where $C_2$ is the order-2 cyclic group $\{1,e^{i\pi}\}$. $C_2$ will define an equivalence in each copy of $SO(3)$ by a $\pi$-rotation of some axis, thus the space $O(3)/C_2$ contains two disjoint copies as $O(3)$, is $\pi_0(O(3)/C_2) = \pi_0(O(3))=Z_2$?
Furthermore, if $H = C_i = \{1,-1\}$, $C_i$ defines a map between the two disjoint copies of $SO(3)$, if so does the space $O(3)/C_i$ contain only one connected copy, and therefore $\pi_0(O(3)/C_i) $ is trivial?
These may be quite naive questions, but I only have a background of physics and the references I read do not explain the $\pi_0$ much. Can any one give me some hits? Any references would be much  appreciated as well?
Answer: $\pi_0$ is not in general a group. It is the set of homotopy classes of maps from a point into the space. Since a homotopy between two constant maps is a path, this is essentially the set of path components of the space (maximal path connected subsets). If the space is a topological group, then the set of path components has a group structure, but this is a special case.
Comment: Does $\pi_0$ always take value from integers which label the different pieces of disconnect subsets?
Comment: I don't understand. $\pi_0$ is a set of homotopy classes from a point into the space.


wget only works when tcpdump is listening

Question: I am running two Virtual Machines over the XEN hypervisor both with Ubuntu trusty (Linaro-Developer version) with the following simple bridge networking setup:

Backend domain (dom0):
br0       Link encap:Ethernet  HWaddr 02:4d:04:41:96:a9
          inet addr:220.127.116.11  Bcast:184.108.40.206  Mask:255.255.248.0
          inet6 addr: fe80::4d:4ff:fe41:96a9/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4896629 errors:0 dropped:814 overruns:0 frame:0
          TX packets:1134 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:356819584 (356.8 MB)  TX bytes:277236 (277.2 KB)

eth0      Link encap:Ethernet  HWaddr 02:4d:04:41:96:a9
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4906298 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2249 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:430584499 (430.5 MB)  TX bytes:362740 (362.7 KB)
          Interrupt:44

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:16 errors:0 dropped:0 overruns:0 frame:0
          TX packets:16 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1248 (1.2 KB)  TX bytes:1248 (1.2 KB)

vif1.0    Link encap:Ethernet  HWaddr fe:ff:ff:ff:ff:ff
          inet6 addr: fe80::fcff:ffff:feff:ffff/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1049 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4767521 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:32
          RX bytes:66258 (66.2 KB)  TX bytes:416912687 (416.9 MB)

guest domain (domU)
eth0      Link encap:Ethernet  HWaddr 00:16:3e:54:95:f5
          inet addr:188.8.131.52  Bcast:184.108.40.206  Mask:255.255.248.0
          inet6 addr: fe80::216:3eff:fe54:95f5/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4879495 errors:0 dropped:815 overruns:0 frame:0
          TX packets:1049 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:358293232 (358.2 MB)  TX bytes:80944 (80.9 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:672 (672.0 B)  TX bytes:672 (672.0 B)

Netwoking in dom0 is working fine (apt-get, wget). Buti n domU i experience a very strange problem: ping works well but apt-get and wget doesn't work.
root@MyUbuntu:~# wget -p http://google.com
--1970-01-01 00:52:49--  http://google.com/
Resolving google.com (google.com)... 18.104.22.168, 22.214.171.124, 188.8.131.52, ...
Connecting to google.com (google.com)|22.214.171.124|:80... connected.
HTTP request sent, awaiting response... No data received.

I install tcpdump on dom0 to debug the problem, running a simple command:
tcpdump -i br0 -n "tcp and src 184.108.40.206"

However, whenever tcpdump is listening wget and apt-get works well:
root@MyUbuntu:~# wget -p http://google.com
--1970-01-01 00:42:27--  http://google.com/
Resolving google.com (google.com)... 184.108.40.206, 188.8.131.52, 220.127.116.11, ...
Connecting to google.com (google.com)|184.108.40.206|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://www.google.de/?gfe_rd=cr&ei=qJIzVs3qJqSh8wfLma_QCw [following]
--1970-01-01 00:42:27--  http://www.google.de/?gfe_rd=cr&ei=qJIzVs3qJqSh8wfLma_QCw
Resolving www.google.de (www.google.de)... 184.108.40.206, 22.214.171.124, 188.8.131.52, ...
Reusing existing connection to google.com:80.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: 'google.com/index.html'

    [ <=>                                   ] 19,468      --.-K/s   in 0.003s

1970-01-01 00:42:27 (5.84 MB/s) - 'google.com/index.html' saved [19468]

FINISHED --1970-01-01 00:42:27--
Total wall clock time: 0.09s
Downloaded: 1 files, 19K in 0.003s (5.84 MB/s)

Does tcpdump open any port allowing the traffic to go through ?
Any help is much appreciated.Thank you.
Answer: When you start tcpdump it places the interface in promiscuous mode.  That might be what is allowing the data to reach domU while tcpdump is active.
You could test that theory by adding --no-promiscuous-mode to the tcpdump command.  Or by manually setting the interface to promiscuous mode.
Not sure how that helps to resolve the actual issue though.
Comment: Uhm you are right. I wonder what is wrong with my bridge network in the first place. Do you have any suggestion ?
Answer: When bridging, the physical interface must be in promiscuous mode. This is so that packets addressed to the bridge and virtual interfaces can be seen and forwarded.
Solution is to ensure that your eth0 is configured with "promisc" enabled.


JQuery .ajax dosen't work with http://127.0.0.1:5984

Question: Help me with my problem,please!
I used CouchDB, and i used jquery.couch.js to communicate with a CouchDB server (http://daleharvey.github.com/jquery.couch.js-docs/symbols/index.html)
but it's dosen't work(( Start of such script:
<code>$.couch.urlPrefix = 'http://127.0.0.1:5984'
function getAllDBs(){
    $.couch.db('mysecondtest').allDocs({
        error: function(status, id, reason) {alert(status+' : '+id+' : '+reason);},
        success:function(data){
            alert(data);
        }

    });
}
getAllDBs();
</code>
return an error:
<code>405 Method Not Allowed localhost:5984
</code>
I think, it means that the server perceives my request as request about the remote server, but I don't know as to correct it. Please help me and sorry for my bad English))
Answer: You are falling into a cross-domain issue.
You may consider using couchdb-xd
Comment: Whenever there's cross-domain issue, you have to consider JSONP instead
Comment: It can be possible as that to get rid from cross-domain?
Comment: Probably you cannot as couchdb runs on different port even if on the same server.
Comment: Please read more on cross-site scripting http://en.wikipedia.org/wiki/Cross-site_scripting
Comment: thancks for couchdb-xd, i will use it)
Comment: Please consider marking the answer as correct for other people know about it
Comment: @AbdulMunim: The error says "method not allowed". Why would that imply a cross domain issue? This surely means our questioner is doing say OPTIONS or PUT where the server only supports GET.
Answer: Ajax requests cannot happen cross-server per design. This is of security-reasons.
Comment: cross-server is also across ports.
Comment: i know, but i don't use cross-server. it's localhost!
Comment: Whether use proxy will help to correct it? And if yes, as it to make?


How can I track statistics regarding the number of sign-ups vs. account deletions?

Question: I'm working on a social networking site in Drupal 7 that I haven't launched yet.  However, once I've launched I would like some basic metrics to track how I'm doing, particularly the number of sign-ups per week (or some other arbitrary interval) and the number of users who have cancelled/deleted their accounts.
Is there a way to track this from within Drupal?
Comment: Just a short thought: users do not necessarily delete accounts. They might just abandon them.
Comment: That's true, and it would be useful to track that as well.  However, my main concern is account deletion, because those users probably had an extremely bad experience at the site or have some other significant reason to leave.
Answer: Views is your friend. You can build a view that shows the total number of registrations per week, for example. You can use an exposed filter to change the date ranges.
You can use user stats to keep track of last login time and then built a similar view.
If you user userpoints you can get stats based on activity (or the lack thereof).
Answer: First of all I wouldn't allow users to delete accounts themselves.
I would suggest to use Webform to gather requests for account deletion and additionally query users about the reason to delete account.
Then the site administrator would use a report based on Views Bulk Operations to delete accounts.
You can gather statistics based on urls used by users to register and to delete account.
See http://drupal.org/documentation/modules/statistics.
For more data analysis I use Google Analytics.


How to make possible to return structs of different types from one function with Golang?

Question: I have a function which queries database, then, depending on result form it, can create a struct OrderWithoutDetails or OrderWithDetails depending on the presence of details about the order.
How do I make the function to be able to return result of both types?
Comment: On what depends, whether you will get details or not? If you know that when you call the function, is better to have 2 different functions. If not, and OrderWith/WithoutDetails is nearly the same, you can write a function, func findOrder (Order, *[]Detail, error), that returns details or nil. Also you can put *Details to order. And also fine is return interface{}, or better interface, that returns you details.
Answer: You can use interface{}
func queryDb() interface{}{

}

But the better will be if your 2 type of struct can have a common function, that can satisfy a common interface, it will be cleaner.
Example :
type s1 struct{
  id int
  name string
}

type s2 struct{
  id int
  age int
}

type reDB interface {
  my_print()
}

func (r *s1) my_print(){
  fmt.Print(s1.id)
}

func (r *s2) my_print(){
  fmt.Print(s1.id)
}

func queryDb() reDB{
 ...
}

Comment: Underscores in names are not idiomatic in Go.  Go uses CamelCase, not snake_case.  This is particularly important because, in your example, the interface `reDB` and the `my_print()` function within it are not exported, and thus cannot be accessed outside the defining package.
Comment: Yep, I knew for the `CamelCase`, I wrote quickly, with my practice from C.
But it has nothing to do with exported or not, only the first letter has something to do with, and `CamelCase` is not `PascalCase`. Plus here we don't care about exported or not, maybe he doesn't want to export these func / var ;)


Change Desktop background using VB.NET

Question: Is it possible to change desktop background using VB.NET?
I'd like to change the icons too?
I plan on making a VB.NET program that can automatically make Windows XP look like Mac in just one click.
Answer: Steps you will do.
Start visual studio 2005 and create a new window project.
Set the following properties of the form
'Text = "Set Wallpaper"
'Size = "1024,750"

Now drip a picture box control on the form and set its following properties.
'Size = "1024,725"
'Sizemode = "centerimage"

Drop a two button controls on the form and set its following properties as below.
'First button control.

'Name = " btgetimage"
'Text = " Brows For Image"

'Second button control.

'Name = " btsetwallpaper"
'Text = " Set Wallpaper"

Now drop an openfiledialog control on the form.
Open you code window and import the following namespace.
Imports System.IO.Directory

Now declare the function and variables as below which will use win API's to set the wallpaper.
Private Const SPI_SETDESKWALLPAPER As Integer = &H14

Private Const SPIF_UPDATEINIFILE As Integer = &H1

Private Const SPIF_SENDWININICHANGE As Integer = &H2

Private Declare Auto Function SystemParametersInfo Lib "user32.dll" (ByVal uAction As Integer, ByVal uParam As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) As Integer

Const WallpaperFile As String = "c:\wallpaper.bmp"

Make a function as below.
   Friend Sub SetWallpaper(ByVal img As Image)

    Dim imageLocation As String

    imageLocation = My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.MyPictures, WallpaperFile)

    Try

    img.Save(imageLocation, System.Drawing.Imaging.ImageFormat.Bmp)

    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imageLocation, SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)

    Catch Ex As Exception

    MsgBox("There was an error setting the wallpaper: " & Ex.Message)

    End Try

    End Sub

Now in the click event of the first button write the following code to open and get the image.
OpenFileDialog1.InitialDirectory = "c:\"

OpenFileDialog1.Filter = "JPG|*.jpg|Bitmap|*.bmp"

Dim dialogresult As DialogResult = OpenFileDialog1.ShowDialog

If dialogresult = Windows.Forms.DialogResult.OK Then

PictureBox1.ImageLocation = OpenFileDialog1.FileName

btsetwallpaper.Enabled = True

End If

In the click event of the second button write following code to set the wallpaper.
SetWallpaper(Me.PictureBox1.Image)

MessageBox.Show("Wallpaper has been changed", "Set Wallpaper", MessageBoxButtons.OK, MessageBoxIcon.Information)

Comment: did you fing this at http://www.devasp.net/net/articles/display/421.html [Changing the Desktop Wallpaper Programmatically] ?
Comment: @astander - would it make a difference if he did??
Comment: How about for dual screens? I'm about to build something since Windows 7 doesn't let you set 2 different backgrounds for dual monitors.
Comment: So glad this whole solution was in an answer and not relying on an external link - the external link is no longer valid!
Answer: Try this program :
Imports System
Imports System.Runtime.InteropServices

Public Class Desktop

    Public Shared SPI_SETDESKTOPWALLPAPER As Integer = 20
    Public Shared SPIF_UPDATEINIFILE As Integer = 1
    Public Shared SPIF_SENDWININICHANGE As Integer = 2

    Public Shared Sub Main(ByVal args() As String)
        If (args.Length = 1) Then
            SystemParametersInfo(SPI_SETDESKTOPWALLPAPER, 0, args(0), _
            (SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE))
        End If
    End Sub

    Private Declare Sub SystemParametersInfo Lib "User32.dll" (ByVal action As Integer, _
        ByVal iparam As Integer, ByVal vparam As String, ByVal option As Integer)

End Class

Answer: you can use Win32 'user32' for change the desktop background.
you need to declare user32 pi function SystemParametersInfo like as:
Private Declare Function SystemParametersInfo Lib "user32″
Alias "SystemParametersInfoA" (ByVal uAction As Integer, ByVal uParam As Integer,
ByVal lpvParam As String, ByVal fuWinIni As Integer) As  Integer

and call this function with valid parameters
you can also check this link, this is the good article for learning how to change desktop background in vb.net
http://www.authorcode.com/how-to-set-desktop-background-in-vb-net/
Answer: This is a simple and functional code that sets your desktop using only a timer
Public Class Form1

   Dim Location As String

   Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" (ByVal uAction As Integer, ByVal uParam    As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) As    Integer

   Private Const SETDESKWALLPAPER = 20
   Private Const UPDATEINIFILE = &H1

   Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

       Location = ("image directory.jpg")

       PictureBox1.BackgroundImage = Image.FromFile("C:\Users\Danny\Desktop\Hacker.jpg")

       PictureBox1.BackgroundImageLayout = ImageLayout.Stretch

       SystemParametersInfo(SETDESKWALLPAPER, 0, Location, UPDATEINIFILE)

   End Sub     End Class

Answer: My personal version timered with 1 button, 1 checkbox, 1 timer (10 seconds) and 1 openfiledialog:
Imports System
Imports System.Runtime.InteropServices
Imports System.Threading

Public Class Form1
    Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" (ByVal uAction As Integer, ByVal uParam As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) As Integer

    'Declare two constant
    Private Const SETDESKWALLPAPER = 20
    Private Const UPDATEINIFILE = &H1
    Private Const SENDWININICHANGE As Integer = 2
    Dim numfiles As Integer = 0
    Dim numtimer As Integer = 0

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        OpenFileDialog1.Multiselect = True
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "JPEG Files|*.jpg|BMP Files|*.bmp|PNG Files|*.png|GIF Files|*.gif"
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            If CheckBox1.Checked = False Then
                SystemParametersInfo(SETDESKWALLPAPER, 0, OpenFileDialog1.FileName.ToString, UPDATEINIFILE Or SENDWININICHANGE)
            Else
                Dim file As String
                For Each file In OpenFileDialog1.FileNames
                    numfiles += 1
                Next file
                Timer1.Start()
            End If
        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = False Then
            Timer1.Stop()
            numfiles = 0
            numtimer = 0
        End If
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If numtimer < numfiles Then
            SystemParametersInfo(SETDESKWALLPAPER, 0, OpenFileDialog1.FileNames(numtimer).ToString, UPDATEINIFILE Or SENDWININICHANGE)
            numtimer += 1
        Else
            numtimer = 1
            SystemParametersInfo(SETDESKWALLPAPER, 0, OpenFileDialog1.FileNames(numtimer).ToString, UPDATEINIFILE Or SENDWININICHANGE)
        End If
    End Sub
End Class

Change Desktop background using VB.NET