Proof of the second part of Schur's lemma

Question: Background
According to PlanetMath Schur's lemma is this:
Let $G$ be a finite group and let $V$ and $W$ be irreducible $G$-modules. Then, every $G$-module homomorphism $\,f: V \to W$ is either invertible or the trivial zero map.
Corollary
Let $V$ be a finite-dimensional, irreducible $G$-module taken over an algebraically closed field. Then, every $G$-module homomorphism $\,f: V \to V$ is equal to a scalar multiplication.
Proof
Since the ground field is algebraically closed, the linear transformation $f: V\to V$ has an eigenvalue; call it $\lambda$. By definition, $\,f - \lambda 1$ is not invertible, and hence equal to zero by Schur's lemma. In other words, $\,f = \lambda$, a scalar.
Question
In the proof above, why can Schur's lemma be applied to $\,f - \lambda 1$? Is it assumed that $\,f - \lambda 1$ is also a $G$-module homomorphism?
Comment: The set of all $G$-module homomorphisms from $V$ to $W$ is a vector space, and it contains $1$.
Answer: $f$ is a $G$-module homomorphisms by assumption. Let $\rho : G \rightarrow GL_k(V)$ by the representation, where $k$ is the field. Then you have
$(f - \lambda I)(\rho(g)(v)) = f(\rho(g)(v)) - \lambda I(\rho(g)( v)) = \rho(g)(f(v)) - \lambda \rho(g)(v)$
by using the fact that $f$ is a $G$-module homomorphism. Since $\rho(g) \in GL_k(V)$, this means that $\rho(g)$ is a k-linear transformation, hence
$= \rho(g)(f(v)) - \rho(g)(\lambda v) = \rho(g)(f(v) - \lambda I(v)) = \rho(g)((f - \lambda I))(v)$
So $f - \lambda I$ has been shown to be $G$-linear.


Why can't I use product rule to derive x ln(3)?

Question: The product rule is defined as $$(f \cdot g)' = f' \cdot g + g' \cdot f.$$
I have the following function $u(x) = x\cdot \ln(3)$. I understand that you can derive it by implicit differentiation and have $\ln(3)$ as the result.
I, however, do not understand why I get the wrong result by applying the product rule:
$$
f(x) = x\\
g(x) = \ln(3)\\
f'(x) = 1\\
g'(x) = 1/3\\
D(f(x) * g(x))=\\
= 1 * \ln(3) + 1/3 * x \\
= \ln(3) + 1/3x \neq ln(3)$$
Comment: The derivative of $\ln(3)$ is 0
Comment: You can, of course...but is overkill.
Comment: You made a mistake, the derivative od $g$ in your case is $0$.
Comment: If $g(x)=\ln(3)$ then $g'(x)=0$. You make it wrongly $g'(x)=1/3$. Probably inspired by the next thing: If you would have $g(x)=\ln(x)$ then $g'(3)=1/3$ since in that case $g'(x)=1/x$.
Answer: $\ln(3)$ is a constant.. There's no need for the product rule.
$(x\cdot c)' = c$ when $c$ is a constant.
You can use the product rule, but there's no need for it, since the derivative of any constant $c$ is given by $(c)' = 0$. That gives us $(\ln 3)' = 0$.
If $x = f(x)$ and $\ln 3 = g(x)$, then the derivative, using the product rule, is given by:
$$f'(x)g(x) + f(x)g'(x) = (1)\cdot\ln(3) + x\cdot (0) = \ln(3)$$

Note that for $g(x) = \ln 3, \;g'(x) \neq \frac 13$. It is true that if $h(x) = \ln x,\;$ then $h'(x) = \frac 1x$, but $x$ is the variable with respect to which we are differentiating. In contrast, the argument of $\ln(3)$, $3$, is a constant, as is $\ln 3$, and like any constant or constant function, in this case, its derivative with respect to $x$ is $0$
Comment: Writing $(5)'$ is not completely rigorous in mathematic terms, but it is just as rigurious as writing $(\sin x)'=\cos x$, because you are not deriving $\sin x$ but the function $\sin$. What i want to say is that such nitpicking is utterly stupid.
Comment: I wasn't the downvote, but if $\ln(3)$ is not a function of $x$, then it doesn't make sense to take the derivative of it with respect to $x$.
Comment: @CamMcLeman. Why doesn't it make sense to say that the derivative of a constant is $0$ ?
Comment: @V.Rossetto:  That comment was in reference to an earlier version of the answer, in which the author claimed that constants were not function of $x$.  If they are not functions of $x$, then it is does not make sense to take their derivative.
Comment: @CamMcLeman. Okay, that was not easy to catch...
Answer: It is not necessary to use the productrule (see the answer of amWhy). You can however consider $\ln(3)$ to be a function of $x$. It is a constant function. The derivative of any constant function is $0$ and applying the productrule with $f(x)=x$ and $g(x)=\ln(3)$ gives: $$f'(x)g(x)+f(x)g'(x)=1\times \ln(3)+x\times 0=\ln3$$


Milton Green's lower bounds of the busy beaver function

Question: Wikipedia states that Milton Green demonstrated in 1964, that the busy beaver
 function $\Sigma(n)$ has the lower bound
$$\Sigma(2k)>3\uparrow^{k-2}3$$
I read the talk about the busy beaver article and someone had doubts about
 these bounds. I am not quite sure, if the bounds turned out to be true at last.
So my quesion : Are the bounds correct, and if yes, is there a simpley way
 to understand the bounds ?
A further question : Are there any higher lower bounds known for the busy
 beaver function $\Sigma(n)$ for $n\ge10$ ?
Answer: You can find some larger lower bounds on the Googology wiki, here.
Some notable lower bounds:
I found a lower bound $\Sigma(25) > F_{\omega+1}(6143) > $ Graham's number. The details are here.  Wythagoras then improved the machine to prove the lower bound $\Sigma(23) > F_{\omega+1} ( F_{\omega+1}(9)) >$ Graham's number; details are in the comments of the previous page.
LittlePeng9 implemented a number of algorithms for fast-growing functions to provide very large lower bounds, and these Turing machines were optimized by Wythagoras as well.  The machines are listed here.  These include:

An implementation of the Kirby-Paris Hydra to prove $\Sigma(41,3) > F_{\varepsilon_0}(374676379)$.
An implementation of the Buchholz Hydra with two labels to prove $\Sigma(81,10) > F_{\vartheta(\varepsilon_{\Omega+1})}(2050)$.  Here $\Sigma(m,n)$ indicates the largest number of ones printable by a Turing machine with m states and n symbols.
An implementation of the Buchholz Hydra with finite labels to prove $\Sigma(134,7) > F_{\psi_{\Omega_1}(\Omega_{\omega})}(2050)$.  We can convert this to a two symbol machine with a conversion algorithm (devised by LittlePeng9) that proves $\Sigma (3350) > F_{\psi_{\Omega_1}(\Omega_{\omega})}(2050)$.
An implementation of the Buchholz Hydra with $\omega+1$ labels to prove $\Sigma(150, 7) > F_{\psi_{\Omega_1}(\varepsilon_{\Omega_{\omega}+1})}(683)$.  The same reduction algorithm proves $\Sigma(3750) > F_{\psi_{\Omega_1}(\varepsilon_{\Omega_{\omega}+1})}(683)$.

It's likely that you are unfamiliar with the notations for these lower bounds.  To understand them, you need to be familiar with the fast-growing hierarchy and notations for large ordinals.  Suffice to say, these numbers are VERY large, making Graham's number seem like an infinitesimal!
Note that these machines are rather complex, and are rather hard to debug since they cannot be run to completion.  So there is a definite possibility for errors.
Finally, Wythagoras modified the Busy Beaver machine for six states to create a seven state machine that prints more than $10^{10^{10^{10^{18705352}}}}$ ones.  The machine is listed here, and the computation is verified here.
Comment: Wonderful results! I was unaware of those.
Comment: Wow! Thank you very much! So, bb(7) is already out of reach. Great answer!
Comment: The site claims that for 18 of the HNR-machines (Hardly-Non-Regular-machines) it is not known whether they halt or not. But the site only gives a description what the machines do, but not the concrete structure. Where can I find the tables for those machines with 5 states?
Comment: And I would also like to have a complete survey for the machines with less than 5 states (I know that all those machines are solved, but did not find a list)
Comment: Skelet's 43 HNR machines can be found at http://googology.wikia.com/wiki/User:Ikosarakt1/Nonregular_Turing_machines_with_5_states, and Skelet's original site is at http://skelet.ludost.net/bb/nreg.html. For machines with less than 5 states, I guess the best resource will be Brady's paper where he finds the value of Sigma(4), available at http://www.jstor.org/stable/2007539.
Comment: I haven't thought of an absolute proof but I think we can define a really strong formal proof system and then prove in an even stronger system that a certain 6 state 2 colour turing machine can never be proven in that system to never halt and if it eventually halts, produces more 1's than any turing machine that can be proven in that system within a googol characters to eventually halt. If it turns out that that turing machine eventually halts, then BB(6) is unfathomably large.
Answer:
I posted that "doubting" question, but (as detailed on the talk page) these lower bounds do indeed follow from Green's paper:
$$\Sigma(2k) > 3 \uparrow^{k-2} 3 \quad (k \ge 2)$$
Note that the bounds published by Green are stated in terms of recurrence relations, and are somewhat larger than what's given by the simpler Knuth arrow formula.
Is there a simple way to understand them? It becomes rather philosophical. If by  "understand them" we mean "comprehend their magnitude", then the answer (at least for $k \ge 6$) is "probably not". Harvey Friedman proposed  $2\uparrow^{4}5$ as a benchmark, such that the magnitude of any number at least this large is considered incomprehensible. He writes that "a profound level of incomprehensibility emerges. The definitions are not incomprehensible, but the largeness is incomprehensible." (For me, this is already true of $3 \uparrow^{3} 3$. I simply cannot comprehend the magnitude of the number denoted by an exponential tower of trillions of $3$s.)
Are any higher lower bounds known for $\Sigma(n)$ for $n\ge10$? Yes; e.g., here is a $64$-state BB-class Turing machine designed to compute a number that's far larger than Graham's number ($G$). As shown in the article, it halts eventually, leaving exactly $h_{\omega+1}(h_{\omega+1}(4)) + 1 $ contiguous ones on the tape, where $h_\omega$ is defined by an accelerated version of the fast-growing hierarchy:
$$h_\alpha(n) = \begin{cases}
& n+1, & \mbox{if }\alpha = 0 \\
& (h_{\alpha-1})^{n+2}(n+4), & \mbox{if }\alpha\mbox{ is a successor ordinal} \\
& (h_{\alpha[n+1]})^{n+5}(n+7), & \mbox{if }\alpha\mbox{ is a limit ordinal}
\end{cases}$$
Hence,
$$ \Sigma(64) \ \ge \ h_{\omega+1}(h_{\omega+1}(4)) + 1 \ \ggg \ f_{\omega+1}(f_{\omega+1}(4)) + 1 \ \ggg \ G  $$
Of course this Turing machine has a "structured design logic" not required by a Busy Beaver, and so is surely nowhere close to having the minimum number of states needed to achieve similar results. (For all we know, even $12$ states with humanly impenetrable logic might be sufficient).
Comment: A very interesting answer! With understanding I did not mean understanding the magnitude, but understanding that there are machines that produces at least so many ones and halt. Quite impressing that bb(64) has been proven to be such an enourmous number!


