Why does string strummed with finger sound different from the one strummed with pick?

Question: What is the physical reason for difference in sound when using fingers instead of pick and vice versa?
Comment: All comments have been purged. Please everyone remember to be civil regardless of people's opinions on the matter. Any future comments that don't keep this in mind will also be purged.
Answer: Per a suggestion, I am converting my comment into an answer.
WARNING: math ahead
(uh-oh, it looks like Music.SE doesn't support MathJAX -- I am going to go ahead and post the TeX code anyway and try to explain it in plain english along the way.  I also added a meta request to see if we can't fix the MathJAX problem.)
Discounting the inharmonicity due to the bending stiffness of the string, and discounting the damping behavior, the behavior of a guitar string can be modeled as a one-dimensional initial value problem (partial differential equation in space and time with boundary and initial conditions).
<code>$$
\frac{\partial^2 u }{\partial t^2} = c^2 \frac{\partial^2 u}{\partial x^2} \\
u(0,t) = u(L,t) = 0 \\
u(x,0) = g(x) \\
\frac{\partial}{\partial t} u(x,0) = 0
$$
</code>

In english:
First line: The acceleration of any particular bit of string is proportional to the local curvature.
Second line: The two ends of the string are fixed.
Third line: At the moment of release, the string is pulled to some particular shape.
Fourth line: The string is simply pulled to a shape and released -- the "plucker" does not impart any velocity to the string (i.e., you are pulling and letting go, not "throwing" or "pushing" the string).

The solution to this equation cannot really be written in a closed form for a bounded problem.  Instead, the behavior generally consists of a linear combination of eigenfunctions, which are of the form
<code>$$
u(x,t) = \sum_{n} k_n \cos \left(\frac{n \pi x}{2L}\right) \cos \left(\frac{n \pi ct}{2L}\right)
$$
</code>

If either you can see through this TeX code or Music.SE enables MathJAX, those who are mathematically inclined should recognize this as simply a weighted sum of the harmonics of the fundamental frequency $c$.
What does all that mean?
The sound you hear is simply a function of the different $k_n$ values (where $n$ is the number of each harmonic).  Those values are simply the Fourier coefficients of the initial shape of the guitar string at the exact moment of release.
I'll spare you the math on these, but in general, the rule of thumb is that the "pointier" the initial shape, the higher the $k_n$ values are for large values of $n$ and the more brilliant the sound.  The rounder the shape, the smaller those values are and the duller the sound.
Ok, but how does this circle back to picked vs fingered?
Simply put, the pick is stiffer than your finger, and it comes to a sharper point than your finger does.  If you look at the initial shape at the exact moment of release, the picked string is going to come to a sharper point than a finger-plucked string.  The $k_n$ rules above then apply, and the rest is just math.
What about the assumptions?
Thick guitar strings will have an inharmonicity term proportional to the fourth spatial derivative of the displacement.  This severely complicates the appearance of the solution, the end result of which is that higher level harmonics are not exact multiples of the fundamental frequency.  For the purposes of answering this question, this is immaterial.
There are also damping terms proportional to the velocity of the string (first time derivative of displacement) for viscous damping, and proportional to the square of the velocity of the string for aerodynamic damping.  The general effect of these terms is that each harmonic's $k_n$ value fades to zero over time, with higher harmonics fading faster than lower harmonics.  Again, for the purposes of answering this question, this is immaterial.
Comment: In a case like this, you could probably be forgiven for posting an image of the formulas.
Comment: _"the picked string is going to come to a sharper point than a finger-plucked string"_ - also the tension doesn't release immediately with a finger, it rolls off your finger-tip, whereas with the pick it's more immediate
Comment: Probably worth noting to the less mathematically inclined that Fourier coefficients are what spectrograms show.
Comment: However, not all pick come to a sharp point and it depends on attack.  There is still a dimension missing to this.  But one of the best answers I've seen.
Comment: That is simply not true for all picks.
Comment: @ggcg Yes, picks come in all different shapes, but I think it's reasonable to address the most common pointed pick shape and how it differs from a rounded finger shape, and then allow readers to take it from there on the fact that a rounded pick will sound more like a finger than a pointed pick.
Comment: Yep.  This answer is more accurate than mine.
Comment: @YourUncleBob I'm hoping it's a reasonably simple thing to just enable MathJAX, as it's available on numerous other SE sites.  Compiling each of the formulas into an image and posting them is considerably more involved.
Comment: @ggcg The important part is that the contact area with the string is a sharper point.   The answer could make this clearer.
Comment: "the higher the $k_n$ values are for large values of $n$ and the more brilliant the sound." For those who haven't been scared off yet by all the math, the less dispersed the displacement is in position space, the more dispersed it is in frequency space. This ties in with the Heisenberg Uncertainty Principle: since the momentum of a photon is proportional to its frequency, "lower positional dispersion means higher frequency dispersion" translates to "lower uncertainty about where the photon is means higher uncertainty about its momentum".
Comment: The pick itself makes a noise that your fiinger doesn't make.  This sound is obviously more percussive or scrapey (for lack of a better term) and is more obvious with little or no amplification.
Comment: If you turn the reference to your meta post into a link to the meta post, it may help it get traction with people who found this answer helpful in the hopes of better supporting similar answers in the future.
Answer: The reason for the difference in sound is that the release of the string from the pick is faster than with fingers, which means that fewer of the upper harmonics are damped as the string is released.  This gives the pick a brighter sound than the fingers.
Comment: Might want to expand to define "faster" as " 2nd, 3rd, and higher derivatives of position are much greater :-) .  But I suspect (and can't prove without a good o'scope) that you are correct that dampening occurs.  I know from experience that (cello) I get significantly different overtones depending on how far from the midpoint I pluck pizzicato.
Comment: @mrpyo You could look at the references yourself and do some web searches. You could also wait and see how the voting goes on the answers and how the comments develop and let the community advise you. In any case, you don't have to hurry to accept, you can wait as long as you want.
Comment: @mrpyo It's **both** initial string shape and total string displacement, as documented in my answer. This answer is simply wrong.
Comment: @ToddWilcox  Why must you insist that this answer is wrong when your own answer quotes "Thicker picks (tend to) remain in contact with the string longer..."? The key concepts of "faster release" and "remain in contact longer" essentially are describing the same thing.  Although this answer is incomplete, it is not "simply wrong".
Comment: Your answer seems to imply that a guitarist cannot control their pick or hand.  It is simply false.  One can set up initial conditions for both s.t. the speed and attack are the same.
Comment: The difference in frequency content is more likely due to the difference in material.
Comment: @Tristan - If I understand correctly, you propose different mechanism: initial string shape vs. string dampening by soft skin proposed by Scott, right? I wonder which one is it, maybe it's both but to different degree...
Comment: @ggcg - I didn't take his answer to imply that, but rather that the release is faster because the process of a string coming off a hard pick is short in duration, while coming off a soft finger takes a longer period of time while the pressure on the string decreases until it finally loses contact.
Comment: @ToddWilcox Well, I'm in a bit of a pickle now - I want to accept an answer, but have no idea which one is correct...
Comment: @CPerkins If by "faster" this answer means "sooner", that's news to me. But the second part about "damping" upper harmonics via longer string contact doesn't have any support in the research I was able to find. That assertion requires a citation. At some point, the string is released and the initial shape of the string is set. I don't see how what happens before release has much effect on the sound, and I haven't found any research suggesting that what happens before release has an effect. The longer contact time leads to more initial displacement, not any kind of "damping".
Comment: @CPerkins Tristan was more subtle about it, but his comment also explains how this answer is wrong. It has nothing to do with anything being "faster".
Answer: The difference is caused by the different shape of the plucking implement. One easy way to verify this at home is to take your pick (same material and thickness), and pluck the strings with the back of the pick or the side of the pick. The tone will be different because of the different profile of the pick (pointed versus rounded).
Also, the thickness of the plucking device makes a difference.
The primary link between the shape and thickness of the plucking device and the change in tone is the difference in initial displacement of the string:
Quoting (emphasis mine):

Plucking with a sharp object such as a plectrum accentuates the higher harmonics in contrast with plucking with the finger or a soft object. This is because the initial displacement is highly angular in form. In order to achieve such a displacement curve... many higher order modes must be introduced, which would not have been the case if the curve had been more rounded

The Musician's Guide To Acoustics, Campbell & Greated, 1994
A more rounded and/or softer plucking instrument produces a more rounded initial string displacement which excites fewer high harmonics in the resulting motion of the string.
Regarding the thickness difference between the pick and the finger (or between different picks), we already have a Q&A here: Why do thicker guitar picks result in a darker tone color?
Quoting the accepted answer to the above question:

Thicker picks (tend to) remain in contact with the string longer. The impulse provided to the string is of longer duration. A longer duration pulse imparts more lower frequency and less higher frequency content.

See: http://acoustics.org/pressroom/httpdocs/160th/carral.html
Comment: This.  And to add to this answer, if you have reasonable fingernails then it is perfectly possible to pluck the strings so that only the nail hits the string in a "rest stroke" (which is how a pick travels).  The result sounds just like a thinner pick.  Replace your normal nails with acrylics, as some guitarists do, and you're even more clearly into pick territory.  The shape of how you file or cut your fingernails also has an effect, in the same way as playing with a sharp piece of plastic or a rounded pick.
Comment: And given that these different tones are available, it becomes a question of what tone you want.  Segovia's ideas of how the right hand fingers should pick the strings were particularly influential, of course, but there have been other approaches.
Answer: As an addition to the other answers, here's the frequency spectrum of an open low E string of an electric guitar (a Squier strat with a bridge humbucker), strummed with the fleshy part of the finger, plucked with a fingernail, and picked with a plectrum (a Dunlop Delrin-500 .71mm). I played each note a couple of times and then selected one that sounded representative, and was of somewhat equal volume.
For the attack phase I used the first 250 ms of the note, for the sustain phase I used the part from 1 to 1.5 seconds. The graph shows the level in dB of frequencies from 50 Hz to 15 kHz on a logarithmic scale.

