Why does vocal harmony 3rd interval up sound better than 3rd interval down?

Question: For a given chord, the chord tones are composed via going 3rd, like a C Major is a {Major 3rd, Minor 3rd} or a C Minor is {Minor 3rd, Major 3rd}. The 7th, 9th, 11th, and etc... are also created via stacking 3rds.
It seems to me that going with 3rds, up or down, can't go wrong.
When I tried to write a harmony line for a vocal melodic line, I noticed that if I go 3rd intervals up, the melody remains intact. It is recognizable to most people. It just becomes fatter and warmer in tone.
However, if I go 3rd intervals down, the melody becomes different. It just doesn't sound like the original melody anymore.
Here's a concrete example, this is Ode to Joy in C (not sure if it is 100% correct, just did it from memory)

The melody is recognizable, it didn't change the quality of the original song. However when I do the opposite, instead of harmonizing E with G, I harmonized it with C (3rd interval down), the quality changed! It sounded like the harmony hijacked the melody.
Here's my problem. I have a female singer who sings the melody. I want to add a male voice to it to thicken the tone. The male cannot reach 3rd interval above the female. What should the male part do to support the melody? Go 3rd interval up and then down an octave?
Thank you
Comment: Going to the 6th below is pretty common, indeed.
Comment: When I tried singing the "3rd up" melody alone, I got a bizarre feeling from it, as if it *was* half unrecognizable and I was trying to sing something in the Phrygian mode instead of a major key-like mode.
Answer: 'Ode To Joy' SORT of works with 3rds above, though a maj7 chord on the third note isn't quite what Beethoven intended!  The more usual harmonisation starts off with 3rds below, though this soon needs to be modified so as not to mangle the intended harmony.

That's the trouble with trying to stick to either 3rds above or below.   It works for a bit, then you have to switch to the other one, or do something else completely.
I expect you listened (with a sigh of relief) to this tune being sung today  - though Lady GaGa took it in 4/4 with a few extra beats thrown in now and again.  Neither constant 3rds over or under are going to be much use, you really need to hit notes that fits the chord, on the main beats at least.
Comment: The "Star-Spangled Banner" begins with 5–3–1, no?
Comment: True.  I don't know it that well :-)
Answer: In short: because good melodies try to implicate a harmonic progression even when sung or played without any accompaniment, they are bound to contain chord root notes in critical points in time. Since chords are built from thirds above roots, you have to place your harmony notes above the melody, in order to produce the chordal harmony implied by the melody in those critical places.

No static interval is guaranteed to always support the harmony appropriately. But I agree that on average, in actual songs, a third above or sixth below the melody tends to work more often than a constant third below or sixth above.
I don't have any statistical evidence, but based on my own experience, the problem with third-below harmony is that the melodies of songs tend to use notes which, if harmonized with a third below, will produce a harmony which does not support the melody's intent at that point. This is because of how melodies tend to be written. Many good melodies work stand-alone, so that the original intended harmony gets across even without any supporting harmony notes.
Since Western chordal harmony is thought to be built from thirds - even if voiced in different octaves - an interval's being a third cannot be the problem in itself. Thirds are not the problem. Harmony is full of thirds. But which thirds do you select - if you select the wrong thirds, you get the wrong harmony.
Therefore the only remaining variable are the melody notes, and where they tend to be in actual songs. At least the tonic note seems to be used quite a lot in actual melodies, particularly in the ends of lines/parts, and there the song attempts to get a "home" feeling. If you harmonize the tonic note with a third below, the result will not be the tonic chord. The melody desperately tries to get home, but your vocal harmony spoils the attempt.
For example, if the song is in A minor and the song wants to end on a tonic chord, a third below - assuming A natural minor scale - will produce an F - A interval. This produces a sensation of NOT being home and NOT being at rest. Many songs want to end! If you want to create perpetual motion music, where all attempts to end are voided, then by all means, harmonize with a third below.
Comment: Another way of looking at things would be to observe that for most melody notes, either the note a third below or the note a fourth below will usually fit the underlying harmony, but in most cases where one works, the other won't (sometimes both may work, e.g. in C major, if an F melody note sits atop a Dm7, the chord will contain the notes a third and a fourth below the melody).
Answer: We tend to hear the lower note as the more stable tone. So, all things being equal, it would be perceived as the root -- or at least the more important note -- of the corresponding chord. Singing a third above, then, suggests a major or minor chord based on the melody note. Whereas singing a third below would make the harmony sound like the defining pitch.
A melody note of C with an E above it will suggest, say, C major. Singing a third below would tend to suggest A minor.
This is, obviously, a vast oversimplification, but in broad terms, that's why harmony in thirds works better above the melody than below.
Comment: I don't think the lower note being _lower_ is really the relevant thing here.
Comment: The argument about harmony is right, but about the relative pitch – no. Lower second voice often sounds great. A very typical example is female lead singer with a background male singer.
Comment: @mofury Lower by a sixth is the same pitch as up a third, so it's a better bet. Ultimately though, you can't generally harmonize with the exact same interval throughout. As a starting point though, a sixth below is fine.
Comment: Thanks for the answer and other comments. I still have the dilemma of how to harmonize if I have to go low (lower in pitch). What would be a good strategy for lower second voice? 6th down?
Comment: @user1079505 Lower isn't a problem, but lower by a third can be.
Comment: Upper third can be a problem for the very same reason: not following the harmony.
Comment: @Aaron I don't agree with the "lower = more important" implication. For the kind of vocal harmonies the OP asks about, there's practically always a much lower bass note. And a sixth below is fine and that's much lower than a third below, and therefore according to this theory it should be even more "important?" I say, bad theory.
Comment: @piiperiReinstateMonica Agreed. I'm only writing in the context of the two vocal parts, not the entire ensemble.
Answer: It seems to me that an easy and fundamental point is being (partially) missed until now: the relation of the degrees of the melody and of the harmonization in the existing underlying harmony.
When the melody plays a note of the harmony, with a third above the harmonization would lead to the seventh or ninth of the chord at most, all notes that are considered part of a chord extension. It wouldn't change the harmony that much (might be a bit off style, but that's it), and it probably will do exactly what the harmony is, by playing the third or fifth.
With the third below, it's much more possible that the harmony becomes destabilized: the tonic is a very common note in the melody, and the result is to have a third below, which is not a standard note in the harmony.
That's why playing the third below won't work well with your example, especially if the singers are accompanied: while for the most part it's ok (the melody starts on the third, the second voice will sing the tonic), when the melody goes to the tonic, the harmony of the Ode is generally again in the tonic harmony (in the symphony it's not always like that, but that's another story), but your male singer would sing a note that is completely off with that chord.
This will be bad at the end of the first 4 bars, and awful on the end of the phrase at the eight bar: A is definitely not in the C major chord (not in the time of Beethoven, at least).
Third harmonization is easy and intuitive, but must be used with care, no matter the direction. Usually, going a sixth below is the easiest trick when things don't sound very well (harmonically is almost the same as the third above), but choosing the right note might dramatically change the result, even if the note is in the chord (and even in the triad).
Depending on the chord, its role and the context, you might prefer a fourth, fifth or sixth above (all three common when the melody plays the fifth of the chord, but not only), or even the unison or octave (usually very powerful and effective for high pitched and long notes at the end of a section or the piece). Second and seventh intervals are more uncommon and often used as small temporary variations.
Generally speaking, if you have a note of the chord in the melody, go with another one in the same chord for the other voice and you'll be probably fine; besides that, use your ears, experiment to understand the differences and then start taking harmony lessons, which will explain all this much better ;-)
Comment: The usual way is to have a tonal line, write a third below except on the tonic, where you skip to the fourth below. That sounds far better to me than parallel thirds above (which hits the leading tone for not much reason). Beyond that you might as well actually write counterpoint.
Answer: What you have to say about harmonizing above the melody sounding better than below is basically your opinion, which is fine, but can't be subjectively answered. Music is art and we make our own esthetic choices when composing or arranging. Also, the fact is that good harmonization is not quite as simple as a 3rd up or down. Sometimes you have to break away and use another interval to make something sound good AND work with the harmony. Your "Ode to Joy" example would be considered objectionable by some since the melody is clearly on top in the symphony. The other issue is genre. In pop music it is more common to harmonize above the melody than below it so people with a pop sensibility will naturally prefer the upper harmony.
As for your musical situation, harmonized melodies need to be done on a case to case basis. Up a 3rd and down an octave is actually down a 6th, which might be a good starting point but many good harmony lines sometimes are a bit independent. They change intervals and weave to and away from the melody. Check out "If I Fell" by the Beatles, it's a great example of this.
Comment: You have a very good point. I forgot about the context. Different type of listeners would form different opinions about what's "good". Do classical musicians and pop/rock musicians harmonize with big difference in approaches?
Comment: I would say there are a lot of commonalities because they're both largely based on tonal harmony but there are things that are done in rock/pop that are not typical to more traditional classical, such as parallel motion in 4ths and 5ths. Also your example of harmonizing a 3rd above is definitely much more common in pop/rock.
Answer: For starters, singing a note a third above, for every note sung is not going to work in every, or many, songs.Those with the same tonic chord for several bars will allow it to sound o.k., but simply following the lead line in thirds, fourths, fifths or any 'parallel' interval is doomed to sound bad at some point. Sorry!
Singing underneath has worked for ever, but for reasons aired in the existing answers, it isn't recommended in thirds. Sixths below works as much as thirds above - it's the same note, an octave lower, so the same caveats as above apply.
Eventually, you'll be able to harmonise on the fly, but for the time being, a good move is to sing the song one word at a time, whilst playing the chords on guitar, or keys, and listen to which notes fit best. Then stick to them. Some will be a 6th under, some a 5th, or a 4th. There may even be some where a 3rd under actually does sound good !!
Then there's the point where the song might modulate. in key C, notes D and F sound good together - not always, but frequently. If the underlying harmony is a D major chord, moving usually to G, then that F will sound awful, not awesome. Sing F♯ though, and all will be well. Still a 3rd above/6th below, but fitting with the chord at that moment.
Answer: A thing that I found only in Aaron's post touched on the original question: If the melody is in C Major, going a 3rd up or a 6th down is like adding a melody in Phrygian scale, going a 3rd down is like adding a melody in Minor scale. Klezmer for example is based on the Phrygian dominant scale.


R: Problem with runif: generated number repeats (more often than expected) after less than 100 000 steps

Question: After executing the code
RNGkind(kind="Mersenne-Twister")  # the default anyway
set.seed(123)
n = 10^5
x = runif(n)
print(x[22662] == x[97974])

TRUE is output!
If I use, e.g., RNGkind(kind="Knuth-TAOCP-2002") similarly happens: I get "only" 99 995 different values in x. Given the periods of both random generators, the results seem highly unlikely.
Am I doing something wrong? I need to generate at least one million random numbers.
I am using Windows 8.1 with R version 3.6.2; Platform: x86_64-w64-mingw32/x64 (64-bit) and RStudio 1.2.5033.

Additional findings:

Having a bag with $n$ different balls, we choose a ball $m$ times and put it back every time. The probability $p_{n, m}$ that all chosen balls are different is equal to ${n\choose m} / (n^m m!)$.
R documentation points to a link where the implementation of Mersenne-Twister for 64-bit machines is available: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html

The uniform sampling from $[0, 1]$ interval is obtained via choosing a random 64-bit integer first, so I computed the above probabilities for the 64-bit and (when $p_{2^{64}, 10^5}$ turned out to be rather low) 32-bit case:
$$
p_{2^{64}, 10^5}\doteq 0.9999999999972... \qquad p_{2^{32}, 10^5} \doteq 0.3121...
$$
Then, I tried 1000 random seeds and compute the proportion of the cases when all generated numbers are different: 0.303.
So, currently, I assume that for some reason, 32-bit integers are actually used.
Comment: Asking for uniqueness of the values would imply non-independence, thus non-randomness.
Comment: @Michael Sure. However, the probability of this happening is rather low, if I understand everything correctly. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html gives the implementation of the default method and it seems that 64-bit integers are used. Then, I went to compute the probability of choosing $m$ different examples out of $n$ options ($n = 2^{64}$, $m = 10^5$): ${n \choose m} / (n^m \cdot m!)$. I used wolfram alpha and the result is quite high: 0.9999999997289...
Comment: Very interesting findings, thanks for digging into it. Btw I was the first with a +1 for this question.
Comment: Somebody showed why this is happening, R uses 32-bit number https://arxiv.org/abs/2003.08009. Also https://twitter.com/johnmyleswhite/status/1252387405954289665?s=20
Comment: this question surprised me a lot and i cannot find the reason why!!!
Comment: Could you include what you intend to use the pseudorandom numbers for? This need not be a problem depending on the application.
Comment: @FransRodenburg I wanted to test some other code and the case where the numbers repeat is trickier, so it seemed reasonable (though not necessary in theory) to start with the case where the numbers do not repeat.
Answer: The documentation of R on random number generation has a few sentences at its end, that confirm your expectation of 32-bit integers being used and might explain what you are observing:

Do not rely on randomness of low-order bits from RNGs. Most of the supplied uniform generators return 32-bit integer values that are converted to doubles, so they take at most 2^32 distinct values and long runs will return duplicated values (Wichmann-Hill is the exception, and all give at least 30 varying bits.)

So the implementation in R seems to be different to what is explained on the website of the authors of the Mersenne Twister.
Possibly combining this with the Birthday paradox, you would expect duplicates with only 2^16 numbers at a probability of 0.5, and 10^5 > 2^16.
Trying the Wichmann-Hill algorithm as suggested in the documentation:
RNGkind(kind="Wichmann-Hill")
set.seed(123)
n = 10^8
x = runif(n)
length(unique(x))
# 1e8

Note that the original Wichmann-Hill random number generator has the property that its next number can be predicted by its previous, and therefore does not meet non-predictability requirements of a valid PRNG. See this document by Dutang and Wuertz, 2009 (section 3)
Comment: Minor nit:  I might replace, in your last paragraph, "...output tobe truly random numbers" with " ... output to meet non-predictability requirements of a valid PRNG..."
Answer: Just to emphasise the arithmetic of the $2^{32}$ point in terms of the number of potential distinct values: if you sample $10^5$ times from $2^{32}$ values with replacement, you would expect an average of $2^{32}\left(1-\left(1-\frac{1}{2^{32}}\right)^{10^5}\right) \approx 10^5 - 1.1634$ distinct values, noting that $\frac{(10^5)^2}{2 \times 2^{32}} \approx 1.1642$ is close to this deficit
So you would expect many earlier examples.  There are two pairs with set.seed(1):
n = 10^5
set.seed(1)
x = runif(n)
x[21101] == x[56190]
x[33322] == x[50637]

If you do something similar to the first $2000$ seeds in R for the default runif you get an average of $10^5 - 1.169$ unique values, which is close to the calculated expectation. Only $30.8\%$ of these seed produce no duplicates from the sample of $10^5$
Sample $10^6$ times and you would expect the issue to be about a hundred times worse and indeed average number of unique values for the first $2000$ seeds is $10^6 - 116.602$ and none of these seeds failed to produce duplicates
There is another way of reducing the likelihood of overlaps while still having a uniform distribution: try pnorm(rnorm(n))
  set.seed(123)
  n = 10^8
  x = runif(n)
  length(unique(x))
  # 98845390
  y = pnorm(rnorm(n))
  length(unique(y))
  # 100000000

Comment: Is `rnorm` using 64bit variables? While that is an ingenious solution, it is a bit strange workaround. There should be a simple `runif` call doing the same. Maybe we should make `runif` able to do the same. (In the other answer it is mentioned that 'most algorithms do this' so maybe it should be stated more explicitly *which* algorithms do this).
Comment: @SextusEmpiricus something slightly peculiar is going on with that alternative: see `n=100; set.seed(123); x=runif(2*n); x=x[2*(1:n)-1]; set.seed(123); y=pnorm(rnorm(n)); summary(x-y)` and the differences are tiny but typically bigger than $2^{-32}$
Comment: @Henry you sure you aren't just running into  floating-point precision errors?  In addition, the `rnorm` function is not as simple as your  "normifier" there.
Comment: @CarlWitthoft `rnorm` is not exactly `qnorm(runif)` but it is very close using the default methods: try `set.seed(2020); a=rnorm(5); set.seed(2020); b=qnorm(runif(10))[c(1,3,5,7,9)]; cbind(a,b)`  to see what I mean
Answer: Even though it is counter intuitive, there are good reasons that explain this phenomenon, essentially because a computer uses finite precision.
A preprint has just been posted (March 2020) on ArXiv (as already mentioned in the discussion, by the way) and treats this question thoroughly. It has been written by an experienced researcher in computational statistics (not me nor a friend of mine) and uses R. All the codes are reproducible and you can easily check the codes and the claims by yourself. Just to cite a few lines (first lines of the Conclusion) of the conclusion that seem to answer your question:

Rather unintuitively (but, as it turns out, not unexpectedly), generating random numbers can lead to ties. For generating $n$ random numbers on a $k$-bit architecture, we showed that the expected number of ties is $n-2^{k}(1-(1-2^{-k})^{n})$. Furthermore, we derived a numerically robust formula to compute this number. For a 32-bit architecture as is still used in random number generators (be it for historical reasons, reproducibility or due to run time), the expected number of ties when generating one million random numbers is 116.

The cited version is the one posted on 18th March 2020.
https://arxiv.org/abs/2003.08009
Answer: There are two problems here.  The first has been well-covered in the other answers, to wit: why do duplicates show up for certain configurations of the input arguments.
The other is very important: There is a big difference between "random with replacement" and " random permutation of a known set. "   Mathematically,  it's completely valid for random integer sequence to contain, e.g.,  6,6,6,6,6 .  Most PRNGs fail to do a complete "replacement" in their algorithm, so what we end up with is much closer to (but not exactly, as the example in the posted question  shows) a random permutation of the set of values.  In fact, since most PRNGs generate the next value based on the current (and possible a few previous) value, they are almost Markov processes.  We call them "random" because we agree that an outside observer cannot determine the generator algorithm, so the next number to show up is unpredictable to that observer.
Consider, then,  the difference between  runif  and  sample , where the latter has an argument explicitly directing whether to select with or without replacement.


How can I quickly change output of channel strip in Logic Pro X

Question: I'm wondering: how can I change an output of a track without deleting it (when you create a track in Logic, you can choose output).
Example:
I have guitar on Output 1+2 and I want to change it to Output 3+4 how can I do it through mixer?
P.S: macOS 10.12.4 Sierra, Logic Pro X 10.3.1.
Answer: You might find it easier to change the output using the Channel Strip in the Inspector, rather than in the mixer, as it has a less restricted view. In the picture below you can see the Inspector window, which is between the Library window and the main tracks window. This should open automatically; if you can't see this, press "I".

To change the Output of your Channel Strip (in the picture above it is "Inst 1"), click and hold or right-click where it says "Stereo Out". You can then select "Output 3-4" as in the picture below:

Just one thing to be aware of: Logic will only give you the option of selecting Output 3-4 if the device it is routed to is connected to your computer (wirelessly or with a lead). So, if Output 3-4 is routed by the OSX Aggregate Device to a bluetooth speaker, for instance, Logic will not show Output 3-4 if the bluetooth speaker is turned off, or not connected to your computer.
Comment: Just one small thing to add - you might not be able to see the "St Out" output button in the Mixer window unless you scroll up. That's why I suggest using the Inspector window instead. If you want to see a much bigger, easier to use separate Mixer window, press Cmd-2.


Quantum physics and principle of non-contradiction