Can I Use ASP.NET Wizard Control to Insert Data into Multiple Tables?

Question: I have an ASP.NET 3.5 webforms project written in VB that involves a multi-table SQL Server insert.  That is, I want the customer to input all their contact information, order details etc. into one control (thinking wizard control).  Then, I want to call a stored procedure that does the insert into the respective database tables.
I'm familiar and comfortable with the ASP.NET wizard control.  However, all the examples I've seen in my searches pertain to inserting data into one table.
Questions:
1.  Given a typical order process - customer information, order information, order details - should a wizard control be used to insert data into multiple database tables?  If not, what controls/workflow do you suggest?
2.  I've set primary keys and indexes on my order details, orders and customers tables.  Is there special stored procedure syntax to use to ensure that referential integrity is maintained through the insert process?
Thanks,
Sid
Answer: Referential integrity doesn't depend on "stored procedure syntax", it depends on how you have the keys/constraints/etc. defined on the database objects themselves. That's really the beauty of referential integrity. It doesn't matter how the insert/update is occurring (i.e. via stored procedure, call from a C#/JAVA program, etc.), the referential integrity will ensure that the integrity of the data is preserved.
To preserve proper parent child relationships between your tables, what you want to use are foreign keys. For example, a foreign key for an order to order_details table might be from order_details->order_num to it's parent table (order->order_num). This relationship would ensure that no order record can be deleted if it has associated order_detail records.
As far as the best way to do the updates (via wizard, etc.) I think the main thing is to stick with stored procedures as much as possible. The high level mechanism you use (a wizard in your example) isn't as important, but by using a stored procedure you encapsulate the database logic in the proper place, and plus, it can be reused later by other applications if need be.
Comment: Thanks for a great answer!  The foreign key setup should make all this work.  Just to make sure I'm on the same page, my stored proc syntax would be something like
Create Procedure addOrder
As
Insert (@PartNumber,@Qty)
Values (PartNumber,Qty)
into OrderDetail
Insert (@OrderDate,@NeedByDate)
Values (OrderDate,NeedByDate)
into Orders

Is this correct?
Comment: @SidC - The basic syntax of your SP looks fine, but don't forget to pass/declare all the parameters you need to it.
Comment: Will Do.  I have fields in my wizard control for each of these parms.  Thanks much!


Why do major and minor triads sound different both harmonically and melodically?

Question:
Sorry if the wording is odd, but basically my question is, why do the major and minor triads have two distinct sounds, if they share all of the same intervals? Not only when they're stacked harmonically as a chord, but also when you play their notes melodically
I'm assuming the reason they sound different harmonically has something to do with the order of the harmonics of each note, but I'm not exactly sure how to make sense of that. What I'm really confused about is why they sound different melodically.
Here is an example of two melodies consisting of the same exact intervals, in the same exact order, that have two distinct sounds: http://onlinesequencer.net/1537233
The only difference is the direction the intervals move.
The first melody consists of notes only from C Minor triad: C1-D#1-G1-C1
The second melody consist of notes only from the C Major triad: G1-E1-C1-G1
The melodic intervals are exactly the same: Minor 3rd - Major 3rd - Perfect 5th
The only difference is the direction (up or down) that the intervals move, however the 'minor triad melody' still sounds darker than the 'major triad melody' and I can't figure out why. My assumption is that it has to do something with the direction they move considering that's the only difference.
Does anyone know why the two melodies sound different? Also, any insight into why they sound different as chords would be great too. Thanks!
Comment: What's with the complaining about note name spellings? This is a perfectly good and understandable question.
Comment: C minor always has Eb, never D#. C>Eb is m3. C>D# is aug2. Where did that misinformation come from?
Comment: I added octave numbers to the melody
Comment: 2nd melody - E>C isn't M3, it's m6 - the 'opposite'.
Comment: I'm voting to close this question because it's based on untrue premises.
Comment: @Tim why do you say *E>C isn't M3, it's m6*? The difference between C5 and E5 is 4 semitones - an interval of a major third, is it not?
Comment: @topoReinstateMonica - I thought intervals are recognised and calculated from the lower note. C>E is indeed 4 semitones (and the also important 3 letter names) whereas E>C is 8 semitones (and the also important 6 letter names).As it stands the question is unclear in that 'E to C' doesn't actually state which is the higher note, so I guess if E is higher, it *could* be construed as M3.
Comment: @Tim did you click the OP's link to https://onlinesequencer.net/1537233? Those are the intervals being discussed. The web page there calls the note 'D#', so OP is just using the same terminology here for clarity.
Comment: No, I didn't. But I wish these 'experts' would get stuff correct. With 'mistakes' like that, they lose all credibility from me.
Comment: @Tim I think it's just the sequencer doesn't 'know' what key you are in, so it's the old problem - what do you call the black notes if you don't know what key you are in?
Comment: @topoReinstateMonica - my sequencer has *both* names for each. Not too difficult?
Comment: @Tim so on each black note it says e.g. "Eb/D#"?
Comment: @YoungCapone it might be clearer if the octave numbers matched the online sequencer link..?
Comment: @topoReinstateMonica - absolutely, two octaves in a 6" span.
Answer: Human perception in general doesn't only detect differences, but the direction of those differences.
If someone pumps more air into a balloon so that it becomes twice as big, you don't think "I can tell that the size has changed by a factor of two, but I can't tell if it has got bigger or smaller" - you can actually tell that the balloon is now bigger!
If a helicopter climbs 200 metres, that doesn't look to us the same as if it were to descend 200 metres. Our senses don't only perceive the amount of change, but also the direction.
In a melody, when you hear a descending major third, what you're hearing is a multiplication of frequency by the ratio 4/5. When you hear an ascending major third, you're hearing a multiplication of frequency by the ratio 5/4. As with the balloon example, we can tell the difference. A descending major third is simply not the same as an ascending major third, and it doesn't sound the same - just as getting hotter doesn't feel the same as getting colder.
Another thing to bear in mind is that the human ear tends to hear notes in chords (and arpeggiated chords, like your melodies) with respect to a root. As you say, what our impression of the root is partly to do with harmonics - if we hear a bunch of notes that between seem to have a lot of harmonics in common with one particular note, that note may be perceived as the root (though there are other factors that affect the perception of what the root is).
If you are perceiving your minor triad melody as darker, it's probably because you are hearing C as the root of the arpeggiated chords that constitute your melodies - and the intervals from C are not the same. C to D# (or Eb) is not the same as C to E.
Comment: Yes, the OP's problem was looking at intervals only, and apparently being unaware of larger scale things. The concept of tonic is easy to miss, because it cannot be seen in the note sequence, you have to subjectively hear the sequence played in some context, and the tonic is an invisible force affecting the perception. The same C major chord sounds radically different in an F minor context compared to an F major context, as shown in my examples 3 and 4. And the other way around as well - in a C major context, an F minor chord sounds totally different than, say, in an F minor context.
Comment: I think this answer misses the most important aspect, the tonic, which is even more important than root notes of chords. And the direction of intervals is ... well not untrue, but it misses the main point as well.
Comment: @piiperiReinstateMonica yes, you could certainly make a similar point about the tonic of a piece as I have about the root of chords (as you have, in your answer). To me, the OP and his example seemed to focus on small units of organisation (chords and arpeggios-as-melody), so to keep the answer simple I followed suit. As for direction of intervals - the relevance of that is that OP opens by saying that major and minor chords contain the same intervals. But of course major and minor chords are different (and sound different) *regardless* of what your tonic is.
Answer: This is the linked source...

The melodic intervals are exactly the same: Minor 3rd - Major 3rd - Perfect 5th

Let's treat the D#5 as Eb5 so we can properly call it a third.
You are overlooking both the direction of the interval (ascending or descending) and the relationship of tones to chord roots.
C5 to Eb5 and G5 to E♮5 are indeed both minor thirds, but their directions and ending tones differ.
The practical thing you need to know is (tertian) chord qualities are determined by the intervals above a chord root. Even when the chord is inverted the chord quality is determined as if the tones are theoretically placed above the root in a stack of thirds.
With your two chords, both have the same root: C.
The chord intervals by the theoretical stack of thirds above the roots are:

minor third above the root, perfect fifth above the root for a C minor triad

major third above the root, perfect fifth above the root for a C major triad.

Why do major and minor triads sound different both harmonically and melodically?

Because relative to the chord root, major chords have a major third and minor chords have a minor third. Regardless of melodic direction or chord inversion, the quality of the third above the root determines the major or minor quality of a chord.
Answer: Edit. I think the OP's primary source of confusion was caused by not realizing that individual "melody" notes affect the perceived harmonic situation just as well as notes played simultaneously as chords, and that the ear's harmony tracking considers actually heard and imagined pitches over a longer time window than just individual note pairs. The note sequence C - Eb (or "D#") - G - C outlines a C minor triad, and G - E - C - G outlines a C major triad, and they sound different just like the chords sound different. The ordering of the notes and the directions of the intervals doesn't matter.

The reason why the note sequences sound different is that the notes' relationships to the perceived harmonic center, the tonic, are different. The tonic is a pitch that your "ear" (brain) figures out, and what you feel to be the tonic is somewhat subjective and depends on when you start hearing the music, what you heard prior to that and how you perceive the rhythmic pulse of the music. Where is the strong beat, the "one" as in "one-two-three-four one-two-three-four", and where the notes you hear sit compared to that strong/weak pulse.
In addition to a central home pitch (note), your brain tries to figure out the expected harmony around the home note. This means, if your tonic is C, the home harmony can be either C minor or C major. This is called the key of the melody - where is home and what does it feel like when you're at home.
In your example sequence, the first triad C - Eb - G is played so that it very clearly establishes C as the tonic, and by the time you hear the major triad G - E - C, your perception is already biased. Pairwise note-note intervals are not as important as each note's relationship to the tonic pitch, so even though in the second part you have a minor third G - E, you don't perceive it as the minor third of E minor. Because C is the tonic, you look at the G - E jump in that context. You always "hear" your expected tonic even when it isn't really sounding.
Let's take a few examples which demonstrate the phenomenon by playing note sequences over a basic drum beat, which makes the strong beats very explicit.
Example 1. Note sequence C - D - E - F

In this sequence, the C note is on the "one", the strongest beat, and the E note is on a strong beat as well. The D and F notes are perceived as more like passing notes or bystanders, and the tonic is C major. Or maybe F major ... it's somewhat subjective, and it's possible to imagine F being the tonic here. But D and E cannot be the tonic IMO, I can't stretch my imagination that far.
Example 2. Note sequence D - E - F - C

In the second example the repeating note sequence is exactly the same, but roles of C+E and D+F are reversed. Now the D and F notes are perceived as setting the tonic more strongly, and C and E are the bystanders. I'd say this is in D minor! All the same notes in the same order as in the C major example, just on different beats.
Example 3. Note sequence F - Ab - C - F - G - E - C - G

This example is a variation of the OP's note sequence, but with the initial minor triad moved to F. The beginning sets the tonic to F minor, and the C major triad G - E - C after it sounds ... dark? (I don't want to say sad, because it would give a pretext for someone to say that a song in a minor key can be happy and a major key can be sad and it's a cultural convention etc.)
The C major, in an F minor context is fifth-degree major chord, the "V chord" or dominant chord. After the C major, you want to hear an F minor again, to feel at home.
Example 4. Note sequence F - A - C - F - G - E - C - G

Now the beginning sets the tonic to F major, and so the C major triad G - E - C in the end sounds brighter, doesn't it?
Example 5. Note sequence G - E ... B - E

If before example 5 you had been listening to something that has C as the tonic, you might hear the starting G - E interval as belonging to a C major chord. But then in the end of this phrase, there is a strong B - E, which very heavily sets the tonic to E, and resets your perspective. Listen to the example again - now you perceive the G and E notes differently, because the tonic bias in your has been set by the B - E ending you heard previously.
Example 6. Note sequence G - E - C

The C in the end, and how it's played as a final note sets the tonic to C. And again I would say that it even gives perspective to the preceding G and E notes.
Now, directly after listening to example 6, listen to example 5 again.
Comment: If we found the OP's music example in a piece of atonal music, I think we'd all still perceive the two halves as different. Now whether they establish a temporary tonic, we'll let the listeners decide....
Comment: Out of interest, I played the OP's sample, starting with the second example. Hear what you think.
Comment: @Dekkadeci the OP seemed to assume that note-pair intervals define everything there is to know about melody and harmony, and I tried to demonstrate that notes are not interpreted as independent intervals but in a larger context, which is defined by many inter-dependent and even subjective factors. The two halves are different, but the small snippets are not self-contained entities floating in emptiness, they always occur in a context which heavily affects interpretation. Establishing an atonal context is very difficult and unintuitive, so I think it's not a good example. :)
Comment: OP here...So, when I made the two melodies, I tried to leave enough space between them so that the listener wouldn't have the first melody in mind when listening to the second. They are supposed to be two separate melodies not two parts of one melody.... I also listened to them individually after long periods of time and my perception of them didn't change. They still gave me the same impression
Comment: @YoungCapone The seqence C - Eb - G - C outlines a C minor triad, and G - E - C - G outlines a C major triad. They sound different. Was your question actually, "why do I get chord-like sensations even if the notes are played one-by-one as a melodic sequence and not simultaneously as a chord"? That's because your ear constantly tries to maintain a harmonic _context_, and a much wider time window is taken into account than a single pair of notes. The perceived most probable tonic - whatever that is at each point in time - decides the meaning notes, not individual intervals or their direction.
Answer: They sound different because, guess what, they're different. Simple as this. But there's a broad spectrum of differences, parameters of differences and how they function within a context. For example, there's also a difference between C Major and F Major triads and still they're both major and discernible chords.
Other example, major and minor chords are within the same pc set class - as all major and minor triads are related by transposition and/or inversion.
But, as anything related to analysis, you'll need always a context. In contexts where set classes (and not chords) are the elements of structural coherence, F Major, C Major and Gb minor triads will be the same (actually, different sets or instances of the set class 3-11 or (037)). But in contexts where chords are these elements, like harmony from common practice or smaller harmonic environments, each of these triads will be and function differently.
Answer: Both Major and minor triads have a Major-3rd, a minor-3rd and a Perfect-5th intervals, which makes them harmonically the same. They sound different, because the middle note of Major triads is one key higher than that of minor triads. Compare the C-Major and C-minor triads:
CM: C-E-G  (melodically, do-mi-so)
Cm: C-Eb-G (melodically, do-ri-so or mi-so-ti)
Since E is higher than Eb, CM creates a higher/brighter overall sound.
Answer: The dimension of pitch doesn't have a symmetry. We perceive left and right as more or less identical dimensions. Space doesn't chance in either direction. Still we would clearly notice when in our familiar environment left and right were exchanged. Frequency space is not even homogeneous. The higher the frequency, the brighter and thinner the sound gets. So it should be expected that flipping a chord upside down will not preserve its character.
A minor triad sounds slightly darker than a major triad, because one note is a semitone lower.
If you introduce the dimension of time, the direction of movement is one of the central priciples determining how a melody feels. Reverse a melody and its character is affected, or in a sense even reversed.
Our perception of harmony depends on pitch as well. You can observe it on any instrument: Every interval has its sweet range, where it has a nice roughness to it. Play it too high, and the roughness is lost, play it too low, and it gets muddy. As a general rule, the higher the consonance of an interval, the lower its sweet range will be.
A minor triad sounds slightly more dissonant than a major triad, because the less consonant third is played below the more consonant one.
There is a fundamental harmonic difference between major and minor triads though: The harmonics of a major triad are all harmonics of a common fundamental note two octaves beneath the chord's root. So this is the note the chord refers to. We also hear the fundamental note implicitly as the beat of the chord: The differences between the major triad's harmonics are all multiples of that fundamental frequency.
In a minor triad the next lower note containing all the harmonics would be a major third and three octaves below the root of the chord. First, that's a different note. Second, since it's a note not contained in the chord and much deeper, the association with that note is much weaker and the fundamental beat frequency is usually below the range where we can hear it. As a result, the minor triad does not have such a well defined beat pattern.
One should add that the beat pattern is less distinct in equal temperament tuning than in just tuning, but the difference between major and minor triads is still clear.
Conversely, the minor triade contains all harmonics of the note two octaves above its top note. It's therefore contained implicitely in the chord. I call this the "core" of the chord. The major triad has its core note three octaves and a fifth above its top note. So again, it's a different note and the association is much less clear.


Understanding the diagonal argument in the proof of a compactness theorem

Question: In the proof of a compactness theorem (Rellich-Kondrachov) in Evans's Partial Differential Equation, the following argument is made:

I'm not able to fully understand step 7.
Here are my questions:

Would anyone elaborate how the diagonal argument is used to give the desired subsequence? (To be precise, assuming Step 6 is done, how to get Step 7?)
How should one understand the notation $\limsup_{j,k\to\infty}$ appropriately?
Answer: Let $F_1=(f_1(n))_n$ be a sub-sequence of $\mathbb N$ with $\lim_{n\to \infty} \sup_{n\leq j<k} \|u_{f_1(j)}-u_{f_1(k)}\|<1.$
Take $G(1)=f_1(n_1)$ such that $\forall j>n_1\;(\|u_{f_1(n_1)}-u_{f_1(j)}\|<1).$
Let $F_2=(f_2(n))_n$ be a sub-sequence of $F_1$ with $f_2(1)=f_1(n_1),$ such that $\lim_{n\to \infty}\sup_{n\leq j<k}\|u_{f_2(j)}-u_{f_2(k)}\|<1/2.$
Take $G(2)=f_2(n_2)$ with $n_2>1$ ( i.e. $G(2)>G(1)\;$) such that $\forall j>n_2\;(\|u_{f_2(n_2)}-u_{f_2(j)}\|<1/2).$
Let $F_3=(f_3(n))_n$ be  a sub-sequence of $F_2$ with $f_3(1)=f_2(n_2),$ such that $\lim_{n\to \infty}\sup_{n\leq j<k}\|u_{f_3(j)}-u_{f_3(k)}\|<1/3.$ ET CETERA.
Consider the sequence $(u_{G(n)})_n.$
This is with the assumption that for any $\delta>0$ and any sub-sequence $F$ of $\mathbb N$ there is a sub-sequence $F'=(f'(n))_n$ of the sequence $F$ such that $\lim_{n\to \infty}\sup_{n\leq j<k}\|u_{f'(j)}-u_{f'(k)}\|<\delta.$
Comment: $(f_1(n))_n$ denotes the sequence $(f_1(1),f_1(2),f_1(3),....).$.. I prefer  that to  "the sequence $ f_1(n)$"  or   "the sequence $(f_1(n))$ " because it can be confusing if at some point you have to refer to a member $f_1(n)$ of the sequence or have to enclose an individual value $ f_1(n)$ in brackets..... In texts, different authors use different notations for sequences.
Comment: Thanks for your answer. What does the subscript $n$ in $(f_1(n))_n$ mean?


Fazer histograma em Python

Question: Olá!
Estou fazendo um histograma em Python, mas na linha histogram = Counter(decile(grades) for grade in grades) encontro erro com a função Counter.
Já fiz o teste utilizando o import collections mas não consegui.
A seguir as linhas até aqui desenvolvidas:
grades = [83, 95 ,91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
decile = lambda grade: grade / 10 * 10
histogram = collections.Counter(decile(grades) for grade in grades)

Answer: Mauro, o import realmente é necessário.
O erro está no for dentro do Counter, você enviou a lista e não o item da mesma:
import collections

grades = [83, 95 ,91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
decile = lambda grade: grade / 10 * 10
histogram = collections.Counter(decile(grade) for grade in grades)

Comment: Obrigado Daniel! Neste caso, qual seria estrutura adequada?
Answer: Coloque...
from collections import Counter

Comment: Como ele usou `collections.Counter`, o correto seria apenas `import collections`. Ou faltou complementar sua resposta colocando como seria ao fazer o `import` como sugerido.

Fazer histograma em Python


forward port 80 to 8080 failed

Question: I am trying to forward a port from 80 to 8080 (default to tomcat). below is what I added to the httpd file.
 <VirtualHost www.example.com:80>
      ProxyPreserveHost On
      ProxyRequests Off
      ServerName www.example.com
      ServerAlias example.com
      ProxyPass / http://localhost:8080/
      ProxyPassReverse / http://localhost:8080/
    </VirtualHost>

After adding this , there are no signs of any change. Is there anything wrong with the code?
Centos 5.9
apache 2.2
tomcat 7
whm/cpanel.
UPDATE:

My target domain is www.99rounds.com:80 direct to :8080
Update 2
After added the code from the answer, and removing the 2 lines of logs. I get:

Note that centos has built-in mod_proxy support, if I force it : loadModule ... It will give me the error saying its built in.
Comment: Yes, that will probably be inactive when added to most default configs.  Can you provide your existing configuration, and the output of `apachectl -S`?
Comment: @ShaneMadden got it updated.
Comment: There's config for the `www` version of the name in `/usr/local/apache/conf/includes/post_virtualhost_global.conf` and the non-www version in `/usr/local/apache/conf/httpd.conf`, probably with `ServerAlias` directives binding them to the other name -- which one of these is the one you added the configuration to?
Comment: `post_virtualhost_global.confGlobal` I added the below code from answer but still no forwarding.
Answer: I have a detailed answer on how I have setup Apache Reverse Proxy over here.
Looking at the configuration you provide:
<VirtualHost www.example.com:80>
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName www.example.com
  ServerAlias example.com
  ProxyPass / http://localhost:8080/
  ProxyPassReverse / http://localhost:8080/
</VirtualHost>

I would suggest the following instead. I am presuming some things—such as ErrorLog & CustomLog—but this is how I would set things up.  The key I believe is the ServerName & ServerAliascombined with the <VirtualHost *:80>:
<VirtualHost *:80>
  ServerName www.99rounds.com
  ServerAlias 99rounds.com www.99rounds.com

  ErrorLog /var/log/apache2/www.99rounds.com.error.log
  CustomLog /var/log/apache2/www.99rounds.com.access.log combined

  # Settings for Apache Reverse Proxy
  <IfModule mod_proxy.c>

    # Proxy specific settings
    ProxyRequests Off
    ProxyPreserveHost On

    <Proxy *>
      AddDefaultCharset off
      Order deny,allow
      Allow from all
    </Proxy>

    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/

  </IfModule>

</VirtualHost>

EDIT: Also be sure you have mod_proxy and mod_proxy_http enabled on your server:
sudo a2enmod proxy
sudo a2enmod proxy_http

Comment: This has nothing to do with port forwarding or CentOS and everything to do with Apache2 virtual host configuration. The error that is key is "VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results" Which basically means you have some virtual hosts set to an ip address "22.214.171.124:80" and then in the example I give it's "*:80"  So perhaps you should use my example, but change the config to read:  or  with your.domain.com being your domain or 220.127.116.11 being your IP.
Comment: I added this to pre_virtualhost_global.confGlobal and it worked. Before it was at post_virtualhost_global.confGlobal. I would +100 if I can.
Comment: a2enmod doesn't work on centos. And I have updated the question with your solution.
Comment: I was just about to update. That I fixed the * issue by defining the star to domain. Ill update the post in 1min.
Comment: Happy this worked out for you! Apache virtual host configs can be confusing. If you can, I would recommend that you setup a clean test server & experiment with differed named virtual host configs.
Answer: Tomcat and other application servers publish an AJP port that can be used to map request from a HTTP server. To do that you have to create a 'workers files' like this:
# server.workers.properties

worker.list=tomcat-server

worker.tomcat-server.type=ajp13
worker.tomcat-server.host=localhost
worker.tomcat-server.port=8009

8009 is the default value for the AJP port in a Tomcat server. You can find this value in $TOMCAT_DIR$/conf/server.xml. Then you have to indicate the previous file in the HTTP configuration file:
JkWorkersFile /location/of/the/file/server.workers.properties

<VirtualHost www.example.com:80>
  ServerName www.example.com
  ServerAlias example.com
  DocumentRoot /srv/www/
  JkMount /* tomcat-server

  <Directory />
    Options +FollowSymLinks
    Order allow,deny
    Allow from all
  </Directory>

</VirtualHost>

This configuration will pass all requests by www.example.com:80 to the AJP 8009 port, so the Tomcat server will get those requests and it will process them.
In the path set in DocumentRoot you have to put the links for each application in Tomcat's webapps directory because if you don't do that, the HTTP server will not be able to load resource files, like CSS and JS.

forward port 80 to 8080 failed


How to Proguard an android project and its modules and libs?

Question: I am using Android Studio,  my application uses many modules and libs
Is it possible to proguard all modules , libs and the application ? Or I can do it only for the app ?
Answer: If you enable Proguard for the app module, that is the module that includes the others, everything will be obfuscated.
To test it:

create a new project
add it a new module, let's call it lib
add some code to the lib, use this code in the app
enable Proguard for the app, not for the lib
in Android Studio:

Build -> Clean
Build -> Build apk
Build -> Analyze apk

You should see that all the code is obfuscated, lib and app.


Search and Replace Arabic in PHP

Question: I am doing a search and replace of a variable.
$search  = array('ي');
$replace = array('G');

echo str_replace($search, $replace, $building);

$building has the value of ي0009
The expected output is: 0009G, instead the output is G0009.
Any suggestions?
Comment: Seems like the replacement turned off RTL ;-)
Comment: Arabic language ist RTL (right to left) and other (western) languages are LTR (left to right)...
Comment: I know what the problem is, I am asking for a solution @Havelock
Comment: "Can not reproduce" it [works with diverse PHP versions](http://codepad.viper-7.com/8hQu5d)... What about your file/input encoding? Also str_replace [works perfectly](http://php.net/manual/en/ref.mbstring.php#109937) with UTF-8...
Comment: The first character of your string is actually ي , followed by 0009.
Answer: Working with multibyte encodings you must use mb_str_replace() directly, or ensure you got multibyte extension enabled.
You may set  string functions to be automatically overloaded by multibyte counterparts as this is supported by PHP and documented here: http://php.net/manual/en/mbstring.overload.php
Comment: With all due respect, it's rubbish. First [`str_repalce`](http://php.net/manual/en/ref.mbstring.php#109937) works perfectly fine with multibyte strings. Second, since you're proposing to overload with `mb_str_replace`, would you please post a link to the documentation or implementation of the proposed function.

Search and Replace Arabic in PHP


Comparison of variance between two samples with unequal sample size

Question: The primary goal of my analysis is to compare the variability in the response variable, Blood Pressure, between sample1 and sample2. The secondary goal is to test for a difference in means. I do not yet have the data but I know for sample1, n=167 and for sample2, n=998. They can be assumed independent.
My current plan for the data:
1) Perform a Shapiro-Wilk test to assess normality.
2) If the data is not normal, perform Levene's test of equal variance. If the data is normal, an F-test.
3) Perform a Mann-Whitney Test (Wilcoxon Test) to compare difference in means. Or alternatively, Welch's t-test if the data is normal.
My concerns:

I've read that when N is large the data can be assumed normal (Central Limit Theorem) but couldn't find what would constitute as 'large'. Could this data be considered normal?
I hypothesize that sample1 will have less variability in response, however given the large difference in sample size will Levene's test/F-test be reliable/ have enough power? Are there any tests of equal variance that are more robust to difference in sample sizes?
I've read that if the data is not normal you can try transforming the data. Would this also work for an F-test given that that the variance is likely to decrease after a transformation? Or would a non-parametric test be better?
Comment: +1.  Although this is a lot of questions for us, they are closely related and all are very thoughtful ones.
Comment: +1. I have been running a number of simulations recently given the number of options out there to choose from when modeling variance. I'll try to write out a longer answer below, but I think the best thing solution I've come across in my simulations is regression of squared residuals on group membership. I tried Levene test with different measures of center, GLS, SEM approaches, F, log squared residuals, ... I'll write up an answer in some time.
Comment: 30 is often given as the rule of thumb for "large enough"; it shouldn't be used blindly, but for analyzing a single variable it is useful. See https://stats.stackexchange.com/q/2541/5503 for some discussion. I'd suggest just before step 1 in your plan comes "plot the data" (then investigate a few of the outliers).
Answer: Location differences
Mann-Whitney does not test mean differences
I'll begin by knocking off the simpler questions. If your primary question about location differences is a difference in means, then you probably do not want a non-parametric test like the Mann-Whitney test. The Mann-Whitney test is a test of stochastic dominance. So given two groups A and B, if I were to randomly draw from A and B, which value would be greater. If they cancel out on average, then there is no stochastic dominance; the opposite follows. This test would work regardless of non-normality or heteroskedasticity. However, if you have non-normality and heteroskedasticity in particular, then this test is anything but a test of the mean-difference. The mean-difference can be zero, but you can easily have stochastic dominance of one group over the other. Given the choice, I personally may be more interested in a test of stochastic dominance, but they are not commonly explained like this in most applied literature I come across.
Non-normality may not be too important
Next issue is normality in relation to mean differences. We will bring up normality again in relation to variance differences as things work somewhat differently there. Unless you expect the data to be extremely non-normal, the sample sizes you have may be large enough to ignore questions of normality. If the data are extremely non-normal or you can hypothesize a theoretical distribution from which they may arise, then maybe it is better to run the model using that distribution, such as Poisson for count data or income. Also, certain transformations might make sense theoretically, such that you can expect to use them even before viewing the data. The point I'm trying to make is with relation to mean differences, heteroskedasticity may be more consequential in your situation.
If you have to examine normality, know that all other things held constant, statistical tests improve in their ability to detect differences given greater sample size. Shapiro-Wilk might be able to detect minor deviations from normality at the sample size you have. Additionally, if you do the test at all, you should probably do it on the data after subtracting off the group means. Most importantly though, making future decisions contingent on such preliminary tests can make your eventual decision flawed. I do not know of studies of the sort with normality testing, but there are such studies with heteroskedasticity-testing, see for one:

Zimmerman, D. W. (2004). A note on preliminary tests of equality of variances. British Journal of Mathematical and Statistical Psychology, 57(1), 173–181. https://doi.org/10.1348/000711004849222

Dealing with heteroskedasticity
So if your primary question about location differences is a difference in means, then my recommendation would be to compute the difference in means and use a test that can adjust for possible violations of heteroskedasticity. The most developed requiring very little additional computer time (wild bootstrapping is good but can take eons) are heteroskedasticity-consistent standard errors in econometrics. I would recommend the HC3, HC4 or HC5 variants. See:

Hausman, J., & Palmer, C. (2012). Heteroskedasticity-robust inference in finite samples. Economics Letters, 116(2), 232–235. https://doi.org/10.1016/j.econlet.2012.02.007
Cribari-Neto, F., Souza, T. C., & Vasconcellos, K. L. P. (2007). Inference Under Heteroskedasticity and Leveraged Data. Communications in Statistics - Theory and Methods, 36(10), 1877–1888. https://doi.org/10.1080/03610920601126589

These methods are more recently developed than Welch's correction and do not require you to know the correct model specification for the variance. So run a regression of the outcome on group, the coefficient is your mean difference, and the robust error correction corrects the p-value for heteroskedasticity. There are methods that allow you to simultaneously model the mean and variance such as generalized least squares, but normality of the data comes back into play in relation to the test of the variance. I hope the above helps in relation to questions about mean differences.
Variance differences
Brief simulation I conducted
I next turn to the other primary question about variance differences. I ran some simulations of this weeks ago. I assumed that the mean and variance of outcome was a function of the groups alone $-$ a simplifying assumption that would be met in say a randomized trial. I varied:

the distribution of the data, normal, or skewed ($\chi^2_8$ centered and scaled to meet mean and variance requirements $\approx$ skew of 1 asymptotically). The choice of $\chi^2$ is not ideal for generating skewed data especially under unbalanced design but I think it suffices.
balanced versus unbalanced design (1:3, so not as extreme as your situation).

And the maximum sample size I considered was 200 persons in both groups.
I tested the ability of the methods I considered to maintain nominal error-rate and statistical power. To knock off power questions now, at sample sizes below OP's, most methods displayed similar statistical power with regard to detecting variance differences. But not all had ability to maintain nominal error rate. So when I use performed relatively well below, I mean maintained nominal error rate.
Levene test with median and OLS on squared residuals may be good choices
The most standard way is the $F$-test. But unless your data are normally distributed, this test behaves very badly. So one can take it off the table. The next standard is Levene's test. If you are concerned about normality, you can robustify it by conducting Levene's test using the median in place of the mean in the formula for the test. In the simulations I conducted, and this approach seemed to perform relatively well across a variety of situations and should be available in major statistical packages. The finding in my own simulations is backed up by the recommendations from the NIST engineering statistics handbook: https://itl.nist.gov/div898/handbook/eda/section3/eda35a.htm.
However, I also found that you can take the results from the first regression you conducted to obtain the mean differences. Square the residuals from this regression, then regress this squared residual on the group variable again. I found this approach to testing the variance differences to perform well across all conditions in my simulation.
In summary
So to recap, if I were in your situation and wanted to make informed decisions a-priori assuming non-normality is not extreme, I would:

conduct the standard regression model regressing the data on group membership to obtain the mean difference, and use heteroskedasticity-consistent standard errors for inference
I would conduct Levene's test using the median as center rather than the mean. I might also use the regression of squared residuals approach.

Additional methods I tested were Levene's test using the Hodges-Lehmann median (a nice robust estimator which has a relation to the aforementioned Mann-Whitney) as the center; generalized least squares; and three methods from the structural equation modeling literature: diagonally-weighted least squares, and mean and variance adjusted OLS, and maximim likelihood with a sandwich estimator commonly referred to as MLM. The methods I focused on in the bulk of the text won out.
Comment: +1, great answer! Quick question: When you regress the squared residuals from the first model on the group indicator, do you use heteroscedasticity-consistent standard errors for inference or not? I ask because the in the ideal case of normally distributed residuals in the first case, they won't be in the second model, I believe.
Comment: @COOLSerdash Great question and no, I did not. When I was writing this answer, I wondered why I didn't. When I was creating the simulation (as self study), I realized this approach is asymptotically equivalent to the Breusch-Pagan test for heteroscedasticity. So I tried it this way and it continued to work under different conditions. I had expected the log squared residuals to perform better but that wasn't the case.
Comment: Thanks Jim. It's interesting to hear that the procedure worked fairly well even though the assumptions are most likely not met in terms of the residual distribution in the second model.


Explanation of this proof of $d\theta$ not being an exact form

Question: I have been reading Spivak's Introduction to Differential Geometry and I cannot get this. I have already seen other proofs of the following statement, and I get those, I just do not follow this one.

$d\theta$ is closed but it is not exact

I need some explanation, the proof is simple, but I do not quite get why is there a contradiction, the proof goes as it follows:
Proof: Let $\omega=d\theta$, and suppose there exists a $C^1$ function $f:\mathbb{R}^2\setminus \{ 0\} \rightarrow \mathbb{R}$ such that $\omega=df$, clearly this implies that $\partial f/ \partial x=\partial \theta / \partial x$ and  $\partial f/ \partial y=\partial \theta / \partial y$, and hence $f=\theta + constant$ on $\mathbb{R}^2\setminus L$, which is impossible. $\square$
Note:
Here $\omega$ is defined (as always) as $$\omega = \frac{-y}{x^2+y^2}dx+\frac{x}{x^2+y^2}dy$$.
I do not get why is it impossible, some explanation would really be appreciation, thanks in advance.
Comment: No worries, it's always good to check these things.
Comment: What is $L$ here?
Comment: L is the positive segment of the $x-$axis, i.e. $L=\{(x,y)\in \mathbb{R}^2 : y=0\text{ and } x>0 \}$
Comment: Should that be "...and $x \geq 0$"? As written $\Bbb R^2 \setminus L$ is not open.
Comment: Yes, you are right, my bad. I am sorry
Answer: This problem illustrates that $d\theta$ is a particularly misleading and hence poor notation for this $1$-form: It isn't the exterior derivative of anything!
(More generally the common notation $dV$ for a volume form on an oriented manifold suffers the same issue. For this reason I prefer a slightly more verbose notation like $\operatorname{vol}$ for a volume form.)
This notation also makes the provided proof possibly confusing. Here's a bit more detail:

If $\omega = df$ for some differentiable (and hence continuous) function $f$, then in particular that equality holds on the slit plane $$S := \Bbb R^2 \setminus L , \qquad L := \{(x, 0) \in \Bbb R^2 : x \geq 0\} ,$$
  where in particular we can define the usual coordinates $(r, \theta) : S \to (0, \infty) \times (0, 2 \pi)$, so that
  $$df \vert_S = \omega\vert_S = d\theta .$$
(The mentioned abuse of notation $d\theta$ makes a sidebar important here: In the preceding equation, $d\theta$ is the exterior derivative of the function $\theta$, and hence is defined only $S$; written there it is not the form $\omega$, but rather its restriction to $S$.)
So, on $S$ we have
  $$0 = df\vert_S - d\theta = d(f\vert_S - \theta) ,$$ and in particular (since $S$ is connected) $f\vert_S - \theta$ is some constant function $C$, that is, as claimed, $$f\vert_S = \theta + C .$$
On the other hand, $f\vert_S$ cannot be the restriction of a continuous function $f$ on $\Bbb R^2 - \{(0, 0)\}$: At any point $(x, 0)$, $x > 0$, in the slit, the limit of $f$ at that point as you approach from above the $x$-axis is $C$, but the limit from below is $C + 2 \pi$, so $\lim_{p \to (x, 0)} f$ does not exist, hence $f$ is not continuous there, a contradiction.

A much faster proof is available once you have access to integration: By Stokes' Theorem (in this case, the Fundamental Theorem of Line Integrals, essentially), if $\omega$ were an exact form, then we would have $\int_\gamma \omega = 0$ for any curve $\gamma$. But parameterizing a convenient closed anticlockwise curve that encloses the origin once---say, the unit circle---and computing directly gives $\int_\gamma \omega = 2 \pi$, a contradiction.
Comment: I am familiar with your last comment, that was the proof I had always seen, but your explanation makes it clear to me why the proof I asked for is also a valid one, thank you very much.
Comment: You're welcome, I'm glad you found it useful.
Answer: The reason is that $\theta+const$ (for any constant) is a function that has a jump along $L$ (a $2\pi$-jump, to be precise). Therefore, no smooth function defined on $\mathbb{R}^2\setminus\{0\}$ can coincide with it on $\mathbb{R}^2\setminus L$.


Android portrait keyboard pop up changing my orientation to landscape

Question: So i have a bug on andriod devices where the keyboard pops up during portrait mode and the background changes (taking the landscape media queries)
I am currently testing on 360x640 devices (HTC One, Samsung S4 etc)
I read here and other webistes to use (max-aspect-ratio: 13/9) for portrait and (min-aspect-ratio: 13/9) for landscape. However it is not working. This is my media queries for the portrait.
@media only screen
and (min-device-width:360px)
and (max-device-width:640px)
and (max-aspect-ratio: 13/9)
Someone please help me :)
Comment: Anyone? even willing to help :(
Comment: Please someone give me a hand? or tips?
Comment: Hi! Have you found any fix for this bug? I also have this issue. I haven't tested it on HTC devices, but it does happen on several Samsung devices. I tested it with Nexus and Motorola devices, but no issue with keyboard.
Comment: I use this tutorial and it helped me out~

http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/
Comment: I have this same problem.  looking for a solution on a galaxy s8
Answer: Using
<code>@media screen and (min-aspect-ratio: 13/9) {
</code>
instead of
<code>@media (orientation: landscape) {
</code>
seems to help. You just gott figure out a good aspect ratio that will cover most devices.
Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/


.bind() not working in firefox

Question: I have following simple javascript code which i wrote to scroll the terms and conditions textarea and after scroll reaches at the end of the terms and conditions textarea it should enabled accept checkbox , its working in chrome but not in ff and ie please help .
javascript code:
    $('#blogger_agreement').bind('scroll', function()
   { alert('hiii');
     if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)
       {
          $('#TermsOfService').removeAttr('disabled');
       }
    });

html :

<textarea name="blogger_agreement"  id="blogger_agreement" class="deadline_date"  rows="15" cols="15" style="resize: none;background-color:white; overflow-y: scroll; height: 350px;" disabled >
<?php
$file_handle = fopen(FOLDER_PATH_HTTP."terms_and_conditions.html", "r");
while (!feof($file_handle))
{
   echo fgetss($file_handle);
}
fclose($file_handle);
 ?>
</textarea>

        <input id="TermsOfService" type="checkbox" name="TermsOfService"  required="required" disabled="true" />

I Accept the Terms and Conditions of The Motherhood.

Comment: use $(this).eq(0) instead of $(this)[0]
Comment: @c-link applied not working it can't alert 'hiii' in ff and ie
Comment: Try `$('#blogger_agreement').bind('scroll', function () {
    if ($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
        $('#TermsOfService').prop('disabled', false);
    }
});`
Comment: @arun : applied not working , please see my updated quetion
Answer: From jQuery 1.7 on is the preferred method of attaching event handlers:
$('#blogger_agreement').on('scroll', function()

Even so, it should work. See this fiddle which works in Chrome 33 and Firefox 28 - alert is called.
Then see this fiddle which is similar to yours, but changes text. Both work in Chrome and Firefox (at least they do for me).
What version of jQuery, Chrome and Firefox are you using?
Comment: sorry for asking question wrong please see my updated question
Comment: @sameerpatil - is the problem that the checkbox is not enabled or that the alert does not show?
Comment: problem is : alert does not show  , it wont go further.
Comment: I tried .on,.trigger,.delegate,.live  ...... but nothing seems to work  please help ... (sorry for spelling mistakes if any ...)
Comment: @sameerpatil - does my second fiddle work for you in Firefox - do you see the change to accepted? If it does then it must be something different about your setup. Try using console.log() instead of alert() incase the alert is causing a break. Have you tried setting a breakpoint in the browser to see if the event handler is called?
Comment: I have tried your second fiddle it works on chrome but not on ff and ie , i also use console.log() but it appears that the event handlers .on or .bind are not getting called .....
Comment: @sameerpatil - interesting. It works fine for me. What version of FF are you using?
Comment: @sameerpatil - I have to step out, but will check back later.
Comment: thanks for all of your answers...... i got the reason why .bind, .on or any other jquery event was not called in ff and ie .... the reason was that the text-area i was scrolling was made disabled hence those events wont work ....... thanks again...
Comment: @sameerpatil - glad you got it.

.bind() not working in firefox


Remove from array of objectId using update mongoDB

Question: I have a model named courier, it has an array named order and orders has some ObjectIds of model order, how can I remove an element from orders array using update or something else ?
(for example removing an order with specific id)
Here is my model:
courier:
var courierSchema = new Schema({
    name: { type: String },
    orders:[{type:Schema.Types.ObjectId,ref:'order'}],
});

I tried this code but it fails :
courier.update({
                   name: 'Mahan'
               }, {
                    $pull : {
                      orders: {
                          _id: order._id
                      }
                  }
                }, (err, count, obj) => {
                    if(err) {
                        console.log(err);
                        return handleError(err, reply);
                    }
                    console.log(count);
                });

Is there any way to do this not using find, remove and then save ?
Answer: This would be the most efficient format to achieve what you are trying to do
db.collection.update({<cond to identify document}, {$pull: {'orders': {'id': <id>}}} )


Why jQuery triggerHandler() works but trigger() doesn't?

Question: Click an element using triggerHandler() works:
$element = $('#gwt-debug-location-pill-edit-div:visible');
$element.triggerHandler('click');

But, clicking it using trigger(), doesn't:
$element.trigger('click');

Why is that?

To replicate this (in Firefox and Chrome):

Go to https://adwords.google.com/select/home, and log in using your credentials
Tools and Analysis -> Keyword Planner
Expand "Enter or upload keywords to see how they perform"
Using browser's console, try to click on the locations box (marked in red in the screenshot below) via the two methods above (you'll need to inject jQuery into the page. I used jQuerify to do that.)
Comment: Think this answers it: http://stackoverflow.com/questions/3772537/triggerhandler-vs-trigger-in-jquery
Comment: Could you pinpoint the exact reason?
Comment: The .triggerHandler() method does not cause the default behavior of an event to occur. else everything is almost same..
Answer: Let's compare jQuery.fn.trigger and jQuery.fn.triggerHandler:
trigger: function( type, data ) {
    return this.each(function() {
        jQuery.event.trigger( type, data, this );
    });
},
triggerHandler: function( type, data ) {
    var elem = this[0];
    if ( elem ) {
        return jQuery.event.trigger( type, data, elem, true );
    }
}

The only real difference is the fourth argument, true, given to jQuery.event.trigger with triggerHandler.
Looking at jQuery.event.trigger, the argument is called onlyHandlers, and among other things, the documentation of triggerHandler notes that:

The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).

We can see where the default behaviour is actually triggered:
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {

In the case that onlyHandlers is false (trigger()), and no event handler stopped the default event from executing, the default action will then be executed.
With onlyHandlers being true (triggerHandler()), this will never happen.
So, for the trigger() case, it ends up executing click() on the target element, which triggers the state change correctly—but it turns out that, in both the trigger() and triggerHandler() cases, the click was already correctly fired up in the loop through the eventPath above:
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {

So trigger('click') ends up clicking the element twice (!) — presumably because click() doesn't return false, so the event default action is never prevented — whereas triggerHandler('click') only does it once.
This can be verified by stepping through the jQuery.event.trigger method with the inspector and seeing the selector open, then close again.
The question is if this what we should generally expect; it seems strange that an otherwise-working event trigger would cause double triggers in the case of a DOM-only reaction.


The midline of a triangle

Question: Triangle $ABC$ is isosceles with $AB = AC$. $P$ is a variable point on $AB$, and $Q$ is a variable point on $AC$, so that $BP = AQ$. Let $O$ be the midpoint of $PQ$. Prove that $d(O, BC)$ is constant, and determine the locus of point $O$.
I feel that it should be solved with the help of center lines, and that the locus of point $O$ will be the centroid of a triangle $ABC$, but I have not been able to prove it.
I need some hints. How can I start?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: When $|BP| = |AQ| = 0 $, where is $O$? Likewise, when $|BP| = |AQ| = |AB|$, where is $O$? That should give you a strong idea of what $d(O, BC) $ and the locus of $O$ is. Can you make that conjecture, then state where you're stuck in proving it?
Comment: In this cases the O will be the midpoint of the sides.
Comment: Right, it's the midpoint of different sides. So what is the only possible value of $d(O, BC) $? And what do you think the locus of $O$ is ? And as we vary $P, Q$, what happens to $O$?
Comment: O will describe the centroid of the triangle as P, Q change. d(O, BC) will be the height of the trapezoid PQBC. But I do not know how these should be proved.
Comment: Centroid is a single point. The midpoints of the sides  are not the centroid, so the locus of $O$ (which includes the midpoints of the sides) is not the centroid (although it happens to be true that the centroid is in the locus).
Comment: I mean O will describe the midline of the triangle as P, Q change
Answer: Let P be a point on AB of the isosceles triangle ABC.

Through P draw the red line parallel to AC. It will cut BC at X.
Through X draw the red dotted line parallel to AB, it will cut AC at some point T, say.
Since APXT is a //gram, AT = PX = PB = AQ. This means T is actually Q. Also, if $O_1$ is the midpoint of the diagonal PQ, it is also the midpoint of the diagonal AX.
Next, starting with some other P' on AB, and going through the similar process as the above, we get the corresponding pint $O_2$.
Applying the midpoint theorem to triangle AXX', we conclude that $O_1O_2 // XX'$. Result follows.
In the limiting case that when P moves to the midpoint of AB, that midpoint is $O_n$ for some n. The same thing happens to Q. We can say that the locus of O is the mid line of the isosceles triangle ABC.
Answer:
First we translate BP to find the Q on AC. For this we take the mid point of AB, M, and reflect P about it to get point P'. Now we draw a circle center on A and radius AP', it intersect AC at Q(why?). In triangle PP'Q, MO is parallel with P'Q and in triangle ABC P'Q is parallel with BC, therefore $MO||BC$, this property  holds for any position of Point P which is the start point of construction. In this way the locus of point O is a line that connects the mid points of legs AB and AC.

The midline of a triangle


Loguru: how to obfuscate data in logs

Question: Using the python logger I can obfuscate data like this:
import logging
import re
import sys

class MySensitiveFormatter(logging.Formatter):
    """Formatter that removes sensitive information."""

    @staticmethod
    def _filter(s):
        """Remove credentials."""
        result = re.sub(r"pass: .*", "pass: xxx", s)
        return result

    def format(self, record):
        """Obfuscate sensitive information."""
        original = logging.Formatter.format(self, record)
        return self._filter(original)

stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(MySensitiveFormatter())
logger = logging.getLogger("demo")
logger.setLevel("INFO")
logger.addHandler(stream_handler)

logger.info("This is a demo and here is the pass: secret")

prints => This is a demo and here is the pass: xxx
In loguru I cannot add a formatter/handler and filter removes the entire record (which is not what I want).  How can I achieve this using loguru?
Answer: This is the correct way provided by the loguru team:
def obfuscate_message(message: str):
    """Obfuscate sensitive information."""
    result = re.sub(r"pass: .*", "pass: xxx", s)
    return result

def formatter(record):
    record["extra"]["obfuscated_message"] = obfuscate_message(record["message"])
    return "[{level}] {extra[obfuscated_message]}\n{exception}"

logger.add(sys.stderr, format=formatter)

See loguru issue for details.
Answer: This is how it works:
def obfuscate_message(message: str):
    """Obfuscate sensitive information."""
    result = re.sub(r"pass: .*", "pass: xxx", s)
    return result

class LoguruInterceptHandler(logging.Handler):
    """Enable loguru logging."""

    def emit(self, record):
        """Get corresponding Loguru level if it exists."""
        try:
            level = loguru.logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # Find caller from where originated the logged message
        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        # filter sensitive data (this does the trick)
        message = obfuscate_message(record.getMessage())

        loguru.logger.opt(depth=depth, exception=record.exc_info).log(level, message)

use like this:
logger = logging.getLogger()
logger.handlers = [LoguruInterceptHandler()]  # overwrite old handlers
logger.info("This is a demo and here is the pass: secret")

Loguru: how to obfuscate data in logs


How to generate multiple output files from single input file that does not share naming convention in snakemake?

Question: I have searched this for some time now, and this thread is the closest I got, but could not get working with my setup.
What I want to do:
I have one text file where every line has an ID and a data point
1234 data2
5678 data3
...

I want to collect the lines that correspond to certain IDs, which I have in my config file, and write them to their own files named according to the IDs value (1234 or 5678)
# config.yaml
IDs:
    ID1: 1234
    ID2: 5678

When I did this without snakemake, I just looped over the list of IDs in my bash script and grepped the text file for them, but I just cannot accomplish this with snakemake.
Either I have an issue with wildcards in target, or my expand function gives all of the IDs to the grep command in shell, or when following that accepted linked answer, I get "missing input files for rule all: And_Laa A_log" I can share what I have now, but I think the correct way to do this is so far removed from what I have, that it will just confuse everyone:
configfile: "config.yaml"

# Trying to replicate stackoverflow answer
speakers = {
  "1": "And_Laa",
  "2": "A_log"
}

def get_speaker(wildcards):
#  return expand("{speaker}", speaker=config["speakers"])
  return speakers[wildcards.speaker]

rule all:
  input:
#    expand("{speaker}_wav-list", speaker=config[speakers])
    expand("{speaker}", speaker=speakers.values())

# Selecting all the audiofiles for the speakers from a very large file
rule select_speaker_files:
  input:
    wav=config["files"]["wavs"]
  output:
    speaker="{speaker}_wav-list"
  params:
    speaker=get_speaker,
  shell:
    'grep "{params.speaker}" {input.wav} > {output.speaker}'

Answer: First of all, I guess that what you call a "speaker" is not a value of the dict, but it's key. So you rule all should expand like that:
rule all:
  input:
    expand("{speaker}", speaker=speakers)

Next, this rule literally says: "I require two files with the filenames 1 and 2." But there is no rule that produce the files with these names. You have:
rule select_speaker_files:
  output:
    speaker="{speaker}_wav-list"

Thir rule claims: "I can produce a file which name ends in _wav-list." Definitely there are no rules that may produce something that the pipeline needs to create. You probably meant that:
rule all:
  input:
    expand("{speaker}_wav-list", speaker=speakers)

In this case the rules at least are in consistency.
Comment: Thanks! I did actually want the value, and the value to be in the grep command and output file. So I modified the Snakefile to this and it seems to work, though I think there must be another way give the wildcard to the shell command

`def get_speaker(wildcards): return wildcards`
`rule all: input: expand("{speaker}_wav-list", speaker=speakers.values())`
`params: get_speaker,`
`shell: 'grep "{params}" {input.wav} > {output.speaker}'`
Comment: Why do you need the function `get_speaker` in this case if it just literally returns the argument?
Comment: You're right, I don't. I just did not know how to access the wildcard in the shell but apparently `grep "{wildcards.speaker}"` does that. I tried it before with just {wildcards} and some other ways but that did not work.
Comment: The best (and recommended) way to access a wildcard from `shell` section is to use its name: `grep "{speaker}"`.
Comment: So I have now extended my script, and it seems to be working nicely. But if I try with just `{speaker}` instead of `{wildcards.speaker}` I get the `NameError: The name 'speaker' is unknown in this context. Please make sure that you defined that variable. Also note that braces not used for variable access have to be escaped by repeating them, i.e. {{print $1}}`
Comment: To answer your question I need to know the whole script that produces this error.
Comment: I'm pretty sure I'll run into a different error with my script quite soon so I think I'll create another question then and link it here (especially since there is a character limit in comments). You have been way too helpful already :)


Como selecionar todas as colunas menos uma em específico?

Question: Existe a possibilidade de selecionar todas as colunas de uma tabela:
SELECT * FROM wp_rw_programacao WHERE id = $id

Mas estou precisando eliminar do resultado a coluna id. É possível?
Comment: Não é possível. A não ser que você crie uma função pra fazer isso.
Answer: Não é possível pegar todas colunas menos uma ou algumas específicas.
Geralmente pegar todos já costuma ser um erro, fica pior quando tem exceções.
Quase sempre que alguém quer fazer isto é para digitar menos. Isto não é adequado.
Se quer pegar uma lista específica deve colocar todas elas. Se quer todos, ou seja, se mudar quer que as colunas diferentes sejam mudadas na query automaticamente, aí cabe o *. Quase nunca é o que a pessoa quer.
Faça da forma semântica correta que precisa.
Se quer realmente que venha a lista de colunas total menos uma teria que tratar isto fora do SQL.
Até existe uma solução automatizada onde você pode ler os dados do MySQL sobre esta tabela e gerar a query a partir disto, mas só deve fazer se realmente precisa que a query seja dinâmica de acordo com a estrutura atual.
Tem um exemplo de como fazer na resposta do Wictor Chaves (mas note que é fácil ter problemas de segurança se abusar disso se não souber bem o que está fazendo, principalmente se esse $id vier de fonte externa). Mas não faça isso para economizar digitação, seu código estará semanticamente errado se não é o que precisa e mesmo que não traga problemas agora trará no futuro.
Para fazer isso funcionar o sistema todo precisa ser feito pensando nisso.
Coloquei no GitHub para referência futura.
Answer: Desta forma você consegue:
SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '
' AND TABLE_SCHEMA = '<database>'), ' FROM
');

PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

Substitua
, <database> e <columns_to_omit>
fonte: https://stackoverflow.com/questions/9122/select-all-columns-except-one-in-mysql
Answer: Pode chamar os campos que desejar fazendo assim, exemplo:
SELECT campo1, campo2, campo3, campo4
FROM wp_rw_programacao
WHERE id = $id

Os únicos campos que vão ser retornados serão: campo1, campo2, campo3, campo4

Mais informação.

Não existe outra forma de ser feito. Veja aqui mais informações no StackOverflowpt.
Comment: @AtilaSilva eu tenho umas 60 colunas e seleciono na mão cada uma =] É uma chatice, mas nem sempre programação é divertido
Comment: Porém tenho muitas colunas.
Comment: Trabalho do cão para eliminar uma coluna , só para complicar o código , não vi uma razão para isto.


Can lmer() use splines as random effects?

Question: Say we're working on a random effects model of some count data over time, and we want to control for some trends. Normally, you'd do something like:
lmer(counts ~ dependent_variable + (1+t+I(t^2)|ID), family="poisson")

to include a quadratic shape for t. Is it possible to use some more sophisticated smoothing techniques like a LOESS smoother or splines to model that relationship?
Answer: If what you show works for a lmer formula for a random effects term then you should be able to use functions from the splines package that comes with R to set up the relevant basis functions.
require("lme4")
require("splines")
lmer(counts ~ dependent_variable + (bs(t) | ID), family="poisson")

Depending on what you want to do, you should also look at the gamm4 package and the mgcv package. The former is essentially formalising the bs() bit in the lmer() call above and allows smoothness selection to be performed as part of the analysis. The latter with function gam() allows for some degree of flexibility in fitting models like this (if I understand what you are trying to do). It looks like you want separate trends within ID? A more fixed effects approach would be something like:
gam(counts ~ dependent_variable + ID + s(t, by = ID) , family="poisson")

Random effects can be included in gam() models using the s(foo, bs = "re") type terms where foo would be ID in your example. Whether it makes sense to combine the by term idea with a random effect is something to think about and not something I am qualified to comment on.
Comment: But note that the call to `bs`  needs to be changed to `bs(t, df=4)`  say, because the naked call `bs(t)` just has the same effect as `t`


how to solve 'Object has been deleted or invalidated.' Realm exception

Question: i have different realm objects in different ViewControllers and from my  settingViewController i'm deleting all the data of app (the realm stored objects ) its working fine but when i move back to those viewControllers i got this exception :
<code>Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'
*** First throw call stack:
(0x180c0adb0 0x18026ff80 0x100a13e7c 0x1001bd54c 0x1001be77c 0x1860c288c 0x1860c2c3c 0x185eb78e8 0x185d775b4 0x185eb6d34 0x192375f40 0x185ef1c94 0x192375ccc 0x1001b97ac 0x1001bbe4c 0x1860bf030 0x1860bf198 0x1860ae298 0x1860c3c64 0x185e548c4 0x185d641e4 0x1836f698c 0x1836f15c8 0x1836f1488 0x1836f0ab8 0x1836f0818 0x1836e9ddc 0x180bc0728 0x180bbe4cc 0x180bbe8fc 0x180ae8c50 0x1823d0088 0x185dd2088 0x100121cc8 0x1806868b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>
i know its happening because system (kernel , iOS) dont knows that i've deleted those Realms Objects and system is trying to use that data which is not exists anymore (Correct me if i'm wrong) ,  any one can guide me on how i can fix this problem ???
Comment: Deleting a Realm file while you're still accessing it will lead to bad things like this. I suggest you stop accessing the Realm prior to deleting the file.
Comment: @jpsim thanks for responding man ,  can you  elaborate me a bit how to do it  ?
Comment: To stop accessing a Realm, you'll need to deallocate all instances that are backed by data from that Realm. That means `Realm`, `Object`, `Results`, `Lists`, `LinkingObjects`, as well as stopping any notifications you have that could still be listening to changes. You'll likely need to read up on ARC and autoreleasepools to learn more about how to do this: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html
Answer: I suggest you to make notification before deleting all your data to all view controllers, that manipulate with it:

Push notification from your settingViewController before wipe
Subscribe to this everywhere you need to clear objects.
delete references
perform clean in your settingViewController.

Or, other way - implement delegate pattern for your purpose. The idea is the same.
Hope this helps.
Comment: hey man thanks for responding , do you know any tutorial related to this ? about your first option , cause i got an idea what to do but no idea about how to do it
Comment: @remyboys, i think https://realm.io/docs/swift/latest/#realm-notifications is what you are searching


find minimum of a function defined by integration in Mathematica

Question: I need to find the minimum of a function $f(t) = \int_0^1\!g(t,x)\,dx$. What I did in mathematica is as follows:
f[t_] = NIntegrate[g[t,x],{x,-1,1}]
FindMinimum[f[t],{t,t0}]

However mathematica halts at the first try, because NIntegrate does not work with the symbolic t. Although Plot[f[t],{t,0,1}] works perferctly, FindMinimum stops at the initial point.
Any way to get around it? Thanks!
Comment: Also, it should be f[t_]:=... ; you need delayed evaluation instead of immediate evaluation of the RHS. Also changing the LHS of the definition to f[t_?NumericQ] might help. This is because FindMinimum[], unlike Plot[], does not have the HoldAll attribute.
Comment: http://stackoverflow.com/questions/3474961/find-minimum-of-a-function-defined-by-integration-in-mathematica
Comment: What's g[t,x]? If you have an explicit expression, we might manage to be more helpful.
Comment: Bah, I don't really hang around in StackOverflow... XD too bad my comment was late!
Comment: thank you guys!. next time i will ask on SO instead.
Answer: OP's equivalent question on Stack Overflow was already answered. This is the accepted answer by Andrew Moylan.

Try this:
In[58]:= g[t_, x_] := t^3 - t + x^2

In[59]:= f[t_?NumericQ] := NIntegrate[g[t, x], {x, -1, 1}]

In[60]:= FindMinimum[f[t], {t, 1}]

Out[60]= {-0.103134, {t -> 0.57735}}

In[61]:= Plot[f[t], {t, 0, 1}]

Two relevant changes I made to your code:

Define f with := instead of with =. This effectively gives a definition for f "later", when the user of f has supplied the values of the arguments. See SetDelayed.
Define f with t_?NumericQ instead of t_. This says, t can be anything numeric (Pi, 7, 0, etc). But not anything non-numeric (t, x, "foo", etc).


How to make this line

Question: l make my first site and have a one question.How to make this line?
enter image description here
Answer: Their are many ways you can make those lines. Personally, I would use an <hr tag which simply creates a line for you in HTML. Or in CSS, you can give a border-left:1px solid #FFCE76; color.

How to make this line


Filter a view on field on a user referenced entity

Question: Given:

A view with some field
A field with referenced entity on user entity, named: assigner
A filter on the field assigner

How i can filter by a list of user? if i apply the same filter on Authored by it works.
The only option view edit form shows me is a filter on text base input.
Answer: Before adding a filter on the user name you need a relationship for your field assigner. This in the advanced section of views. After you have set up the relationship:
User referenced from field_assigner
You can add a filter:
Name (autocomplete)
and choose the relationship:
field_assigner: User


Como criar ordenação com relacionamento de vários níveis no laravel 5.4?

Question: Eu realizei várias pesquisas para encontrar uma solução, porém só encontrei algumas bibliotecas que realizam a ordenação com apenas 1 nível.
<code>$anuncios = Anuncio::with(['veiculo' => function($q){
        $q->orderBy('nome', 'asc');
    }]);
</code>
Dessa forma está ordenando apenas pela coluna "nome", mas eu preciso ordenar pela coluna de outra tabela com relacionamento, por exemplo, "veiculo.marca.nome". Existe uma biblioteca que disponibiliza esse funcionamento ou um código que poderia resolver esse problema?
Comment: Coloque esses models na pergunta e os relacionamentos.
Comment: Vamos supor que tenho os seguintes Models: Paises, estados e cidades. Tenho uma listagem com todas as cidades de todos os países. Como ordenar as cidades a partir do nome dos países?
Answer: Eu aconselho a fazer da seguinte forma.
<code>$transformer = function(Anuncio $anuncio) {

$anuncios = $anuncio->veiculo->marca->nome;

 return $anuncios->orderBy('nome');
}
</code>
Obs. Não sei como estão suas relações, mas acredito que já seja possivel chegar por anuncio no valor de nome.
Comment: Em que lugar ficaria esta função? Dentro do controller?
Comment: Sim, o que eu fiz foi pegar o seu codigo e fiz uma collection, dessa forma fica mais facil de trabalhar os dados, no meu entendimento.
Comment: De certa forma, assim estaremos ordenando a collection e não o builder propriamente dito. Correto? Isso não pode trazer problemas de desempenho? Há algum exemplo de como fazer essa ordenação com paginação?
Comment: Pelo que vi do codigo não deve ser algo muito pesado, então logo isso deve resolver, caso chegue a crescer o ideal seria quebrar isso em serviços.Eu faria assim pelo menos.


Como converter um JSONArray em um array de Strings?

Question:  String mensao = "[\"brega_falcao\",\"SamiPietikainen\",\"TecRahul\",\"gpantuza\",\"mkyong\",\"mkyong\",\"YouTube\"]";

Mensao é o JSONArray  que quero converter.
Tentei isso mas não funcionou:
//Retiro o '[' do inicio e do fim ']' do array json
    String modificada = mensao.substring(1, mensao.length() - 1);

        List<String> lista = Arrays.asList(modificada);
        for (int i = 0; i < lista.size(); i++) {
            System.out.println(i + " " + lista.get(i));
        }

O problema é que ele imprime uma string  grandona e não criar um array de strings...(foi isso que eu mandamos o codigo fazer , ma não é o que queremos...)
Saida
0 "brega_falcao","SamiPietikainen","TecRahul","gpantuza","mkyong","mkyong","YouTube"

Enquanto o desejado é isso:
0 brega_falcao
1 SamiPietikainen
2 TecRahul
3 gpantuza
4 mkyong
5 mkyong
6 YouTube

Answer: Você precisa separar a String maior em Strings menores pelo separador (",") antes de passá-la para o Arrays.asList(...) utilizando o método split(String). Além disso, deve remover as aspas:
String mensao = "[\"brega_falcao\",\"SamiPietikainen\",\"TecRahul\",\"gpantuza\",\"mkyong\",\"mkyong\",\"YouTube\"]";
String modificada = mensao.substring(1, mensao.length() - 1);

Arrays.stream(modificada.split(","))
        .map(s -> s.substring(1, s.length() - 1))
        .foreach(System.out::println);

Para coletar a Stream como um array, você pode utilizar o método toArray. Exemplo:
String[] strings = Arrays.stream(modificada.split(","))
                         .map(s -> s.substring(1, s.length() - 1))
                         .toArray(String[]::new);

Uma observação importante: esse método funciona para o caso exemplificado por você, porém não funcionará adequadamente caso suas Strings contenham vírgulas ou caso hajam espaços próximo as vírgulas. Caso você precise levar esses problemas em conta, será necessário uma outra solução, como através do uso de expressões regulares.
Comment: Obrigado, mas como posso retornar um Array de String ao invés de imprimir, podeira adicionar mais essa função  a sua resposta?
Comment: @PenaPintada Quando você fala "array", você diz realmente um `array` ou uma lista (como no exemplo da sua pergunta)?
Comment: String[] mensao = new String[tamanho];
Comment: @PenaPintada Adicionado na resposta.


Joomla additional view override

Question: I'd like to know if it's possible to add an additional view override to my Joomla 2.5 Template without having to create an entirely new MCV model.
For example.
Currently I have an override for the categorylist. But I'd like to make another override for the categorylist and for that to work it'd need to be an available option in the backend aswel.
So I'd be able to choose between something like:
- categorylist
- categorylist-2

So say the override file is default.php, is it possible to add a default2.php and somehow make it available in the backend, or can I only do this by copying an entire com_content view and changing it so it's a new MVC model?
Answer: I had never tried this before, but on testing it did get this to work in a way. I'm not sure if this is exactly what you are looking for, but it should help. With this method, you would be able to create a menu item that links to this view.
Say you were wanting to create a new category layout. You already have overridden the default layout in your template as such templates/your-template/html/com_content/category/default.php and now you want a second version.
Make a copy of default.php and rename it default2.php. Then copy the default.xml file from components/com_content/views/category/tmpl/default.xml to templates/your_template/html/com_content/category/default.xml and rename this to default2.xml.
Open default2.xml and edit the title attribute of the layout tag at the top.
Go to the menu manager and add a new menu item and you should see your new title in the list!

Joomla additional view override


Android adapter unable to update

Question: I have an adapter and I want to add data to adapter.This is my source code:
private static class Random{
    public  JsonObject randomData=null;
    public  Integer badgeNumber=null;

    private Random(JsonObject randomData,Integer badgeNumber) {
        this.randomData=randomData;
        this.badgeNumber=badgeNumber;
    }
}

private static class Randoms{
    private List<Random> randoms=null;

    public Randoms(List<Random> randoms) {
        this.randoms=randoms;
    }
    public Random get(int position) {
        return randoms.get(position);
    }
    public int size() {
        return randoms.size();
    }
}
private static class RandomsAdapter extends BaseAdapter{
    private Randoms randoms;
    private LayoutInflater inflater;
    private RandomsAdapter(Context context,Randoms randoms) {
        this.randoms=randoms;
        this.inflater = LayoutInflater.from(context);
    }
    public void updateRandoms(Randoms randoms) {
        this.randoms=randoms;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return randoms.size();
    }
    @Override
    public Random getItem(int position) {
        return randoms.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position,View convertView,ViewGroup parent) {
        View view=convertView;

        if (convertView == null) {
            convertView=inflater.inflate(R.layout.random_bars,parent,false);
        }
        Random item=getItem(position);
        Log.w("testt",""+item);
        return convertView;
    }
}

And I am defining the adapter with this code:
Randoms randoms=new Randoms(randomsList);
randomsAdapter=new RandomsAdapter(this,randoms);
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(randomsAdapter);

When I try to add a data I am using this line
randomsList.add(new Random(result.get(i).getAsJsonObject(),1));

But this not working,I can't see any log with "testt" tag.How can I resolve this ?
I mean getView method is not working.
Comment: where you are calling `RandomsAdapter.updateRandoms(randomsList)` ?
Comment: When I call this method I am getting :The method updateRandoms(MainActivity.Randoms) in the type MainActivity.RandomsAdapter is not applicable for the arguments (List)
Comment: Ok,try as `Randoms randoms=new Randoms(randomsList);RandomsAdapter.updateRandoms(randoms)`
Comment: what is randomsList, where do you declare it?
Answer: after adding
randomsList.add(new Random(result.get(i).getAsJsonObject(),1));

call notifyDataSetChanged() on your adapter
randomsAdapter.notifyDataSetChanged();

Edit
((RandomsAdapter) randomsAdapter)notifyDataSetChanged();

Comment: I am getting this error:The method notifyDataSetChanged() is undefined for the type ListAdapter
Answer: As suggested by others, use
randomsAdapter.notifyDataSetChanged();
If you get an error like "notifyDataSetChanged() is undefined for the type ListAdapter", I guess it's because you're getting your adapter through getAdapter() or such method which returns a ListAdapter. In this case, you should cast it to either BaseAdapter or RandomsAdapter. For instance,
((RandomsAdapter) randomsAdapter).notifyDataSetChanged();

Comment: The method getAdapter() is undefined for the type ListAdapter

Android adapter unable to update


Why are my radio buttons not displaying?

Question: I'm working on enhancing a search form on a site I inherited. I'm trying to add a radio button set to allow the user to narrow potential search results, but I cannot for the life of me get the radio buttons to display. The label displays, but the buttons themselves do not.
Here's the function in template.php:
function ismiv3point1_search_block_form($form) {
    $form['search_block_form']['#title'] = '';
    $form['search_block_form']['#value'] = 'Search mysite.org';

    $form['submit']['#type'] = 'markup';
    $form['submit']['#value'] = '<input type="image" name="submit" value="Search the Site" src="/icons/search.png" alt="Search the Site" />';
    $form['submit']['#weight'] = 2;

    // this is the new field I'm trying to add
    $form['image_switch'] = array(
        '#type' => 'radios',
        '#title' => t('Image Switch Radios'),
        '#prefix' => '
',
        '#suffix'   => '',
        '#weight' => '3',
        '#options' => array(
            1 => t('Images'),
            2 => t('All'),
        ),
        '#default_value' => 1
    );

    return '

'.drupal_render($form).'

Sort by newest first

Sort by newest first

Sort by relevance

';
}

Here's the rendered source:
<form action="/"  accept-charset="UTF-8" method="post" id="search-block-form">

      <input type="text" maxlength="128" name="search_block_form" id="edit-search-block-form-1" size="15" value="Search mysite.org" title="Enter the terms you wish to search for." class="form-text" />

   <input type="image" name="submit" value="Search the Site" src="/icons/search.png" alt="Search the Site" />
   <input type="hidden" name="form_build_id" id="form-17ad7cfea143f9acf10cca6602a02df0" value="form-17ad7cfea143f9acf10cca6602a02df0"  />
   <input type="hidden" name="form_token" id="edit-search-block-form-form-token" value="65a199ea9da3f7a52ed4c2693012997b"  />
   <input type="hidden" name="form_id" id="edit-search-block-form" value="search_block_form"  />

    Image Switch Radios

Sort by newest first

Sort by newest first

Sort by relevance

</form>

Any ideas? Is it because the field is being added after the submit? The reason for that is because the submit is a graphic (the magnifying glass) at the end of the search box; we want the radio buttons to be positioned below that.

Answer: Form builder functions must return a form array, not a string, otherwise they won't work with drupal_get_form(). If you need to add markup before and after the form you you should use the #prefix and #suffix properties, or do it outside of the form function altogether.
Also the function signature for Drupal 6 should not contain the $form variable as an argument, but the $form_state variable instead. And you're currently setting the value (text) of the submit button to the HTML representation of a an <input> field which will never do what you want.
Try using code like this instead:
function ismiv3point1_search_block_form($form_state) {
  $form['search_block_form']['#title'] = '';
  $form['search_block_form']['#value'] = 'Search mysite.org';

  $form['submit']['#type'] = 'markup';
  $form['submit']['#value'] = 'Search the Site';
  $form['submit']['#weight'] = 2;

  // this is the new field I'm trying to add
  $form['image_switch'] = array(
      '#type' => 'radios',
      '#title' => t('Image Switch Radios'),
      '#prefix' => '
',
      '#suffix'   => '',
      '#weight' => '3',
      '#options' => array(
          1 => t('Images'),
          2 => t('All'),
      ),
      '#default_value' => 1
  );

  $form['#prefix'] = '
';
  $form['#suffix'] = '

Sort by newest first

Sort by newest first

Sort by relevance

';

  return $form;
}

EDIT
Just a bit of extra info on how to do this with a form alter hook:
function ismiv3point1_form_search_form_alter(&$form, &$form_state, $form_id) {
  $form['image_switch'] = array(
    '#type' => 'radios',
    '#title' => t('Image Switch Radios'),
    '#prefix' => '
',
    '#suffix'   => '',
    '#weight' => '3',
    '#options' => array(
        1 => t('Images'),
        2 => t('All'),
    ),
    '#default_value' => 1
  );
}