I don't make any claims as to how scientific this is, but it's better than looking at the black body radiation of an incandescent light bulb :-)
I think it's fair to say that there is a clear difference in the spectrum of the plectrum-picked note; the harmonics up to around 10 are of comparable amplitude, whereas in the finger-plucked note the first three harmonics clearly dominate the sound. The frequencies between 1 and 2 kHz are also more prominent, and the troughs around 2.5, 6 and 10 kHz are narrower and they all but disappear in the attack phase.
Comment: Nice. I once heard an actual engineering professor say "Far be it from me to suggest you should ever calculate anything you can measure."
Answer: Good answers, but they're either incomplete or very technical.
The simple answer is that the shape and stiffness of your finger is different from the shape and stiffness of the pick. For this description, let's presume that the pick is an infinitely hard single point that releases the string instantaneously. In reality, a pick is an edge, like a tiny violin bow, but that can be ignored if you're comparing it to a finger.
By comparison, your finger is a soft, round shape. When it releases the string, the string slides across the finger's surface. Imagine that you ran a circle of sandpaper across the string. Each of the grains would provide a tiny pluck. Similarly, your finger also sends many microscopic plucks (waves) down the string.
Unlike with a pick, These waves will have origins that are the entire width of your finger, and that will slightly alter the harmonics that they produce.
Your finger is also soft. This means that any wave that runs into it mid-pluck will be absorbed by your finger's surface, decreasing the strength of the wave as it travels down the string. This is a much smaller effect than the one you get when you hold a finger above the string at a fret in order to isolate a harmonic, but it's still noticeable in the resulting sound.
The combination of these factors results in a blurring of the tone that is produced. Although not nearly as extreme, the audio effect can be compared to the visual effect of the differences between the spiky spectrum that a florescent bulb produces

and the smooth spectrum of black body radiation you get from an incandescent bulb.
Comment: This doesn't seem to address why different shapes of picks also sound different. @ggcg I wonder if there's something about this topic that you are interpreting differently from most of the rest of us. I'm not able to understand the wording of your criticisms of the question or the answers. I don't think whether all picks or fingers are the *same* is important. 99% of picks are much more similar to each other than they are to 99% of fingers. The differences between most fingers and most picks are very clear and well-documented. That's what the question seems to be about.
Comment: The analogy is nice, but you'd be better serving the community if you could track down audiograms of different attacks, -- even if you have to settle for, say,  piano vs. harpsichord.
Comment: The major piece missing is method of attack.  You can make almost any pick sound like anything by changing your method of attack.  This large parameter space makes the question moot.
Comment: Again, someone is asserting as fact that all pick and fingers are the same.  You don't know that.
Comment: Many of these comments suggest extending the answer beyond the domain of the question asked. They want to know why a pick sounds different from a finger, not why various picking techniques sound different, nor how the shape of one's finger alters the sound. @CarlWitthoft, the hammering of a piano string is so outside of this question that I wonder why you suggested it.
Answer: Another factor not yet mentioned is the direction the string is traveling as it leaves the plucking appendage or implement.  Guitar strings support two primary modes of vibration--parallel to the body and perpendicular to it--and the resonant frequency in these modes will be influenced differently by the shape of the contact points on the nut, frets, and saddles, and (for electrics) by the pickups.  Some of the "warmth" of a guitar's sound comes from the interplay of these vibrations as they go in and out of phase, and the initial direction of motion will influence that behavior.
Incidentally, on an electric guitar, this effect may be demonstrated to a somewhat extreme degree by raising the neck pickup excessively and then playing notes high on the fretboard.  On one of my guitars, doing that can cause a single string to play two pitches simultaneously that are more than a semitone apart.  Having the pitches of the modes be that far apart probably wouldn't be useful musically, but it demonstrates their existence and independence.
Comment: Do you mean that the magnetic "drag" of the pickup on the string changes the frequency, but only of the perpendicular motion?
Comment: @YourUncleBob: Most pickups would probably change the frequency of parallel motion as well, but to a much lesser degree.
Answer: It's because your fingertips are fleshy pads that cover hard bone. When they strike the string and release it, there's not a strong separation, and your skin mutes and muffles the string somewhat. The skin is elastic and will compress somewhat when striking the string, instead of just pushing it more directly. When it leaves the string, it uncompresses somewhat, so it sort of "stays behind" a brief moment (milliseconds) and muffles the string's vibration
Meanwhile, the pick is usually stiff plastic, not very elastic (though they sell different stiffnesses of picks). In any case, it's not as elastic as skin.
When the pick plucks the string, it's a smaller, stiffer surface that strikes the string. When it releases, the pick doesn't rebound (as much as your fingertip skin does), and the string is free to vibrate.
You can demonstrate these principles to yourself by playing finger-style with thick cotton gloves. The cotton is even more elastic, and will muffle the sound even more.
Then try playing with finger picks (what banjo players often use, to keep the sound bright and unmuffled). Instead of elastic skin striking the string, it's now stiff plastic. It will sound more like a string plucked with a guitar pick.
Comment: Also no. The answer to this question has been studied and documented. It's not guesswork.
Comment: Yes, see my answer that I just posted. The Campbell/Greated source is not available online, but is very well researched and is probably the second greatest book on musical acoustics after Benade.
Comment: @ToddWilcox Do you have a source?
Answer: Sound is caused by vibrations, and the way something vibrates depends on what hits it.  Knock on a wall with your knuckle and then with a hammer.  They will sound different because the physical properties of a knuckle are much different than a hammer. This will result in a difference in how the force propagates through the other medium (the wall) and thus will result in the atoms of the wall vibrating in a different manner.  Likewise, a string will vibrate differently depending on the physical properties of the object that hits it.
The exact reason for why the atoms in the string are vibrating in the manner they are can be release speed, but there are lots of factors that can cause slight differences in the resulting vibration which may or may not be audible to humans.


How to get the id of a group when using the Group module?