Question: We all know that mathematics is based on axioms in the science of logic. These axioms we proceed through to prove the validity or falsehood of any statement. One of the most important of these axioms is the principle of non-contradiction, which is to assume that something false is true , then we reach a contradiction, so we conclude that it is wrong. Many of those who introduce popular science and some physicists say that quantum physics allow the contradiction to occur, for example in the so-called Schrödinger's cat,As they say the cat is alive and dead together at the same time which oppose the law of non-contradiction. And alot of similar examples. Also when they talk about a superposition Which is the sum of two vectors in a Hilbert space they also say the electron spin up and spin down at the same time and in the same sense as an interpretation for quantum superposition , so how true are these allegations? and Can any experiment contradict the laws of mathematical logic?
Comment: There is no contradiction. The system is either in the state $| \text{cat alive}\rangle$, the state $| \text{cat dead}\rangle$ or a superposed state $\alpha | \text{cat alive}\rangle + \beta | \text{cat dead}\rangle$. But it's not in those states at the same time. The problem with Schrödinger's cat is that we do not observe the superposed states. It's not a problem of logical contradictions.
Comment: There are attempts to manage contradictions; see e.g. [Paraconsistent Logic](https://plato.stanford.edu/entries/logic-paraconsistent/), [Dialetheism](https://plato.stanford.edu/entries/dialetheism/), [Quantum Logic](https://plato.stanford.edu/entries/qt-quantlog/).
Comment: *quantum physics allow the contradiction to occur* -- The use of "paradox" in reference to Schrödinger's cat or quantum superposition is not a paradox in quantum physics itself, but rather a paradox between quantum physics and classical (non-quantum) physics, so (at least) one of these must be incorrect, and since quantum physics reduces to classical physics when Planck's constant approaches zero, classical physics is more suspect, although of course classical physics is still "correct in non-quantum domains" like my walking from one room to another room doesn't affect the Moon's orbit.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: @MauroALLEGRANZA ok i will do it
Comment: To be fair, [QL](https://plato.stanford.edu/entries/qt-quantlog/#InteQuanLogi) does not reject the NC principle. Maybe we have to consider [Quantum Computing](https://plato.stanford.edu/entries/qt-quantcomp/): if a quantum computer perform computations, we can assume that we have no contradictions...
Comment: @MauroALLEGRANZA I tried the tags you gave me, but it didn't accept, I don't know why
Comment: @DaveL.Renfro Excuse me, just to clarify. Do you mean that the contradiction occurs if we try to explain quantum physics by the laws of classical physics, and not that the contradiction is in quantum mechanics itself?
Comment: To be more specific: we do not observe them for cats. We do observe them for atoms, molecules, subatomic particles, etc...
Comment: @DaveL.Renfro well that's good , could you give me an example of superposition for atomic molecule i mean if we talking about spining of electrons it possible to spin up and spin down when we say electron is in superposition of spining up and down a|up>+b|down >can we observe or is detect this superposition or it's just a mathmatical structure to descripe the electron state before we making messurments
Comment: @DaveL.Renfro:  Your walking from one room to another affect's the Moon's orbit in classical physics.  The effect is too small to measure.  see [here](https://www.newscientist.com/article/mg21829184-700-earths-tides-are-shoving-the-moon-away-faster).
Comment: @John Doe: *Your walking from one room to another affect's the Moon's orbit in classical physics. The effect is too small to measure.* -- Of course it affect's the Moon's orbit. The point I was making is that NOT taking into account quantum mechanics in (most) classical physical settings, while technically not correct according to our best current understanding, is like NOT taking into account things like my walking from one room to another (or fleas jumping around on a dog's back) when calculating aspects of the Moon's orbit (also technically not correct according to our best current ...).
Answer: Schrodinger's paradox is resolved by the fact that the cat exists in a superposition of states which contradicts determinism. We cannot determine whether or not the cat is alive until we observe the cat. This is not the same as a mathematical inconsistency which would allow us to prove that the cat is alive and to prove that the cat is dead.
You asked "Can any experiment contradict the laws of mathematical logic?". The answer is no. What can be determined by an experiment is whether or not a mathematical model is a valid description of a physical phenomenon.
Suppose we lived in a universe where we could prove, experimentally, that straight lines don't exist. Every theorem of Euclidean geometry would still be true. What may no longer be true is that Euclidean geometry is a good model for physical space.
Comment: +1 Good answer. And consider Hilary Putnam's [Is Logic Empirical? (1968)](https://en.wikipedia.org/wiki/Is_Logic_Empirical%3F): maybe also logic is "empirically determined" and our progress in the understanding of reality (in a broad sense) will need the adoption of a non-classical logic (exactly as the case of non-euclidean geometries).
Comment: @Mauro ALLEGRANZA: Regarding Putnam's article, I suppose I should mention some writings by John Stuart Mill and Augustus De Morgan from the middle 1800s, which I discuss in my answer to [How do I convince someone that $1+1=2$ may not necessarily be true?](https://math.stackexchange.com/a/246724/13130). (You've probably seen this before, as I've cited it often in Stack Exchange comments, but perhaps others here who would be interested haven't seen it.)
Comment: @John Douma I didn't understand the meaning of last sentense well  (suppose we lived in a universe ... )Is mean that logic can't applied in quantum physcis or you mean  if the result of the expermints oppose the mathmatical description then we should find other mathmatical models .
Comment: @MahmoudMrowi That is correct. In fact, some models only do well at certain scales like classical. relativity or classical gravitational theory. There was a mathematician named [George Box](https://en.wikiquote.org/wiki/George_E._P._Box) who once said "all models are wrong but some are useful".
Comment: @John Douma just to be sure ,we can say that the problem is not in logic, but in the interpretation of the mathematical model or the mathematical model of phenomena .Right like that?
Comment: @MahmoudMrowi I am not sure what you are asking. If you are trying to make sense of quantum mechanics you may waste this life doing so. Although we use mathematical models to describe many physical phenomena, mathematical truths are independent of physical reality.
Comment: @JohnDouma ok that's fine
Answer: It is incorrect to assert that Schrödinger's cat or some subatomic particle is in a state $|\phi\rangle$of being $|0\rangle$ and $|1\rangle$ at the same time. Every such cat or particle is in a state that is a linear combination of two distinct vectors: $|0\rangle$ and $|1\rangle$. To say the cat is both fully dead and fully alive is to assert the following two statements:
$1.$ $|\phi\rangle = 1|0\rangle + 0|1\rangle = |0\rangle + |0\rangle = |0\rangle$
$2.$ $|\phi\rangle = 0|0\rangle + 1|1\rangle = |0\rangle + |1\rangle = |1\rangle$
which would lead to the contradiction $|0\rangle = |1\rangle$ by substitution. Hence, at least one of the above statements is false.
When the cat is in a state of superposition, its state is represented as follows
$ |\phi\rangle = \alpha|0\rangle + \beta|1\rangle$
such that $\alpha \neq 0, \beta \neq 0$ and $|\alpha|^2 + |\beta|^2 = 1$. According to the math, the best description of the cat's state is that the cat is not both fully dead and fully alive but partially dead and partially alive, and the extent to which it is either one depends on the corresponding amplitude $\alpha$ or $\beta$. In other words, the state of the cat is some combination of dead and alive. Now, this does not imply the cat is in the process of dieing or recovering. Whatever it means, it's definitely unfamiliar because the cat partially occupies two states we normally consider mutually exclusive. To make the weirdness more apparent, imagine partially eating a hamburger in America while talking to your mom while also partially sipping soup in China while watching a movie... and you're doing all of this at the same time. How can this be?
I don't think anyone truly understands what the math is pointing at. If you're familiar with Plato's allegory of the cave, the math is a shadow on the wall. It happens to be a good description of whatever is actually there (i.e. a model of reality), and it's even good at making predictions, but the math is not the substance. The true forms casting the shadows are out of sight.


Why do we need natural log of Odds in Logistic Regression?

Question: I know what an odds is. It's a ratio of the probability of some event happening to the probability it not happening. So, in the context of classification, the probability that an input feature vector $X$ belongs to class 1 is $p(X)$ then the Odds is:-
$O = \frac{p(X)}{1-p(X)}$
This is what I don't understand. When we have probability, why do we need Odds here at all?
Comment: You may be interested in the concept of [link functions](https://en.wikipedia.org/wiki/Generalized_linear_model#Link_function)
Comment: What you called an odds ratio, is actually an odds. The odds ratio is the ratio of two odds. I edited the question to correct this.
Comment: I don't why it's so hard to understand. What about you just move the log to the other side of the equation?
Comment: I got confused about what I wanted to ask -- but the main thing is I was not able to get intuitive feeling of why the concept of odds is required in the context of logistic regression. This is what I have explained in the answer. Maybe I didn't ask the right question to begin with, but this is what I wanted to understand.
Comment: rephrased the question for the answer I have already specified.
Answer: I think I figured out the answer myself after doing a bit of reading so thought of posting it here. It looks like I got little confused.
So as per my post
$$O = \frac{P(X)}{1-P(X)}.$$
So I forgot to take into account the fact that $P(X)$ itself is the probability given by the logistic function:-
$$P_\beta(X) = \frac{e^{\beta^TX}}{1 + e^{\beta^TX} }.$$
So replacing this in in the equation for $O,$ we get
$$O = \frac{\frac{e^{\beta^TX}}{1 + e^{\beta^TX} }}{1-\frac{e^{\beta^TX}}{1 + e^{\beta^TX} }} = e^{\beta^TX}.$$
So $e^{\beta^TX}$ is nothing but the odds for the input feature vector $X$ to be of a positive class. And with further algebraic manipulation, we can obtain a linear form and the reason for doing this is to be able to interpret the coefficient vector $\beta$ in precise manner. So that algebraic manipulation is basically taking a natural log of the latest form of $O $ ($e^{\beta^TX}$)
i.e.
$$\ln(O) = \ln \left(e^{\beta^TX}\right) =\beta^TX $$
So the expanded form of $\beta^TX$ is:-
$$\ln(O) = \beta_0+\beta_1x_1+\beta_2x_2+\cdots+\beta_nx_n$$
So the real use of this, as I have understood it, is to be able to interpret the coefficients easily while keeping the linear form just like in multiple linear regression. So looking at the latest expanded form of $\ln(O)$ we can say that a unit increase in $x_i$ causes the log of Odds to increase by $\beta_i.$
Comment: Yup. The main reason is to try and obtain a linear combination that is interpretable in a similar way to linear regresion. Not to say different ways can't be useful, but this one is very neat.
Answer: In the equation:
$$
ln (p/1-p)= \beta_0 + \beta_1X
$$
The range of the right hand term is $(-\infty,+\infty)$ while without log the range of the left hand term $(p/1-p)$ is $(0,\infty)$.
Without log, we are using a $(-\infty,+\infty)$ predictor set to map $(0,\infty)$ values, which is not possible. Log transforms the range of $(p/1-p)$ from $(0,\infty)$ to $(-\infty,+\infty)$.
Answer:
Why do we need natural log of Odds in Logistic Regression?

The log of odds is logistic regression by definition. So the question is more like, why do we need logistic regression? For this there are several questions that already deal with this
Difference between logit and probit models
Why sigmoid function instead of anything else?
What is the difference between linear regression and logistic regression?


ldap_add no such object (32) matched dn dc=domain dc=com

Question: When im trying to import users to LDAP using this command:
ldapadd -x -D "cn=Manager,dc=domain,dc=com" -W -f  /etc/openldap/root.ldif

I have this error:
ldap_add no such object (32)
          matched dn dc=domain,dc=com

Let me show you the files:
/etc/openldap/domain.ldif
dn: dc=domain,dc=com
dc: domain
description: LDAP Admin
objectClass: dcObject
objectClass: organizationalUnit
ou: rootobject

dn: ou=People, dc=domain,dc=com
ou: People
description: Users of adminmart
objectClass: organizationalUnit

/etc/openldap/root.ldif
dn: uid=root,ou=People,dc=domain,dc=com
uid: root
cn: Manager
objectClass: account

Someone can help me?
Thanks
Comment: Is your base DN actually dc=domain,dc=com? Check `ldapsearch -hlocalhost -x -sbase | grep '^dn:'` or the configuration on your LDAP server. For OpenLDAP, it'll be the "suffix" line in slapd.conf.
Comment: Also, I wouldn't recommend putting root in LDAP. How will you log on to a machine when it can't reach the LDAP server?
Comment: @IsaacFreeman The command not return anything, and the suffix is "suffix: "dc=domain,dc=com"
Answer: I had the same problem doing the same command:
No such object (32)
matched DN: dc=example,dc=com

I checked the LDIF file and all my OUs from LDAP and I was trying to add an entry to an OU that does not exist.
I solved changing the OU on ldif file for one that exist. And all worked fine.
Comment: This is a good answer. Perhaps including an example on how to add a new OU to LDAP would improve the answer, as I had to go to the Google machine to find an example of adding an OU to LDAP.
Comment: If you want, you can add the information in order to add a new OU and I will approve it.
Comment: This can help: https://unix.stackexchange.com/a/535082/28279
Answer: i had same problem and was pulling my hair out over it, then added new OU to my ldif, like this:
dn: ou=(what your error says that is missing),o=(company name),dc=(company name),dc=country
objectclass: (class type)
objectclass: top
ou: people

just replace info in ()'s matching to yours and it should work!


hide passwords in drupal module settings

Question: we have a local community site for drupal and site is run by volunteer admins. my question is, is there any way I can 'hide' passwords in module settings? some modules ask for user password of the service they integrate. it's not safe to have them in plain text in their settings page.
and I don't want to restrict access to those module settings.
this is a common issue with drupal. you can create the permission using hook_permission in your own module. then in your own module use hook_form_alter, find the form of the module andon those password fields use '#access' => user_access('your_permission'). but I have no idea how.
for example, Bot module has a password field. Mailchimp has API Secret field. etc
Comment: ["You should only ask practical, answerable questions based on actual problems that you face."](http://drupal.stackexchange.com/help/dont-ask) - please provide the name of a module, and tell us how it is not ["Issues found in existing modules"](http://drupal.stackexchange.com/help/on-topic) - if module has a security hole, you should file a bugreport in module's issue queue, not ask here.
Comment: this is a common issue with drupal. you can create the permission using hook_permission in your own module. then in your own module use hook_form_alter, find the form of the module andon those password fields use '#access' => user_access('your_permission'). but I have no idea how to do these stuff, hence asking here
Comment: for example, Bot module has a password field. Mailchimp has API Secret field. etc
Comment: Please edit your question. Data provided in comments may get purged without notice.
Answer: As you've already noted in the question, you can set '#access' => FALSE to any form element to remove it from display.
The correct place for this is in hook_form_alter():
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'relevant_form_id') {
    $form['some_element']['#access'] = FALSE;
  }
}

If you're asking for a way to do this generically, without having to target each element with a specific form ID/element key, then you're out of luck. Those fields are nothing special, just standard text fields, so there's nothing to distinguish them from any other text field.
Bottom line - you need to decide exactly what fields you want to disable, find the appropriate form IDs/element keys, and use the method above to apply the rule one-by-one.
Answer: The settings.php  is a starter of drupal core, maybe you can put your password in another database(temp database) and fetch them in settings.php , but if another admin access settings.php, also can access you temp database.
I think restrict unix users by groups users in seperate groups and by file permission restrict them to access settings.php .
Comment: Will not help. If settings form reads default value from variable, then it will be displayed no matter where the variable's content is loaded from.
Comment: Yes , I know, I think only way to do this job is restrict by user group of server.
Comment: that doesn't help since other admins can still see module passwords. I'm not talking about db pass and other stuff. those can be omitted in gitignore file
Comment: @HadiFarnoud you said  "my question is, is there any way I can 'hide' passwords in module settings?" !!!
Comment: yeah, I meant in /admin/config/[module]
Comment: @HadiFarnoud There no way there.


how to show the my current location in the Google Map?

Question: I want to show my current location in google map. it should be coming dynamically i.e. longitute and latitude should be set dynamically.
Like if now I am in New Delhi , and if I start my android application,my current location should be shown in New Delhi and it should change if I travel to other cities.
Answer: Get the current location
What is the simplest and most robust way to get the user's current location on Android?
and pass that value to google map api.


Does Intermediate value theorem work depending on the domain

Question: Does it work when the domain and codomain are subsets of the reals? For example, any continuous function from a discrete subset of reals that satisfies the least upper bound property? Is this possible? If it breaks down, why?
Comment: Because of trivial examples such as $\Bbb Z\to \Bbb R$, $x\mapsto x$
Answer: No. It is not true that every function from $\mathbb Z$ into $\mathbb R$ satisfies the intermediate value property (note that every function from $\mathbb Z$ into $\mathbb R$ is continuous), in spite of the fact that $\mathbb Z$ is discrete and that it satisfies the least upper bound property.
Comment: all subsets of Z don't satisfy l.u.b?
Comment: Yes they do: a non-emtpy subset of $\mathbb Z$ with an upper bound always has a least upper bound.
Comment: oh right yes, we need that it has an upper bound in the proof anyway
Answer: Let's say that a subset $\Bbb X$ of $\Bbb R$ has the IVT property if for every continuous map $f\colon X\to \Bbb R$ and every $x_1,x_2\in X$, $y\in \Bbb R$ with $f(x_1)<y<f(x_2)$, there exists $\xi\in X$ with $f(\xi)=y$.
Then $X$ has the IVT property iff $X$ is connected.

Assume $X$ has the IVT property. Let $U,V\subseteq \Bbb R$ be open sets such that $X\subseteq U\cup V$ and the sets $X\cap U$ and $X\cap V$ are disjoint. Define  $f\colon X\to\Bbb R$ as $f(x)=\begin{cases}1&x\in U\\0&\text{otherwise}\end{cases}$. Then $f$ is continuous. If there were $x_1,x_2\in X$ with $f(x_1)=0$ and $f(x_2)=1$, then the IVT property would tell us that $f(\xi)=\frac12$ for some $\xi\in X$. As this is absurd, such $x_1,x_2$ cannot exist, i.e., one of $U\cap X$, $Vcap X$ is empty. We conclude that $X$ is connected.
Assume $X$ is connected. Let $f\colon X\to \Bbb R$ be continuous, $x_1,x_2\in X$, $y\in \Bbb R$ with $f(x_1)<y<f(x_2)$. Then the sets $f^{-1}((-\infty,y))$ and $f^{-1}((y,\infty))$ are disjoint and, by continuity of $f$, open subsets of $X$, They are also non.empty (contain $x_1$ and $x_2$, respectively). By connectedness of $X$ they thus cannot cover $X$. Hence there must exist $\xi\in X$ such that $f(\xi)\notin(-\infty,y)\cup(y,\infty)$, i.e., $f(\xi)=y$.

Quite obviously, discrete subsets of $\Bbb R$ (with at least two points) are not connected. Of course you can also see immediately that for any such discrete (or "gappy" in any other way) subset of $\Bbb R$, the continuous map $x\mapsto x$ breaks the Intermediate value prperty.
Comment: Why can we assume that there exist two open sets $U, V$ such that $X\cap U$ and $X\cap V$ are disjoint? thanks in advance.


Sum of a list in Python

Question: I thought sum a list of numbers in Python would answer my question but it didn't.
For context, I am working on Project Euler, Problem 9: https://projecteuler.net/problem=9
I am getting the error
TypeError: unsupported operand type(s) for +: 'int' and 'list'

for the line
while sum(triplesList) <= 1000:

I don't know why sum(listname) isn't working.
Here is all the code:
triplesList = []

a = 0
b = 0

while sum(triplesList) <= 1000:
    a += 1
    b += 1

    triplesList = [[a,b] for i in range(1)]
    triplesList.append( a**2 + b **2)

    if (math.sqrt(triplesList[1])).is_integer():
        triplesList[1] = int(math.sqrt(triplesList[1]))

    if sum(triplesList[0], triplesList[1]) == 1000:
        print triplesList
        print sum(triplesList[0] , triplesList[1])
        print reduce(lambda x, y:  x * y, triplesList[0], triplesList[1])

I appreciate the help!
Comment: `triplesList = [[a,b] for i in range(1)]` makes a `list` of `list`, therefore you cannot sum `triplesList`.
Comment: No it doesn't. I can literally promise that `sum([])` is legal and results in `0`. The `while` condition does fail, but not until the second iteration
Comment: I'm confused as to why I can use the sum as a conditional BEFORE I've made it a list of lists.
Comment: Because you intialized it to `triplesList = []` so it was just a list. It doesn't become a list of lists until you perform the list comprehension that I commented on.
Comment: Sorry.  I meant that I'm confused as to why I CAN'T use the sum as a conditional...for exactly the reason you stated.  The error message comes at the while statement.
Comment: Because what would that even mean? For example what is the sum of `[[1,2,3],[1,2,3]]`?
Comment: Pretty sure we're not understanding each other.  The error message happens when the list is still empty. It happens BEFORE triplesList becomes a list of lists.
Answer: sum() only accepts a iterable objects of numbers, not a list of lists.
triplesList is a list of lists when you do this to it:
triplesList = [[a,b] for i in range(1)]

Thus, sum() whines that it doesn't know how to add lists of lists, just lists of integers
I believe that line could instead read:
triplesList = [a, b]

Comment: [sum](https://docs.python.org/2/library/functions.html#sum) can be used on anything iterable which contains number types valid for the '+' operator
Answer: Change this line
triplesList = [[a,b] for i in range(1)]

To
triplesList = [a, b, a**2 + b**2]

And remove the
triplesList.append( a**2 + b **2)

This will produce a 1D list of the form [a,b,c] which is what I get the feeling you are after from your question.
The former will produce a list of the form
[[a,b], c]

Which you cannot sum

Sum of a list in Python


yii2 gridview: how to config css for filterModel

Question: I want to config form text for 'filterModel'. Here's my code.
<code>GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
])
</code>
Comment: Just a friendly tip, you may want to read over this page: [The How-To-Ask Guide](https://stackoverflow.com/help/how-to-ask) so you can always be sure that your questions are easily answerable and as clear as possible. Be sure to include any efforts you've made to fix the problem you're having, and what happened when you attempted those fixes. Also don't forget to your show code and any error messages!
Comment: What do you mean by "config"?
Answer: Here is some options of GridzView for filterModel.
GridView api
<code>/**
 * @var array the HTML attributes for the filter row element.
 * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
 */
public $filterRowOptions = ['class' => 'filters'];
/**
 * @var array the options for rendering the filter error summary.
 * Please refer to [[Html::errorSummary()]] for more details about how to specify the options.
 * @see renderErrors()
 */
public $filterErrorSummaryOptions = ['class' => 'error-summary'];
/**
 * @var array the options for rendering every filter error message.
 * This is mainly used by [[Html::error()]] when rendering an error message next to every filter input field.
 */
public $filterErrorOptions = ['class' => 'help-block'];
</code>


mod_rewrite and Apache questions

Question: We have an interesting situation in relation to some help desk software that we are trying to setup.  This is a web based software application that allows customers and staff to log into it and access tickets and supply updates, etc.  The challenge we are having deals with the two different domains that we use and the mod_rewrite rules to make it all work with our SSL certificate that is only bound to one of the domains.  I will list the use case scenarios below and the challenges that we are having.

If you access http://support.domain1.com/support then it redirects fine to https://support.domain2.com/support
If you access http://support.domain2.com/support then it redirects fine to https://support.domain2.com/support
If you access https://support.domain1.com/support then it throws an error of "server cannot be found"
If you access https://support.domain1.com/support/ after having visited https://support.domain2.com/support then you are presented with a "this connection is untrusted" error about the certificate only being valid for the domain2 domain instead of the domain1 domain name

I have tried just about every mod_rewrite rule that I can think of to help make this work and I have not been able to locate the correct combination.  I was curious if anyone had some ideas on how to make the redirects work correctly.  In the end, we are needing all customers and staff to land at https://support.domain2.com/support regardless of the previous URL combinations that they enter, like listed above.
Thanks in advance for your help with this.
Comment: Can we see your existing rewrite rules?
Answer: If you don't have a certificate for support.domain1.com then no amount of rewrite magic is going to change the errors the users will see when they enter https://support.domain1.com

mod_rewrite and Apache questions


Surprising necessary condition for a "shift-invariant" determinant

Question: Let $A$ be a $4\ x\ 4$ binary matrix and $Z=\pmatrix {s&s&s&s \\ s&s&s&s \\s&s&s&s \\s&s&s&s}$
Then $\det(A+Z)=\det(A)=1\ $ (independent of s, so $\det(A)$ is "shift-invariant") can only
 hold if the number of zeros in $A$ is exact 8.
 This condition is not sufficient because only $72$ out of the $12\ 870$ matrices
 with exactly 8 zeros do the job. I checked this funny and surprising condition
 by brute force. Is there a proof without checking all $65\ 536$ matrices ?
Comment: One example of such a  matrix with "shift-invariant" determinant 1 is $$\pmatrix {1&1&0&1 \\ 1&0&0&0& \\ 0&0&0&1 \\ 1&0&1&1}$$
Comment: How many of the $12,870$ matrices with exactly $8$ zeros have determinant $1$?
Comment: Are you viewing everything over $\Bbb{F}_2$? Talk about binary matrices first left me with that impression, but then I started thinking. $A=I$ and $A'=I+Z$ are both invertible (identity+nilpotent is invertible) and thus have determinants $=1_{\Bbb{F}_2}$. So the claim does not hold ($A=A'+Z$ has 12 zeros, $A'=A+Z$ only four). You are probably calculating the determinant in $\Bbb{Z}$ anyway?
Answer: Some thoughts on your question : denote by $C_1,C_2,C_3,C_4$ the columns of $A$. Let $V$ be the
all-ones column $(1,1,1,1)$, and let $U$ be the matrix of all
whose columns are equal to $V$ (so that $Z=sU$). Then
$\det (A + sU) = $
$$\begin{array}{lcl}
&=& [C_1+sV,C_2+sV,C_3+sV,c_4+sV] \\
&=& [C_1,C_2,C_3,C_4]  +s([V,C_2,C_3,C_4]+[C_1,V,C_3,C_4]+
[C_1,C_2,V,C_4]+[C_1,C_2,C_3,V])
\end{array}\tag{1}
$$
So your "shift-invariance" property $\det(A+sU)=\det(A)$ will hold iff
$$
[V,C_2,C_3,C_4]+[C_1,V,C_3,C_4]+
[C_1,C_2,V,C_4]+[C_1,C_2,C_3,V]=0
$$
Hope this helps.
Comment: Sorry for the edit attempt. I was just trying to work at breaking up the last equality so it doesn't run into the right column of the page.
Comment: @amWhy you're welcome.


MLE for uniform distribution with two parameters

Question: A finite number of random variables $X_1 ... X_n$ have a uniform distribution $[a, b]$ with $b>a$, such that it has the following density:
$$f_X(x) = \frac{1}{b-a}, a\le x \le b$$
find the MLE.
Here's what I have tried:
$L(b,a;x) = \prod_{i=1}^nf(x_i;b, a) = \prod_{i=1}^n\frac{1}{b-a} = \left(\frac{1}{b-a}\right)^n \\
\mathbf{L}(b,a;x) = \log L(b,a;x) = -n\log(b-a)$
Taking the first and second derivative in respect to b, and then with respect to a.
$\frac{\partial\mathbf{L}(b,a;x)}{\partial b} = -\frac{n}{(b-a)} \\
\frac{\partial\mathbf{L}(b,a;x)}{\partial a} = \frac{n}{(b-a)} \\
\frac{\partial^2\mathbf{L}(b,a;x)}{\partial b^2} = \frac{2n}{(b-a)^2} \\
\frac{\partial^2\mathbf{L}(b,a;x)}{\partial a^2} = -\frac{2n}{(b-a)^2} \\
\frac{\partial^2\mathbf{L}(b,a;x)}{\partial ba} = -\frac{2n}{(b-a)^2}$
When I set the first two derivatves to zero to find the turning points, and these are when $b=a$.
To find the local maximum, I plug these into the hessian matrix:
$$H :=\begin{pmatrix} \frac{\partial^2\mathbf{L}(b,a;x)}{\partial b^2}&\frac{\partial^2\mathbf{L}(b,a;x)}{\partial ba} \\ \frac{\partial^2\mathbf{L}(b,a;x)}{\partial ba}&\frac{\partial^2\mathbf{L}(b,a;x)}{\partial a^2} \end{pmatrix} \implies \begin{pmatrix} \frac{2n}{(b-a)^2}&-\frac{2n}{(b-a)^2} \\ -\frac{2n}{(b-a)^2}&-\frac{2n}{(b-a)^2} \end{pmatrix} \\
\\
= -\left(\frac{2n}{(b-a)^2}\right)\left(\frac{2n}{(b-a)^2}\right) -\left(\frac{2n}{(b-a)^2}\right)\left(\frac{2n}{(b-a)^2}\right) =  -\frac{8n^2}{(b-a)^4}$$
Given that $\frac{\partial^2\mathbf{L}(b,a;x)}{\partial b^2}>0$ and $Det(H) < 0$, then our turning point is not a local maximum as the reverse inequality should happen for this to be the case.
However, this cannot be true. The actual question assumes three random variables such that $x_1 = 1.5, x_2 = 4.6, x_3 = 7.2$, and I'm supposed to plug these into the MLE. However, if there is no MLE then I cannot do this. So I have gone wrong somewhere.
Comment: The values corresponding to maximum likelihood do not have to be where the derivative is zero; they could be at the extremes or where the likelihood is discontinuous or where its derivative does not exist
Comment: @Henry my book (Guide to mathematical methods - gilbert) mentions to find the values $x_1 .. x_n$ for which $f'(x) = 0$, however when I check again for those values $x_i$ for which $f''(x_i) < 0$ give a local maxima, if I plugin $b=a$ then I just get zero.
Comment: In your example, the likelihood of $b=a$ is $0$ since you should have $a \le 1.5 < 7.2 \le b$.  But your expression for the likelihood $\left(\frac{1}{b-a}\right)^n$ suggests it should be infinite.  So perhaps your expression is missing something
Comment: @Henry I aimed to produce a general case but did not expect the results to not match what I had in mind. Instead, we would have $\prod_{i=1}^3 \left(\frac{1}{b-a} \right) = \left(\frac{1}{b-a}\right)^3$. Oh! would it be possible that I have to take the cdf first? $F_X(x) = \frac{1}{b-a} \int_a^x dt = \frac{x-a}{b-a}$ otherwise, the product then makes sense. Because we have $\prod_{i=1}^3f(x_i; b, a) = \prod_{i=1}^n\frac{x_i-a}{b-a} = \left(\frac{x-a}{b-a}\right)^n$?
Comment: In this particular example, the key point is that $a \le \min(x_i)$ and $b \ge \max(x_i)$ and so the likelihood of $a,b$ given $\{x_i\}$ is proportional to $\left(\frac{1}{b-a}\right)^n I_{[a \le \min(x_i)]}I_{[b \ge \max(x_i)]}$ using indicator functions.  So the likelihood is no longer a continuous function of $a$ and $b$, with discontinuities at $a = \min(x_i)$ and $b=\max(x_i)$.  And that takes you back to my original comment.
Comment: @Henry Ah thanks for sharing this! it took me a while to remember continuous functions again and the use of your notations. So it's not a continuous function, meaning it does not strictly increase nor decrease. However, what do you mean by "derivative does not exist"? I'm still trying to piece some of your comments, could you perhaps write up an answer compiling the comments as a hint? Also is there a special term for the case $a \le x \le b$ when x is the infimum or supremum?
Comment: In another situation, if the likelihood was for example proportional to $e^{-|b-x|}$ then the maximum likelihood value for $b$ would be when $b=x$, even though the likelihood had no derivative with respect to $b$ there.  This situation is different and the issue is the discontinuities caused by the indicator functions.  Suppose  you saw your example data and you knew $a=0$.  Then you want to maximise $\frac1{b^3} I_{[b \ge 7.2]}$.  It might be worth sketching that for some values of $b$ above and below $7.2$ to see where the maximum is.
Answer: Given a sample $X$, then $(X_{(1)},X_{(n)})$ is the MLE of $(a,b)$ where $X_{(k)}$ are the order statistics. Indeed the likelihood is
$$L((\theta_1,\theta_2),X)=\frac{1}{(\theta_2-\theta_1)^n}\prod_{k\leq n}\mathbf{1}_{[\theta_1,\theta_2]}(X_k)$$
which is maximized by $(X_{(1)},X_{(n)})$. To see this, note that $(\theta_2-\theta_1)^{-n}$ grows as $\theta_2-\theta_1\to 0^+$, but $L$ becomes $0$ as soon as the parameters 'pass' at least one of the observations $X_k$ (due to the product of the indicators).


Pass along field delta value to a rendered entity in an entity reference field

Question: I have a field on a node type that references another node type. On the display side, I am setting it to a view mode to be rendered.
What I want to do is add a zebra stripe class. Every other node needs an extra class on its wrapper. I figure this should be done at the field twig level, but how do you pass in a value when it is rendered?
field--field-related-content.html.twig:
{% for item in items %}
  {{ item.content }}
{% endfor %}

In the node view mode template:

      {% include "@mytheme/svg/general/how-to.html.twig" %}

How-To

{{ label }}

      DESCRIPTION HERE

The node is unaware of where it is, so, whats the best way to pass a class? Is that possible? The field.html.twig file in classy wraps the field with a div, but thats not what I need to do here.
I suppose one way to do it is change the field twig to something like:
{% for item in items %}
  {% set classes = '...' %}

    {{ item.content }}

{% endfor %}

But that feels dirty, and doesn't really make it reusable, not to mention I would have to inject the background image url through a field preprocess instead of just handle it in the node rendering.
Comment: If you want to make the node aware of where it is placed you get more cache variations. For performance it is better to add the index to the field container and target the node and its elements by combining multiple css selectors or apply the zebra with `:nth-child(even/odd)` or a bootstrap class.
Answer: I did something like this in Drupal 7 and did have caching issues as 4k4 mentioned, but I think the cache issues would be easier to avoid in D8. You could do this by creating a new Field Formatter that extends EntityReferenceEntityFormatter.
You should be able to alter just the viewElements() method and add the delta information to the referenced entities. However, this will create an issue with the view mode being cached with your delta info. For example, you may have an entity be the first item the first place it's referenced and the second item the second place it's referenced, but it'll be cached from the first call so your delta alterations won't work how you'd expect. To workaround this issue, you can update the #cache settings for the entities and add a new key for the delta.
I would start by calling parent::viewElements() and then make a pass through that result to make the alterations (adding the delta value and updating the cache settings).
I would still alter the field template for the parent EntityReference field and add the class to a wrapping div rather than on the entity itself. You could create your own template file and add your own theme suggestion to make it more reusable, something like field__zebra, rather than relying on the default theme suggestion you mentioned above, field__my_field_name. I love Display Suite so I would create a Zebra DsFieldTemplate that I could reuse on any field I wanted.
Comment: Great answer. I think caching should work if you add to #cache an additional cache key for the delta. Entities have already one for the view mode, then they would also vary by the delta.


How to normalize to integer values in Vector2 values?

Question: I can't understand my question, too.
but help me.
I want {1.5f , 4.5f} to {1 , 3}
ex) {0.5f , 2.5f} to {1 , 5}
I want to change float to integer value.
Is there a useful function in this situation?
Comment: How does 4.5f turn into 3 and 2.5f into 5? What kind of math are you trying to perform?
Comment: I want to change all values to integer values.
(1.5 * 10 , 4.5 * 10) = (15 , 45)
(15 / 15 , 45 / 15)  = (1 , 3)
Answer: In fact you do not want to normalize, you want to divide by x.
var vec = new Vector2(.5f, 1.5f);
vec /= vec.x;
Debug.Log(vec); // (1.0, 3.0)

Answer: You can multiply all your case with 1/(first case) like:
my_array = [1.5, 4.5, ...]
coef = 1 / my_array[0]
for i in range(1, len(my_array)):
    my_array[i] = my_array[i] * coef

Answer: For your situation here,
You could always set your X to 1, and then your Y value would become Y / X
this would only work when X is a factor of Y however.


Steps for Removing a Site from Windows 2003 Active Directory

Question: What are the steps to delete a site from AD 2003 that no longer exists. A MS knowledge base gave instructions for removing it out of Sites and Services but it still exists in AD under mydomain>>_msdcs>>dc>>sites. Is it a manual delete from both locations, any others?, or is there a process to clean it up everywhere?
Thanks for your help.
Answer: You need to use the adsiedit tool - http://technet.microsoft.com/en-us/library/cc773354(WS.10).aspx
This will help you clean up the objects that are lingering in AD...
Good luck!


Ajax ignoring my default_value

Question: I have a drupal form that contains a select box. Next to the select box is a link that pops a ctools modal up with an inner form that adds a value to the database table that drives the original select box. When someone clicks submit on the modal form, I would like to rebuild the select box on the original form and set the new value to the default. I've had success with adding the new elements to the select box by doing some ajax in the form_submit hook for the modal form, but it seems like Drupal ignores the value in #default_value in my render array. I have the following in my form_submit hook after the database update and after getting the render array from another function:
if(isset($id)) {
   $newdata['data_source']['#default_value'] = $id;
}
$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', drupal_render($newdata));
print ajax_render($commands);
exit();

Again, the select box is getting the new value, and my render array seems fine. I just can't get it to select the new value by default.
Comment: I'm pretty sure default_value is out of the picture by that point, try setting `$form_state['input']['data_source'] = $id;` or `$form_state['values']['data_source'] = $id;`. I've had varying levels of success in the past with something similar
Comment: Thanks for the reply. I thought of that but I would need to modify the $form_state on the original form, while in the hook_submit of the modal form. Is it possible to modify one form's $form_state from a different form on the same page?
Answer: Alright, so this is slightly hackey, but I got this to work. I totally gave up on trying to set a default value in the render array, and instead did the drupal_render and set it to a variable. I then modified the html directly in the variable. The code I originally posted now looks like this:
if(isset($id) && is_numeric($id)) {
  $newrender = drupal_render($newdata);
  $newrender = str_replace('value="'.$id.'"', 'value="'.$id.'"  selected="selected"', $newrender);
}

$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', $newrender);
print ajax_render($commands);
exit();

If anyone on here has a more elegant solution, I'd be happy to know the "correct way" of doing this, but this produces the desired result.

Ajax ignoring my default_value


Suppose $f(x)$ is a total computable function. Use minimlization to show that there is a computable function $g(y)$

Question: Suppose $f(x)$ is a total computable function. Use minimalization to show that there is a computable function $g(y)$ with $dom$ $g = im$ $f$ and $f(g(y))=y$ for all $y \in dom$ $g$
I know this then means that $f(g(y))=y$ for all $y \in im$ $f$ but I don't know where to go from here.
Comment: @BrianM.Scott Haha it autocorrected me :P I meant minimalization but i've also heard it called minimisation
Comment: *Minimization* (US) or *minimisation* (UK) is the usual term. (But I really liked *mineralization*: autocorrection sometimes produces really funny results.)
Answer: $g(y)=\min\{x:f(x)=y\}$ (plus a few more characters because the site doesn't like minimalization of answers)
Comment: I have no idea how you got to this answer, can you explain?
Comment: I'm assuming $g(y)$ is the minimum $x$ such that $f(x)=y$ but I don't get how
Comment: The question was not to prove something about some already given $g$, which might very well not have chosen the minimum $x$ for each $y$, but to show that there exists a computable $g$ satisfying the requirements in the question. So, of the (possibly many) $g$'s that satisfy $f(g(y))=y$ for all $y\in\text{Im}(f)$, I chose the simplest one. It has the advantage that minimization immediately proves that this $g$ is computable.


Problema para atualizar registro do banco com ajax

Question: Boa noite,
Estou tentando atualizar dados do banco via ajax, só que não está funcionando,tenho dois text area, e atualizo ele com update. Antes de tentar sem o ajax, estava funcionando perfeitamente, só agora que não quer pegar mais... não consigo mais identificar o erro, podem me ajudar?
Meu form e ajax:
            <form method="POST" id="formulario_mensagem">

                <input type="text" name="msg_id" id="msg_id" value="<?php echo $row['msg_id'];  ?>">

                <textarea type="text" name="msg_original" id="msg_original" rows="5">"<?php $st=$row['msg_text']; echo
                str_replace('+', '
', $st);?>"</textarea>

                <textarea type="text" name="msg_nova" id="msg_nova" rows="5" placeholder="Digite a Resposta Aqui"></textarea>

                <button type="submit" onclick="inserir_registo()">Reenviar</button>
            </form>

Meu fetch_mensagem.php:
<?php
 include "verifica_sessao.php";
  include "config.php";

      date_default_timezone_set('America/Sao_Paulo');

      $data=date("d/m/Y H:i:s");
      $id = $_POST['msg_id'];
      $texto = $_POST['msg_original'];
      $novo = $_POST['msg_nova'];

//Aqui arrumo o texto e faço o update
      $saida = '';
      $saida .= $id;
      $saida .= '.';
      $saida .= '\n \n';
      $saida .= $texto;
      $saida .= '.';
      $saida .= '\n \n';
      $saida .= $novo;

      $result = $db->prepare("UPDATE mensagens SET msg_text='$saida' WHERE msg_id='$id' AND msg_status=0");
      $result->execute();
       while($row = $result->fetch()){
        if( $result->fetch()){
             echo '1';
                  }
                  else{
                     echo '0';
                     }
                }
?>

Antes estava utilizando o action e pegava normal, só que agora simplesmente parou...quem puder me ajudar agradeço..
Comment: vc alterou algo em seu arquivo fetch_mensagem.php?
Answer: Corrija a sua chamada com ajax assim, teste e me retorna se está ok. Acredito que já vai resolver o seu problema:
Mude o seu botão: <button type="submit" onclick="inserir_registo()">Reenviar</button>
para: <button type="submit" name="enviar" value="enviar" id="enviar">Reenviar</button>
Ao invés de onClick() vamos chamar o ajax no submit do form. Ok?

Eu deixei alert(data); assim vai te retornar o tiver na sua página. Qualquer coisa só me falar.
Comment: Muito obrigado Leandro funcionou perfeitamente!


Rules module not enabling via Drush in drupal 7

Question: this may be a simple one however while downloading Rules through drush and getting the following error.
root@li:/var/www/drupal7/sites/default# drush en rules*

No release history was found for the requested project (i18n_string).[warning]
Module rules_i18n cannot be enabled because it depends on the        [error]
following modules which could not be found: i18n_string

I also tried doing drush dl il8n_rules but to no use.
What is wrong here?
Answer: You'll need the i18n module to install rules_i18n
drush dl i18n
drush en i18n_string
drush en rules*

Alternatively, enable the rules submodules individually, excluding rules_i18n


CSS - What to look for when Margin has no effect

Question: I'm effectively a noob with HTML and CSS, I don't consistently live in this space to retain and progress so feel free to treat me like an idiot.
Very often when I'm styling a page the margins have no effect. For example, in the following snippet:

Title

I introduce the section and talk about the stuff in this area.

I am some XML

  Download XML
  < ... form controls, input etc. ... >

If I try and set a top margin on the Download XML anchor, it has no effect at any size. Why could this be?
Is there a general lesson here about the way this all works that I either keep forgetting or don't quite have a handle on yet.
I have read good-sized CSS books cover-to-cover - I do try - and I've been a netmag subscriber for about 6 years. I know there are lots of quirks and gotchas, I just can't remember them all.
Thanks.
Comment: It's a duplicate of Mr Alien's link, not James Donnelly's. Its not the question, its the reason.
Comment: @James Donnelly: I don't think so.
Comment: Ah, for some reason I saw that anchor as a paragraph instead. Silly me!
Answer: I think in these situations you might be mainly encountering the differences between block-level elements and inline elements.
In HTML, a block level element is used for larger sections of content, and often contains other elements. You use them to lay out everything on your page. Block level elements are, for example, section, div, header.
Inline elements are smaller tags that hold either links or small chunks of texts, like a or span. While block level elements will automatically place themselves on a new line in your layout, inline elements, by definition, will stay exactly where they are in the markup.
Because of this distinction, block level elements can usually be though of as inside an invisible, clearly defined block, that usually spans the width of the page. With a block like this, you can easily imagine padding and margin, because its edges are well defined. Inline elements, however, are tricky, and don't render themselves inside any specific block or rectangle -- their dimensions are defined solely on the text inside them. This is why it is more difficult to apply margins.
A fix in the above would be to give your a a display: block style in the CSS. It will then by default take up the entire width of the page, and its height will be as large as is required by the size of the text. Margins and padding can be easily added.
If you're then faced with not wanting your a to be so wide, but position itself snugly next to other elements, you can change the display property to inline-block -- this can be thought of as kind of half way between block and inline elements. It will only be as wide as the text inside, but it will get that imaginary rectangle around it that can then be made larger with margins and padding.
Here's some reading: The CSS box model
Answer: Sorry for misunderstanding your question.
You need convert your  into an inline-block element for it to work.
Here is the code.
The Code:
Download XML

PS: 40px is a dummy value for margin-top. You can replace it with your value.
Comment: Does this work when the box-model fix is NOT set? http://www.paulirish.com/2012/box-sizing-border-box-ftw/
Comment: Nope. Without that too it works.
Comment: Ok. In practice, for this mark-up at least, it pushes the element up and out over the code in the pre above, rather than move anything down.
Comment: @Luke: `box-sizing` has no effect on margins (unless there was a hypothetical `box-sizing: margin-box`, but it wouldn't even make sense in CSS anyway).
Comment: Sorry for misunderstanding your question. [I have updated my answer here.](http://stackoverflow.com/questions/17991174/css-what-to-look-for-when-margin-has-no-effect/17991251#17991251) - @LukePuplett
Comment: @BoltClock - That comment was in response to Nathan's suggestion to use padding, but he's updated his answer. By the way, I marked your answer as err, the answer, but you'd deleted it.
Comment: @NathanLee I assume inline styles are used illustratively on SO.
Comment: Well I assume they are mostly used when they are meant to be used and most importantly to know and solve the OP's purpose of their questions. :) - @LukePuplett
Comment: @Luke: Oops, I saw Elise's answer which is more comprehensive and entirely right so I removed mine. Anyway, I see you've gone ahead and ticked her answer now.
Answer: If you have defined position of the element relative or absolute that time margin value would not work, for this you can try using top


Sigma-algebras generated by maps

Question: Let $(\Omega,\mathbb{F},P)$ be a probability space and $\epsilon_1,...,\epsilon_n$ be real-valued random variables defined on $\Omega$. Now let $\mathbb{D}_n$ be the sigma-algebra generated by $\epsilon_1,...,\epsilon_n$, i.e
$$
\mathbb{D_n}=\sigma(\epsilon_1,...,\epsilon_n)= \sigma \left(  \bigcup_{i=1}^n \{ \epsilon_i^{-1}(B)|B\in \mathbb{B} \} \right)
$$
where $\mathbb{B}=\mathbb{B(\mathbb{R})}$ is the Borel sigma-algebra.
With $X_0=0$ define recursively $$
X_k=\alpha X_{k-1}+\epsilon_k \quad \quad \quad \text{for} \quad k=1,...,n$$
I have shown that each $X$ can be defined as
$$
X_k=\sum_{i=0}^{k-1} \alpha^i\epsilon_{k-i}=\epsilon_k+\alpha \epsilon_{k-1}+ \cdot \cdot \cdot + \alpha^{k-1}\epsilon_1
$$
Now the problem is that i am to show that
$$
\sigma(\epsilon_1,...,\epsilon_k)= \sigma(X_1,...,X_k) \quad \quad \quad \text{for} \quad   k=1,...,n$$
So far my strategy for showing the above is to first show that $$\left(\bigcup_{i=1}^k \{\epsilon_i^{-1}(B)|B\in\mathbb{B}\} \right) \subseteq \left(\bigcup_{i=1}^k \{X_i^{-1}(B)|B\in\mathbb{B}\} \right)
$$
and conversely $\supseteq$, by taking an arbitrary element in the first and showing that it is in the other.
Now the great question: How is this done?
Answer: Hint: there is a bijective linear map $T$ which maps $(\epsilon_1,\dots,\epsilon_k)$ to $(X_1,\dots,X_k)$.
If $B$ is a Borel subset of $\Bbb R$, this allows us to see that $$X_j^{-1}(B)=(X_1,\dots,X_k)^{-1}(B')$$
where $B'=\Bbb R^{j-1}\times B\times \Bbb R^{k-j}$. Indeed, $X_j(\omega)\in B$ if and only if $(X_1(\omega),\dots,X_k(\omega))\in B'$.
Comment: Okay, i will give it another try constructing the argument, based on your hints. Anyway thanks for taking the time and helping me, i'm very grateful for that.
Comment: Okay im not sure how to use that information, anyway i have found the lower triangular matrix mapping $(\epsilon_1,...,\epsilon_k)$ to $(X_1,...,X_k)$.
Comment: Okay, im having trouble seeing how $(X_1,...,X_k)^{-1}(B')=X_j^{-1}(B)$ and not equal to $(\Omega,...,\Omega,X_j^{-1}(B),\Omega,...,\Omega)$. But that aside i dont know how the argument of the inclusion is supposed to continue from there. Anyway thanks for taking the time answering the question.
Comment: Note that $X_l^{—1}(\Bbb R)=\Omega$. You can try to show that the LHS is contained in the RHS, and the converse. Do you see how it helps?
Comment: I cant see how
$$(X_1,...,X_k)^{-1}(B')=( \stackrel{j-1 times}{\overbrace{ \Omega,..., \Omega}},X_j^{-1}(B), \stackrel{k-j times}{\overbrace{\Omega,...,\Omega}})$$
Could help showing equality between the pre-image sigma-aglebras
Comment: No i can't see how to use your hints, so i decided to come up with a different approach on a proof. I have postet it below, and im pretty confident that it is correct. Do you not concur?
Answer: My answer:
$\sigma( X_1,...,X_k)$ is the smallest $\sigma$-algebra that makes $X_1,...,X_k$ $\sigma(X_1,...,X_k)/\mathbb{B}(\mathbb{R})$-measurable
Note that $\epsilon_1,...,\epsilon_k$ can be written as
$$
\epsilon_i=-\alpha X_{i-1}+X_i \quad \quad \quad \text{ for } \quad i=1,...,k
$$
We know that the constant function $h:\Omega\to \mathbb{R} $ given by $h(\omega)=\alpha$ is $\sigma(X_1,...,X_k)$-measurable because
$$
h^{-1}(B)= \begin{cases} \Omega &\mbox{if } \alpha \in B \\
\emptyset & \mbox{if } \alpha \notin B \end{cases} \quad \quad \quad \text{for} \quad B\in \mathbb{B(\mathbb{R})}
$$
Using that any $\sigma$-algebra on $\Omega$ contains both $\Omega$ and $\Omega^c=\emptyset$.
Furthermore we got that the product of two $\sigma(X_1,...,X_k)$-measurable functions is  a $\sigma(X_1,...,X_k)$-measurable function. Now with the property that the sum of two $\sigma(X_1,...,X_k)$-measurable functions is a $\sigma(X_1,...,X_k)$-measurable function, we get that every $\epsilon_1,...,\epsilon_k$ is $\sigma(X_1,...,X_k)$-measurable.
By using that $\sigma(X_1,...,X_k)$ makes every $\epsilon_1,...,\epsilon_k$ a measurable function, and that $\sigma(\epsilon_1,...,\epsilon_k)$ is the smallest $\sigma$-algebra making $\epsilon_1,...,\epsilon_k$ measurable, it must be true that
$$
\sigma(\epsilon_1,...,\epsilon_k) \subseteq \sigma(X_1,...,X_k)
$$
Conversely we know that $ \sigma(\epsilon_1,...,\epsilon_k)$ makes every $\epsilon_1,...,\epsilon_k$ measurable, and since
$$
X_i=\sum_{n=0}^{i-1} \alpha^n \epsilon_{i-n}\quad \quad \quad \text{ for } i=1,...,k
$$
Which by the same arguments as before makes $X_1,...,X_k$ the sum of $ \sigma(\epsilon_1,...,\epsilon_k)$-measurable functions and thus becoming $ \sigma(\epsilon_1,...,\epsilon_k)$-measurable. But since $\sigma(X_1,...,X_k)$ is the smallest $\sigma$-algebra making $X_1,...,X_k$ measurable, it must be true that
$$
 \sigma(X_1,...,X_k) \subseteq \sigma(\epsilon_1,...,\epsilon_k)
$$
which implies that
$$
 \sigma(X_1,...,X_k) =\sigma(\epsilon_1,...,\epsilon_k)
$$
which was what was wanted.

Sigma-algebras generated by maps


What is the difference between Ruby and Python versions of"self"?

Question: I've done some Python but have just now starting to use Ruby
I could use a good explanation of the difference between "self" in these two languages.
Obvious on first glance:
Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.
Python methods receive self as an explicit argument, whereas Ruby does not.
Ruby sometimes has methods explicitly defined as part of self using dot notation.
Initial Googling reveals
http://rubylearning.com/satishtalim/ruby_self.html
http://www.ibiblio.org/g2swap/byteofpython/read/self.html
Comment: The python version is more annoying :-)
Comment: well, I would say... it is more present.  :)
Answer: Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.
Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are.
If you're inside an instance method of one of your class, self is a reference to said instance.
If you're in the definition of the class itself (not in a method), self is the class itself:
class C
  puts "I am a #{self}"
  def instance_method
    puts 'instance_method'
  end
  def self.class_method
    puts 'class_method'
  end
end

At class definition time, 'I am a C' will be printed.
The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method.
c=C.new

c.instance_method
#=> instance_method
C.class_method
#=> class_method

Comment: Its also worth noting that literals in Python are full objects just like in Ruby.  Evaluating (1).__class__ gets you . There is a difference in the tokenizer (unrelated to the object system) that treats "1." as a float, but using brackets, or "1 .__class__" will work as expected.
Comment: What should be done about an answer like this that is factually wrong? The very first version of Python published had a full class system.
Comment: Decided to just edit out/correct the false part, but it'd be nice if answerers would refrain from posting things that are easily refuted by a glance at wikipedia.
Comment: Ouch! Good catch. I'm actually not a Python developer, I should have put a disclaimer in there. I went from memory from an interview about 2 years ago with Guido van Rossum (on FLOSS Weekly)
Answer: Despite webmat's claim, Guido wrote that explicit self is "not an implementation hack -- it is a semantic device".

The reason for explicit self in method
  definition signatures is semantic
  consistency. If you write
class C: def foo(self, x, y): ...
This really is the same as writing
class C: pass
def foo(self, x, y): ... C.foo = foo

This was an intentional design decision, not a result of introducing OO behaviour at a latter date.
Everything in Python -is- an object, including literals.
See also Why must 'self' be used explicitly in method definitions and calls?
Answer: Well, I don't know much about Ruby. But the obvious point about Python's "self" is that it's not a "keyword" ...it's just the name of an argument that's sent to your method.
You can use any name you like for this argument. "Self" is just a convention.
For example :
class X :
    def __init__(a,val) :
        a.x = val
    def p(b) :
        print b.x

x = X(6)
x.p()

Prints the number 6 on the terminal. In the constructor the self object is actually called a. But in the p() method, it's called b.
Update : In October 2008, Guido pointed out that having an explicit self was also necessary to allow Python decorators to be general enough to work on pure functions, methods or classmethods : http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
Comment: Even better, as methods are just callable attributes of a class, you can define `class X: pass` then `def foo(b): print b.x` totally outside the class, and conclude by `X.p = foo`. This is fantastic as you can create methods as lambdas or even closures. Example use-case: dynamic `clean_foo` methods for Django forms.
Answer: self is used only as a convention, you can use spam, bacon or sausage instead of self and get the same result. It's just the first argument passed to bound methods. But stick to using self as it will confuse others and some editors.


vlans and unmanaged switches

Question: For the scenario like this: [managed switch 1, vlan0]-[unmanaged switch]-[unmanaged switch]-[managed switch 2, vlan0],

Is it possible to have a vlan defined based on the managed switch 1 and 2? I guess it boils down what happens to the tagged frames at the unmanaged switches.

If the answer for (1) is yes, will the devices under vlan be able to access the segments of the lan within the unmanaged switches?
Answer: There are 2 ways of handling VLANs.

You have a physical port on a routing device and you tell it that any traffic that comes along with a destination header that matches your rule (such as 192.168.1.0/24, so all IP's between 192.168.1.0-254) gets sent down that cable. The switch will also helpfully add a VLAN ID to all that traffic so you now know which VLAN it belongs to. Also the switch is smart and ONLY sends it down that cable and nowhere else so the network doesn't get congested.

This is more interesting to you. You setup a rule on your router; the rule says if the traffic matches the rule then it is given the desired VLAN ID. However because the switches don't know if that traffic belongs to a VLAN it has to be sent to a router to be processed and have the correct VLAN ID added to the header. Obviously sending all traffic through the router can cause a bottleneck, but there is hardware designed for this.

So in your case don't configure the port on your [managed switch 1] to do anything special. Just let it broadcast and the traffic should have no trouble reaching it's destination. By default all VLAN's can communicate with anything on the network as long as you send it to the correct IP. If you want to restrict traffic you setup firewall rules to block it as it goes through the router.

vlans and unmanaged switches


Fancybox thumbnail without first image

Question: I have a fancybox gallery with thumbnail helper like this:

So I keep just the first image visible and hide the other. When the first image is clicked on, it opens the gallery, with thumbnail showing all the three images.
I want to remove the first image from the gallery (and from the thumbnail). So when I click on it, it opens the gallery but just with the "img2" and "img3".
How can I do that?
Answer: First, if you are going to hide some images, then they don't have to have a thumbnail. Just wrap their anchors in a hidden container like

Notice we are just wrapping images 2 and 3 since 1 will be visible.
Second, remove the class fancybox-thumbs from the image 1 as well as the data-fancybox-group="thumb-1" attribute since this image won't be part of the gallery but the trigger. Then set a different class for it and keep the thumb like :

And bind a click event to this image that will trigger the fancybox gallery like :
jQuery(document).ready(function ($) {
    $(".fancyboxTrigger").on("click", function (e) {
        e.preventDefault(); // prevents to follow the link of first image
        $(".fancybox-thumbs").fancybox({
            // fancybox API options
        }).eq(0).trigger("click");
    })
}); // ready

Notice that we bound and chained the .fancybox(), .eq() and .trigger() methods to the .fancybox-thumbs selector.
Also notice that .eq(0) targets the first element of the gallery (indexes in javascript start from 0)
See JSFIDDLE
Last note : If you want the first anchor to trigger the gallery without a thumbnail, just replace the  tag by a text like
Open fnacybox gallery

Fancybox thumbnail without first image


Regular expression doesn't work in Rust, what's wrong?

Question: ^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$

program has panicked with error: unrecognized escape sequence
Answer: Why not post the error message? It literally points to the problem:
regex parse error:
    ^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$
                  ^^
error: unrecognized escape sequence

So... The error is telling you that \/ is an unrecognized escape sequence. Because / is not a regex meta character, so I don't know why you're escaping it. So change all occurrences of \/ to /:
^((?:https?:)?//)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(/(?:[\w\-]+\?v=|embed/|v/)?)([\w\-]+)(\S+)?$

Comment: It compiles just fine: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4146a732b659e01217c1fd76cb849a8c --- Please consider spending a bit more time to provide more detail to your question. You need help us help you.
Comment: ... that's a different question. Your original question asks about escape sequences. And you never actually say what "works" means.
Comment: Your regex is using `^` and `$`, which anchor it to the beginning and end of the text. It looks like you want to be line anchors too, which you can do by enabling multi-line mode. Put `(?m)` at the beginning of your regex and you'll see matches. In the future, please please please add more detail to your questions. Answering this question has been very frustrating for me because of the missing detail in your question.
Comment: i tried, but also RegExp don't work
Comment: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b9a470ad2e01b1d47c0c853e0bbf6d59
try this, nothing to print
Comment: okay, sorry, i'm a novice in stackoverflow
Comment: If I answered your question, then please mark this as the answer.


Instanciando form para bloquear button

Question: Estou instanciando um form com um único textbox apenas para colocar a senha para liberar a ação do botão.
O botão tem função de exportar os dados contidos no datagridview para uma planilha no Excel, estou tentando fazer desta maneira:
private void btnExportar_Click(object sender, EventArgs e)
        {
            formExportar form = new formExportar();
            form.ShowDialog();

            if (exportar.txtsenha.Text == "123")
            {
               //código para exportar arquivos para o excel
            }
            else
            {
                MetroFramework.MetroMessageBox.Show(this, "Senha incorreta", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
    }

No caso o formExportar é o form de autenticação onde insiro a senha, estou instanciando ele no form principal dessa forma:
public partial class TelaInicio : MetroFramework.Forms.MetroForm
    {
        internal formExportar exportar = new formExportar();

    public TelaInicio(formExportar exportar)
    {
        InitializeComponent();
        this.exportar = exportar;
    }

Porém pelo fato do botão OK que existe no formExportar não estar sendo executado acaba por não acontecer nenhuma ação.
Eu tentei também jogar todo o código de exportação no formExportar ao invés de deixar no form principal mas isso acaba ocasionando um erro pelo fato de não existir um DataSource naquele form, realmente não sei como proceder com isso.
Answer: Basta criar no btn para abrir a solicitação da senha:
        DialogResult resultado = new DialogResult();
        Form1 f = new Form1();
        resultado = f.ShowDialog();
        if (resultado == DialogResult.OK)
            MessageBox.Show("ok");
        else
        {
            MessageBox.Show("erro");
        }

e no form de exportação acrescentar dois botões, sendo um para ok e outro para sair.
Botão para tentar senha:
        if(textBox1.Text == "123")
        this.DialogResult = DialogResult.OK;
        else
        {
        MessageBox.Show("Senha incorreta");
        }

O que foi criado é semelhante a uma messagebox.

Instanciando form para bloquear button


Is there a sense in which a countably generated sigma-field is computable?

Question: This is a bit of a soft question because I'm not very strong in computability and recursion theory, but here goes.
In measure theory, one starts with a measurable space $(\Omega, \mathcal F)$, which is just a set $\Omega$ and a sigma-field $\mathcal F$ of subsets of $\Omega$. It is often convenient to assume that $\mathcal F$ is countably generated, which means that there is some countable subset $\mathcal C$ of $\mathcal F$ such that $\mathcal F$ is the smallest sigma-field containing $\mathcal C$.
My (again, soft) question is whether countable generation can be motivated by or viewed as a kind of computability condition.
My (very rough) idea is something like the following: the members of $\mathcal F$ should be "computable" (I don't have a precise definition in mind here, just a rough idea) and computability (whatever it is) requires countable operations, so $\mathcal F$ should be countably generated.
Perhaps an analogy will help. A real number is computable if it can be computably approximated by the members in a countable set (the rationals). That sentence can be made perfectly precise using computability and recursion theory. I want to know if the sentence "A member of $\mathcal F$ is computable if it can be computably approximated by the members of a countable set ($\mathcal C$)" can be made perfectly precise in way that entails that $\mathcal C$ generates $\mathcal F$.
Thanks for your patience with this very open-ended question!
Comment: I figure you need some definition for what it means for one sufficiently but finitely refined sigma field to approximate the "limiting sigma field". Is there a measure present which has the measure of the missing sets uniformly small or something similar? Or maybe some topological structure? I'm just stream of consciousness here tossing out ideas...
Comment: @jdods I am not sure
Answer: Countable generation of the sigma algebra $\mathcal{F}$ implies that for any $\sigma$-finite measure $\mu$ on $\mathcal{F}$ and $p \in [1, \infty)$, $L^p(\Omega, \mathcal{F}, \mu)$ is separable, i.e. has a countable dense set.
Another related result, which is actually part of the proof of the previous result is that if $\mathcal{A}$ is an algebra that generates the $\sigma$-algebra $\mathcal{F}$ and $\mu$ is a finite measure on $(\Omega, \mathcal{F})$, then the closure of $\mathcal{A}$ in $L^1(\Omega, \mathcal{F}, \mu)$ contains $\mathcal{F}$, that is, for any $A \in \mathcal{F}$ and any $\varepsilon > 0$, there exists $B \in \mathcal{A}$ such that $\|1_{A} - 1_{B}\|_{L^1} = \mu(A \Delta B) < \varepsilon$. This result is an immediate consequence of the $\pi$-$\lambda$ theorem since $\mathcal{D} = \{A \in \mathcal{F} : A \in \overline{\mathcal{A}}\}$ is a $\lambda$-system.
Both of these results are very useful in probability theory.


Converting output of cv2.mean() to other color models (LAB)

Question: Using OpenCV 2 (3.1.0) and python 2.7 If you pass a image or video frame to cv2.mean() you get an output like
(57.679779052734375, 70.36699761284721, 102.41968960232204, 0.0)

Does the returned value follow the OpenCV convention of BGR (not
RGB) and what does the last value mean?
If I wished to translate the value returned to LAB color model
what is the best way of doing so without recalculating the mean?

I've tried using colormath module to convert from rgb to xyz to lab but if I use manual online colour converters the input(RGB) doesn't look like the same colour when converted to LAB and the inputI start with isn't what I was expecting as the mean of the source image/frame
    from colormath.color_objects import XYZColor, sRGBColor,LabColor
    from colormath.color_conversions import convert_color
    #RGB-Blue   RGB-Green   RGB-Red
    #57.6797790527  70.3669976128   102.4196896023

    #BGR
    #107    127 133

    rgb = sRGBColor(133, 127, 107)
    xyz = convert_color(rgb, XYZColor, target_illuminant='d50')
    lab = convert_color(xyz,LabColor)

Comment: It calculates mean for each channel independently. The result contains one mean per channel, in the same order (wouldn't really make sense otherwise). What the particular channels represent is irrelevant to that function. | If the result has 4 values, then you passed it a 4 channel image - something with transparency. You can easily verify that by inspecting the `shape` attribute of the input array.
Comment: I'm my case it's a frame from a video accessed via cv2.VideoCapture and read()
Answer: So OpenCV has its own convention for the range of values for different color spaces, which in turn is dependent on the type of image you use. For example, CV_64 has different conversion equations than CV_32 and CV_16 and so on.
For an example:(Technically, if you did some homework on the documentation you would understand it from here)
If [R,G,B] = [220, 233, 119] and you go to this website and convert it
the Lab values would be
[L, a, b] = [89.31, -20.33, 53.44]
Now, in OpenCV, for the type CV_32FC3, the Lab conversion would be as follows:
[R, G, B][220, 233, 119] = CV[L, a, b][2.55 * 89.31, 128 + (-20.33), 128 + 53.44]
Note - Important to check the type of the image when using the convention.
Alternatively, if you have the motivation, why don't you create images with all channels with the same value, convert them using Imgproc.cvtcolor to whatever color space you want and then come up with the formula? That's how I did it. The confusion after this was solved with the documentation when I changed the image types.
Hope it helps!
Comment: Thanks for joining in. Maybe some extra background will help. I'm not interested in converting frame X or Y to another colour model. I'm taking the mean of individual frames to build up a dataset to give a representation of a video as 1 image. I set the height but each pixel along the width represents a frame and is coloured by its mean. I'll to apply k-means to cluster the LAB colour to see if I can see segments of the original video using just colour. I'd prefer not to create mulitple images and just convert from RGB to lab where the euclidean distance can be used to cluster
Comment: If I understand correctly, you have a video, you scan it frame by frame (RGB) calculate its mean and save it as Lab. Then with these values, you classify using k-means. I don't really understand where the problem is, looks to me it is straight forward.
Comment: Yip easy to say but stumbling to do the conversion without needing to create a interim image just to convert it to lab
Comment: With this formula, you don't need to
Comment: Hi Rick, I don't follow where you found the formula to go from rgb values to lab, can you link to the code or explaination for the values?
Comment: [Here](http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor)