What is an intuitive explanation for $\operatorname{div} \operatorname{curl} F = 0$?

Question: I am aware of an intuitive explanation  for $\operatorname{curl} \operatorname{grad} F = 0$ (a block placed on a mountainous frictionless surface will slide to lower ground without spinning), and was wondering if there were a similar explanation for $\operatorname{div} \operatorname{curl} F = 0$.
Comment: See this similar MO question: http://mathoverflow.net/questions/21881/how-should-one-present-curl-and-divergence-in-an-undergraduate-multivariable-calc
Comment: Strang points out in his CSE book that div curl = 0 is the transpose of curl grad = 0.
Answer: Update: I felt that in my original answer, the intuition got lost in all of the formalism, so I've rewritten it to make it clearer. The core idea is still much the same as Qiaochu's answer on the linked MO question.
First off, I don't think you're going to get an explanation for $\nabla\cdot (\nabla\times \mathbf F) = 0$ that's on quite the same level as your sliding block example, because while the gravitational force is well-known to be the gradient of the negative potential, there aren't any tangible vector fields that are the curl of something. The curl, like the cross product, is a little "unnatural" as it depends on the choice of handedness; classical physics, on the other hand, is independent of handedness, so you can never observe a curl directly, only hidden under an integral or cross product to make the handedness goes away.
Nevertheless, the most mathematically natural argument that $\nabla\cdot (\nabla\times \mathbf F) = 0$ is quite easy to grasp. For a warm-up, let's look at another explanation for why $\nabla\times (\nabla f) = 0$. The curl of any vector field $\mathbf F$ describes how much $\mathbf F$ "spins around", right? So take any closed loop in space; the net curl inside the loop is nothing but how much $\mathbf F$ "circulates" around the loop, i.e. $\oint \mathbf F \cdot d\mathbf x$. But if $\mathbf F$ is a gradient of something, say $f$, then $\mathbf F \cdot d\mathbf x$ is actually how much $f$ is going up or down as you walk along $d\mathbf x$. So if you walk along a closed loop and come back to where you started, the net change in $f$ has to be zero! Or as wzzx's comment states: you can't walk from home to school and back and have gone uphill both ways.
Now we can do the same thing for $\nabla\cdot(\nabla\times \mathbf F)$. Intuitively, the divergence of a vector field $\mathbf G$ measures how much $\mathbf G$ is "spreading out" or "pulling in". In other words, pick any region of space; what does the total divergence of $\mathbf G$ inside it tell you? It tells you exactly how much $\mathbf G$ is flowing out of the surface of the region, i.e. $\oint \mathbf G \cdot d\mathbf A$. But if $\mathbf G$ is the curl of another vector field $\mathbf F$, then $\int \mathbf G \cdot d\mathbf A$ on a surface just measures how much $\mathbf F$ circulates around the boundary of that surface. What's the boundary of a closed surface? Imagine taking a portion of the entire surface and growing it to cover the whole. Its boundary eventually gets smaller and smaller, and then disappears. So there is nothing for $\mathbf F$ to circulate around, and the circulation must be zero.
All I've shown here is that the integrals of $\nabla\times(\nabla f)$ and $\nabla\cdot(\nabla\times\mathbf F)$ are zero on any arbitrary region, but that should be enough to see that (at least for smooth $f$ and $\mathbf F$) their values must be zero everywhere.
Comment: Yes, I think the most geometric way to think about all of these issues is to take the various relevant forms of Stokes' theorem as _definitions_ of all these operators and prove that they exist from there...
Comment: The assumption "at least for smooth $f$ and $F$" seems to be important. I'm thinking about how Stoke's Theorem requires at most continuity of first partials, but $\mathrm{div}\ \mathrm{curl}(F)=0$ requires continuity of second partials (because it depends on Clairaut's Theorem). So the appropriate integrals of continuously differentiable "counterexamples" to Clairaut's Theorem over arbitrary (suitable) regions might be zero even though $\mathrm{div}\ \mathrm{curl}(F)\ne 0$ for every point in the regions.
Answer: Formal Intuition
"Formal intuition" is a bit of a contradiction, but look at
$$\mathbf{A} \cdot (\mathbf{A} \times \mathbf{B})$$
Cross products are perpendicular to the things being crossed, so $\mathbf{A \times B}$ is perpendicular to $\mathbf{A}$. The dot product of perpendicular vectors is zero, so
$$\mathbf{A} \cdot (\mathbf{A} \times \mathbf{B}) = 0$$
Replacing $\mathbf{A}$ with $\nabla$ would give the identity, but I'm not sure if this counts as intuitive.  Note: This isn't supposed to be a proof.  It's only supposed to suggest the identity.
Geometric Intuition
Here, I'll use Gauss's theorem and Stoke's theorem, which themselves have intuitive explanations.
Make a coordinate system like this:

Consider a cubical box.  Make it centered at the origin with sides of length $1$, so the corners are $(.5,.5,.5)$, $(.5,.5,-.5)$, $(.5,-.5,.5)$, etc.  This is for convenience - the area of each side is $1$ and the volume is $1$, so any time I need to divide or multiply by the area of a side or by the volume, nothing changes.
We are looking at $\nabla \cdot (\nabla \times \mathbf{F})$.  Ignoring the stuff inside the parentheses, we're looking at a divergence of something.  Let's call that thing $\mathbf{C}$ since it's a curl.
Gauss' theorem says that the integral of the divergence over the volume of the box is equal to the net flux coming out.  This means that we can find the average divergence over the entire box by thinking only about the faces.
Consider the top face.  To find the flux coming out of the top face, first find the average of $\mathbf{C}$ over that face.  Then project that vector onto a unit normal vector, $\hat{z}$.  This gives a vector $\mathbf{C}_z$ that either points into or out of the box.  If it points out, it contributes positive flux, and if it points in, it contributes negative flux.

If we can show that all six such vectors (one for each face) contribute zero net flux when combined, we know that the average divergence over our box is zero.  How do we get information about the average of $\mathbf{C}$, projected onto a normal vector, over some face?
This is where the curl comes in.  Stokes' theorem says that the average of $\mathbf{C}_z = (\nabla \times \mathbf{F})\cdot\hat{z}$ over the top is equal to the line integral over the edges of the top face of $\mathbf{F}\cdot \hat{r}$, with $\hat{r}$ a unit tangent vector.  In other words, each of the four edges of the top gives some contribution to the average of $\mathbf{C}_z$ on the top.
Grab one particular edge - the one from $(.5, -.5, .5)$ to $(.5,.5,.5)$ will do.  Suppose we traverse it from left to right, and get a positive number, say $4.2$, out of the line integral of $\mathbf{F} \cdot \hat{r}$ along that edge.

The purple vector is the original vector field $\mathbf{F}$.  It gets projected onto $\hat{r}$ to make $F_r$, the purple segment.  This gets integrated along the edge, and contributes to the black vector $\mathbf{C_z}$, which itself contributes to the flux.
The important thing to note is that this $4.2$ value of the line integral along the edge gets used twice in finding the flux because the edge borders on two different faces.  For the top face, going left-to-right on our edge means circling clockwise as viewed from above.  The right-hand rule tells us that the positive $4.2$ of the line integral along our edge contributes positively to a vector $\mathbf{C_z}$ point out of the top.  Since it points up out of the top, it contributes negative flux.  All told, traversing our edge, thinking of it as part of the top of the cube, contributes $-4.2$ to the total flux.
When we look at the front of the cube, going left-to-right on our edge means going clockwise around the front, as viewed from in front of the cube.  The right hand rule means that a positive clockwise line integral around the front creates a vector $\mathbf{C}_x$ pointing into the cube - positive flux.  So this time our edge contributes $+4.2$ to the total flux.

The edge's two contributions to the flux cancel each other because one point outwards and the other points inwards.  There is nothing special about this edge, so all edges will be canceled by their two contributions to the flux.  The total flux for this cube is zero.  That means the average of the divergence over the cube is zero.  There was nothing special about this cube, so the average divergence over any cube is zero, and the divergence itself must simply be zero everywhere.
Physical Intuition
This theorem about the divergence of the curl is responsible for the conservation of charge.  Begin with Maxwell's equation for the curl of the magnetic field
$$\nabla \times \mathbf{B} = \frac{1}{c}\frac{\partial \mathbf{E}}{\partial t} + \frac{4 \pi}{c} \mathbf{J}$$
Take the divergence of both sides.
$$\nabla \cdot (\nabla \times \mathbf{B}) = \frac{1}{c} \frac{\partial}{\partial t} \nabla \cdot \mathbf{E} + \frac{4\pi}{c}\nabla\cdot\mathbf{J}$$
Now use Maxwell's equation for the divergence of the electric field
$$\nabla \cdot \mathbf{E} = 4\pi \rho$$
Insert this into the above to get
$$\nabla \cdot (\nabla \times \mathbf{B}) = \frac{4 \pi}{c} \left(\frac{\partial \rho}{\partial t} + \nabla\cdot\mathbf{J}\right)$$
We expect that electric charge will be conserved.  That means the the flux of charge current coming out of some region must be compensated by a loss of charge density there.
$$\nabla \cdot \mathbf{J} = -\frac{\partial \rho}{\partial t}$$
Plugging this into our previous expression gives
$$\nabla \cdot (\nabla \times \mathbf{B}) = \frac{4 \pi}{c} \left(\frac{\partial \rho}{\partial t} -\frac{\partial \rho}{\partial t}\right) = 0$$
This means that if electromagnetic fields obey Maxwell's equations and if electric charge is conserved, then the divergence of the curl of any magnetic field must be zero.  However, I'm not sure how intuitive this is, and also the magnetic field cannot be chosen arbitrarily because it must be divergenceless.
We could repeat the procedure for Maxwell's equation for the curl of the electric field.  There, we'd get
$$\nabla \cdot (\nabla \times \mathbf{E}) = \frac{\partial}{\partial t}\left(\nabla \cdot \mathbf{B}\right) = 0$$
because the magnetic field is divergenceless.  So the absence of magnetic charge implies that the divergence of the curl of all electric fields is zero.  Electric fields, unlike magnetic fields, can be essentially arbitrary as far as I know, and so viewed in a certain light Maxwell's equations imply the sought vector identity.
Comment: The formal part is slightly misleading, generally you cant replace the vectors in vector identities with operators
Comment: @kake Right.  It's not supposed to be a proof so much as a heuristic to suggest the identity might be true.
Comment: @kake. Actually, the formal part can be made rigorous by applying a Fourier transform which maps $\nabla \mapsto q$.
Comment: @Greg Ofcourse it can be made rigorous, because its true in this case.
Comment: @Mark Eichenlaub I think you have a typo: "I'll [prove?] Gauss's theorem..."
Comment: @Billare Thanks.  Should say "I'll use Gauss's..."
Comment: Why the down votes?
Comment: @Mark: Not sure, but you-know-what to them and the horses they came in on! Thanks for the answer.
Answer: Here's an explanation I was given while I was still in high school (but not in school, of course!). I didn't fully understand it at the time, but it might be illuminating if you're willing to accept the generalised Stokes theorem. Essentially, it's the claim that
$$\int_{M} d\omega = \int_{\partial M} \omega$$
where $\omega$ is a differential $(n - 1)$-form, $d\omega$ is its exterior derivative, $M$ is an $n$-dimensional smooth manifold with boundary, and $\partial M$ its boundary. (There are some technical conditions which I'm glossing over.) I should probably explain what these things are though:

A smooth $n$-manifold with boundary is an $n$-dimensional smooth geometric object where every interior point has a neighbourhood which looks like a piece of our familiar Euclidean $n$-space $\mathbb{R}^n$, and every boundary point has a neighbourhood which looks like a piece of $\mathbb{R}^{n-1} \times [0, \infty)$, which is just $\mathbb{R}^n$ chopped in half. For example, the interval $[0, 1]$ is a smooth 1-manifold with boundary, and its boundary is the set $\{ 0, 1 \}$; and the closed unit disc is a 2-manifold with boundary the unit circle.
Note that the unit circle is a 1-manifold without boundary; this is an instance of the general fact that the boundary of a smooth $n$-manifold with boundary is a smooth $(n-1)$-manifold without boundary.
A differential $n$-form is essentially what you integrate when doing an $n$-fold integral. For example, in $\displaystyle \int_{-\infty}^{\infty} \exp(-x^2) \, dx$, you are integrating the differential 1-form $\exp(-x^2) \, dx$ over the 1-manifold $\mathbb{R}$, and in $\displaystyle \int_{0}^{2\pi} \int_0^1 r \, dr \, d\theta$, you are integrating the differential 2-form $r \, dr \wedge d\theta$ over the closed unit disc.
The exterior derivative of a differential $(n-1)$-form is a differential $n$-form. It's simultaneously a generalisation of the gradient, curl, and divergence operators. (More on this later.)

Now, I suppose I should explain what this has to do with div, grad, and curl. Let's start with a function $f$ of 3 real variables $(x, y, z)$. This can be regarded as a differential 0-form, and so it has an exterior derivative $df$. This is essentially the same thing as $\nabla f$; indeed, we can expand $df$ using the chain rule to get
$$df = \frac{\partial f}{\partial x} \, dx + \frac{\partial f}{\partial y} \, dy + \frac{\partial f}{\partial z} \, dz$$
which, neglecting certain subtleties, is the same as $\nabla f$ expanded out in the standard basis. Suppose instead I give you a differential 1-form $F = a \, dx + b \, dy + c \, dz$. Its exterior derivative is
$$dF = \left( \frac{\partial c}{\partial y} - \frac{\partial b}{\partial z} \right) \, dy \wedge dz + \left( \frac{\partial a}{\partial z} - \frac{\partial c}{\partial x} \right) \, dz \wedge dx + \left( \frac{\partial b}{\partial x} - \frac{\partial a}{\partial y} \right) \, dx \wedge dy$$
which, with a little squinting, is seen to be more-or-less the curl $\nabla \times F$. (This is basically the chain rule again, but you might be wondering why there aren't 9 terms in the exterior derivative and where all the minuses are coming from. This is because for any differential 1-form $\alpha$, $\alpha \wedge \alpha = 0$. Applying this to $(dx + dy) \wedge (dx + dy)$, we see that $dx \wedge dy = -dy \wedge dx$ — that is, the wedge product $\wedge$ of differential 1-forms is anticommutative, just like the cross product of two vectors.)
Finally, suppose I have a differential 2-form $A = a \, dy \wedge dz + b \, dz \wedge dx + c \, dx \wedge dy$. Its exterior derivative is
$$dA = \left( \frac{\partial a}{\partial x} + \frac{\partial b}{\partial y} + \frac{\partial c}{\partial z} \right) \, dx \wedge dy \wedge dz$$
which is quite obviously related to the divergence $\nabla \cdot A$.
The generalised Stokes theorem is a vast generalisation of the fundamental theorem of calculus, the Kelvin—Stokes theorem, and the divergence theorem. Indeed, they are all special cases: again, working in 3-dimensional Euclidean space, we get

When $\omega$ is a 0-form, the fundamental theorem of calculus: $$\displaystyle \int_{P}^{Q} \nabla f \cdot d\vec{x} = f(Q) - f(P)$$
When $\omega$ is a 1-form, the Kelvin—Stokes theorem: $$\displaystyle \int_S \nabla \times \vec{F} \cdot d\vec{S} = \oint_{\partial S} \vec{F} \cdot d\vec{x}$$
When $\omega$ is a 2-form, the divergence theorem: $$\displaystyle \int_V \nabla \cdot \vec{A} \, dV = \int_{\partial V} \vec{A} \cdot d\vec{S}$$

Of course, exactly as with div, grad, and curl, just by fiddling with the definitions, you can show that for any differential $n$-form $\omega$, the exterior derivative of the exterior derivative is $d^2 \omega = 0$. But this doesn't explain why it should happen, and I think the best explanation is through the generalised Stokes theorem:
$$\int_M d^2 \omega = \int_{\partial M} d\omega = \int_{\partial^2 M} \omega$$
This shows that the fact that $d^2 \omega = 0$ is intimately linked to the fact that $\partial^2 M = \emptyset$, i.e. that the boundary of a smooth manifold itself doesn't have a boundary. Translating this to the classical notation, we immediately have the identities
$$\nabla \times (\nabla f) = 0$$
$$\nabla \cdot (\nabla \times F) = 0$$
as promised.
Answer: The curl of a vector field $F$ at a point on an infinitesimal surface $S$ can be thought of as how the vector field "spins" $S$. The divergence, on the other hand, describes how much the vector field "passes through" $S$. If you take the a vector field which spins a surface, how much does it pass through the surface? None.
Of course, this is a highly non-technical explanation.
Comment: I don't understand. Let $S$ be a sphere centered at the origin, and take the vector field which "spins" about the $z$-axis, so $F(x,y,z) = (-y,x,0)$. Now $F$ is tangential to $S$, so it does not "pass through" the surface at all. But how does this show that $\nabla\times F = (0,0,2)$ does not "pass through" the surface?
Comment: Sorry- I meant the net flow through an infinitesimal surface. In your example, the flow out of the surface is equal to the flow in.
Answer: Think of the surface of water, and a two dimensional vector field $\mathbf{F}(x,y)$ which gives its velocity everywhere. Think that you put a needle that floats somewhere on its surface. If the needle is rotating, then it is in a region of non-zer curl, and if the needle (EDIT: a bunch of them) appears to be translating inwards or outwards towards or away from some point, then it is a region of non zero divergence. Finite divergence just means there's like a hose pipe somewhere which is sucking in or spewing out fluid radially.  This is how you can think of the divergence and the curl individually.
For your question, think of a mixed region with non zero divergence and non-zero curl. The direction of the curl would be along the axis of rotation and hence perpendicular to the surface.
$$\mathbf{\nabla} \times \mathbf{F}(x,y) = g(x,y) \hat{z}$$
$$\nabla \cdot \mathbf{\nabla} \times \mathbf{F}(x,y) =  \frac{\partial g(x,y) }{\partial z} = 0$$
Or intuitively, the curl is perpendicular to the divergence, which is an abuse of notation because divergence is really an operator, so this is as far as the analogy goes.
Comment: I like the analogy to a fluid flow, but for the divergence, were you referring to many needles converging to or diverging from a point rather than one needle?  That would make more sense to me since one needle cannot change its shape or grow and shrink.  I'm also wary of considering a two-dimensional fluid when the curl is defined in three.
Comment: @Mark True. We need atleast two needles which should be coming together or going away.
Answer: I apologize first if my explanation below had been proposed before because there are so many answers that I have no time to check every comment. I also wish to thank my student in my Electromagnetic Theory class, Yung-Chi Chien, for helpful discussions this year.
To show that div curf F = 0, the simplest way is to expand curl F and then div curl in the Cartesian coordinate system. Changing the order of partial differentiation will cancel out all of the expanded terms.
Here is a "proof" without using specific coordinate systems. Consider a surface integral of curl F over an arbitrary closed surface, say, a spherical surface S.  Due to the divergence theorem, that surface integral equals the volume integral of div curl F.
At the same time, let the sphere S be cut into two.  The surface integral of curl F over the upper hemisphere equals a line integral of F along a circle determined by the boundary curve C (a circle here) of the two hemispheres.  The line integral on C may be, for example, counterclockwise. Similarly, the surface integral of curl F over the lower hemisphere is again equal to a line integral on C but integrating clockwise.  These two line integrals on C thus cancel each other.  Hence the surface integral over the whole S will be zero, and the volume integral of div curl F is zero, too.  Since we can change the radius and position of the sphere at will, div curl F must be zero.
curl grad phi can be proved similarly, and many people have pointed out clear interpretations.
Answer: Below is the entry I put in my RemNote. I hope it is helpful. It is not formal; but, it is intuitive.


Efficient method for generating combined spectra from N-body simulation data using Python (convolution)

Question: (I asked this same question also in StackOverflow, due to being both astronomy/coding problem, here link : https://stackoverflow.com/questions/78166419/efficient-method-for-generating-combined-spectra-from-n-body-simulation-data-usi )
I'm working with some N-body simulation data, and attempting to generate a combined spectrum from particles within a specific region (i.e. inside one 'pixel' or voronoi bin). Each particle has associated line-of-sight (LOS) velocities. My current approach involves Doppler shifting a stellar template spectrum (see top panel of figure below) for each particle and interpolating it back to original wavelenght points to sum up the fluxes. This method works, but it is a bit slow when applied to the full dataset of about 8 million particles.
Example of stellar template (obtained from Miles  ). The template includes 4300 wavelenght points. The lower panel represent the combined spectrum of 112,866 particles.
Example stellar template and combined spectrum
Current method :

# Variables used in this method
template_wavelength_ln # Wavelengths of the template spectra with even intervals in ln scale
template_flux_ln # Fluxes of this template spectra

LOSv  # Line-Of-Sight velocities of particles corresponding to certain 'pixel'
# --------------
# The coding method itself

wavelengths_shift = DPF.doppler_shift(np.e**template_wavelength_ln, LOSv.reshape(-1,1))
# This calculates the doppler shift of the template wavelengths for each particle.
# Returns 2d array. Due to high particle number, I have used some chunking method here but I took it off here as its not relevant to the problem itself. (i think)

df_tot = pd.DataFrame({'lambda': np.e**template_wavelength_ln, 'Flux_tot':np.zeros_like(template_flux_ln), 'Flux_1':np.zeros_like(template_flux_ln),
'Flux_2':np.zeros_like(template_flux_ln)})

# The above is just data frame which would include the spectrum infos. Currently I'm doing this for two different stellar templates, thus Flux_1 and Flux_2, but for the sake of example we use only one template.

for wave in wavelenght_shift:
    flux_1 = np.interp(df_tot['lambda'], wave, template_flux_ln) #interpolate the shifted wavelenghts back to the original positions
    df_tot['Flux_1'] += flux_1
    # df_tot['Flux_tot'] += (flux_1 + flux_2)

# -----------------

And this generated the nice combined spectrum of the particles. However, its quite slow when the doing 8 million particles, mainly due to np.interp() I guess.
where DPF.doppler_shift is
def doppler_shift(wavelenghts, velocity, c=299792.458):
    ...
    lambda_shifted = wavelenghts * (1 + velocity/c)
    return lambda_shifted

Method 2
This method would use the advantage of convolution. Here is a link to a paper which describes how one could generate the spectrum of galaxy using a template and LOSVD (line of sight velocity distribution) Improving the full spectrum fitting method: accurate convolution
with Gauss-Hermite functions by Cappellari equation 1.
So, what I have done so far :
Obtained LOSVD of the particles in form of a Gauss-Hermite function. First I do a histogram of the LOS velocity particles, and then fit the Gauss-Hermite function to that histogram.
from scipy.optimize import curve_fit
# Same initial variables are used here as in the code above

# Initial guess for the Gauss-hermite parameters
initial_guess = [LOSv.mean(), LOSv.std(), 0, 0] # V_mean, sigma, h3, h4

# Histogram binning
bin_width = 10 # km/s
bin_edges = np.arange(LOSv.min() , LOSv.max() + bin_width, bin_width)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2

hist_density = np.histogram(LOSv, bins=bin_edges, density=True)[0]

params_fit_total, error_fit_total = curve_fit(DPF.gauss_hermite, bin_centers, hist_density, p0=initial_guess, maxfev=10000)

# ---------------
# where DPF.gauss_hermite is
from scipy.special import hermite
def gauss_hermite(v, v_mean, sigma, h3, h4):
   ...
   w = (v - v_mean) / sigma
   H3 = hermite(3, monic=True)(w)
   H4 = hermite(4, monic=True)(w)
   # One could also use these, I think
   # H3 = (2*np.sqrt(2)*w**3 - 3*np.sqrt(2)*w)/np.sqrt(6)
   # H4 = (4*w**4 - 12*w**2+3)/np.sqrt(24)
   L = 1/(sigma*np.sqrt(2*np.pi)) * np.exp(-0.5*w**2) * (1+h3*H4 + h4*H4)
   return L

# and then the LOSVD function i.e.

LOSVD_func = lambda v : DPF.gauss_hermite(v, *params_fit_total)

Now this params_fit_total includes the v0, sigma, h3 and h4 parameters of the LOSVD. Below is plot of the histogram and the LOSVD, including the v0 sigma h3 and h4 values in the legend.
LOSVD histogram and Gauss-Hermite function
The challenge now is to generate the 'total' spectrum using the initial stellar template and this LOSVD function via convolution. However I have some difficulties on understanding how to do this, as I have not used convolution very much. I believe that the units of 'parameters' within the convolution factors have to match, so one might need to convert everything to either wavelengths or velocities. I remember that I have heard/read somewhere that
"uniform sampling in the logarithm of the wavelength corresponds to a uniform sampling in velocity", which suggests a method for converting the units, but I'm not entirely sure how to implement this in practice.
Here are some equation algebra how I tried to justify the statement:
Doppler shift
$$\lambda_0 = \lambda_e (1+\frac{v}{c})$$
$$\rightarrow \lambda_0 - \lambda_e = \lambda_e \frac{v}{c}$$
$$\rightarrow \frac{\lambda_0-\lambda_e}{\lambda_e} = \frac{\Delta \lambda}{\lambda_e} = \frac{v}{c}$$
which for small changes in $\lambda$ , thus small change in $v$  yields into
$$\Delta \ln(\lambda) = \frac{v}{c}$$
meaning that small and uniform change in the ln scale indeed relates to uniform sampling in velocity.
Yet... i'm not completely sure how to implementate this information to the convolution. I feel like this is close to the answer, but I have not got the convolution working...
I have tried something like
from scipy.signal import fftconvolve

step_h_log = wave_log[1] - wave_log[0]
c = 299792.458 # km/s

# step_h_log = 0.0001717861122...
# so this would mean velocity bin of 51.5 km/s (step_h_log * c)

vel_space = np.arange( np.min(LOSv.min()), np.min(LOSv.max())+ step_h_log*c, step_h_log*c  )

test_convo = fftconvolve( DPF.doppler_shift(np.e**wave_log, vel_space), LOSVD_func(vel_space), mode='same' )

but indeed this gives error as the shapes differs... I have tried different ways but none gave the correct output.
If one is interested where to obtain the stellar templates, one can get them i.e. from here
http://research.iac.es/proyecto/miles/pages/webtools/tune-ssp-models.php .
I am not sure if I could paste the .txt files here which contain the wavelengths and fluxes
Any ideas? I would greatly appreciate the help for both coding aspect and perhaps understanding how the convolution actually works in this context (unit conversion).
Answer: Presumably the particles inside the pixel have a line-of-sight velocity profile. I would bin that profile in bins of width that are sufficient to sample the velocity resolution of the spectrum you want to generate (e.g. 2 bins per velocity resoluton FWHM).
Then it is simply a case of adding up the shifted and scaled (according to the frequency) spectrum for each bin.
For greatest efficiency I would bin your template spectrum in equal log wavelength intervals, of size equivalent to the velocity bins in your histograms. That way, the velocity shift translates into a simple integer number of log wavelength bins.
See for example How do I apply a velocity shift to a wavelength array with uniform logarithmic spacing?
If you really do want to represent your velocity profile with some fited function and then do a convolution, then you should still be applying that to the template spectrum binned in steps of equal log wavelength increment. After that you can either do the convolution integral numerically, step by step, or use a FFT algorithm, multiply the FTs of your velocity profile and template spectrum and then do the inverse FFT to get the result.


add GeoDjango dependencies on alpine docker

Question: I want to use GeoDjango on alpine docker and should add some dependencies on docker to use postgis database, refers to Django website I have to install by
$ sudo apt-get install binutils libproj-dev gdal-bin
I found that gdal and gdal-dev have already existed on alpine, so I used RUN apk add gdal gdal-dev but after running this docker-compose exec web python manage.py migrate --noinput Django says that :
'django.contrib.gis.db.backends.postgis' isn't an available database backend.
Try using 'django.db.backends.XXX', where XXX is one of:
    'mysql', 'oracle', 'postgresql', 'sqlite3'

How to add GeoDjango dependencies on alpine dockerfile?
Answer: You will have to install geos-dev library too for that.


Doubt about identity on the Wikipedia page Feynman slash notation

Question: I have the following doubt about the identity in this page:
$$ {a\!\!\!/}{a\!\!\!/}  \equiv   a^\mu a_\mu \cdot I_4 = a^2 \cdot I_4 $$
however:
$${a\!\!\!/}{a\!\!\!/}=a^{\mu}\gamma_{\mu}a_{\mu}\gamma^{\mu} = a^2 \gamma_{\mu}\gamma^{\mu}=4 a^2 I_{4}$$
Comment: You have repeated the index $\mu$ four times and should only do so twice. The a components are not contracted until later, as in the answer below
Comment: @lux That seems more like an answer that an comment.
Answer: Since $a$ is a vector, its entries $a_\mu$ are just numbers and they commute with everything
$$ {a\!\!\!/}{a\!\!\!/} = a_\mu\gamma^\mu a_\nu\gamma^\nu = \gamma^\mu \gamma^\nu a_\mu a_\nu,$$
using $\gamma^\mu\gamma^\nu + \gamma^\nu\gamma^\mu = 2 \eta^{\mu\nu}I_4 $ to get $\gamma^\mu\gamma^\nu = 2 \eta^{\mu\nu}I_4 - \gamma^\nu\gamma^\mu  $, the expression above becomes:
$$ \gamma^\mu \gamma^\nu a_\mu a_\nu = (2 \eta^{\mu\nu}I_4 - \gamma^\nu\gamma^\mu) a_\mu a_\nu = 2 I_4 a^\mu a_\mu  - \gamma^\nu\gamma^\mu a_\mu a_\nu.$$
The last term, via commutation of $a_\mu$, can be written $\gamma^\nu\gamma^\mu a_\mu a_\nu =  a_\nu\gamma^\nu a_\mu\gamma^\mu = {a\!\!\!/}{a\!\!\!/}$. Bring it to the LHS to get:
$$2 {a\!\!\!/}{a\!\!\!/} = 2 I_4 a^\mu a_\mu, $$
$$ \Rightarrow {a\!\!\!/}{a\!\!\!/} = I_4\,a^\mu a_\mu = I_4\, a^2.$$
Answer: OP has an error in the application of the Einstein summation convention. In their expression
$a^{\mu}\gamma_{\mu}a_{\mu}\gamma^{\mu}$ the index $\mu$ is repeated 4 times. OP then incorrectly sees the terms $a^{\mu}a_{\mu}$ and $\gamma_{\mu}\gamma^{\mu}$ and applies the summation convention individually to them.
However in the expression $a\!\!\!/a\!\!\!/$ the contractions are between the vector $a$ and a gamma matrix and not between $a$ and itself:
$$a\!\!\!/a\!\!\!/= a_{\mu}\gamma^{\mu}\,\, a_{\nu}\gamma^{\nu}$$
which makes it clear that there is not yet an inner product of $a$ with itself. From here we take advantage of symmetry of the product $a_{\mu}a_{\nu}$ to take only the symmetric part of the decomposition $\gamma^{\mu}\gamma^{\nu} = \frac{1}{2}\{\gamma^{\mu}, \gamma^{\nu}\} + \frac{1}{2}[\gamma^{\mu}, \gamma^{\nu}]$. We get
$$a_{\mu}\gamma^{\mu}\, a_{\nu}\gamma^{\nu} = a_{\mu}a_{\nu}\frac{1}{2}\{\gamma^{\mu}, \gamma^{\nu}\} = a_{\mu}a_{\nu}\eta^{\mu\nu}I_{4} = a^{2}I_{4}. $$


jquery validation based on radio button selection

Question: In my form i have two radio buttons(seller and buyer).same form fields for both radio buttons. But the diffrence is while i click buyer radio button some fields will hide i used javascript for hide that. Then i used jquery form validation.Also used jquery validation for hide fields. In seller mode the form is submitted sucessfully.In buyer mode while i click submit button jquery also validate hide fields. I want to stop validate in buyer mode. How i do that?
Answer: You can call validate function with different options in handler, that switches buyer/seller mode. Or you can add/remove rules in that handler
Answer: I assume you are using something like
$("#myForm").validate();

to validate the form; you can pass an option to validate() to ignore certain elements. So, for example, if all your elements that get hidden have the class ".hideForBuyer" then something like the following will ignore them:
$("#myForm").validate({
    ignore: ".hideForBuyer"
})

See partway down http://docs.jquery.com/Plugins/Validation/validate#toptions


How can I implement the pop out functionality of chat windows in GMail?

Question: I'm not looking for a full implementation, I'm more interested in how they do it.  I know they use GWT, but I'd like a more low level answer.  Naively, I would start by thinking when you click the popout link they simply open a new window and copy content into it.  There are lots of reasons why that won't work out well, so I'm wondering if anyone knows or has ideas on how they do this or how it could be done.
Answer: I recently needed to solve exactly this problem in an app. I ended up using this great little jQuery plugin to do the trick: WindowMsg (see link at bottom) While I'm sure there are other ways to accomplish the same task, that plugin does works thusly:

first you create a new child window from your original window using window.open
you save a reference to the window object returned by window.open
you call a library method in the child window that adds a hidden form for the library to store data in
you call a library method in the parent window that uses window.document.forms to populate form fields on the child window (the library abstracts all of this stuff so you wouldn't even know there was a form involved unless you looked at the source) window.document.forms works the same on all major browsers so this abstraction in x-browser compatible
finally, the child window refers back to its parent window using window.opener and can communicate back via a parallel hidden form on the parent
the library implements a convenient helper that takes a callback function to run on each side to make the callback chain easy to deal with

In my experience working with the library, it would have also been quite nice if they had included the JSON 2 lib from JSON.org. Out of the box, WindowMsg only allows you to send string messages between windows, but with some pretty simple use of the JSON 2 lib, I was able to hack it to allow the sending of full JSON objects between windows. I bet more mature libraries (such as whatever google uses) include that kind of serialization and de-serialization baked in.
I am putting this link here because for some reason, the Stack Overflow formatter turns it into an anchor link with no closing tag and I don't want my whole post to be one giant hyperlink!
WindowMsg:
http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/
Comment: Unfortunately the link for **WindowMsg** is broken - do you have another one, or can you add a little example to your answer? (i.e. a code sample)
Answer: I would say the easiest way would be to have the data stored on the server (which you probably do already), then just have the new window retrieve that data.
Of course that wouldn't persist things like contents of a text-box the user has input, so depending on what the window is for, it may be impractical..  but it's always best to start trying the simplest option!


Can the standard list of reasons for closing a question be extended?

Question: A recent question was put on hold for closure because "... As it's currently written, it's hard to tell exactly what you're asking". Since the question was obviously clear enough, the OP, or other casual observer, would gain the impression that the site is run by robots. The real reason for closing was, rightly, that the question was posted as an intended joke (too cheap, puerile, and unfunny for me to wish to repeat it here). Thus, could the reasons for rejection include something to the effect that "The question does not appear to be serious"?
Answer: There are far too many possible reasons why a question can be closed, the stock reasons are meant to cover the most common cases. For questions that don't fit into any of the existing categories just choose "off-topic" and select the option that allows you to add a custom reason. This reason will be posted as a comment on the question.
If you have some strong evidence that joke posts are a major source of closed questions, a new off-topic sub reason would be possible, but I doubt that there are enough of those to bother with this.
Comment: The question was a mathematical one, not actually "off-topic", and not closed for being "off-topic". It was worded so as pass all the checks listed under "What types of questions should I avoid asking?". The problem with the question was its intention, its stupidity, and its unfunniness. However, I have now learned that "off-topic" includes "on-topic, but not serious".
Answer: If I had closed the question like that (I haven't seen the one the OP is referencing), I would closed it under "Off-Topic > Other: leave comment" and gave the reason that "This question appears to be a joke, and is not serious."
The number of "joke" posts that we receive doesn't (in my opinion) warrant a separate close reason; if necessary, we can say that it's a joke in the "Off topic" option.
Answer: Here are some kinds of questions whose closure conditions make me unhappy.
There is the honest-but-ignorant question, often from a beginner, being rejected because it is a duplicate.  In the classroom one sometimes asks oneself, why am I repeating myself: didn't I explain all this last semester?  (Yes, but to a different batch of kids.)  To say "go away, somebody else thought of this question before you" is to some extent a dereliction of a teacher's duty.
There is the in-the-heat-of-the-moment technical question, often from a student enrolled in an upper-division course, who doesn't bother to name the course or define the terms.  (For example: "why is $\text{df.}=(r-1)\times(c-1)$?) These are rejected as "off topic" or "lacking context" or "not clear what you are asking."  The first reason must seem absurd to the asker (it's a math course, after all) and the second is often false, as the terms or symbols used in the question often make it clear to a specialist what the context is, and what the asker is asking.
There is the stupid question (like "is $\sinh \theta$ a polynomial?"), whose answer should be obvious to the asker, if he had ever been awake in class.  It's obviously a mathematics question, its obvious what's being asked, but it's not at all clear to me what a legitimate reason to reject could be.
The stupid non-question ("I just can't get my head around X") doesn't seem to bother me: for once "not clear what you are asking" is appropriate.
Comment: I am not sure an answer to this feature-request is the best place to record this. That said, I do not understand your analogy. Questions that are duplicates are not rejected. It is pointed out to the asker where they already can find an answer to their question. If a student this year asks me for a write up of a solution to an exercise I type up already last year, I really do not see a problem with giving them last years copy I wrote for somebody else rather than type it up yet again.
Comment: You could ask a new question on this meta site. (I'm not sure how it would be received; depends how you'd present it.) It depends on the precise meaning of rejecting it. If a student sends me an email asking me how to solve exercise 3.b from the last assignment and I reply "please look at {some link}; it's example 5.b there" did I then reject their question? I do not think so. How do you think duplicate questions should be handled? Copy over the  old answer? Type up the old answer for a second time? What else?
Comment: What would be a better forum?  BTW, So I'm looking at a review/close vote ballot, and when I clicked the "close" button got a popup that asked for a reason, the first choice was "because its a duplicate that has already been answered".  So I don't quite understand your 3d sentence.


Why I can't log in MYSQL with phpmyadmin?

Question: I have a problem. I can log in MYSQL by SHELL or Adminer (root or not-root user, whatever). But I can't with phpmyadmin. 'Cannot log in to the MySQL server'. What can be wrong?
P.S. Passwords are valid.
Comment: Can you provide us with a more descriptive error? Is everything setup correctly for PHP MyAdmin
Comment: Can you search your config.inc.php file for phpmyadmin, looking for lines containing `$cfg['Servers']`, and post them here? Be careful to remove any passwords. It's likely that your web server is not accessing the mysql server the same way as your shell/adminer instance (socket vs tcp, localhost vs remote). If it is local vs remote, ensure your mysql server is listening on non-local IPs, and that your users have permissions on remote IPs.
Comment: When you connect from the command line client, run the `STATUS;` command and note the user, host, and connection type. Then compare those to the error message provided by MySQL. This could be a host name mismatch or trying to connect via socket instead of tcp/ip (or vice-versa).
Answer: First Step:
check if port 3306 is open. If not then either you can open port 3306 by doing entry in iptables or simply you can stop this service (if not using any other purpose) by below command.
$ service iptables stop

Second Step:
User should have permission to connect from your ip, if not then provide rights as per below-
> grant select,insert,update,delete on your_db.* to your_user@'your_ip' identified by 'your_password';

If this is not production server then initially you can provide globally full rights to check the problem by below command-
> grant all privileges on *.* to your_user@'%' identified by 'your_password';

Answer: The error "Cannot log in to the MySQL server" can have multiple causes. It simply means, that phpMyAdmin is not able to connect to the MySQL Server in general.
There are two causes I know:

flawed settings in the Config.inc.php file (solution)
the MySQL server rejects any queries, because the root password needs to be updated (solution)


What is the amount of dark energy in the Universe, in joules?

Question: I'm toying with an idea, and need absolute amounts of dark energy.  I'd also like the same for dark matter.  If these values are not estimated, why not?
Comment: Thanks to all for the info. Very helpful and informative.  I now move from crazy idea to crazy calculation.  I like absolute numbers.
Answer: The dark energy density in the universe is about $7 \times 10^{-30}$g/cm$^3$ on average according to Wikipedia. This is uniform through out the Hubble volume of the entire universe i.e. the volume of the universe with which we are in causal contact. The Hubble volume is $10^{31} \ ly^3$ i.e. cubic light years. This gives $8.46732 \times 10^{84}$ cm$^3$ as the volume of the universe. Using the mass-energy equivalence, you find that the total dark energy content in the entire universe is around $10^{69}$ Joules, which is truly massive. This is in agreement with the result here.
Comment: Dear @RobJeffries, thank you for your comment. Yes, of course, this depends on whether there are also local field contributions from say scalar fields which can lead to non-uniformities. I wanted to make the answer as simple as possible but I have now included your comments in my answer. Thanks :)
Comment: Actually now I think it is made more complicated. I retract my comment. Just say that the average density is .... My original comment was confusing dark matter and dark energy, apologies.
Comment: Also since more space is being created, it means this number will keep increasing as well.


How to avoid "Cycle of dependency" when rigging a mechanical model

Question: I'm trying to rig this clamp to move how it would in real life. However, I can't figure out how to do it without causing a situation where there is a "cycle of dependency". I rigged this clamp and in the viewport it was working beautifully. When I went to render the animation, however, it started to get glitchy. I reported it as a bug and that was when they told me its because I had built a cycle of dependency. I don't know how to rig this to get the same result while avoiding that error I caused.
Basically for constraints I got the long vertical bone the parent of the smaller vertically bone that is in rest orientated in the -z position. That smaller downward facing vertical bone is then tracked to the long horizontal bone that is the clamp arm. That Clamp arm is also tracked to that smaller downward facing vertical bone. I cant figure out how to cause this motion in which the movement one causes everything to be pulled along with it, without having this cycle of dependency.
Answer: You can work well using IK. See for detailed structure.


Can the refractive index of a medium be negative?(<0)

Question: Recently I was asked in a test what would happen if the refractive index of a medium was negative. Is it possible really? The refractive index is the ratio of the speed of light in a vacuum and another medium. It can't be less than $1$ also the speed of light is the fastest in a vacuum. So how come it'll be negative? Does the light refuse to enter a medium?
Answer: A negative refractive index is a concept that arises in the field of metamaterials, which are artificial materials engineered to have properties not found in naturally occurring materials. This concept significantly alters our understanding of wave propagation, especially in terms of the direction of travel, the direction of information transfer, and the behavior of light. Here's a breakdown of what a negative refractive index means in these contexts:
Wave and Poynting Vector (Direction of Energy Flow):
In normal materials with a positive refractive index, the wave vector (which represents the direction of wave propagation) and the Poynting vector (which represents the direction of energy flow) are parallel to each other.

In materials with a negative refractive index, the wave vector and the Poynting vector are antiparallel. This means that although the wavefronts of light (or other electromagnetic waves) are moving in one direction, the energy carried by the wave is flowing in the opposite direction.

Wave Propagation (Direction of Travel, Direction of Information Transfer):
The unusual alignment of the wave vector and the Poynting vector in negative refractive index materials leads to some counterintuitive effects, such as reverse Cherenkov radiation and reversed Doppler effect.
The direction of information transfer, typically aligned with the direction of energy flow (Poynting vector), is opposite to the direction in which the wavefronts seem to travel (wave vector). This can have implications for how signals and information are transmitted through such materials.
Speed of Light:
In any medium, the speed of light is affected by the medium's refractive index. In materials with a negative refractive index, light behaves in unconventional ways, but the principles of causality and relativity still apply.
The phase velocity (related to the wave vector) can be in the opposite direction to the group velocity (related to the energy and information transfer). However, it's important to note that the group velocity, which is typically associated with the actual transport of information, does not exceed the speed of light in a vacuum, thus adhering to the principles of special relativity.
These phenomena are at the frontier of optical and material science research, and they have potential applications in developing new technologies such as superlenses (which can achieve resolution beyond the diffraction limit of light) and cloaking devices. The field of metamaterials, which predominantly explores these unusual properties, is constantly evolving, leading to new theoretical and practical insights.


How do I get kopete to hide/ignore status changes?

Question: I'm tired of kopete showing me every time someone goes away, online, it's annoying as it doesn't matter to me. How do I get kopete to hide these messages, or at least not alert me to them.
Answer: This one is well hidden :-)
To remove the KDE event notification

Go to KDE system settings
Select "Application and System Notifications".
Choose Kopete Messenger in Event source,
Select "Status Change" and uncheck all options.

To remove the event in the Kopete chat window

In Kopete, go to menu Settings / Configure...
Select Behavior / Chat
Uncheck "Show events in chat window".
Comment: @xenoterracide I thought the word "alert" referred to the notification. you may want to clarify what you meant (e.g., hide these messages in the chat window).
Comment: but this doesn't actually prevent kopete from printing the status changes in the chat window
Comment: I just added another option in my answer.
Answer: You should be able to configure what you do and don't get notified about by Kopete and how it notifies you by going to Settings->Configure Notifications.
Comment: but this doesn't actually prevent kopete from printing the status changes in the chat window.


Can I install Valgrind on Mac OS X 10.7.4 without having Xcode?

Question: I have been searching for quite some time now as to whether there is a way by which I can install Valgrind without the need of installing Xcode, knowing that I have apple's Command Line Tools already installed. During the installing of Valgrind I get the following:
Making all in coregrind
(cd m_mach && mig /usr/include/mach/mach_vm.defs /usr/include/mach/task.defs /usr/include/mach/thread_act.defs /usr/include/mach/vm_map.defs)
xcode-select: Error: No Xcode is selected. Use xcode-select -switch /Applications/Xcode.app to select /Applications/Xcode.app, or see the xcode-select manpage (man xcode-select) for further information.
/usr/bin/mig: line 174: Error: /usr/bin/xcode-select returned unexpected error.: No such file or directory
mig: fatal: "<no name yet>", line -1: no SubSystem declaration
make[2]: *** [m_mach/mach_vmUser.c] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2

Regards.
Answer: As you can see there is xcode-select: Error: No Xcode is selected message.
Check this out.


How is gamma ray blocked in the atmosphere in cosmic rays?

Question: I would like to know how gamma rays from cosmic rays are blocked by the earth's atmosphere. I know that the sun's gamma radiation don't usually reach the earth so I wouldn't be worrying much about it. I have did some research and I only see that ozone will block uv radiation but not gamma radiation. So I am wondering how is gamma radiation being blocked by the atmosphere? What molecules in the atmosphere specifically absorb gamma radiation? Thank you!
Comment: Possible duplicate of [How Earth protected from the gamma rays generated by Sun?](https://physics.stackexchange.com/q/142005/)
Comment: Why say that you know that the Sun's gamma radiation doesn't usually reach Earth, then award Best Answer to an answer which gives that explanation?
Comment: It seems to me te proposed dupe is more about the sun's emissions of gamma rays while this question is about what it is in the atmosphere that stops gamma rays from hitting us.
Answer: Cosmic gamma rays are largely absorbed in the atmosphere by three ionizing interactions with atmospheric molecules: photoelectric effect, Compton scattering and pair production. Therefore, in order to observe cosmic gamma rays for astronomical purposes, gamma ray observatories (like the Compton Gamma Ray Observatory) have to be placed in space.
Comment: This should be the accepted answer because it actually answers the question. To make this answer even better, you could write that gamma rays are absorbed in the upper reaches of the atmosphere, the thermosphere. This absorption is why the thermosphere is so named. Temperature in the thermosphere increases with increasing altitude due to this absorption.
Comment: Good grief, you couldn't find list of the dozen $\gamma$-ray or cosmic ray telescopes made in the last decade? You had to go early-90s with CGRO?
Comment: @KyleKanos - That's probably an effect of age, that you remember the old stuff best. It stopped working in 2000 I think. It would be interesting, of course, if you could name a couple still operational gamma observatories.
Comment: possibly, but at this point it's been dead twice as long as it was even alive (17 vs 9 years) that it's hard to fathom it being referenced these days (especially with the massive success of Integral and Fermi).
Comment: @Kyle Kanos - I was not aware that there are so many in orbit. I think that it is  very good that they are many continuing this important work.
Answer: Gammas lose energy predominantly via Compton scattering, $\gamma +e\to \gamma +e$, during which they impart much of their energy to the electron and change direction.  Low-energy gammas, which you might better call x-rays, tend to induce bound-free transitions, $\gamma +atom\to e+ion$.


Detecting the fundamental frequency

Question: There's this tech-festival in IIT-Bombay, India, where they're having an event called "Artbots" where we're supposed to design artbots with artistic abilities. I had an idea about a musical robot which takes a song as input, detects the notes in the song and plays it back on a piano. I need some method which will help me compute the pitches of the notes of the song. Any idea/suggestion on how to go about it?
Answer: This is exactly what I'm doing here as my last year project :) except one thing that my project is about tracking the pitch of human singing voice (and I don't have the robot to play the tune)
The quickest way I can think of is to utilize BASS library. It contains ready-to-use function that can give you FFT data from default recording device. Take a look at "livespec" code example that comes with BASS.
By the way, raw FFT data will not enough to determine fundamental frequency. You need algorithm such as Harmonic Product Spectrum to get the F0.
Another consideration is the audio source. If you are going to do FFT and apply Harmonic Product Spectrum on it. You will need to make sure the input has only one audio source. If it contains multiple sources such as in modern songs there will be to many frequencies to consider.

Harmonic Product Spectrum  Theory
If the input signal is a musical note,
  then its spectrum should consist of a
  series of peaks, corresponding to
  fundamental frequency with harmonic
  components at integer multiples of the
  fundamental frequency.  Hence when we
  compress  the spectrum a number of
  times (downsampling), and compare it
  with the original spectrum, we can see
  that the strongest harmonic peaks line
  up.  The first peak in the original
  spectrum coincides with the second
  peak in the spectrum compressed by a
  factor of two, which coincides with
  the third peak in the spectrum
  compressed by a factor of three.
  Hence, when the various spectrums are
  multiplied together, the result will
  form clear peak at the fundamental
  frequency.
Method
First, we divide the input signal into
  segments by applying a Hanning window,
  where the window size and hop size are
  given as an input.  For each window,
  we utilize the Short-Time Fourier
  Transform to convert the input signal
  from the time domain to the frequency
  domain.  Once the input is in the
  frequency domain, we apply the
  Harmonic Product Spectrum technique to
  each window.
The HPS involves two steps:
  downsampling and multiplication.  To
  downsample, we compressed the spectrum
  twice in each window by resampling:
  the first time, we compress the
  original spectrum by two and the
  second time, by three.  Once this is
  completed, we multiply the three
  spectra together and find the
  frequency that corresponds to the peak
  (maximum value).  This particular
  frequency represents the fundamental
  frequency of that particular window.
Limitations of the HPS method
Some nice features of this method
  include: it is computationally
  inexpensive, reasonably resistant to
  additive and multiplicative noise, and
  adjustable to different kind of
  inputs.  For instance, we could change
  the number of compressed spectra to
  use, and we could replace the spectral
  multiplication with a spectral
  addition.  However, since human pitch
  perception is basically logarithmic,
  this means that low pitches may be
  tracked less accurately than high
  pitches.
Another severe shortfall of the HPS
  method is that it its resolution is
  only as good as the length of the FFT
  used to calculate the spectrum.  If we
  perform a short and fast FFT, we are
  limited in the number of discrete
  frequencies we can consider.  In order
  to gain a higher resolution in our
  output (and therefore see less
  graininess in our pitch output), we
  need to take a longer FFT which
  requires more time.

from: http://cnx.org/content/m11714/latest/
Comment: How does this deal with the inharmonicity of real instruments?  The harmonics are increasingly sharp from the ideal multiples the higher you go.
Answer: Just a comment: The fundamental harmonic may as well be missing from a (harmonic) sound, this doesn't change the perceived pitch. As a limit case, if you take a square wave (say, a C# note) and completely suppress the first harmonic, the perceived note is still C#, in the same octave. In a way, our brain is able to compensate the absence of some harmonics, even the first, when it guesses a note.
Hence, to detect a pitch with frequency-domain techniques you should take into account all the harmonics (local maxima in the magnitude of the Fourier transform), and extract some sort of "greatest common divisor" of their frequencies. Pitch detection is not a trivial problem at all...
DAFX has about 30 pages dedicated to pitch detection, with examples and Matlab code.
Answer: Autocorrelation - http://en.wikipedia.org/wiki/Autocorrelation
Zero-crossing - http://en.wikipedia.org/wiki/Zero_crossing (this method is used in cheap guitar tuners)
Answer: Try YAAPT pitch tracking, which detects fundamental frequency in both time and frequency domains. You can download Matlab source code from the link and look for peaks in the FFT output using the spectral process part.
Python package http://bjbschmitt.github.io/AMFM_decompy/pYAAPT.html#
Answer: Did you try Wikipedia's article on pitch detection? It contains a few references that can be interesting to you.
In addition, here's a list of DSP applications and libraries, where you can poke around. The list only mentions Linux software packages, but many of them are cross-platform, and there's a lot of source code you can look at.
Just FYI, detecting the pitch of the notes in a monophonic recording is within reach of most DSP-savvy people. Detecting the pitches of all notes, including chords and stuff, is a lot harder.
Answer: Just a thought - but do you need to process a digital audio stream as input?
If not, consider using a symbolic representation of music (such as MIDI). The pitches of the notes will then be stated explicitly, and you can synthesize sounds (and movements) corresponding to the pitch, rhythm and many other musical parameters extremely easily.
If you need to analyse a digital audio stream (mp3, wav, live input, etc) bear in mind that while pitch detection of simple monophonic sounds is quite advanced, polyphonic pitch detection is an unsolved problem. In this case, you may find my answer to this question helpful.
Answer: For extracting the fundamental frequency of the melody from polyphonic music you could try the MELODIA plug-in: http://mtg.upf.edu/technologies/melodia
Extracting the F0's of all the instruments in a song (multi-F0 tracking) or transcribing them into notes is an even harder task. Both melody extraction and music transcription are still open research problems, so regardless of the algorithm/tool you use don't expect to obtain perfect results for either.
Answer: If you're trying to detect the notes of a polyphonic recording (multiple notes at the same time) good luck. That's a very tricky problem. I don't know of any way to listen to, say, a recording of a string quartet and have an algorithm separate the four voices. (Wavelets maybe?) If it's just one note at a time, there are several pitch tracking algorithms out there, many of them mentioned in other comments.
The algorithm you want to use will depend on the type of music you are listening to. If you want it to pick up people singing there are a lot of good algorithms out there designed specifically for voice. (That's where most of the research is.) If you are trying to pick up specific instruments you'll have to be a bit more creative. Voice algorithms can be simple because the range of the human singing voice is generally limited to about 100-2000 Hz. (Speaking range is much more narrow). The fundamental frequencies on a piano, however, go from about 27 Hz. to 4200 Hz., so you're dealing with a wider range usually ignored by voice pitch detection algorithms.
The waveform of most instruments is going to be fairly complex, with lots of harmonics, so a simple approach like counting zeros or just taking the autocorrelation won't work. If you knew roughly what frequency range you were looking in you could low-pass filter and then zero count. I'd think you'd be better off though with a more complex algorithm such as the Harmonic Product Spectrum mentioned by another user, or YAAPT ("Yet Another Algorithm for Pitch Tracking"), or something similar.
One last problem: some instruments, the piano in particular, will have the problem of missing fundamentals and inharmonicity. Missing fundamentals can be dealt with by the pitch tracking algorithms...in fact they have to be since fundamentals are often cut out in electronic transmission...though you'll probably still get some octave errors. Inharmonicity however, will give you problems if somebody plays a note in the bottom octaves of the piano. Normal pitch tracking algorithms aren't designed to deal with inharmonicity because the human voice is not significantly inharmonic.
Answer: You basically need a spectrum analyzer. You might be able to to a FFT on a recording of an analog input, but much depends on the resolution of the recording.
Answer: what immediately comes to my mind:

filter out very low frequencies (drums, bass-line),
filter out high frequencies (harmonics)
FFT,
look for peaks in the FFT output for the melody

I am not sure, if that works for very polyphonic sounds - maybe googling for "FFT, analysis, melody etc." will return more info on possible problems.
regards

Detecting the fundamental frequency


How to make a media library image searchable with few keywords rather just the item name?

Question: Simply wondering how to tag an image with a few different keywords and find it that way later on within the media library. It seems like currently the search function of the media library only picks up on the terms within the file name and nothing else. (using sitecore 8.2)
Answer: I would recommend you to explore Sitecore Cognitive Services which is an integration between Sitecore and Microsoft Cognitive Services. The foundation of Sitecore Cognitive Services uses Sitecore's Content Search to analyze text and images with a number of cognitive API's. The analyses is based on computed fields so content is indexed as it's created and will store the analysis in the index.
For your specific requirement about Advanced Image Search, Sitecore Cognitive Services are equipped with:

Visual Analysis
Emotional Analysis
Facial Analysis
Text Analysis etc.

For more details please checkout the URls below:
Sitecore Symposium 2017: Sitecore Cognitive Services Presentation:-
https://www.youtube.com/watch?v=F8aRrj_uWMk
Blog post by Mark Stiles:
https://markstiles.net/blog/2017/2/22/sitecore-cognitive-services/
Answer: You will definitely want a computed field here.  As for what to put in the computed field- it depends.  If you have alternative text, that would be great.  Otherwise, you will need to do some image processing at indexing time to infer what the image may be related to.
As Amitabh pointed out, you can use something like Azure Cognitive Services to do this.
As for setting up the computed field, there are a ton of tutorials out there.  I've blogged about how to manipulate what goes into the visualization field before.  It would be a very similar approach in your case.
Hope this helps!


Possible to use Cane Creek angleset cups on top and bottom of headset

Question: I currently have a -1.5 degree angleset cup installed on the bottom of my bikes headset and a 0 degree on the top. I would like the head tube angle a little slacker so am wondering if it is possible to use a -1.5 degree cup on the top as well which would give -3 degrees of HTA. Am. I dont think there would be an issue but wondering if im missing something.
Comment: Is this something that the manufacturer claims as supported? What about the decrease in bottom bracket height that accompanies change in the HTA?
Comment: Manufacturer doesnt claim it is supported and i wouldnt expect them to. I also am not worried about the warranty or anything. Just playing around with parts and geometry, trying to make.bike more stable on descents.
Answer: You can 100% physically do it. Just make sure the angles of the bottom bearing and race will cope with the shift. ie that it works with the change, and is not designed to only work with that specific top one.
Now, you haven't mentioned the bike or the type of riding, or the reason for why you want it slacker.
As a general rule, if you make a bike slacker (from it's intended angle), it will make turning less snappy and stright downs more stable. But obvs whether this is a good thing, is subjective to the bike, the type of riding and the riders ability and preferance/style.
Worst come to worst, you don't like it and you can just switch the headset back. Just keep the original one just in case.
Other things to consider, is how the slacker angle will affect the rest of the bike, both in geometry and in physical forces. For example, if you slacken a bikes, which is not inteded to be, you increase the chance of the headtube splitting from the frame. You also decrease the uphill riding efficiency, lower the bottom bracket hight and the way the front fork travels might change too.
Comment: Yup 100% agreed with all above. Im just trying to make bike a bit more stable on descents. 2014 Opus Nelson. Nice dual suspension carbon bike but head tube angle a little too steep so trying to see how it will ride by slackening it out. With the change from 67.5 to 66 it is already better. Only thing is i cant get the infamous angleset knocking to go away.
Comment: I would also check the clearance between the fork's steering tube and the bicycle's head tube in the desired position (-3°). There is a geometrical limit to how un-parallel they could be set up before they start touching each other. Even if they do not  touch statically, there should be some stack left for when they flex under loads, such as heavy landings.


What are slow time events good for?

Question: So, sometimes during fight in Middle Earth the fight will get in slow motion. Is there something special about it? Like some R2+Square (Finisher). I've seen it for both getting an enemy stunned or getting them in downed state. Or is this slow motion the "well-timed" event that can double the Hit streak?
Answer: I believe that this is simply an influence gained from the Batman: Arkham series of games. The slow-motion would generally happen when you defeat the last enemy that is aware of you in a fight. It serves no purpose, but it's supposed to look cool.
However, Caragors have two separate attacks. An unblockable attack, which must be dodged, and a leap attack, which will cause the game to go into slow motion. If you have the correct skill unlocked, this leap can be countered to throw the Caragor to the floor.
Comment: Thanks! Know about the Caragors. But thought that I can do some combo finisher during "normal" slow-downs :) Will now stop wasting time with smashing buttons then.

What are slow time events good for?


Why version 5.* does not satisfy dependency on >= 4.*?

Question: As shown below, package powertop depends on libstdc++6 (>= 4.4.0) and I have libstdc++6 version 5.2.1-23, which should satisfy that dependency. Note the option -t testing does not influence whether or not I get this error. My system is mixed in that there are a few packages from the testing distribution, but the stable packages have higher priority so are not installed by default. My libstdc++6 is from the testing distribution.
domas@nc4010-bl ~> sudo apt-get install -t testing powertop
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 powertop : Depends: libstdc++6 (>= 4.4.0) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
domas@nc4010-bl ~> dpkg -l libstdc++6
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  libstdc++6:i38 5.2.1-23     i386         GNU Standard C++ Library v3

Why is this dependency not satisfied?
Comment: Could this be a multilib issue? Are you on a 64 or 32bit system?
Comment: Rerun with the debug flag, please. Paste the result of `apt-get install -o Debug::pkgProblemResolver=true -t testing powertop` in the question, not a comment .
Comment: @FaheemMitha http://pastebin.com/AjzeJjFu
Comment: @terdon 32bit system.
Answer: I don't know which version of powertop you are using but it seems that is a known issue :
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=795297
Comment: The bug report seems to have been closed as fixed. I might open a bug report.
Comment: Yes, it's a good idea but do you check if you are installing the last version ?
Comment: I would post a bug report with Debian. I believe that's the protocol, the package maintainer may then choose to report a bug with the upstream developers.


What language does Cull Obsidian speak?

Question: In Avengers: Infinity War Cull Obsidian responds verbally to his mates but it seems hard to comprehend. At least for me I have no clue as to what he says. What were his responses or what language does he speaks?
Comment: "In contrast with his siblings, he was apparently the least intelligent of the Black Order, as he was only able to communicate in grunts and growls." from the MCU wiki. Considering one of the other henchmen (Corvus Glaive) is apparently his biological brother and speaks English, might be accurate?
Comment: Yeah possibly but he says something when ebony maw says "he exhausts me". I thought possibly that it was not heard well due to poor editing.
Comment: You're right, he's not just grunting or growling.
Answer: Cull is speaking in his own native tongue. We don't know what planet that is, but at least we know that he's using words.

Cull Obsidian added something vicious sounding in his native tongue, which sounded more like a series of grunts and growls. As Tony grew more and more impatient. Maw continued. "Be thankful that your meaningless lives are now con—"
... [later]
Ebony Maw sighed in exasperation. Sensing Cull's desire for a fight, he waved his thin hand toward the quartet facing them. "He exhausts me." Cull Obsidian answered Maw in his own unintelligible language, bringing his weapon up into battle stance. "Bring me the Stone." At Ebony Maw's words. Cull Obsidian grunted in agreement, and slammed his massive hammer into the New York pavement, cracking it as if it were made of the thinnest sheet of ice.
Infinity War: Destiny Arrives
Comment: I knew it sounded like a grunt. I thought that I was going crazy
Answer: Unfortunately, we don't know. I initially thought he was only grunting but after paying attention and re-watching the introduction scene with him and Ebony Maw on Earth he certainly is making words not just noises. I've checked all the common places and no information is given. The closest we get is the subtitles on Disney+ which simply say:

(SPEAKS ALIEN LANGUAGE)

The Road to Marvel's Avengers: Endgame - The Art of the Marvel Cinematic Universe very briefly says:

As brutish as he is big, Cull Obsidian is a creature of few words, preferring his fists to do the talking.

Again this implies that he does actually speak but once again no mention is made of what language.
In fact of the loyal members of the Black Order we don't get any back story to them just that like Nebula and Gamora they were taken as children from their home planets. Unlike those two though we don't know what planets they are. The Black Order's backstories just aren't filled out in the MCU as far as I can tell.
Comment: Good insight. I thought that at least the the lines of the cast word have some help but neither do.

What language does Cull Obsidian speak?


light switch will not move

Question: My kitchen light switch suddenly will not move up or down and I cannot turn the kitchen light on. Is there anything I can do to fix it (I'm a duct tape/WD40 kind of fixer) or do I need to call someone?
Comment: Replacing the switch will be the most reliabld and long-term-cheapest solution. Nothing lasts forever; things wear out.
Comment: As @keshlam says. And standard toggle switches cost less than a dollar.
Answer: If you are here on Stack Exchange asking if there is a way to fix a light switch, then I would guess you're handy enough to replace it. It truly is simple and should only require a screwdriver. Turn off the breaker, 2-screws on the cover, 2-screws on the switch, 1-screw for each wire (probably). Take a photo of it with your phone before disconnecting the wires so you'll remember where they go. You can purchase a standard switch at any hardware store (or even Walmart!) for pocket change.
If you come up with anything other than what is described here when you take it apart, post a photo and we'll help.
Answer: The switch sounds like it needs to be replaced. There are a few tools that everyone should have when they do electrical work.
These tools in no particular order are:

Linesman's pliers
Needle nose pliers
Insulated phillips and flat head screwdrivers
Small flat screwdriver for the cover plate
Wire strippers
Non-contact voltage tester
Electrical tape

The first thing to do is locate the breaker panel and shut off the breaker to the light fixture. This may take time if the panel is not well marked. Once the circuit has been identified, turn off the breaker and place a piece of tape over it to remind anyone to not turn it back on. Blue painter's tape works well for this because it does not damage the sticker on the breaker when the tape is removed. Also take note of the amp rating on the breaker. It should either be 15 or 20 amps.
Remove the switch cover, and test that the circuit is off with the circuit tester. The tester usually will beep and flash if it detects current. If the circuit is on, verify that the correct one has been turned off.
Once the power has been verified as off, check the amp rating on the switch. It should match or exceed the breaker amperage. The rating will be stamped somewhere on the switch. It is code to use a 20 amp switch on a 15 amp circuit, but not vice versa.
Count the number of wires on the switch. A normal 2-way switch will have two wires which are usually black, or a black wire and a white wire with the white wire wrapped with black electrical tape. It will also have a bare wire for the ground. A 3-way switch will have 3 conductors and a ground. From your original question, you said you can't turn the light on, which means you probably have a standard 2-way switch.
When you have determined that correct amperage, and type of switch, go to your local home or hardware store and purchase a switch with the same rating.
With the power still off, remove the retaining screws and gently pull the switch out of the box. Unscrew the terminals one at a time, and keep note of how the wires were connected. You can do this by bending the wires in a certain direction, or marking them with tape. If the end of the wires are chewed up, cut the tips off and strip them back. You only want to strip just enough so you have enough bare wire to wrap around the screw terminal. You don't want to strip in excess to that. The existing installation should be a good guide on how to strip the wire and bend it for the terminals. The direction that you bend the wire matters. You want it to bend in the same direction as the screw tightens which is clockwise. If the wire is on the right hand side, bend it up, and bend it down on the opposite side. If you do it the opposite way, then the wire will tend to pop out of the terminal as you tighten it. Some switches have push in terminals that allow you to push the wire in. It is much better to use the screw terminals. When you screw down the terminal, make sure that there isn't any insulation trapped under the screw.
After all of the electrical connections are done, wrap the terminals with a layer of electrical tape. You basically will wrap it all the way around the switch at least once so the tape won't peel. This is done to help prevent a short circuit in the box. The shorts are more common in metal boxes, but it could happen in any of them.
Assemble the switch by reversing the steps you took to disassemble it. Turn on the power, and test it.
Answer: The light switch needs to be replaced. Even if it starts working by some trick, unreliable contact is a fairly large fire risk. Do not spray any chemical into electrical equipment, especially not without cutting the power first.
As to who does the replacement, that depends on where you live. If you rent, it should be the landlords responsibility. If you own the house, you'll probably want to call in an electrician. In some countries you are also allowed to replace it yourself - it is not a difficult job if you do a bit of research.

light switch will not move


prove that $N(x^m=a)=N(x^d=a)$.

Question: Let $p>2$ be a prime, $m\in \mathbb N$, $d=$ GCD$(m,p-1)$.
Let $N(x^n=a)$ denote the number of solutions to the equation $x^n=a$ in $\mathbb F_p$.
prove that $N(x^m=a)=N(x^d=a)$.
I am familiar with the claim that if $n\mid p-1$ then $N(x^n=a)=\sum_{\chi\in S}\chi(a) $ where $S=\{\chi:\chi^n=\epsilon\}$, $\chi$ is a character on $\mathbb F_p$ and $\epsilon$ is the identity character.
I manged to show that $N(x^d=a)=N(x^{\alpha m}=a)$ where $d=\alpha m+\beta (p-1)$.
This question appeared in "A Classical Introduction to Modern Number Theory"
Answer: The special case $a=0$ is obvious, so let us assume  $a \neq 0$.
Recall that the multiplicative group of the field is cyclic and let $g$ be a generating element (a primitive root). Further let $k$ be an integer such that $g^k = a$.
We have $x^n = a$ if and only if $x = g^s$ with $sn \equiv k \pmod{p-1}$.
So you are trying to show that the number of solutions to
$$mX \equiv k \pmod{p-1}$$
is the same as that to
$$dX \equiv k \pmod{p-1}$$
where $d = \gcd (m,p-1)$.
Let $m = cd$. Then the first congruence becomes
$$d(cX) \equiv k \pmod{p-1}$$
Since $c$ and $p-1$ are co-prime,  "multiplication by $c$" is bijective and your claim follows.

prove that $N(x^m=a)=N(x^d=a)$.


When I turn on my MacBook Pro, I see the Apple logo and the progress bar but then it turns off

Question: When I switch on my MacBook Pro 2011, I see the Apple logo with progress bar but before it enters the next screen it turns off. Why?
Comment: Does your computer actually turn off and stay off, or does it keep restarting at the same point?
Comment: Yes. it will gonna turn off. and I have to press power button again.
Comment: but battery indicator doesn't response.
Comment: Could you please edit your question to add what version of macOS you have installed?
Answer: Troubleshooting is a process of elimination and can take quite some time. This means trying various things and reporting back with the results in order to try and get to the bottom of your problem.
Apple Hardware Test / Apple Diagnostics
The first thing to try is running Apple's built-in hardware diagnostics. To do this:

Ensure your MacBook Pro is connected to AC power
Start your computer
Immediately press and hold down the D key before the grey screen appear
When the icon appears on the screen let go of the D key
Select your language and click the right arrow
Select the "Perform extended testing" checkbox
Click the Test button
Take a note of the results that appear in the bottom-right window

Report back with your results.
NOTE: If holding down the D key doesn't work, you can also try holding down the OptionD keys during startup to try and run the diagnostics test via the internet.
Comment: Thanks it is worked. and I could see, there is no any hardware problem. but, in addition I checkout Hardware Profiles > Power. and I could see then the battery capacity shows 0%. so this result has based on this problem? because, I gave the command to RESTART on that screen but, the later problem makes again. again it went to permanent shut down.


Does the quadrupole moment tensor contracted with itself yield Kronecker delta?

Question: I have trouble understanding the Kronecker delta and how it comes up in tensor equations. I know the metric contracted with itself gives the Kronecker delta which either is 0 or 1 depending on if the indices are equal or not. However, I'm not sure if any two given tensors that contract each other's indices gives the Kronecker delta. Like two quadrupole moment tensors.
Comment: [Kronecker delta](https://en.wikipedia.org/wiki/Kronecker_delta)?
Comment: and yes, oops i have a typo =(
Answer: No, in general a contraction that leaves a two-index tensor will not produce the Kronecker delta.
For example, contracting the appropriate two indices of the four-index Riemann tensor gives the Ricci tensor, not the Kronecker delta. (Contracting other pairs gives the zero tensor.)
Contracting the product of two quadrupole tensors will not give the Kronecker delta either.
The metric tensor is unusual in this regard. In general, the fully contra-variant form of a two-index tensor is not the inverse of the fully-covariant form.
Answer: Simple way to get a Kroenecker delta is to consider coordinate transformation where you tranform into the same coordinate system you started with
So usually if you have a (e.g.) vector $V^\alpha$ in coordinates $S$ and you change to $\tilde{S}$, the vector components will change as
$\tilde{V}^\alpha=\Lambda^\alpha_{\:\beta} V^\beta$, where $\Lambda^\alpha_{\:\beta}=\frac{\partial \tilde{x}^\alpha}{\partial x^\beta}$. If $\tilde{S}=S$ then $\Lambda^\alpha_{\:\beta}=\delta^\alpha_{\:\beta}=\frac{\partial x^\alpha}{\partial x^\beta}$
Using the definition $\delta^\alpha_{\:\beta}=\frac{\partial x^\alpha}{\partial x^\beta}$ it is also easy to check that delta is indeed a tensor:
$\tilde{\delta}^\alpha_{\:\beta}=\frac{\partial\tilde{x}^\alpha}{\partial{\tilde{x}^\beta}}=\frac{\partial x^\gamma}{\partial\tilde{x}^\beta}\frac{\partial\tilde{x}^\alpha}{\partial x^\gamma}=\frac{\partial x^\gamma}{\partial\tilde{x}^\beta}\frac{\partial\tilde{x}^\alpha}{\partial x^\eta}\delta^\eta_{\:\gamma}$


Required to put roof or door overhang on a sliding door?

Question: I have no experience in architecture or house building. I am currently brainstorming a house design and I am thinking of putting a sliding door as one of the entrance to the house aside from the main door. Is it required or advisable to out a roof that will cover the sliding door considering it gets quite rainy in my country? The house is 2 story and the roof on the 2nd floor should be able to cover the space but not sure if it will be enough.
Answer: I know that in the USA sliding glass doors can leak if directly exposed to rain, which can be windblown.
Comment: @FreeMan Any sliding "door" (glass or otherwise) will leak when exposed directly to the wind and rain.
Comment: Very true, @LeeSam. However, when I wrote that comment, the answer was talking about an overhead garage door. It's been edited since & my comment deleted.
Answer: My personal experience would suggest that "it's advisable" though it's not specific to "a sliding door" particularly - I have a (slightly taller than average) 2-story building with generous roof overhangs (2 feet, or about 600mm) and I have found that I want "small roofs right over doorways" due to rain blowing sideways far enough to hit the door openings down at first floor level despite the overhang.
The roof edge is 20-25 feet (6-8 meters) above ground level.


Multinomial logistic regression, weighted logistic regression?

Question: I have a binary predictor with many response variables.  The binary predictor was originally continuous but was converted to binary ... if the response was $>1000$ then 1, else 0.  I would like to have a model in which responses of greater magnitude are more likely be to 1 vs responses of lesser magnitude. I have also thought of splitting the response to more categories ... anyone have any ideas?
Comment: Why not, instead of binarizing your response, build a model to predict your continuous response variable and then binarize the prediction itself?
Comment: thank you for your suggestion Matthew. my problem is that this is a big data set (65 000 records, 100 predictor variables) and there are a lot of legitimate 0 values. Do you think I should try Principal Component Regression?
Answer: Whatever the problem is, you should not be binning a continuous response. You didn't give us much context, so advice is difficult to give, please add more context. But you say "there are a lot of legitimate 0 values." Why is that a problem? Maybe because you wanted to log-transform an otherwise positive variable? Then there are many other options, for instance modeling $\log( Y+c)$ for some positive constant $c$ (which could be estimated from that in a way similar to Box-Cox transforms). Or an extended Box-Cox transform of the form $\frac{(Y+c)^\lambda+1}{\lambda}$ Can be used, see Wikipedia or Transforming variables for multiple regression in R. Or you could simply use a glm (generalized linear model) with log link. That log-transforms the (estimated) expectation, not the observations!  Many other possibilities, but tell us more about context first.
One other possibility that merits mention (since it is not too well known) is continuous ordinal regression.  This is implemented in R in orm in package rms, and discussed at length in Frank Harrell's book "Regression Modeling Strategies".
Answer: I agree with @kjetil that binning is a bad idea.
If the reason for binning is "legitimate 0 values" then you can consider methods for zero inflation. These are better known when the dependent variable is a count, but they exist for continuous DV as well. See this thread also see Modeling nonnegative data with clumping at zero by Min and Agresti for a fairly comprehensive review (the article is a bit old, but I don't think there have been a lot of new developments here).
Another idea is to use quantile regression.


Hierarchical Clustering: Dendograms

Question: What are dendograms? How de we interpret them? By looking at the dendograms, how can we decide the number of clusters to be formed?
Answer: Dendrograms are tree-like diagrams used to represent the arrangement of the clusters produced by hierarchical clustering. They are particularly useful in visualizing the data and understanding the structure of the clusters.
Interpreting a dendrogram involves understanding its structure. Each leaf of the dendrogram represents one data point. As you move up the tree, leaves that merge together do so because they belong to the same cluster. The height of the merge (represented by the vertical lines) indicates the distance between the two clusters, with lower merges indicating that the clusters are closer together.
To decide the number of clusters by looking at the dendrogram, you can use a simple strategy called the "largest vertical distance without crossing any horizontal line". Essentially, you draw a horizontal line across the dendrogram and count the number of vertical lines it crosses. This will give you the number of clusters. The idea is to choose a cut such that the distance (or difference) between two clusters is maximum, which means they are the most dissimilar and hence should be separate clusters.
However, the decision also depends on the context and the specific problem you are trying to solve. Sometimes, domain knowledge can also help in deciding the number of clusters.
Answer: Dendrograms are visual representations of hierarchical clustering results. They illustrate the hierarchical relationships between data points by showing how they group together at different levels of similarity. Dendrograms are commonly used in cluster analysis to assist in understanding the clustering structure and determining the number of clusters.
Interpreting dendrograms involves examining the vertical lines (branches) and horizontal lines (called fusions or f-fusions) that connect the branches. The height of the vertical lines represents the similarity or dissimilarity between the data points or clusters. The longer the line, the greater the dissimilarity.
To determine the number of clusters from a dendrogram, you can follow these steps:

Identify the longest vertical lines that do not intersect with any other lines. These lines represent the largest distances or dissimilarities.
Draw a horizontal line across the longest vertical lines, and count the number of times it intersects with the vertical lines.
The number of intersections corresponds to the number of clusters you can form.
The point at which you draw the horizontal line is subjective and depends on your desired level of granularity or the specific problem you are trying to solve. You can choose to draw the line at a height that gives you a suitable number of clusters.

Another approach is to look for significant increases in the vertical line lengths. If there is a substantial increase in line length compared to the previous level, it may suggest that the clusters are forming at that point, indicating a possible number of clusters.
Keep in mind that dendrograms provide a visual representation, and deciding the number of clusters can still involve some level of subjectivity and domain knowledge. It's important to consider the specific context and objectives of your analysis when interpreting dendrograms and determining the appropriate number of clusters.

Hierarchical Clustering: Dendograms


Bootloader For Atmega4809

Question: I have designed a project using Arduino Every board which uses MCU Atmega4809 chip and I have used Arduino IDE for programming but now I am planning to design my custom board I have used schematics of Arduino every board available on Arduino website . how can i upload the bootloader (Where can I get the bootloader from ) and how can I upload the Arduino code on new Atmega4809 Chips.
Answer: Nano Every doesn't use a bootloader. The ATmega4809 on Nano Every is flashed with the SAMD11 used as UPDI programmer with Arduino firmware.
Optiboot supports ATmega4809 and MCUDude MegaCoreX supports different ATmega4809 configurations and Optiboot.

Bootloader For Atmega4809


Should LLC be opened in US or overseas?

Question: I am a dual US and EU citizen looking to open an investment holding company under an LLC.  For optimal tax circumstances, should the LLC be opened in the US or overseas?
Comment: Is it for tax saving purposes or something different ?
Comment: off topic - this site is not about corporate finance
Answer: If its purely for investments then beware of the CFC and PFIC rules that you are subject to. The IRS mandates these and are purely for non-United States structures.
Basically they tax you about 10% on the value of the holdings while the assets are stationed offshore in the LLC.
The way around this is to only hold intellectual property offshore. The key point is that intellectual property cannot be priced easily and therefore the 10% tax could be nullified. Ideally because you transferred IP to the LLC for $1 or the LLC was the original owner of the IP at time of creation.
(example: is that patent worthless or worth $2 billion dollars? nobody knows and it was transferred to that LLC for $1 at the time, yet your offshore LLC can license it out for $2 billion a month..... at which point your LLC is more than a passive foreign investment company and is not subject to the PFIC rules)
enjoy. the rules create the opportunities.
Answer: What is your reason to choose LLC over (US) C-Corporations or (EU, offshore) Ltd/GmbH?
What you need to look into are corporate capital gains taxes, and that depends on types of investments you'd be holding - assuming paper assets, I'd go for Cyprus or Gibraltar.
Answer: The question is one of residency to start off with.  Where are you resident for tax purposes?  If you are resident for tax purposes in the US then it doesn't much matter where you create the company because it will be subject to Subpart F and the income will be deemed taxable in the US regardless of whether you bring it home or not.  If you are an EU resident for tax purposes then it depends on the country you are resident of (please note resident does NOT mean where you live,it means where you are legally liable to pay taxes you could spend 2 solid years out of certain countries and still be liable to pay taxes there).  In a perfect world you're tax resident in a country that has no CFC rules like Cyprus and you can structure a holding company out of a zero tax jurisdiction and potentially run the investments through there, but then it will also depend what type of investments they are.  If for example they are real estate investments you're going to be subject to tax on them in the jurisdiction there they are located and potentially also in the jurisdiction where you live when you bring the money back home.  Anyone who gives you advice without first delving into your tax residency is someone you should run from because they aren't giving you good advice.
Comment: The OP states he's a US citizen, there's no question of residency.
Answer: In the US the LLC would be transparent for tax purposes, so you won't gain any benefit (other than liability protection).
If you create the LLC elsewhere, the US will tax it as a CFC/PFIC (as had already been mentioned by others) and you don't want that.
Talk to a tax adviser who's licensed in the US (EA/CPA) and in your EU country, and is well-versed in the tax treaty between the US and your current country of residence. It is not simple at all. You may be out of compliance (in the US) already with regards to CFC/PFIC/FBAR/Sub F regulations as many US expats are.

Should LLC be opened in US or overseas?


What to do with transmission hoses during radiator change

Question: When changing my  radiator (94 Chevy k1500 4x4 ext) do I need to plug the transmission hoses after disconnecting them?
Comment: Welcome to Motor Vehicle Maintenance & Repair! Not sure what the image is for? Did you post the right one? Was going to edit it so it could be viewed within the post, but decided that might not be a good idea considering.
Answer: You don't need to plug them while they are disconnected, unless the vehicle is going to sit for a while. You obviously don't want dirt getting into them, but if this is a quick in/out to replace the radiator, it's not going to be an issue. You may see a little drainage of transmission fluid from the lines, so plan accordingly. If they are flexible lines you can suspend them so they won't leak onto whatever surface. If you are going to leave the vehicle for a while, you'd want to put something over the ends of the lines just to prevent foreign matter from entering. A small plastic bag with rubber bands would work just peachie. If you have some old nitrile gloves, you can cut a couple of fingers off of them and do the same with the rubber bands. They are about the right size and fit on there nicely.