Question: I'm using the Group module.
How can I get the id of a group whose a user is a member (I have the user id)?
Answer: I would just start with creating a view (using Views) of all "Group memberships", and include all available colums of that specific base table. It should include things like "user id" and "group id".
If you then add a contextual filter to limit it to some selected user id, you'll get 1 views result (row) for each group that the selected user is member of, or is invited for, revoked from, etc (membership status for each group is one of the available columns to include in your view). For each group you'll have its group id available also, so if needed you can add a relationship to the group itself to have access to additional data about the group itself (eg: the group title, or any of its custom fields you added).
After you have such view created, you have a prototype of anything else you want to do with that, e.g use whatever you want in your custom module to invoke the Group's API functions.
PS: refer to my answer to "How to add a column to the list of group members or create a Views equivalent of it?" for getting started with creating such view (even though it's for D7, for D8 you can use a similar one).
Answer: Assuming you mean how to do this programmatically.
One thing to understand is that there are mid level entities between a user account and groups called GroupMembership entities.
There is a service called group.membership_loader that provides the utility functions for retrieving the membership entities:
<code>  $group_memberships = \Drupal::service('group.membership_loader').loadByUser($account);
</code>
With a list of memberships, you can then load the groups:
<code>  $groups = [];
  foreach ($group_memberships as $group_membership) {
    $groups[] = $group_membership->getGroup();
  }
</code>


Proof that the tautochrone is a cycloid

Question: In the Wikipedia article about the tautochrone curve, there is a proof of the fact that the tautochrone curve must be a cycloid. The proof starts with the following statement:

One way the curve can be an isochrone is if the Lagrangian is that of a simple harmonic oscillator: the height of the curve must be proportional to the arclength squared.

How is the statement in bold justified?
Answer: The statement in bold is better phrased as:

If $s(t)$ describes simple harmonic motion, then the curve traced by the particle will be an isochrone.

The motivation for this assumption is the fact that in simple harmonic motion, the period is independent of the amplitude of the motion. So if $s(t)$ could be arranged to follow SHM, the particle's time of descent to its lowest level would be the same regardless of its starting position -- which is the goal of a tautochrone.
To understand what's going on in the rest of that paragraph, recall that the Lagrangian under the SHM assumption would then be
$$
L(s) = \text{kinetic energy - potential energy} = \frac12 m\dot s^2 -\frac12 ks^2.
$$
This explains why the paragraph is supposing that $y=s^2$ ("the height of the curve must be proportional to the arclength squared"), since the particle's potential energy is proportional to its vertical displacement above the lowest level, which is what $y$ represents. The rest of that paragraph goes on to derive the cycloid solution from the assumption $y=s^2$.

Proof that the tautochrone is a cycloid


Drush 6 on Windows not doing anything

Question: I've installed Drush 6 on Windows using this installation package and have ensured that the following is in my PATH variable:

C:\ProgramData\Drush\;C:\Program Files (x86)\Drush\GnuWin32\bin;C:\Program Files (x86)\Drush\Php

When I open the Drush Command Prompt and type "drush status", nothing happens. The cursor moves a line down and blinks as if it's working on executing the command, but nothing is shown, and the process never ends. I have to Cntl+C to get out of it.
The same thing happens in Git Bash. No error messages, nothing. Just the ever blinking cursor. Any idea what's happening or how to fix it? Thanks in advance!
Answer: Figured it out. It was a problem with the reverse-proxy we're using. I installed a different version of drush in cygwin and tried to run it. Here it paused like I described above, but after a minute showed me this error:

Drush needs a copy of the PEAR Console_Table library in order to function, and the attempt to download this file automatically failed.
  To continue you will need to download the 1.1.3 package from http://pear.php.net/package/Console_Table, extract it into C:\cygwin64\usr\local\src\drush/lib directory, such that Table.php exists at C:\cygwin64\usr\local\src\drush/lib/Console_Table-1.1.3/Table.php.

I installed this package manually and now things are working. I just didn't realize Drush was trying to download extra content.

Drush 6 on Windows not doing anything


C++0x regex in GCC

Question: The following code:
#include <regex>
using namespace std;

(snippage)

regex_search(s, m, re);

works in Microsoft C++, but GCC 4.4.3 gives the following error message:

/usr/include/c++/4.4/tr1_impl/regex:2255: warning: inline function 'bool std::regex_search(_Bi_iter, _Bi_iter, std::match_results<_Bi_iter, _Allocator>&, const std::basic_regex<_Ch_type, _Rx_traits>&, std::regex_constants::match_flag_type) [with _Bi_iter = __gnu_cxx::__normal_iterator, std::allocator > >, _Allocator = std::allocator, std::allocator > > > >, _Ch_type = char, _Rx_traits = std::regex_traits]' used but never defined

Of course it wouldn't surprise me if regex were simply one of the C++0x features still on the to-do list for GCC, but what I'm scratching my head over is, in that case, why does it happily take the include directive, variable declarations etc. and only trip over the function call (which it even seems to understand).
Is there something I'm missing?
Comment: you may use  instead.
Comment: Are you compiling with `-std=c++0x` ?
Comment: Yes. Seems the issue is regex only being partly implemented as yet.
Answer: The regex library was mostly not implemented in libstdc++ up to branch 4.8.
Versions 4.9 and above do have <regex> implemented though.

Implementation tracker bug for <regex>
Current library support status for C++11
Comment: [`` is now implemented as of GCC 4.9](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53631#c17)
Comment: Here's a link to the c++0x project that covers all versions of gcc and their support statuses. http://gcc.gnu.org/projects/cxx0x.html
Answer: For g++, compile with flag "-std=c++0x"
Comment: This will only work for versions of gcc that have the feature implemented. For example I was trying to use std::basic_regex but there is no implementation behind this function in gcc 4.4 and 4.5.

C++0x regex in GCC


Consulta em duas tabelas Oracle

Question: Como faço para consultar duas tabelas ao mesmo tempo? Tenho duas estruturas de tabelas da seguinte forma.
TGFCAB
___________________
|NUNOTA|   DTMOV  |
------------------|
|  1   |01/06/2019|
|  2   |02/06/2019|
|  3   |03/06/2019|

e
TGFITE

|NUNOTA|CODPROD|QTDNEG|VLRUNIT |VLRTOTAL|
|------|-------|------|--------|--------|
|  1   |  18   |5,2   |10      |52      |
|  1   |  26   |1,3   |10      |13      |
|  2   |  11   |10,5  |10      |105     |
|  2   |  26   |16,5  |10      |165     |
|  2   |  18   |2,5   |10      |250     |
|  3   |  18   |2,0   |10      |200     |

No caso eu fiz um SELECT na primeira tabela, para procurar os valores do dia 01/06/2019 e 02/06/2019, ficou da seguinte forma.
SELECT * FROM TGFCAB
    WHERE DTMOV
        BETWEEN
            to_date('01-JUN-19', 'dd-mon-yy')
        AND
            to_date('02-JUN-19', 'dd-mon-yy')
    ORDER BY DTMOV;

Preciso agora automaticamente pegar somente as notas fiscais 1 e 2, que são respectivamente dos dias 1 e 2. Há alguma forma de fazer isso sem ter de digitar manual?
Comment: Uma junção entre as duas tabelas via campo NUNOTA? Uma INNER JOIN fornecerá o que necessita.
Answer: você pode fazer
SELECT *
FROM TGFCAB
INNER JOIN TGFITE
ON TGFCAB.NUNOTA = TGFITE.NUNOTA
WHERE TGFCAB.DTMOV
    BETWEEN
        to_date('01-JUN-19', 'dd-mon-yy')
    AND
        to_date('02-JUN-19', 'dd-mon-yy')
ORDER BY TGFCAB.DTMOV;

Comment: Funcionou! Uma ótima coisa a se fazer no código também é atribuir um "alias" para cada tabela, assim não precisando rescrever o nome completo dela durante o código.

Consulta em duas tabelas Oracle


Combining two survey samples

Question: I have two surveys of business owners.  One is a sample (sample 1) of business owners who were not members of the association, done using a random digit dialing approach.  The other is a sample (sample 2) of business owners who were members of an association (used the list of members for the frame).  Both samples were stratified by state.  Sample 1 was weighted using state and gender.  Sample 2 was weighted for non-response and weighted to reflect the association characteristics.  As it turns out, there is a greater proportion of males in the association data (sample 2) than in the non-member data (sample 1 data).  At first look, it appears that the association appeals to males more than females. We have 500 responses for each sample.
I want to use a probit regression to find the factors (mostly demographic type of factors) influencing association membership.  What is the best way to do this?  I was hoping I could just combine the samples. However the samples were done independently. Clearly there is a huge difference in the size of the populations - sample 1 is huge (all owners in the country) and sample 2 is just the members. The survey instrument (questions) was almost identical - there were some extra questions for the members of the association (sample 2) related to the satisfaction with the association.
Comment: I'm wondering why you want to use probit. Logistic regression is standard for relating covariates to a discrete binary response. Should you be interested, I wrote a good deal about all that here: [difference-between-logit-and-probit-models](http://stats.stackexchange.com/questions/20523/30909#30909).
Answer: This looks like a case-control study (all cases are sampled, a similar number of controls are sampled at a much lower rate) -- read up Alastair Scott and Chris Wild's s work on this (book chapter, invited lecture). I second gung's opinion about logistic regression being somewhat more suitable (the theoretical advantages being the exponential family and sufficient statistics).
Comment: Thanks to everyone for the answers.  I'm now clear on what I need to do and I've found a couple of very useful papers.  You're correct,it is logistic regression I want - to get the odds ratios out.  Thanks!!

Combining two survey samples


Can exponential functions have "complex" solutions?

Question: Do exponential functions, take $e^x$, have imaginary solutions just as a function like $\sqrt x$ has complex solutions? I know $e^{i\pi} = -1$ but I'm not sure how this works or relates.
Comment: Functions don't have solutions. Equations have solutions, problems have solutions, but functions don't have solutions. So, what do you actually want to know?
Comment: $$e^{\ln\left(\sqrt{b^2+c^2}\right)+i\arctan\frac cb}=b+ic$$
Comment: @GerryMyerson I was thinking about the function y=e^x (any base, it doesn't matter)  and how obviously no real value of x will ever make y a negative number. But is there some sort of z such that y in y=e^z can be negative? Analogous to how no real value of x can produce a negative number for y in y=x^2.
Comment: Yes, there is such a $z$, and you've written it: $e^{i\pi}=-1$. More generally, if $a$ is real, then $e^{a+i\pi}$ is the negative number $-e^a$. But that doesn't mean that the function $e^x$ has imaginary *solutions*; it means the *equation* $e^x=w$ has complex solutions, for negative real values of $w$.
Comment: Anyway, are you happy with the answer José Carlos Santos posted a couple of months ago? or is there something still not clear to you?
Comment: @GerryMyerson I think its all good now. I was just confused at the time.
Answer: If $w\in\mathbb C\setminus\{0\}$, you can write it as $r(\cos\theta+i\sin\theta)$, with $r>0$ and $\theta\in\mathbb R$. Then$$e^{\log r+\theta i}=r(\cos\theta+i\sin\theta)=w.$$


PHP função da classe!

Question: Criei uma função dentro da classe que recebe um parâmetro e troca o valor de uma variável da classe, mas ela não funciona. Alguém pode explicar-me o porquê? O resultado dá NULL
<?php

class book{

    public $nome;

    function nao($x){
        $nome = $x;
    }
}

$pirata = new book();

$pirata->nao("caribe");

echo $pirata->nome;
var_dump($pirata);

Comment: Você não está definindo o valor do campo `$nome`. O método `nao` está apenas criando uma variável local (que não pode ser acessada fora dela). Para alterar um campo global, utilize o [`$this`](http://php.net/manual/pt_BR/language.oop5.basic.php), por exemplo: `$this->nome = $x`
Comment: @ValdeirPsr Seria interessante se você colocasse como resposta e se possível exemplificasse, pra que a pergunta possa ser marcada como respondida.
Comment: yaaay gratiluz!!! funcionou perfeitamente =DDD
Answer:
O correto seria um Get e Set, e não se esqueça do "$this" para referenciar um valor global

<?php

class book{

    public $nome;

    function setNome($x){
        $this->nome = $x;
    }

    function getNome(){
        return $this->nome;
    }
}

$pirata = new book();
$pirata->setNome("caribe");

echo $pirata->getNome();

PHP função da classe!


Centered family in a Boolean algebra

Question: I do not understand the definition of a centered family in a Boolean algebra.  Here's the definition

A family $R\subset A$ is said to be centered, if for every finite set $\{a_1,\ldots, a_n\}\subset R$, $a_1,\ldots,a_n > \mathbb{O}$.

this is from Logic of Mathematics by Adamowicz and Zbierski.  Part of Exercise 3.9 on page 23.  I cannot do the exercise because I don't understand the definition.
Is it saying, "For every finite set $S$, it is the case that $S\subset R$" or is it saying, "For every finite subset $S$ of $R$, all of its elements are positive"?  But in a Boolean algebra every element is greater than $\mathbb{O}$.
Answer: This appears to be a typo.  It should instead say that the meet $a_1\wedge \dots\wedge a_n$ of $a_1,\dots,a_n$ is greater than $0$.
Comment: No!  My bad.  I misread it.  In this book they use $\cdot$ in place of $\wedge$.  There is no comma, I wrote that when I asked the question.  I confused $\ldots$ with $\cdots$.  This makes sense! Awesome, thank you

Centered family in a Boolean algebra


Modify Checkboxes based on changes in Streamlit

Question: I wanted to create a checkbox which checks all other checkboxes if checked and if the checkbox is unchecked that all other checkboxes also get unchecked.
For example:

Clicking on "all" should be also checking "option1, option2, etc.". Same if I uncheck.
I tried to use session_states but could not come up with a solution.
Is there a possibility to modify checkboxes?
Answer: You can use this way.
<code>import streamlit as st

isall = st.checkbox(label="All")

st.checkbox(label="option1", value=isall)
st.checkbox(label="option2", value=isall)
</code>


Webmin + SSH Public Key

Question: Is it possible to upload a UNIX user's public key to Webmin? I would think this would be on this screen, but I'm not finding it....
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: You can't do it there. Upload the public key, move it to <code>~/.ssh</code>, and give it the right permissions.
Comment: I think it's a great question. To me it was also unclear. So the steps are: 1. add to authorized_keys in ~/.ssh ... thats it??? or do we also need to create a user and link the keys?

Webmin + SSH Public Key


How to conduct a multilevel model/regression for panel data in Python?

Question: I have yearly data over time (longitudinal data) with repeated measures for many of the subjects. I think I need multilevel modeling/regressions to deal with sure-to-be correlated clusters of measurements for the same individuals over time. The data currently is in separate tables for each year.
I was wondering if there was a way that was built into scikit-learn, like LinearRegression(), that would be able to conduct a multilevel regression where Level 1 is all the data over the years, and Level 2 is for the clustered on the subjects (clusters for each subject's measurements over time). And if so, if it's better to have the longitudinal data laid out length-wise (where the each subject's measures over time are all in one row) or stacked (where each measure for each year is it's own row).
Is there a way to do this?
Answer: Linear regression will not be suitable for a multilevel model.
A mixed effects model is a good way to fit most multilevel models.
In python you can use mixedlm in statsmodels. For example:
In [1]: import statsmodels.api as sm

In [2]: import statsmodels.formula.api as smf

In [3]: data = sm.datasets.get_rdataset("dietox", "geepack").data

In [4]: md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"])

In [5]: mdf = md.fit()

In [6]: print(mdf.summary())
         Mixed Linear Model Regression Results
========================================================
Model:            MixedLM Dependent Variable: Weight
No. Observations: 861     Method:             REML
No. Groups:       72      Scale:              11.3669
Min. group size:  11      Log-Likelihood:     -2404.7753
Max. group size:  12      Converged:          Yes
Mean group size:  12.0
--------------------------------------------------------
             Coef.  Std.Err.    z    P>|z| [0.025 0.975]
--------------------------------------------------------
Intercept    15.724    0.788  19.952 0.000 14.179 17.268
Time          6.943    0.033 207.939 0.000  6.877  7.008
Group Var    40.394    2.149
========================================================


How can i send OTP to users phone number in Laravel just before registration

Question: I already have a function that takes a phone number and sends OTP to the number in laravel..
But now i want to be able to send OTP to phone number during registration in laravel...i am thinking this will be at this point of creating the users information below....
Please help as i am not sure at what stage to send the OTP and verify it too.
I already have a function that takes a phone number and sends OTP to the number in laravel..
protected function create(array $data)
    {
    $otp = rand(100000, 999999);
    $MSG91 = new MSG91();

    $msg91Response = $MSG91->sendSMS($otp,$users['mobile']);

    return User::create([

        'password' => Hash::make($data['password']),
        'customers_telephone' => $data['mobile'],
        'customers_firstname' => $data['fname'],
        'customers_lastname' => $data['lname'],
        'email' => $data['email'],
    ]);
}

What i want to archieve is to send OTP to the user and let the user verify the OTP before users can access the dashboard
Answer: To solve your issue, you need to add a otp_verified field in your users table as Boolean. Example if 0 means not yet verify and 1 is verified.
Then when a user logged in, they will not proceed in the dashboard instead a popup or redirected to a page where they need to put the otp with a submit button that needs to verify the otp.
If it's success then redirect the user to the dashboard.
Comment: Are you using `AJAX` on the registration?
Comment: If it's not an ajax, then you need to have a button where if a user clicks it will send an otp, and store the otp in a session. Then add a validation on the registration where you need to check if the session otp is matches the users input otp.


Fitting a distribution on Income data

Question: Why is the Pareto Distribution a better fit to the upper tail of Income data, and the Lognormal distribution a better fit to the lower tail? What happens if we fit the data the other way around?
My argument is that if we truncate the hump of the lognormal distribution it should perform nicely as a fit for the upper tail, and I cannot find a good reason to suggest that the Pareto distribution should not be used as a fit for the lower tail.
Comment: 1. Where's the assertion that this is the case?  (Do you have a reference? ... NB I believe the assertion is probably true but it's best if we can see who claimed it in what context -- maybe it's not even true).   2. You wouldn't happen to have some smallish dataset people can use to talk about it with, would you?
Comment: @Glen_b The last sentence of the penultimate paragraph of 11.2 [here](https://books.google.com/books?id=Kus8AAAAIAAJ&pg=PA108&redir_esc=y#v=onepage&q&f=false)  in the book *The Lognormal Distribution* mentions a similar fact. Does this mean the same thing as in OP's question?
Comment: @Stubborn Thanks! Yes, that has the claim the OP is discussing
 > "*We recall here the finding of Quensel[169] that the lognormal curve is the better approximation in the lower range of incomes, whilst the Pareto curve is better in the higher range.*"
 It makes no mention of what the evidence was there (nor even any indication of how that conclusion was arrived at), only the bare statement and a reference to Quensel (1944) which is a book written in Swedish. I can find a number of other references to Quensel's book but the ones I looked at all say no more than this...
Comment: ... Clearly then, this is (as it appeared) an empirical claim, and it would presumably be that the shape of the cdf of log-income is closer to the shape of a normal than the shape of an exponential on the left, but heavier tailed than a normal on the right, closer to an exponential. At least if I was trying to investigate that claim, I'd be looking at it that way -- say by producing a pair of QQ plots on the log scale (against approximate expected quantiles for the standard normal and standard exponential) to look for this effect and if present, the approximate location of the transition.
Answer: I would have thought that what is most suitable must be empirically justified.
I am used to looking at income distributions something like this (from the UK), though strictly speaking this is only the bottom 92% of the distribution

A Pareto distribution really does not work for the lower part of this distribution, as it fails to fit those incomes between zero and the mode.  (Just to catch the unwary, there is also a non-zero number of individuals with zero reported income, almost visible as about $0.55$ million in the graph)
Again in the upper tail the justification for using a particular distribution would need to be empirical.
Different income distributions form different countries might need different models
Answer: Consider the log of income.
The assertion corresponds to the claim that for log-income the left side of the distribution is closer to normal but the right side has a tail that is more like an exponential. If it's the case in a particular data set, this should be able to be seen.
Here's an example (which had very fine divisions of income so we can see clearly what happens).
It's UK income data, taken to the log-scale of income:

Data from here ("Supporting tables" link)
(negative incomes and incomes above one thousand pounds per week are omitted)
The log income data was generated from the original table by randomly generating a very large sample from the given distribution of income uniformly in each income interval (then values below the centre of the leftmost interval were omitted before taking logs, because of the resulting distortions it produced if the very lowest values were retained). I did it this way because trying to do a plot of the log income directly from the original data had problems at the lower end.
The original claim would have this being normal on the left and exponential on the right. We see that the first part may not be too bad an approximation but we don't have enough of the right tail (which was truncated) to tell for sure whether the upper tail might be reasonably approximated by an exponential.
We can see that we don't have an exponential on the left half for log-income. We might just have something approximately normal on the right (we can't rule it out because of the truncation), but if it is then it looks like it's at least a bit heavier than the left tail.
Edit: It looks like the data used in this post could be the same data used to generate the plot used in Henry's post.

Fitting a distribution on Income data


TableView Delegate Messages Not Being Called

Question: SOLVED: Not really a solution, but I just used a .xib rather than trying to use the storyboard thing. Whatever I was trying to do with the storyboard was somehow messing up the TableView delegate methods from being called. Thanks for all the insight you guys provided.
I have a UIViewController that contains a UITableView that should be populated by an array.
Unfortunately the UITableView does not get populated by the array (which is not empty).
My .h file:
@interface Directory : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate> {
NSArray *listData;
NSArray *savedListData;
MKMapView* mapUI;
UISearchBar* searchBar;
NSArray * originalListData;
UITableView* placeList;
DirInfoListing *infoInst;
NSString *searchInit;
NSString *openInit;
NSMutableArray *buildings;}
@property (nonatomic, retain) NSArray *listData;
@property (nonatomic, retain) NSArray *savedListData;
@property (nonatomic, retain) IBOutlet UISearchBar* searchBar;
@property (nonatomic, retain) IBOutlet UITableView* placeList;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil list:    (NSArray*)array  mapView:(MKMapView*) map;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil list:(NSArray*)array  mapView:(MKMapView*) map search:(NSString*) ss;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil list: (NSArray*)array  mapView:(MKMapView*) map open:(NSString*) openTx;
-(void)doDBLoad;
@end

And relevant stuff from my .m file:
#import "Directory.h"

@interface Directory ()

@end

@implementation Directory
@synthesize listData, savedListData;
@synthesize searchBar;
@synthesize placeList;

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"ListData count: %lu", (unsigned long)savedListData.count);
        //This returns a valid number of 74 items
    return [self.savedListData count];
}

/*
 * Populates the table with list data and provides title. AND DOES NOT GET CALLED
 */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tID = @"tablIDDirect";
    UITableViewCell *c = [tableView dequeueReusableCellWithIdentifier:tID];
     if(c == nil) {
        c = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tID];
    }

    NSInteger r = [indexPath row];
    if([self.listData objectAtIndex:r] != nil){
        c.textLabel.text = ((DBBuilding*)[self.savedListData objectAtIndex:r]).Name;
        c.detailTextLabel.text = ((DBBuilding*)[self.savedListData objectAtIndex:r]).Acronym;
    }
    c.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return c;
}

/*
 * Displays an entry according to the table selection and redirects the user to the     Directory Information Listing.
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger r = [indexPath row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if(infoInst != nil) {
        infoInst = nil;
    }
    infoInst = [[DirInfoListing alloc] initWithNibName:@"DirInfoListing" bundle:nil building:[self.savedListData objectAtIndex:r] map:mapUI];
}

/*
 * Notification that the Directory is the active view
 */

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if(openInit != nil)
    {
        [self openEntry:openInit];
        openInit = nil;
    }

    placeList = [[UITableView alloc] init];

    placeList.dataSource = self;
    placeList.delegate = self;
    [placeList reloadData];
}

/*
 * Notification that the Directory is no longer the active view
 */

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
    NSLog(@"ListData count: %lu", (unsigned long)listData.count);
        //Also returns a valid number of 74 objects within the array
    savedListData = [[NSArray alloc] initWithArray:listData];
        //That get put into another array just for my sanity

        [super viewDidLoad];
    // Do any additional setup after loading the view.
    searchBar.text = searchInit;
    [self performSearch:searchInit];
 }

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

The -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionmethod gets called, but none of the other UITableView delegate methods are called and I am at a loss as to why this happens.
Also, this whole chunk of code is pulled from another one of my apps (That works correctly) using .xibs and DOES NOT use storyboards. This app (the one I'm having problems with) uses storyboards, which I am not very familiar with. I may be doing something wrong with calling and using the storyboard, but I am just not sure. If there may be something related to that I can provide more information.
Could you guys please go over my code and maybe see where I've gone wrong?
Thanks!
Comment: Do you have an `@synthesize` line for `savedListData` in your .m? If so, please show it. If you don't, just say so.
Comment: Sorry, I forgot the top part of the .m file
Comment: Are you using storyboards? If so, did you connect the UITableView delegate and datasource to the View Controller?
Comment: @Jon Yes, I am using storyboards (and I've never worked with them before so I might be doing something terribly wrong related to them) but my dataSource and delegate are connected to the TableView within the view controller, should they be connected to the view itself?
Comment: The data source and delegate should be connected to the controller (Directory). Did you put a log as the first line of cellForRowAtIndexPath, not inside the if clause to see if that method is being called? I don't see how it could not be, if numberOfSections and numberOfRows are both called, and return valid numbers.
Comment: @VonKnoob, Within the Storyboard, click the UITableView and hold the control key (A blue line should appear). Then, drag the connection to the view controller (The orange/yellow circle beside First Responder). A black selection box will appear, select datasource. Then, repeat these steps and select delegate.Also, make sure that the View Controller is set to the correct file. You can do this by going to the Identity Inspector and under Custom Class type in the name of your View Controller class name.
Comment: @rdelmar Both the dataSource and the delegate were connected to the controller, and that was my entire problem, the numberOfSections and numberOfRows were both called, but cellForRowAtIndexPath and other delegate methods were not called when I was using the storyboard (but not when using a .xib).
Comment: @Jon Thanks for your suggestions, but I had already done all of the things you presented, the View Controller was correctly set through the identity inspector. For whatever reason, the TableView delegate methods were not called when I was using a storyboard but worked perfectly fine when I took the .xib out of the storyboard and used it as a standalone file.
Comment: Hmm..., I just don't see how that's possible. If it calls the two data source methods I mentioned, and they both return non-zero value, cellForRowAtIndexPath should be called. Can you post the project on Github, or somewhere where we could actually look at it?
Comment: @rdelmar I couldn't see how that was possible either, but no I am not able to post the project on Github since it is not mine to distribute openly. Thanks for all your suggestions and hopefully I have no further problems related to the storyboard/xib and delegate methods issue I was having.
Answer: In your "viewDidLoad" method, change one line to this:
self.savedListData = [[NSArray alloc] initWithArray:listData];

Except "listData" needs to be something.  "self.listData" might be that something, but on my first pass, I do not see where "self.listData" gets populated or set.
With properties, you usually use "self." to access (set and get) everything for the properties everywhere except in the init methods.
The reason the table is not displaying anything is because your "numberOfRowsInSection" method is likely returning zero.  Set a breakpoint and check that.
Comment: The reason the other delegate methods aren't being called is because the "`numberOfRowsInSection`" method is returning zero. Use the Xcode debugger and step through that method and make certain everything is not null and returning a valid number, and once it's non-zero, the other delegate methods should start getting called.
Comment: Hmmm, I tried that but the other delegate methods were still not called. The listData is populated by the previous viewController, but when I NSLog the listData it returns the array
Comment: That is exactly why I am confused, the "`numberofRowsInSection`" method DOES return a valid number.
Comment: what is the valid number?  is it the count of the number of entries in the array?  if you set a debugger breakpoint at the beginning of "`cellForRowAtIndexPath`", does it hit?
Comment: The valid number is 74, the number of entries in the array (should it not be returning the `[self.savedListData count]`"?). A breakpoint placed at the beginning of "`cellForRowAtIndexPath`" does not get hit.
Comment: One thing to rule out here: Override and implement ["`numberOfSectionsInTableView:`"](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/numberOfSectionsInTableView:) in your .m file and make sure you're returning exactly one (for one section).
Comment: Ahhhh, you might be onto something there, the "`numberOfSectionInTableView:`" returns 0, not one.
Comment: An oddity that I found while comparing two of my projects (The code I have presented here is from another, working app). When I add the "`numberOfSectionsInTableView:`" method to my previously existing app, it returns 0 and DOES NOT populate the table. However, when I do not include the "`numberOfSectionsInTableView:`" method, the table IS populated (despite the sections most likely being 0)
Comment: @VonKoob, no, the default is 1 if you don't implement numberOfSectionsInTAbleView.
Comment: @rdelmar So if I did not implement "`numberOfSectionsInTableView`", it would return 1? Then why does it return 0 when I include it?
Comment: @VonKoob What are you returning?
Comment: I do not believe I ever set the number of sections and I assumed it defaulted to 1. When I include that method though, it returns 0.
Comment: @VonKoob, What code do you have in the method? The boilerplate code that comes with the table view controller returns 0 and has a warning attached to it.
Comment: Just a simple "`return [self.listData count];`"
Comment: @VonKoob, and if you log [self.listData count] what does it give you? 0?
Comment: My mistake, it is actually [self.placeList numberOfSections], and both my apps (the working one and nonworking one) return 0. However, the working app fails to work when I include that method, for whatever reason.
Comment: @VonKoob, I'm not sure I understand. Are returning  [self.placeList numberOfSections]? If so, that's just wrong. If you want multiple sections, you have to return a count of something in your model. If you want one section, just don't implement the method, or do implement it and return 1.
Comment: @rdelmar Ah, well I have the "`numberOfSectionsInTableView`" returning 1. But I'm still back at my original issue of the other tableview delegate methods not being called.
Comment: @VonKoob, you should update your question with the code you now have in there, and include logs in the data source methods, and what they each give you.
Comment: @rdelmar, I have edited my question and code to reflect the changes I've made (which is just putting some logs in there and saying what they return).
Comment: @VonKoob if you're having a new problem you should create a brand new question. I hope I was able to help you out with solving your original problem.
Comment: @MichaelDautermann No, I am not having a different problem, your suggestions were helpful in determining what wasn't the problem. I still have my original problem of having only 1 of the delegate methods called and not the rest.


Prove that $\Bbb{R^3}\setminus\Bbb{Q^3}$ is path connected in the euclidian metric space $\Bbb{E^3}$.

Question: I understand the concept of one coordinate moving while the rest don't change, however I can't make up the  exact mapping that would prove this. Can anyone give me the concrete mapping?
Comment: Read this : https://math.stackexchange.com/questions/882234/show-that-s-mathbb-r2-setminus-a-ba-b-in-mathbb-q-is-path-connected?noredirect=1&lq=1 Could qualify as a duplicate as well? Please reply if this answers your question, and any doubts you have on the answers there.
Comment: I can't find a mapping defined on that answer either :/
Comment: Look at Nishant's answer : the coordinatewise thing is explained. If you want to be exact and precise about the mapping , you will have to break into cases where each particular coordinate is irrational, and so on. Providing the explicit path is then just a case-by-case analysis, which I would not consider necessary to expound on unless you are in an exam or submitting an assignment.
Answer: Take $(a_1,a_2,a_3),(b_1,b_2,b_3)\in\Bbb R^3\setminus\Bbb Q^3$. Assume, for instance, that $a_1,b_3\notin\Bbb Q$. Then consider$$\begin{array}{rccc}\gamma\colon&[0,2]&\longrightarrow&\Bbb R^3\\&t&\mapsto&\begin{cases}\bigl(a_1,tb_2+(1-t)a_2,tb_3+(1-t)a_3\bigr)&\text{ if }t\in[0,1]\\\bigl((t-1)b_1+(2-t)a_1,b_2,b_3\bigr)&\text{ if }t\in[1,2].\end{cases}\end{array}$$Since $a_1,b_3\notin\Bbb Q$, $(\forall t\in[0,2]):\gamma(t)\in\Bbb R^3\setminus\Bbb Q^3$.
Answer: Let $(a,b,c)$, $(d,e,f)$ be two points in $\mathbb{R}^3\setminus\mathbb{Q}^3$. Then at least one of $a,b,c$ is not rational. By symmetry, we may assume WLOG that it is $a$.
If $d$ is not rational, we can follow the following path which is entirely contained in  $\mathbb{R}^3\setminus\mathbb{Q}^3$:
$$(a,b,c) \to (a,\sqrt2,c)\to(d,\sqrt2,c)\to(d,e,f)$$
where $P\to Q$ signifies a straight line path from $P$ to $Q$.
If $e$ is not rational, we follow:
$$(a,b,c) \to (a,e,c) \to (d,e,f)$$
If $f$ is not rational, we follow:
$$(a,b,c) \to (a,b,f) \to (d,e,f)$$


Single Sign on for RDS

Question: I currently have an RDS farm which is used for running remote apps for a large group of users.
When logging in these users must authenticate to the RDS web page to view their list of applications. Then they authenticate again upon clicking the application the require.
How can I enable this to use the users current windows authentication so they do not have to log in at each step. Ideally since the user is logged in to their local machine with their windows account, they should not need to continuously authenticate.
Comment: Do you have Integrated Windows Authentication enabled for your sites?
Answer: This article seems to address your need, although I'm not sure if it's exactly what you're looking for:
http://blogs.msdn.com/b/rds/archive/2009/08/11/introducing-web-single-sign-on-for-remoteapp-and-desktop-connections.aspx

Single Sign on for RDS


How do I set color hues for a grouped line chart?

Question: I'd like to set the colors for my ggplot line chart from dark blue to light purple.
I think I might have to use color brewer but I'm not sure the right way to do it
Can I set the high color to some color and the low color to some other color?
iris %>%
  ggplot(aes(Sepal.Length, Sepal.Width, group = Species)) +
  geom_line()

Comment: Try adding  `+ scale_color_gradient(low = "darkblue", high = "purple")`
Comment: I'm using a group = to create my groups
Comment: @Cauder please add a MRE so that we can better help you
Comment: I added in an example
Answer: scale_color_gradient will work for continuous data, but not for factors.
You can use colorRampPalette to brew your own palette which interpolates any number of desired shades between two chosen colors.
There is no color named 'light purple' in R's default colors so I used one that looked close. Try this code:
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3

### create color making function
colfunct <- colorRampPalette(c("darkblue", "darkorchid1 "))

###  brew desired number of colors, which is 3 for the built-in iris dataset
shades <- colfunct(3)

### plot the data and map color to the factor of interest
ggplot(iris, aes(Sepal.Length, Sepal.Width, color=Species))+
  geom_point(shape=1)+
  geom_smooth(method = lm, formula = y~x, se=FALSE)+
  scale_color_manual(values =  shades)

Created on 2020-10-10 by the reprex package (v0.3.0)
Comment: @Cauder your example maps "Species" to "group", not to color. Try using `aes(Sepal.Length, Sepal.Width, color= Species)` and it should work ?


Comparing two dates and avoiding duplication

Question: I am working on HP ALM where i try to perform this query :
SELECT  ONE.ID, ONE.Num_QC_EDF, ONE.Statut, TWO.Proprietaire, ONE.ChangeDate
FROM
(SELECT B.BG_BUG_ID as ID, B.BG_USER_15 as Num_QC_EDF, AP.AP_NEW_VALUE as Statut, BG_RESPONSIBLE as Proprietaire, AL.AU_TIME as ChangeDate
FROM  BUG B
INNER JOIN AUDIT_LOG AL
ON AL.AU_ENTITY_ID = B.BG_BUG_ID
INNER JOIN AUDIT_PROPERTIES AP
ON AL.AU_ACTION_ID = AP.AP_ACTION_ID
AND AL.AU_ENTITY_TYPE = 'BUG'
AND AL.AU_ACTION_ID= AP.AP_ACTION_ID
AND AP_FIELD_NAME= 'BG_STATUS')ONE,
(SELECT B.BG_BUG_ID as ID,B.BG_USER_15 as Num_QC_EDF, AP.AP_NEW_VALUE as Proprietaire , BG_STATUS as Statut , AL.AU_TIME as ChangeDate
FROM  BUG B
INNER JOIN AUDIT_LOG AL
ON AL.AU_ENTITY_ID = B.BG_BUG_ID
INNER JOIN AUDIT_PROPERTIES AP
ON AL.AU_ACTION_ID = AP.AP_ACTION_ID
AND AL.AU_ENTITY_TYPE = 'BUG'
AND AL.AU_ACTION_ID= AP.AP_ACTION_ID
AND AP.AP_FIELD_NAME = 'BG_RESPONSIBLE'
AND B.BG_STATUS = 'TU leger OK')TWO,
BUG B
WHERE
ONE.ID= TWO.ID AND ONE.Num_QC_EDF= TWO.Num_QC_EDF AND ONE.STATUT= TWO.STATUT and ONE.Proprietaire= TWO.Proprietaire and TWO.ChangeDate <= ONE.ChangeDate
Order by BG_BUG_ID, Num_QC_EDF, Proprietaire, ChangeDate

I would like to compare the ChangeDate situated in the second sub query to the one in the first sub query which must be  <= ,also the whole query must'nt return duplicated rows in the result of it (PS: distinct doesn't work in nested queries)
I am asking for help.
Comment: Can you add your table structures, some sample data, and expected results to the question as an edit? You seem to have a cartesian join from `BUG B` to the result of the join between `ONE` and `TWO` which might not be helping you, and might be causing your duplicates. Depending on the requirement, this might be solvable with analytics, but it's hard to tell at the moment.
Comment: Youn can refer to this page: http://qtp-automate.blogspot.com/2010/04/how-to-retrieve-quality-center-bug.html   where you can find all about table structures and relation between them .
Comment: @Alex Poole   You can refer to this page : http://qtp-automate.blogspot.com/2010/04/how-to-retrieve-quality-center-bug.html  where you can find what you are asking about
Comment: I agree with @AlexPoole, the `BUG B` on the 4th line from the bottom (and the comma on the line above it) are adding the entire BUG table and you are not joining to it anywhere. I would expect your results to include data from your ONE and TWO columns duplicated by the number of records in the BUG table. It's hard to say without sample data however. @user3491503, I reccomend using http://sqlfiddle.com/ to build a sample set to explain your question which will make it easy for users to help you.
Answer: Firstly, you added BUG B which doesnt join with other two sub-query tables ONE and TWO. So, you get hell lot of duplicates.
Without knowing your table structure, it is not possible to alter your query.
In case, you dont want to change your query and still want to get unique records, you can do the following:
Select DISTINCT AA.* FROM (*YOUR ENTIRE QUERY*) AA;

Above solution is not recomended, you need to join BUG B properly to other two tables.


R stats wilcox.test returns anomalous P = 1 for two.sided test

Question: I'm running a series of Wilcoxon-Mann-Whitney tests using wilcox.test from the stats package in R.  I keep getting results where P = 1 for a two-sided test.  I have pulled out the simplest case and converted the raw numbers to integer ranks (which gives the same result because this is a ranks-based test):
# unique values from 1 to 14, arranged in 2 sets
x <- c(5, 10, 8)
y <- c(9, 7, 6, 13, 1, 2, 12, 14, 11, 4, 3)
wilcox.test(x, y, alternative = "two.sided")
# for comparison
wilcox.test(x, y, alternative = "less")
wilcox.test(x, y, alternative = "greater")

I have two questions: (academic) what is happening here?  (practical) how can I get a more reasonable P value?  The context here is that I'm doing multiple tests and combining P values using Stouffer's method, which doesn't work when P = 1 for one of the results. So, this behavior is ruining my strategy.
I'm pretty sure that what is happening is that I'm repeatedly stumbling on cases where the chance of x being ranked lower than a randomly chosen y is exactly 0.5.   If this is true, then simplest case must be
x <- 2
y <- c(1, 3)

and this also gives P = 1.  It doesn't matter whether I'm using wilcox.test from the stats package or wilcox_test from the coin package.
Answer: You are right.  For the examples you give, the probability of an observation from x being greater than an observation from y is very close to 0.5.
One statistic to evaluate this is Vargha and Delaney's A, which is the probability of an observation from the first group being greater than an observation from the second group.  Cliff's delta is linearly related to this.
if(!require(effsize)){install.packages("effsize")}

x <- c(5, 10, 8)
y <- c(9, 7, 6, 13, 1, 2, 12, 14, 11, 4, 3)

library(effsize)

VD.A(x,y)

   ### Vargha and Delaney A
   ###
   ### A estimate: 0.5151515 (negligible)

This is so close to 0.50 that you would have to increase your sample size over 500 times to get a significant difference.
X = rep(x, 589)
Y = rep(y, 589)

wilcox.test(X, Y)

   ### Wilcoxon rank sum test with continuity correction
   ###
   ### data:  X and Y
   ### W = 5897700, p-value = 0.04993


Convergence to the mean estimate with bootstrap

Question: Let's say I am running a regression over the full sample and I get my coefficient values for each variable.

y = intercept + alpha X1 + beta X2
coef:
y = 1.8354 + 0.23234 X1 + 0.4564 X2

I woudl like to the check the values I obtained using bootstraping (because I don't have any hold out sample ).
Running a bootstrap on the regression I was wondering if the mean values for the coefficients obtained (alpha and beta) would always converge to the value from the full sample regression. And thus the only "meaningful" insight would be the confidence intervals ?
Answer: Yes they do converge. When bootstrapping you draw m samples $B_i$ of size n with replacement (means that some observations can get into the sample more than one time). Thus when you draw enough samples the coefficients, i. e. the mean of the samples, will converge to that of the full sample. The standard errors are robust against heteroscedasticity and thus compared to standard OLS they could be greater (approximately like robust standard errors).
$\hat\theta =\bar B = \frac1m\sum_\limits{i=1}^m\hat B_{i}$
Hence the estimated standard error is obtained by
$\hat s_\hat\theta=\sqrt{\frac1{m-1}\sum\limits_{i=1}^m(\hat B_i-\bar B)^2}$.
Assuming a normal distribution the confidence intervals are obtained accordingly:
$[\hat\theta-\hat s_\hat\theta z_{1-\alpha/2}, \hat\theta+\hat s_\hat\theta z_{1-\alpha/2}]$.
For comparison in OLS the standard error is estimated by
$\hat s_{\hat\beta_j} =\sqrt{\sigma^2\frac{1}{\sum\nolimits_{i=1}^n(X_i-\bar X)^2}}$
where $\sigma^2$ is the variance of the measurement errors.
Comment: Thank you for your answer. So what ever I do it will converge and how close they are does not give me an idea of the stability of my estimates because they should converge anyways ? So if they don't it means I need to run more bootstraps... And It would be the same if I were to calculate the Gini index, it would converge and thus it wouldn't give me an idea of my performance estimation stability, just give me some confidence bounds ?


UWP Memory Leak by calling ServiceReference (C#)

Question: I have a Problem:

I created a default ServiceReference
[OperationContract]
string GetData(int value);

Implementation:
public string GetData(int value)
 {
    return string.Format("You entered: {0}", value);
 }
Add ServiceReference into a new UWP Project
(Add Reference Pic.)
In the UWP Main Constructor I Call:
void Test()
        {
            ServiceReference.Service1Client h = new ServiceReference.Service1Client();
            for (int i = 0; i < 10000; i++)
            {
                var u = h.GetDataAsync(5);
            }
        }
Or:
async void Test()
 {
   ServiceReference.Service1Client h = new ServiceReference.Service1Client();
   for (int i = 0; i < 10000; i++)
   {
     var u = await h.GetDataAsync(5);
    }
  }
The Problem:
The WCF Service works. The UWP-App works. But the process memory decreases never.
Memory Pic.
The garbage collector do nothing.
When I call:
GC.Collect(2);
GC.WaitForPendingFinalizers();
It Change "Nothing" (does not rise as much). But the process memory decreases never.
On devices with low memory the App will crash when the Memory is full.(raspberry pi 2 / 3).
What am I doing wrong.

Raspberry pi 2 / 3 Scenario: A App is calling a ServiceReference in a daily loop. THe App is Running the whole year. Sometime the app will Crash because the Memory is full.
Comment: You posted just a part of your code but, isn't missing the dispose or put your client inside a using block?
Comment: The ServiceReference has no dispose function. Only IDisposable Objects can be use in a Using-Block.
Answer: (1)set "ServiceReference.Service1Client h = new ServiceReference.Service1Client();"
to Global parameter
or
(2)h.Dispose() in the end
Comment: The Global-Option work.
The ServiceReference has no dispose function.


Gloves weight for muay thai/boxing training

Question: I am starting to train for muay thai / boxing, and
I would like to know if there is any weight restriction for gloves.
Comment: I'm voting to close this question as off-topic because it is a shopping question, of a type that Stack Exchange does not cover.
Comment: The answer to this question makes it clear that the closing reason is not justified. And question was never about shopping gloves.
Comment: @Multitut I edited your question to make it more general to make it on-topic for the site, if you disagree with edit please roll back edit.
Comment: The fact that someone can give an answer is irrelevant to whether the question is of a certain category, be it on-topic or off-topic. The question here requests specific personal advice that will almost certainly never help anybody except the original asker, and that advice is on the particular items the asker should obtain. **It is therefore a shopping question, is off-topic, and should be closed.** Editing to make it a general question about the factors that go into making the decision, so that many users can apply the information in answers, is what could happen to keep it on-topic and open
Comment: @Nij Sir, I tried to make it general but there is not much to it, maybe OP sees this and changes something.
Answer: There are two ways to approach this question:

What the rules permit for your weight class
What your training instructor recommend

The World Muay Thai Council's rules state in section 3.3:

3.3. The glove sizes for competitions are as follows:

The boxers between the Mini Flyweight division and the Featherweight division must use the gloves of six (6) ounces (132
  grams).
The boxers between the Super Featherweight division and the Welterweight division must use the gloves of eight (8) ounces (227
  grams).
The boxers between the Super Welterweight division and over must use the gloves of ten (10) ounces (284 grams).

The USMTA also uses rules listed above, with this addendum for section 3.2:

Gloves at 12 oz, 14oz, 16oz, 18oz can be used for higher weights.
The weight of the leather shall not be more than half of the total
  glove weight, including the internal cushioning, which should always
  be in good condition. The laces are to be tied at the back of the
  wrist band. Gloves with Velcro fastening may also be used.

So it seems that you'd need gloves of at least 10 oz. for competition - perhaps larger ones if required for your weight class.
However, you should consult with your trainer/instructor to determine what type of gloves you should use for training. Perhaps he/she might want you to use heavier gloves to work on endurance, or gloves with more padding for protection.
Comment: Sir I edited the question and if there is anything that you need to change please look into it.


div 100% height - CSS

Question: como posso deixar minha coluna com 100% height?
exemplo:
EXEMPLO
onde está escrito Teste, é a coluna q tem que ficar 100% height,
DETALHE
em algumas telas, eu irei adicionar conteúdos usando jQuery, preciso também que não deixe esse conteúdo que não está visível ainda fora do height
CODIGO

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>
                Brand

 Item

 Item

 Item

 Item

 Item

Log off

 Item

 Item

 Item

 Item

 Item

      Teste

Comment: Você precisa de 100% da tela ou do espaço que está faltando para chegar até o rodapé?
Comment: Seria interessante você postar o código do "exemplo" aqui também, assim, o link fica sendo apenas referencia para o código descrito.
Comment: Ok @DiegoFelipe
Comment: uma alternativa seria pegar o tamanho da tela via jquery
Comment: Queres que esse `h1` divida a página ?
Comment: @CelsomTrindade espaçio que falta até o rodapé
Answer: Vamos começar do mais fácil e vamos ao mais complicado.
Para deixar o conteudo visivel, você precisa adicionar o overflow: scroll na coluna.
Com relação ao height: 100% que é a parte mais complicada disso. Você precisa declarar um tamanho de referencia que seja pai do nó. Isso é um problema antigo do CSS em que você não pode alterar o tamanho, sem ter um de referencia. Algo do tipo body: 600px.
Com CSS3 foi acrescentado uma alternativa chamada view height e view width. Com ela você consegue os 100%, em qualquer dispositivo, mas tem alguns problemas de compatibilidade. Os suportes só existe para IE9+ e não existe suporte para Opera mini. Você pode consultar a lista aqui.
E segue o exemplo da classe.
.content {
    height: 100vh;
    overflow: scroll;
}

Answer: Além da alternativa citada acima pelo @flpms é possível descobrir o tamanho da tela, e por meio do jquery implementar em seu css esta altura.
var altura = $(window).height();
$(".coluna").css("height",altura);

Assim passando a altura da sua tela para a coluna, assim tendo sempre 100%.

div 100% height - CSS


Add element to the beginning of form, via hook_form_alter()

Question: Using Drupal 7, I'm trying to utilize Drupal Form API in combination with hook_form_alter to place my added inputs at the beginning of the form.
I thought the best way to do this was to create a new form element like so:
$form['program_list'] = array(
    '#type' => 'select',
    '#title' => t('Select a preferred Program'),
    '#options' => $program_list,
    '#weight' => -1,
);

I read the documentation, and it looks like there is a #weight attribute. I tried setting the weight to either 0 and negative integers, but my added inputs are still at the bottom.
I then used var_dump() to check the weights of my Webform-generated inputs. They were as I expected: a 0-based, incremental weight index.
I also tried placing the elements in $newform then  using $form = $newform + $form, but that as well placed my new inputs at the bottom of the form.
What am I doing wrong?
Answer: I was facing the same problem but found the answer thanks to this post: http://drupal.org/node/235354
Problem was that the field I was adding to my web form was not in a group when all the already existing fields were part of the group 'submitted' maybe because this is a webform. So setting the weight to -1000 didn't change anything.
function webform_boncommande_form_webform_client_form_6721_alter(&$form, $form_state, $form_id)  {

    $form['my_new_field_name'] = array (
      '#type' => 'checkbox',
      '#title' => t ('My new field is after the others'),
      '#weight' => -1000,
    );

}

To correctly make it work I just needed to create my new field inside the group 'submitted' like that :
$form['submitted']['my_new_field_name'] = array (...

Answer: The #weight property is indeed the right way to go, it might be that another module that's processed after yours is moving some of the other elements back above yours.
If this is the case you could either try changing the #weight to a very low number (I normally go for -1000 when what I'm doing doesn't seem to be having the desired effect), or ensuring that your module's hooks are processed after any others.
The second option basically involves setting the weight of your module to a higher number than the others in the system table. See How to update a module's weight for more information.
Comment: Thanks for the response Clive. I have tried setting the new input, $form['program_list'], to weight -1000. I've also set my module's row in the system table to weight 2999. I've confirmed that there are no higher weights in that table. I also flushed all caches, but the element remains at the bottom! I'm going out on a limb; here's a pastebin, in case there is anything that pops out about the $form. http://pastebin.com/Ygkh8Pij
Comment: Weird! What form are you trying to alter out of interest? Maybe there's a clue in that
Comment: I've created a Webform node. The ID is webform_client_form_[nid]. Webform module via http://drupal.org/project/webform.
Answer: I've done a terrible hack JS job. Before reading this answer, please see if Clive's answer will work.
My JavaScript for getting my uncooperative selects to move to the top is:
jQuery(document).ready(function() {
  var inputs = jQuery('select[name=CampusID], select[name=ProgramID]').parents('.form-item');
  inputs.prependTo('.webform-client-form');
});

Answer: For the next person who comes along with this problem (specific to altering Webform nodes):
The behaviour is caused by the webform-form.tpl.php template. Since I wanted something to display before the webform components, I just overrode the template and drupal_render()'d my part of the form first.
(You can just stick your modifications into the $form['submitted'] array, but then they start getting processed/stored along with the submission, which was undesirable in my case.)
Answer: For adding markup to the beginning of the form, this works (but was not easy to find):
 $form['#prefix'] = '
A title
';


requestAction Cakephp 3

Question: Boa tarde, gostaria de uma ajuda para fazer um requestAction no Cakephp 3, antes no cake2 eu fazia dessa forma:
<code><?php $post = $this->requestAction('/Posts/latest'); foreach ($post as $value) : ?>

function latest()
{
    return $this->Post->find('all', array('order' => 'Post.id DESC','limit' => 1));
}
</code>
Comment: Relação: http://www.sanisoft.com/blog/2014/09/15/view-cell-cakephp-3-quick-start/
Comment: Outra relacionada: http://stackoverflow.com/a/30348446/6402423
Answer: <code>$this->requestAction(['controller' => '', 'action' => ''], ['pass'] => ['algum parametro se houver']);
</code>
Espero ter ajudado!
Comment: Poderia explicar como sua resposta resolve o problema, quanto mais detalhes an sua resposta melhor
Comment: Exatamente isso, muito obrigado

requestAction Cakephp 3


Is this signal band-limited?

Question: I'm self-learning signal processing now, and I've run into this question about band-limited signals:
Consider the signal $x(t) = 1$ for $0 \leq t \leq T$ and $0$ otherwise.
I've found that its Fourier transform is:
$$ x_\phi(\Omega) = \frac{1-e^{-j\Omega T}}{j\Omega} $$
How can I determine if this signal is band-limited signal, or not?
Thanks in advance
Answer: Check if there is some $R>0$ such that $x_\phi (\Omega)=0$ holds for all $|\Omega |\geq R$. That would be the definition.
Another way is the following: Every unlimited signal is smooth (infinitely differentiable), even analytic by the Palye Wiener Theorem. Is this the case for your signal? (Is your signal continuous?)
Comment: Try to find a sequence $(\Omega_n)_n$ with $\Omega_n \to \infty$ and $x_\phi (\Omega_n)\neq 0$ for all $n$. This will.imply that the definition is not satisfied.
Comment: I don't think, intuitivelly, that my signal holds the definition. But how can I prove this?
Comment: What about $f(x) = 1$ if $x = 0$ and $f(x) = 0$ is $x\neq 0$? It's not smooth but has unlimited bandwidth.
Comment: @AnonSubmitter85: First of all, you probably mean that the function has **limited** bandwidth. The (apparent) contradiction is resolved by noting that the actual statement is that there is a smooth function $g$ with $f=g$ **almost everywhere** (i.e. on the complement of a null set). I will edit the post this evening to reflect this.
Comment: @PhoemueX Perhaps I am misinterpreting "unlimited signal" to mean a bandlimited signal?

Is this signal band-limited?


Click anchor link and keep page position / prevent page-jump to top?

Question: I've seen variants of this question asked on SO previously, but these all concern anchors that point nowhere (i.e., href="#") or are placeholders for some javascript. My situation is different in that my anchors DO point somewhere, e.g.,

More specifically, they interact with a css gallery that advances the main image each time a thumbnail or the image itself is clicked, as below. What I would like to do is have this occur without the default 'target = top' behaviour of href.

<map name="gallerymap">
<area shape="circ" coords="429,157,30" href="#two"></map>

Whilst I have seen many javascript solutions to this, they all deactivate the link functionality in so doing.
I should say that while I'm happy to have a js / jquery solution, I am not looking to change my html / css navigation for javascript / jquery -- I wish navigation to remain operative for those who use Noscript.
Can anyone help -- with a demonstrably working solution?
N.B. I've tried 'scroll-sneak' (http://mrcoles.com/blog/scroll-sneak-maintain-position-between-page-loads/) but it has zero documentation and is notoriously difficult to get working.
UPDATED the js that captures the url hash to switch thumbnail opacity (to match gallery navigation) can be seen working, but for the scroll-sneak element, at http://www.ddsol.net/soDavePage/page/testFixed.htm
Answer: Scroll Sneak

Here's a method that implements scroll sneak. There's a slight flickering in Firefox 3 due to the small delay in the browser firing the scroll event, but it works as requested.
var sneaky = new ScrollSneak("gallery", false);
var capture = true;

$(document).ready(function() {

    var urlHash = window.location.hash;

    $(".thumbs a").on("click", function(e) {
        sneaky.sneak();
        capture = true;
        dimThumbs($(this).attr("href"));
    });

    $("#gallery-interior area").on("click", function(e) {
        sneaky.sneak();
        capture = true;
        dimThumbs($(this).attr("href"));
    });

    if(urlHash) {
        dimThumbs(urlHash);
    } else {
        $(".thumbs a:first-child img").addClass("dimmed"); // Dim first thumbnail
    }

    capture = false;

});

window.onscroll = function () {
    if (capture) sneaky.scroll(), capture = false;
};

window.onbeforeunload = function () {
    sneaky.sneak();
};

function dimThumbs(active) {
    $(".thumbs a img").removeClass("dimmed");
    $(".thumbs a[href='" + active + "'] img").addClass("dimmed");
}

Another Update

It's become a mission now. This is a slight modification of the second version; I think that considering the only problem was that the image wasn't showing, this will likely address that.
$(document).ready(function() {

    var urlHash = window.location.hash;

    if(urlHash) {
        setTimeout(function() { $("body").scrollTop(0) }, 1); // Scroll to top.
        changeImage(urlHash);
    } else {
        $(".thumbs a:first-child img").addClass("dimmed"); // Dim first thumbnail
    }

    $(".thumbs a").on("click", function(e) {
        changeImage($(this).attr("href"), e);
    });

    $("#gallery-interior area").on("click", function(e) {
        changeImage($(this).attr("href"), e);
    });

});

function changeImage(active, e) {
    var e = window.event || e;
    preventNav(active, e);
    $(".thumbs a img").removeClass("dimmed");
    $(".thumbs a[href='" + active + "'] img").addClass("dimmed");
    $("#gallery-interior li").hide(0, function(){
        $("#gallery-interior " + active).show();
    });
}

function preventNav(hash, e) {
    if (e) {
        if (typeof e.preventDefault != 'undefined') {
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
    }
    var node = $(hash);
    node.attr("id", "");
    document.location.hash = hash;
    node.attr("id", hash.replace("#", ""));
}

Second Update

This should operate exactly as you wanted, just replace the script you currently have. It flips between the gallery images, dims the correct thumbnail, prevents page navigation and stops the page from jumping to the element while still changing the document hash. Here's a fiddle to demo http://jsfiddle.net/C2B2M/; it's missing the images, I didn't want to hot-link to your site.
$(document).ready(function() {

    var urlHash = window.location.hash;

    if(urlHash) {
        setTimeout(function() { $("body").scrollTop(0) }, 1); // Scroll to top.
        changeImage(urlHash);
    } else {
        $(".thumbs a:first-child img").addClass("dimmed"); // Dim first thumbnail
    }

    $(".thumbs a").on("click", function(e) {
        changeImage($(this).attr("href"), e);
    });

    $("#gallery-interior area").on("click", function(e) {
        changeImage($(this).attr("href"), e);
    });

});

function changeImage(active, e) {
    preventNav(active, e);
    $(".thumbs a img").removeClass('dimmed'); // Wipe out all dims
    $(".thumbs a[href='" + active + "'] img").addClass("dimmed"); // Dim the current thumbnail
    $("#gallery-interior li").hide(); // Hide all gallery images
    $("#gallery-interior " + active).show(); // Show current image
}

function preventNav(hash, e) {
    if (e) e.preventDefault();
    var node = $(hash);
    node.attr("id", "");
    document.location.hash = hash;
    node.attr("id", hash.replace("#", ""));
}

Update
Here's another attempt and also a fiddle for you to try it out. http://jsfiddle.net/EPsLV/4/
$(function () {
    $("a").on("click", function(e){
        var hash = $(this).attr("href");
        if (hash.match(/^#\w+/g)) {
            e.preventDefault();
            var node = $(hash);
            node.attr("id", "");
            document.location.hash = hash;
            node.attr("id", hash.replace("#", ""));
        }
    });
});

This snippet captures any hash links and removes the id of the destination element long enough to change the page hash and then resumes the event propagation. I think that may be what your gallery is using to change the images, this script shouldn't stop the event itself from bubbling.

Previous
This should work for you
$("div.thumbs a").on("click", function(e){
if ($(this).attr("href").match(/^#/))
e.preventDefault();
});
Comment: Thanks, but it doesn't work This is why I asked for a "...a demonstrably working solution", e.g., in a fiddle, as I have asked this question in two previous instances and none of the suggestions work.
Comment: Do the links for the gallery stop working entirely when this is used? This jQuery specifically targets only the gallery nav links.
Comment: The links continue to work, but the script seemingly has no affect -- the default scroll to top behaviour is unaffected. JQuery installed.
Comment: There, I think that should do exactly what you're needing. It's tested and appears to be working fine.
Comment: Thanks for the detailed reply aecend; as your fiddle script works but still doesn't in my code, I've updated the question, posting a link to the live gallery showing the other js code (courtesy of SO member 'Spanka') that links the gallery to the thumbs. I don't know if interaction between the two is the problem, but whichever script runs first the result is the same.
Comment: Impressive, and exactly what I want -- but it has a problem. Looking at your code, I wondered about the necessity for the 'Hide/Show all gallery images' sub-elements of the function, as this aspect of functionality is controlled by the css. In this vein, the problem is that the main gallery image disappears on page refresh -- not in all browsers certainly, but the code fails in FF3 where the current js doesn't. I know FF3 is a very old browser, but this and IE6 are my baseline for operability and I need js that degrades gracefully when unsupported not code that breaks basic page functionality.
Comment: Can this show/hide functionality be excised from your solution as it's not clear why it's necessary (i.e., css-based) and I need code that is safe cross-browser?

best,
D
Comment: You say that your code "...flips between the gallery images", and this appears to be what the function below does:

function changeImage(active, e) {
    preventNav(active, e);
    ...
    $("#gallery-interior li").hide(); // Hide all gallery images
    $("#gallery-interior " + active).show(); // Show current image
}

Why was this aspect implemented, as it is very much not what was wanted ("...I am not looking to change my html / css navigation for javascript / jquery -- I wish navigation to remain operative for those who use Noscript")?
Comment: This does not remove the HTML/CSS navigation. In the case that a user is not using JavaScript, it operates exactly as it did before. The only way to prevent the page jumping on a link click is by using JavaScript. The script I provided switches the images and title in the gallery without changing pages, but it still updates the document hash. If the user refreshes the page, the gallery returns to the image last viewed by reading the document hash. No links other than ones related to the gallery are affected at all. I read the comments in your code and implemented fixes for each of the problems
Comment: Try the JavaScript out on the test page that you posted. If it still doesn't operate as you've asked, I'd be glad to make another attempt with further information as to what is missing.
Comment: One more thing, I made no changes at all to the way the gallery operates when no script is present; the only changes to HTML I made were fixes to tags that hadn't been closed properly. This only extends functionality when the script is being used.
Comment: I just noticed you're previous comments, not sure how I missed them. Give me a minute, I'll see what I can do.
Comment: Sorry about that, I believe the problem is fixed now.
Comment: Afraid not aecend; whilst the blank image in FF3 is rectified, it is at the expense of broken functionality in the rest of the js -- the page jump has returned and the opacity class is no longer functional, i.e., the thumbs no longer change state in tandem with the navigation... This is the case in all three browsers tried (IE, FF, QupZ)
Comment: Another possibility is applying the scroll-sneak code (http://mrcoles.com/blog/scroll-sneak-maintain-position-between-page-loads/), perhaps; it is functional on a similar unordered list on the developer's demo site.
Comment: Would you mind describing in a comment exactly what is happening when you click a thumbnail and refresh the page? From what you're saying, it sounds like the page is continuing to navigate despite the e.preventDefault
Comment: Sorry, I have no experience with console-logging, and my brief inquiries just now show that it's non-trivial for the non-js adept. Clicking a thumb activates the opacity and jumps the page to the top. Clicking a nav link doesn't activate the thumb opacity and also jumps the page to the top. Incidentally, the "problems" identified in my js-code comments are those that the code addresses -- that code works faultlessly across browsers and only wants for the scroll-sneak code at the end to be successfully implemeted.
Comment: Ok, thanks for your efforts aecend -- unfortunately, this doesn't change anything from the previous iteration: the page-jump is still there and the gallery-thumb opacity link remains broken. You say that "...this isn't a scrolling issue", but your 'Second Update' worked fine but for losing the gallery images. Still, unless you'd like to take a shot at making the scroll-sneak function at the end of my js work, I guess we'd better leave it there. Thanks again.
Comment: The issue was the return false I added at the end of the changeImage function. It was never setting the click handlers on the images. I also moved the code for showing the correct image into the hide function's callback. That should prevent the show from being called while the hide is still happening.
Comment: And what a mission -- now working. Thank you for your determination aecend! If you would would like to apply this rather formidable js skill-set to the 'scroll sneak' problem in a simpler code scenario, please see my other open and unanswered question at http://stackoverflow.com/questions/23723615/making-scroll-sneak-work. cheers!
Comment: There's the scroll sneak method. I finally just downloaded FF3 and ensured that it was working properly. Hope it works for you :)
Comment: Thanks aecend, please drop your solution into the SO page I linked to to be accepted as the answer for that question. Whilst it is a bit jerky, as you say (where the scroll-sneak demo is not), the 'scope' of your solution is applied to every element on the page where scroll-sneak is able to be applied as an event handler to specific tags and elements. Also, your js has functions for elements (thumbs, gallery-interior) that don't appear on these other pages, and what I was after was a sneak implementation that could be applied to the TH links (see specific question). In any event, I thank you!


Login shared between subdomains

Question: If I should allow users to log in using the same username/password, what should I consider when choosing between the following solutions?

Install, and use Bakery Single Sign-On System on the main site, and all the subdomains.
Share the database table containing the user data.
Answer: Bakery decouples the multisites — if you're sharing a table, you must use exactly the same Drupal version on all sites in the multisite configuration, and update them in lockstep.  With Bakery, the Master and Slaves can be running different Drupal versions.  Additionally, any modules that modify the users table on the Master site would need to be applied to the Slave sites with corresponding settings.
Bakery improves scalability — user accounts are not created on slave sites until they are needed, conserving server computational and data storage resources.
Bakery synchronizes sessions — for example, if the user logs out of one Bakery site, the user will be logged out of all Bakery sites in that group.  (To achieve equivalent behavior with shared tables, you'd also need to share the sessions table, which would further complicate maintenance.)
Comment: Also, sharing the DB tables for users is not recommended, and isn't supported by Drupal for upgrades.
Answer: If your only concern is sharing username and password you might want to consider OpenID, especially since support is in Drupal core.
If that doesn't seem like something your users could manage then I'd consider the Janrain module it would allow your users to sign in with a whole host of accounts they probably already have, like Facebook, Twitter and Google.
It's worth pointing out that this is the method used by StackExchange.

Login shared between subdomains


Easiest way to restart MongoDB

Question: What's the easiest and safest(low data loss, no file locking issues) way to restart mongodb on a production system?
Comment: "Low data loss" as being acceptable?
Comment: On a write heavy app, losing less writes while restarting I meant - not about letting the existing data go. But thanks a lot.
Answer: You haven't mentioned, but I'll assume you are running in a replica set and are mainly concerned about shutting down a primary.  To do that in the safest way, first step it down from Primary:
http://www.mongodb.org/display/DOCS/Forcing+a+Member+to+be+Primary
Then you can just follow the regular shutdown process, depending on your preference:
Starting And Stopping MongoDB
Or, if you have installed it from a package, just use the init/upstart script to shut it down.
If you are not running in a replica set, then you should - the fire & forget nature of writes from apps (by default, but manageable if you wish) means that if your apps could just keep sending data into the abyss until your TCP connection errors out - that's lost data but it has nothing to do with how you shut down the DB.

Easiest way to restart MongoDB