Is the IV chord a perfect fifth in disguise?

Question: They say the root of the IV chord is a perfect fourth away from the key's tonic. But isn't it a perfect fifth from the tonic (if we go the other way)? let's for the sake of coolness, call it a perfect fifth shadow.
So if we take the key of C:
F F# G G# A A# B [C] C# D D# E F F# G
If we go 7 semitones (perfect fifth) from the right of C then we get G,  the root of dominant V chord.
If we go 7 semitones (perfect fifth) from the left of C, then we get F, the root of "sub-dominant" IV chord.
Now the root of the chord. essentially defines the sound of the chord. So I'll just talk about the actual chords..
According to hooktheory, the IV chord is equally as popular as the V chord in music (and they are both more popular than the I chord), so that makes the V and IV the most used chords in all of music.
http://www.hooktheory.com/blog/i-analyzed-the-chords-of-1300-popular-songs-for-patterns-this-is-what-i-found/
So I think the IV chord is as popular as the V chord because they are essentially both perfect fifths, so maybe they're both dominant (?)
But we usually call the IV a sub-dominant perfect fourth. But it's equally as popular as the fifth. Maybe because it's just a reflective image of it. It's just the perfect fifth shadow raised an octave. I've heard from a variety of sources that the perfect fifth is the most important interval in music. according to mathematician Pythagoras, he said that after the octave, the most consonant interval in music is the perfect fifth which has a musical ratio of (3:2), whereas the octave has (2:1). Also in the wikipedia "Perfect Fifth" page, it says "The perfect fifth is more consonant, or stable, than any other interval except the unison and the octave." So people just gravitate towards consonant sounds.
And so in the key of C major (or any other major or minor key?) we're essentially just playing the tonic, and perfect fifth (G), and a perfect fifth shadow (F). Am I right on this or completely off?
Comment: Your question is confused betwee chords (IV and V) and intervals (perfect fifth). The IV chord contains a perfect fifth, of course, but that doesn't seem to be what you're asking about: you're asking whether IV is some kind of a dual of V, which it is, by symmetry.
Comment: I'm was mainly talking about the root of the chord. and chords essentially sound like their roots. so the root of F is F, root of G is G and I was comparing them to their key of C. but yeah.. good point.
Comment: Certainly an interesting theory. Not sure if anyone would be able to confirm it, seeing as we haver difficulty even confirming the more common explanations... +1
Answer: F is a perfect fifth from the root, but obviously in the other direction, so it's a bit like "moving the goalposts." If you're measuring G as up a perfect fifth from C, you have to measure F up from C as well, otherwise your system lacks consistency.
That said: you're homing in on the concept of harmonic dualism. This is a nineteenth-century German idea, and one of the outgrowths of it is that the IV chord is in some ways equivalent to the V chord because of this very reason: if the V chord is a perfect fifth above C, the "harmonic dual" is a perfect fifth below.
There are a lot of ways to explain this, but here's one:
The perfect fifth is one of the first intervals in the harmonic series, and this is why the fifth is so closely related to its parent pitch. In short, the parent pitch generates the fifth. One of the questions in dualism is: if we're emphasizing the fifth that is generated, let's look at the fifth below tonic, because it is what actually generates the tonic in the first place.
However, there's an added issue: one of the ideas with harmonic dualism is symmetry. And as it turns out, major and minor triads are symmetrical reflections of each other. So the connection is not between V and IV, but actually iv (minor!). The claim is thus that, while B (the chordal third of V) is the leading tone of C, A♭ (the chordal third of iv) is a different type of leading tone that leads down by half step to scale-degree 5:

Another outgrowth of this is that the plagal cadence (IV or iv to I) is "equivalent" in some way to the authentic cadence (V to I).
Comment: You're not the only one that doesn't see the implied relation; harmonic dualism is one of the lesser-respected branches of music theory.
Comment: Actually, now that I've googled it, the [picture provided on the Wiki page](https://en.wikipedia.org/wiki/Riemannian_theory#/media/File:Minor_as_upside_down_major.png) makes everything clear. I'd suggest simply adding a link to your answer!
Comment: Hm, I am not familiar with the idea of major and minor triads being "inversions" of each other. Clearly you don't mean "inversions" in the sense of changing the bass note, but I'm not sure what you do mean.
Comment: "Inversions" in this sense means "symmetrical reflections." Major triads have a M3 on bottom, m3 on top, but minor triads have the m3 on bottom, M3 on top.
Comment: Ah, got it. I am still not quite clear on how that implies a relationship between V and iv, though I do see some similarity to the borrowed vii°, which incorporates the flat-6th leading to the 5th scale degree that you describe.
Comment: ...and, coincidentally, I'm pretty sure that if I'd been able to finish the music theory course sequence at the first college I attended (where I sadly only stayed for one year), I would have been introduced to this; I believe the course was predicated on Riemannian ideas.
Answer: Fifths and fourths are inversions of each other. A perfect fifth and a perfect fourth add up to an octave. Note that in a typical "cycle of fifths" (also called a "cycle of fourths"), the bass line often moves up and down by fourths and fifths alternately (or fifths and fourths).
C up to F down to B up to E down to A up to D down to G then up to C. The moves are short and the range of the bass line is less than an octave (G to F) and so easy to sing or play.
Intervals that are inversions of each other have similar harmonic "meaning," differing in which is the bass note. The who thing of fourth vs fifth in the original question is essentially just a matter of terminology.
Comment: F down to B? That's a tritone, did you mean Bb, which then throws out the rest. To get back to C, there needs to be all 12 keys/chords in the loop.
Answer: Not completely off.  But a fourth is still a fourth.  If you play it a fifth below the tonic, yes, it's a fifth down, and yes, it has the same intervallic relationship therefore to the tonic.  But the tonic stays the tonic in any case, due to the construction of the chords themselves.
The reason (probably) that certain intervals "sound good" is that their frequency ratio is simple.  Octaves "sound alike" because their frequency ratio is 2:1, meaning that a sound an octave higher than a note vibrates twice as fast as that note.  Ratio for a fifth is 3:2, and a fourth is 4:3. (I'm leaving out the concept of "equal temperament"; feel free to look it up if you're interested.)  For contrast, a half step has a ratio of about 18:17.
So, not only do the notes have a close frequency relationship, they also share overtones, which are additional components of a sound that give it its character or timbre.  (For example, overtones are what makes a violin sound different from an oboe when they are playing the same note.)  Unless a note is a pure sine wave (a single oscillation between two points; a close approximation is running your finger around a wine glass), then it will have overtones.
If you pluck a guitar string, it will vibrate not only along its entire length, but simultaneously in twos, threes, fours and so on. This means that two notes an octave apart share a lot of overtones, and as the interval ratio becomes less simple, the two notes share less overtones.
Wandering around looking for pictures of a string vibrating in twos, etc. led me to this page, which has a diagram that lays it out very well.  It also has some beyond fascinating (to me at least) recordings of "Tuvan throat singers" who are able to emphasize overtones in their voice so strongly that it sounds like they're singing two notes at once.  You might be interested in giving it a listen.
Answer: I don't think any interval can be called the most important interval. They are all important. But, more to the point: I think you are mixing up the interval of the bass movement with the identity of the chord. In your example the important thing is that you are moving to the subdominant (IV) chord. It's important to understand that the bass moving down a fifth does not mean you are moving to the IV chord. The bass could move from DO to FA - down a fifth - but if the upper voices above FA move to RE and LA the chord is the supertonic (ii) chord. If the bass didn't move and stayed on DO you could sill move to the IV chord - a I V6/4 chord. There is no bass movement of a fifth, but we still get a IV chord. It isn't the interval of the bass movement that defines the harmony, it's the root movements and the chord identities (tonic, subdominant, dominant, etc.)
As to the popularity of the IV chord. It depends on style. In classical style you should look into the idea of functional and pre-dominant harmony. In functional harmony the IV and ii 6/3 are both pre-dominant chords and are very commonly used to lead to V. Functional harmony basically says the IV will precede the V by convention. For this reason the IV is very common found.
Comment: I would argue that the octave is *objectively* the most important, since without it you can't even have the concept of pitch-classes.
Answer: Here's a simple way to see it. A fourth and fifth are the same notes, but not necessarily the same interval in the same key. The IV chord of a C key is C  F A all together. If you raise the C, it is now F A C which is a one chord, which has a fifth. The answer is yes. A perfect fourth and fifth are really quite similar.
Answer: You are conflating multiple concepts. A "perfect fifth" is an interval, whereas a "IV chord" is a triad built on a scale degree. The interval is a more primitive "unit" of harmonic analysis than the scale-degree-triad.
When you say that the IV and V chords "are" perfect fifths, it appears that what you mean is that the root of each chord is a perfect fifth away from the tonic of the scale.
This is absolutely a reasonable thing to take note of! But on its own, it doesn't really mean much. Here are some questions you ought to ask yourself:

Why does the interval between the root of a chord and the tonic matter?
Why does the interval between any scale degree (whether used as the root of a chord or not) and the tonic matter?
What gives different scale-degree-triads different "functions" in harmonic theory? (Or, with less music-theoretical terminology: why do we differentiate between I, ii, iii, IV, ... chords?)

The important thing to take note of here is that the concept of "intervals" is insufficient to answer any of these questions, because they involve harmonic context, which is not included in our idea of an "interval".
So, let's start by eliminating the concept of chords from your question, and ask:

Is the 4th scale-degree really a "perfect fifth" in disguise?

When phrased that way, it's not clear what's "in disguise" here, because the obvious answer is yes, the 4th is a perfect fifth away from tonic. The next step is to ask about the connection with the 5th scale degree (which we'll need to consider if we want to eventually understand the relationship to the V chord):

Is the 4th scale-degree really "equivalent to" the 5th scale degree?

Well, here we need some notion of "equivalence". Yes, each scale degree is a perfect fifth away from the tonic. But the 4th degree is a fifth down, whereas the 5th degree is a fifth up.
In other words, in order to understand scale-degrees, we need to recognize that although our idea of "interval" doesn't include a direction, we need an idea of interval with direction. This is similar to how numbers don't have "direction" in mathematics, but it's sometimes necessary to discuss a "number with direction", which we call a "vector".
Let us take a step back and consider what harmony is. A musical harmony is not just a collection of pitches; it is a collection of pitches that change over time. Thus, the "direction" in our "interval with direction" is the direction in which a pitch moves over time. A "fifth up" is found when a voice starts on a particular pitch, and then moves to a pitch a 5th above that.
So, the relationships between scale degrees have something to do with when the scale degrees are played in relation to each other. If we imagine a voice moving from the 5th degree to the tonic, that is a "fifth down"; and if we imagine a voice moving from the tonic to the 4th degree, that is also a "fifth down".
Since we can take this idea of moving between scale degrees and apply it by chordal movements by simply discussing triads built on the scale degrees instead of scale degrees on their own, we have enough context to create a less misleading version of your original question;

Is the (function of the) harmonic movement V -> I equivalent to the harmonic movement I -> IV?

The answer is, essentially, yes, depending on context! The movement I -> IV could be considered an opportunity to recontextualize IV as the new "tonic", with I as the new "dominant" (V). Though note that in most contexts, I is preserved as the tonic. This is part of why the sequence I -> IV -> V -> I works well; I -> IV "sounds good" in the same way that V -> I does, but it introduces an ambiguity, since IV may now be treated as the "new" I. The IV -> V demonstrates that IV is not functioning as the tonic, since V includes the seventh scale degree, which would be a half-step lower if the 4th scale degree were the tonic. (Concretely: in C major, C M -> F M implies that we might be moving to F major, but F M -> G M shows that we can't be in F major because we have B natural.)
Answer: A lot of great replies here.  I love theory, but it all comes down to sound.  There is most certainly a connection, but they are not the same.  If you add a harmonic layer and turn each of the chords into dominant 7  (FACEb , CEGBb, GBDF) then it adds a direction to the progression.  So to reiterate what another person said,  the intervals between the pitches G C & F  are all  4th or 5th inversions,  but attaching harmony to the pitches creates a definite direction which makes each chord function differently in relation to each other.
Here is a fun interval experiment to try which helps show the difference between a static interval, and one in context.
play the notes  C and B together (middle C)   sounds awful!   add an E below, and a G above, and now what does it sound like?  (EBCG)  Answer:  a beautiful major 7 chord in 1st inversion.  great question!
Answer: If a person hears a combination of frequencies, the brain will generally try to identify groups of frequencies that share common factors, and those factors will themselves be perceived as pitches.  For example, if someone hears 220Hz (A3), 330Hz (E4), and 440Hz (A4), the brain will often perceive those together as a tone with a frequency of 110Hz (A2).  This effect is especially strong in the presence of distortion, which is why power chords are so popular on the electric guitar (an A power chord in a guitar's upper octave would have the above frequencies).
If the brain hears just two frequencies 220Hz and 330Hz (a fifth apart), the same effect will occur, though it's not as strong as with all three frequencies.  Likewise (though to an even lesser extent) if the brain hears just 330Hz and 440Hz (a fourth apart).  Note that with notes a fifth part, the perceived pitch will be that of the lower note, one octave down, but with notes a forth apart the perceived pitch will be that of the upper note, two octaves down.
Things get more complicated when chords are built up that include thirds, so I wouldn't say a IV chord is a perfect fifth in disguise, but intervals of fourths and fifths are very strongly related.  The relationship between a I and IV is the same as the relationship between a V and I, but the relative popularity of the V and IV perhaps best be expressed by thinking of them as being on opposite sides of the I; music which harmonically flits around both sides above a restful state can be more interesting than music that only deviates to one side of it.


Negative continued fraction of Euler Mascheroni constant

Question: $\gamma$, the Euler-Mascheroni constant, has the following simple regular continued fraction:
$$\gamma=[0; 1, 1, 2, 1, 2, 1,\dots]=0+
\cfrac{1}{
  1+\cfrac{1}{
    1+\cfrac{1}{
      2+\cfrac{1}{
        1+\ddots
      }
    }
  }
}$$
I wondered which would be its negative continued fraction, but after searching I have not found anything about it in the literature I have checked.
Just using rough approximation methods, I have derived that it seems that
$$\gamma=1-
\cfrac{1}{
  3-\cfrac{1}{
    2-\cfrac{1}{
      3-\cfrac{1}{
        2-\ddots
      }
    }
  }
}$$
(although there is an initial pattern in the alternating $2$ and $3$, this pattern ceases).
I would like to know if there is some way to transform a regular continued fraction into a negative continued fraction, to see if that transformation could give some valuable info about $\gamma$. Also, if the negative continued fraction of $\gamma$ is already known, it would be great if you could provide where I can consult it.
Thanks in advance!
Answer: I found this interesting research that I share with you in case you are interested in the relationship between the negative and positive continued fractions:
https://scholarship.claremont.edu/cgi/viewcontent.cgi?filename=2&article=1183&context=hmc_theses&type=additional
According to Definition 8, the first terms of the negative continued fraction of the Euler Mascheroni constant would be:
$$\gamma=[1,3,2,3,2,3,2,2,2,5,2,2,2,2,2,2,2,2,2,2,2,2,7,3,2,2,2,2,2,2,2,3,2,...]$$


Line integral and attraction of a material point by a material curve

Question: According to Newton's law of universal gravitation, a material point $P$ with mass $m$ attracts a material point $P_0$ with mass $m_0$ with a force directed from $P_0$ towards $P$, of size $k\cfrac{mm_0}{r^2}$ (further for simplicity k=1).
When point $P_0$ is attracted by $n$ points $P_1, P_2,\ldots, P_n$ with masses $m_1,m_2,\ldots,m_n$, to obtain the resultant force, the attraction forces of individual points must be added geometrically. If we denote the projections of the resultant on the axes by $X$ and $Y$, and the angle made by the vector $r_i=\overline{P_0P_i}$ with the $x$ axis by $\alpha_i$, we get
$$X=\sum_{i=1}^{n}\frac{m_0m_i}{r_i^2}\cos{\alpha_i}, \hspace{1cm} Y=\sum_{i=1}^{n} \frac{m_0m_i}{r_i^2}\sin{\alpha_i},$$
where $r_i$ is the length of the vector $r_i$.
Now let us establish that the attractive mass has a continuous distribution on the $\sigma$ curve. Then let's divide the curve into parts and find the approximate values of the projections of the resultant on the axes. Concentrating the mass of each part at any chosen point $P_i$ and taking into account that the mass of the $i$-th part is approximately equal to $f(P_i)\cdot\Delta s_i$, we obtain
$$X\approx\sum_{i}\frac{m_0f(P_i)\Delta s_i}{r_i^2}\cos{\alpha_i}, \hspace{1cm} Y\approx\sum_{i}\frac{m_0f (P_i)\Delta s_i}{r_i^2}\sin{\alpha_i},$$.
So far everything is clear to me. Unfortunately, I don't understand the next transition. How to explain this?
If all $\Delta s_i$ tend to zero, we get
$$X=m_0\int_{\sigma} \frac{f(P)\cos{\alpha}}{r^2} ds, \hspace{1cm} Y=m_0\int_{\sigma} \frac{f (P)\sin{\alpha}}{r^2} ds;$$
where $r$ is the length of the vector $r=\overline{P_0P}$, and $\alpha$ - the angle that this vector makes with the $x$ axis.
Comment: WQhat part of it don't you understand ? Explain.
Answer: This transition from the sum to the integral is essentially an application of the limiting process inherent to the definition of the Riemann integral. I'll break it down for you:

Discretization and Summation:
First, note that when you're approximating the forces from each segment of the curve, you're effectively discretizing the curve. The curve $ \sigma $ is divided into small segments, each of length $ \Delta s_i $, and the force due to each segment is computed using the approximate mass $ f(P_i) \cdot \Delta s_i $ located at a chosen point $ P_i $ within that segment.

Limiting Process and Integration:
The Riemann integral is, conceptually, the limit of the sum as the size of the segments tends to zero. That is, the curve is divided into smaller and smaller segments, making the approximation more accurate. If you let all $ \Delta s_i $ tend to zero (which means the number of segments is going to infinity, and the length of each segment is becoming infinitesimally small), then these approximating sums:
$$
\begin{align}
X & \approx \sum_{i} \frac{m_0 f(P_i) \Delta s_i}{r_i^2} \cos{\alpha_i} \\
Y &\approx \sum_{i} \frac{m_0 f(P_i) \Delta s_i}{r_i^2} \sin{\alpha_i}
\end{align}
$$
become the exact integrals:
$$
\begin{align}
X &= m_0 \int_{\sigma} \frac{f(P) \cos{\alpha}}{r^2} ds \\
Y &= m_0 \int_{\sigma} \frac{f(P) \sin{\alpha}}{r^2} ds
\end{align}
$$

Geometric Interpretation:
Think of the curve $\sigma$ as being made up of an infinite number of infinitesimally small segments. Each segment exerts a tiny force on the point $P_0$. The net force due to the entire curve is the sum of the forces due to all these tiny segments. This summation, in the limit as each segment size approaches zero, is represented by the integral.

In summary, the transition from the summation to the integral is a way of saying: "Instead of approximating the force due to each segment of the curve, let's compute the exact force by considering all the infinitesimally small pieces of the curve". This is the essence of integration, and this transition is a fundamental concept in calculus, often visualized in the move from Riemann sums to definite integrals.


Can I override a theme function from a contributed module

Question: Per this question, Can I modify guestbook.module safely? I have overridden theme_guestbook_entry() from the guestbook.module file.  The problem is that my modifications are not taking effect. (Yes, I rebuilt the cache.)
I am following these instruction here, http://drupal.org/node/11811. I notice they don't mention contributed modules at all. Am I able to override these?
Answer: The page you are referring is for Drupal 5.
In Drupal 6, you alter a theme function defined in a module by defining the theme function, as in the following code. (Replace mytheme with the short name of your theme.)
// Drupal 6
function mytheme_guestbook_entry($uid, $entry, $comment_entry = NULL, $zebra, $confirm_delete = FALSE) {
  // Your own code.
}

// Drupal 7
function mytheme_guestbook_entry($variables) {
  // …
}

In Drupal 7, if you just want to alter the variables passed to the theme function, you need to implement the preprocess function for that theme function.
function mymodule_preprocess_guestbook_entry(&$variables) {
  // Alter the values passed to the function, such as $variables['uid'], $variables['entry'],
  // $variables['comment_entry'], $variables['zebra'], or $variables['confirm_delete'].
}

The code I shown works whatever a theme function is implemented in Drupal, or a third-party module.


Robustness of GLM to link function

Question: When I first learned about GLMs I was taught that the link function wasn't that important so long as the domain and codomain match up. For instance, in a logistic regression we certainly need $g: (0,1) \rightarrow \mathbb R$ but beyond that we don't much care. I also learned that the canonical link makes the math easier but doesn't much matter beyond that.
More recently, though, I've encountered cases where the link function is estimated. If my teachers were right in that the results are generally robust to the link function, why would we ever want to go to all the effort of estimating it?
Comment: Can you give examples of places where the link function is estimated? It will help people to answer and understand this question.
Comment: I assume the OP is referring to cases where different links are tried & the one that optimizes a goodness of fit metric is chosen. IMO, this Q isn't so unclear it needs to be closed.
Comment: Most typical link functions yield lines (sets of predicted probabilities) that are very similar. You can also mimic a different curve w/ splines. It may help to read my answers here: [Difference between logit and probit models](http://stats.stackexchange.com/a/30909/7290) & here: [Is the logit function always the best for regression modeling of binary data?](http://stats.stackexchange.com/a/48137/7290)
Comment: @C11H17N2O2SNa: "Single index" models are an example of a case in which the link is estimated.  In fact, it's non-parametric!  See for example http://arxiv.org/pdf/1506.08910v1.pdf.
Comment: See here:  http://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353   for a case where the link function do matter.
Comment: @AndrewM, thanks for the link, I should have mentioned that single index models were what I had in mind.
Answer: If you're fitting only nominal categorical predictors (and models of full order), the link function will be of essentially no consequence --- in the sense that it doesn't alter the fit.
Here's an example using log and identity links with a Poisson glm. First the data (y is the response, a count, and x1f and x2f have the levels of the factors):
<code>     y    157  909  249  144  876  248   34  205   62   26  243   48
     x1f    1    1    1    1    1    1    2    2    2    2    2    2
     x2f    1    2    3    1    2    3    1    2    3    1    2    3
</code>
Here's the fitted values for the full model with interaction:
<code>    fitted(glm(y ~ x1f+x2f+x1f:x2f, family=poisson(link="log")))
        1     2     3     4     5     6     7     8     9    10    11    12
    150.5 892.5 248.5 150.5 892.5 248.5  30.0 224.0  55.0  30.0 224.0  55.0

fitted(glm(y ~ x1f+x2f+x1f:x2f, family=poisson(link="identity")))
        1     2     3     4     5     6     7     8     9    10    11    12
    150.5 892.5 248.5 150.5 892.5 248.5  30.0 224.0  55.0  30.0 224.0  55.0
</code>
We see the fit didn't change even though the link function did.
If you're fitting categorical models which leave some interactions out (such as a main effects only model), then the link function can matter, because under some link functions, those interactions may indeed disappear (leaving the smaller model suitable and more easily interpreted) --- but then those simpler, additive models won't be suitable for other link functions.
Continuing the earlier example, omitting the interactions:
<code>    fitted(glm(y ~ x1f+x2f, family=poisson(link="log")))
            1         2         3         4         5         6         7         8
    145.65183 900.94330 244.90487 145.65183 900.94330 244.90487  34.84817 215.55670
            9        10        11        12
     58.59513  34.84817 215.55670  58.59513

    fitted(glm(y ~ x1f+x2f, family=poisson(link="identity")))
            1         2         3         4         5         6         7         8
    238.72879 618.67616 268.07978 238.72879 618.67616 268.07978  21.90564 401.85300
            9        10        11        12
     51.25663  21.90564 401.85300  51.25663
</code>
Now we see the fitted values are indeed different. In this case, the log link gives a reasonable fit, but the identity link gives quite a poor fit.
If you're fitting continuous predictors, then it may matter quite a bit --- even ignoring the issue of interactions. One example would be with binomial GLMs --- in many cases, the fit with a probit and a cloglog link can look quite different, even though they both have $g$ taking $(0,1)$ to $\mathbb{R}$.
How much it might matter really depends on the specifics of the problem and your tolerance of deviation.
In many cases ease of interpretation matters more than differences in fit (at least where those differences tend to be small), but you have competition between how easy the link function is to deal with and how interpretable the linear predictor is, and you also have the issue of potential lack of fit: if your curve relating the mean of your binomial variates to the predictor(s) isn't symmetric, it might be much more interpretable to choose a more suitable link than to expand the model class.
Comment: +1 for the notion that interpretation is a primary motivation for choosing a link function, especially in binomial GLM.
Comment: Thanks a lot for the answer. Can you clarify the first paragraph? I don't see why the link doesn't matter in that case.
Comment: @alfalfa I've added some clarification of the intent, and an example that shows what I claim happens.

Robustness of GLM to link function


Is there a way to let users edit something only if they are a members of an OG?

Question: We have a number of different users who want to edit 'sections' of our website. This mostly aligns to Organic groups.
Is there a way to allow people to edit pages of a group which they are members of?
Comment: Have you visited this page: `admin/config/group/permissions`? There you can set permissions per group content and per group role respectively.
Comment: Yes, I see the group permissions. Is the solution to *not* allow in Drupal permissions but *do allow* in OG permissions. Is it that simple?
Comment: Why not? Have you tried it already? OG is a great module and has taken into consideration the group members and their actions. If that don't meet your needs, feel free to elaborate your thoughts.
Answer: You could, for sure, use the Group module to let users edit something if they are a member of some group. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.
For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.
For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Comment: Upvote for making me aware of this module and a potential solution. However, this current site is knee deep in OG. I'm afraid of confounding the situation with OG and Groups. For the time being I'd like to stick to a purely OG based solution for this.
Comment: Hey @rgchi ... I can see your current objection (challenge?) for using the [Group](https://www.drupal.org/project/group) module. Would you be interested in another approach using the [Rules](https://www.drupal.org/project/rules) module ?


Stand-alone animate function (like Jquery)

Question: I am currently using JQuery to perform a single task: animation of width on a div.  I really hate to be loading in the entire JQuery library for this single task and was wondering if anyone knew how to do a standalone function like:
<code>div.animate('56');
</code>
Where 56 is the percentage of the width I'd like the div to animate to.  If anyone has any advice or ideas, I'd really appreciate it!
Ben
Answer: To be honest, at 55kb (or 19kb if your server supports gzip), I'd just go with jQuery.
However, this page looks like it has some scripts and info to help you do what you want:
http://www.hesido.com/web.php?page=javascriptanimation
And the source is here:
http://www.hesido.com/web/animfunctions.js
Comment: Normally I would just go with JQuery but its going to be used for widgets on other sites...so I need it to be as lightweight as possible.  These links helped a good amount though, so thank you!
Answer: Certainly possible, but it's generally a pain to get animations working properly across the standard array of browsers.
If jQuery/jQuery UI is overkill for what you're doing, you may want to give smaller libraries like MooTools and moo.fx a try. Also take note that Google offers a javascript API to include libraries that are likely to already be cached on a user's browser.


Problemas ao percorrer json aninhado

Question: Tenho um response em json estou com um problemas para percorre-lo, o primeiro é que só consigo chegar até uma parte do json e não no valor que eu quero, o segundo que é que conseguente do primeiro é não estar percorrendo o número de response que ele me devolve. Por exemplo ele e retorna uma lista com 3 response porém só percorre e captura o valor de uma.
Minha Resposta JSON
[
  {
    "geocoded_waypoints": [
      {
        "geocoder_status": "OK",
        "place_id": "ChIJh5W-RbJzPIYRixw_andVya4",
        "types": [
          "establishment",
          "point_of_interest"
        ]
      },
      {
        "geocoder_status": "OK",
        "place_id": "ChIJeRXE_uZSeYYR7KP0sO1KcE8",
        "types": [
          "establishment",
          "food",
          "meal_takeaway",
          "point_of_interest",
          "restaurant"
        ]
      }
    ],
    "routes": [
      {
        "bounds": {
          "northeast": {
            "lat": 30.1853475,
            "lng": -93.3394257
          },
          "southwest": {
            "lat": 23.7202912,
            "lng": -99.1646927
          }
        },
        "copyrights": "Map data ©2018 Google, INEGI",
        "legs": [
          {
            "distance": {
              "text": "695 mi",
              "value": 1118019
            },
            "duration": {
              "text": "11 hours 20 mins",
              "value": 40783
            },
            "end_address": "Calz Gral Luis Caballero 732, Zozaya, 87070 Cd Victoria, Tamps., Mexico",
            "end_location": {
              "lat": 23.7202912,
              "lng": -99.1646927
            },
            "start_address": "301 Main St, Hackberry, LA 70645, USA",
            "start_location": {
              "lat": 30.0351393,
              "lng": -93.3394257
            }
          }
        ]
      }
    ]
  }
]

Obs:  Estou recebendo uma lista dessa mesma resposta, onde quero os valores especificos dessa lista.
Meu código
<?php
    $v = [];
    $aux = [];
     foreach ($json as $dest) {
            foreach ($dest->routes as $key => $value) {
                foreach ($value->legs[0] as $k => $val) {
                    $aux = array( "distancia" => $val->distance->text, "lat" => $val->end_location->lat, "lng" => $val->end_location->lng );
                }
            }
        }
?>

Obs: o valor que eu quero é o que está na varivel $aux, porém eu até consigo chegar mas ele só me retorna um dos valores da lista da resposta em json
Answer: Cada vez que você está montando uma array para adicionar na variável $aux, você está atribuindo o valor daquele momento e não adicionando ao vetor.
Você está fazendo assim:
$aux = array(...);

E deveria fazer assim:
$aux[] = array(...);

Ou
array_push($aux, array(...));

Comment: Então fiz como você falou, porém continuo tendo o mesmo resultado apena um único registro de uma lista de três, porém se eu subo um nível do loop ele me retorna os três registro mas não consigo pegar o valor que que quero.
Comment: Pode ser que no último `foreach` você está pegando apenas o primeiro item da `array`, tente assim: `foreach ($value->legs as $k => $val) {` . E no JSON que você mostrou só tem um resultado para a informação que você quer.
Comment: é verdade na resposta json só estava vindo um resultado.

Problemas ao percorrer json aninhado


Como colocar a lista de letras recebidas da base de dados na posição horizontal e juntá-la numa só página à lista de palavras da letra pesquisada

Question: Estou a construir a base de dados de um dicionário e fiz os código da página indice.php que mostra as letras do abecedário:
a) A lista aparece na vertical mas eu queria na horizontal.
b) Como juntar na mesma página a lista de letras e a lista de palavras?
Podemos ver aqui nestas páginas:
https://www.corampopulo.pt/login/dicionario-penal/indice.php
https://www.corampopulo.pt/login/dicionario-penal/lista.php

...
Segue o código da página 1...
<?php

    include 'conn.php';

    $sql = "SELECT DISTINCT(SUBSTR(`Palavra`, 1, 1)) As abc from Definicoes_palavras";

    $result = $conn->query($sql);

    ?>

    <!DOCTYPE html>

           <meta charset="utf-8">
    Indice das Letras

    <?php
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                ?>
                <a href='lista.php?letter=<?php echo base64_encode($row["abc"]); ?>'><? echo strtoupper($row["abc"]); ?>

                <?
            }
        }
    ?>

    <?php

    $conn->close();

    ?>

Segue o código da página 2...
    <?php
include 'conn.php';

$letter = mysqli_real_escape_string ($conn,htmlspecialchars(base64_decode($_GET["letter"])));

$sql = "SELECT Id,Palavra from Definicoes_palavras where Pronta != 0 AND Palavra LIKE '".$letter."%'";

$result = $conn->query($sql);

?>
<!DOCTYPE html>

       <meta charset="utf-8">

Letra <?php echo $letter;?>

 Voltar ao Índice

Seleccione um item da lista:

<?php
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            ?>

             <a href='fundamentacao1.php?word=<?php echo base64_encode($row["Id"]); ?>'><? echo $row["Palavra"]; ?>

            <?
        }
    }
?>

<?php

$conn->close();

?>

Answer: Para ele ficar lado a lado é só vc retirar o
 dessa linha:
<a href='lista.php?letter=<?php echo base64_encode($row["abc"]); ?>'><? echo strtoupper($row["abc"]); ?>

Ficando dessa forma:
<a href='lista.php?letter=<?php echo base64_encode($row["abc"]); ?>'><? echo strtoupper($row["abc"]); ?>

Se precisar espaçar a letras só adicionar:
echo " ";

no final da tag  que o &nbsp é um código HTML para espaçamento
Comment: Ok é isso mesmo Luan Brito... outra pessoa amiga já me tinha explicado quase ao mesmo tempo do seu post. Mas muito obrigado na mesma.
Comment: opa tranquilo então fera


O que são comentários WET?

Question: O que são comentários W.E.T., em Python? Por que eles são ruins?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Não é só para Python, isso funciona para qualquer código. O acrônimo significa Write Everything Twice que é oposição ao DRY (foi escolhido assim para fazer um trocadilho com o DRY). São os comentários óbvios, que dizem exatamente o que o código já está dizendo de forma clara e legível para qualquer programador.
Se você escreveu um código simples e óbvio não tem porque comentar o que ele faz. Se não conseguiu fazer isso, refaça o código. Comentários servem para dizer porque fez uma coisa não óbvia, porque tem algo ali que parece estranho, porque teve que mexer naquilo ou de onde veio a informação referência para fazer aquilo. Comentário não é para dizer o que o código faz.
<code>total = qtde * valor #calcula o total
</code>
Coloquei no GitHub para referência futura.
Ah vá? Se não tivesse o comentário eu nunca saberia!
Esses comentários só são aceitáveis quando está sendo didático em uma amostra para ensinar alguém como se faz, não para código em produção.
Quase todo comentário viola o DRY do código e te obriga a ficar atento a ele em qualquer mudança no código.
O WET não se aplica só a comentários, qualquer duplicação real, e que não são iguais apenas por coincidência, devem ser evitadas.
Comment: É diferente. Mas tem problema semelhante, porque se você mudar o código e não mudar a doc tá lascado. Porém como costuma fazer parte do contrato, não deve mudar muito, o ideal é nunca, e se mudar deve ter um cuidado extra.
Comment: Só para completar a ótima resposta: um dos piores problemas com comentários é que muitas vezes as pessoas não atualizam eles quando mudam o código. Então os comentários passam a ficar desatualizados e mentir para o programador, aumentando o tempo para entender o código.
Comment: Comentários que explicam a função e seus argumentos (e.g. JavaDocs) podem ser considerados WET também, caso seja algo muito óbvio? Ou é diferente, porque isso é uma documentação do código? Não sei se deveria fazer essa pergunta em uma pergunta nova.

O que são comentários WET?


How to determine fast if song has constant tempo

Question: I'm trying to remix a song (which I have yet to find) and add a basic drum track and some bass to it. I am basically looking for acoustic versions / covers of popular songs (with no drums), which I will add the drum track to. However in order for this to work, I need to know the tempo, and ideally that tempo has to stay the same for the entire song (or at least it shouldn't fluctuate from verse to verse). Songs recorded in the studio have constant tempo, but covers aren't professionally recorded, so there could be tempo fluctuations. So if my drum track goes steady and the song fluctuates just a bit, it will seem out of sync.
So my question is, is there a way to quickly tell if a song has constant tempo, or will I just have to pull the metronome out and start following the beats? I am using FL Studio for the editing and stuff, if that's any help.
Comment: Sorry if this is a dumb question -- but why don't you listen to the song you want to accompany on the drums with earbuds, while you are playing and recording yourself?
Comment: I don't have physical drums. I'm producing the drums electronically via a software called FL Studio. That means that the tempo needs to be perfectly aligned, or people will be able to hear the difference.
Answer: Even if music is professionally recorded in a studio, the tempo is not guaranteed to be precise unless they record with a metronome.  Having done many transcriptions over the years, I find it interesting that most bands don't use metronomes (and some don't even tune!)
Since most of the pablum on the radio is dance music and is electronically produced, it shouldn't be hard to determine a steady tempo.
An easy way to calculate tempo is the same method doctors/nurses use to take your pulse: count the number of beats in six seconds, then multiply by ten.  Boom, you have your tempo.  If you cue up a rhythm track and you find out your track and the recording start to deviate, then you know that their tempo fluctuates.
Fortunately, it's pretty straightforward to micro-adjust tempo in FL Studio; that, unfortunately, is just trial and error.
Last thought: always make sure you secure permission before using someone else's work.
Comment: Pablum........?
Comment: That's a good way to determine the tempo, but not a great one. In FL Studio I need the BPM to 2 decimal points, or the offset will be noticeable. With your method I can approximate the tempo, and then fine-tune it by going up or down. So far I've only found 1 acoustic song for which the tempo is perfectly constant, but I need more :)
Comment: @Tim ˈpabləm/
noun
noun: pabulum; noun: pablum

    bland or insipid intellectual fare, entertainment, etc.; pap.
Comment: @EduardLuca To be fair, you asked for a *quick* way to determine constant tempo, not the *most accurate*. To guarantee that **any** song you want to use will work, you'll either need to *transcribe* the music into FL Studio or learn it yourself and re-record with a metronome.  I've done both. Both require work, but both come out well. There are many things in life where the answer is: work.  Sorry, no get-finished-quick schemes here.
Comment: @Tim Not a problem :)
Comment: @EduardLuca a more precise way of calculating the tempo is to measure the duration of six beats (for example with a stopwatch) and divide 360 by that duration.  For example, if 6 beats take 4 seconds, the tempo is 90 bpm (that's 60 seconds per minute multiplied by 6 beats per 4 seconds, so if you time 20 beats for example instead of 60 you have to divide 1200 by the duration instead of 360).
Answer: What I would do in your case is put the acoustic track in my editor.
Then I would play the acoustic track while tapping out the beat on a mic and record the mic tapping on a separate track below the acoustic track.
Then I would add my drum track below the tapping track.
I would then be able to visually see, after just one time through the tune, if all the beats lined up by comparing the peaks of my tapping track with the peaks of my drum track.
If it's close, then I would stretch and shrink my acoustic and tapping tracks to fit.
And then mute my tapping track.
Hope this helps!
Comment: Thanks, it's probably the closest I'm going to get. This method is prone to (my) human error, but I guess that's the best thing I can do right now.
Comment: This solution is contingent upon *your* ability to accurately time your beats.  Try playing this little game here to see how inaccurate human-tapping is: http://www.concerthotels.com/got-rhythm
Comment: In my experience, foot tapping is pretty accurate.  Maybe it's more accurate than finger tapping.  Maybe you should kick the mic. :-)
Answer: Even two tracks made in a sequencer set to the same tempo will drift apart over the length of a song.  That's why the advanced sequencers like Cubase have tools for detecting tempo, aligning and stretching audio clips etc.    Forget about finding two versions of a song that fit together perfectly, concentrate on finding and using the tools that will MAKE them fit.  I don't know FL very well, but I think this is exactly the sort of music construction it's designed for.


"Piecewise Continuity" of $f$

Question: Suppose $M$ is a metric space and $\{ A_i \}$ is a countable collection of closed subsets of $M$ whose union is $M$ and s.t. $f$ restricted to $A_i$ is continuous for each $i$. Give an example to show that $f$ need not be continuous on all of $M$.
My instinct has been to construct some relatively simple function on $\mathbb{Q}$, but I'm wondering now if the example might be more pathological.
Comment: Any bijection from $\Bbb Q$ to $\Bbb N$, where each has its usual topology, will work and be pretty pathological. In what way did you think that you might make something worse?
Answer: Take $M = \{ 0 \} \cup \{\frac{1}{n}\}_{n=1}^{\infty}$, with the usual metric on $\mathbb{R}$. Define $f : M \rightarrow \mathbb{R}$ by $f(\frac{1}{n}) = 1$, $f(0) = 0$.
Then let $A_0 = \{0\}$, $A_n = \{\frac{1}{n} \}$, for $n=1,...$. $f$ restricted to each $A_i$ is trivially continuous, but $f$ is not continuous at $0$ (and $M$ is the union of the $A_i$).
Answer: Let $X$ be any countably infinite space whose topology is $T_1$ but not discrete, and let $f:X\to\Bbb N$ be a bijection. Give $\Bbb N$ the discrete topology. Then $X$ is the union of the countably many closed sets $\{x\}$ such that $x\in X$, and of course $f\upharpoonright\{x\}$ is continuous for each $x\in X$, but $f$ is not continuous on $X$. If $X=\Bbb Q$ with the usual topology, $f$ is not continuous at any point of $X$.
If you want the space $X$ to be compact, you can take it to be $[0,1]$ and use the function
$$f:[0,1]\to[0,1]:x\mapsto\begin{cases}
0,&\text{if }x=0\\
1,&\text{if }0&ltx\le 1\;.
\end{cases}$$
Take your closed sets to be $F_0=\{1\}$ and the intervals $F_n=\left[\frac1n,1\right]$ for $n\in\Bbb Z^+$; $f$ is constant and therefore certainly continuous on each of the closed sets $F_n$.

"Piecewise Continuity" of $f$


how do you know when you fully integrated something

Question: How do you know when you've fully integrated something?
For instance, the integral:
$$\int \tan^5(x)\sec^3(x)\,\mathrm{d}x$$
Firstly, how do I integrate this, and secondly, how do I know if the integral is fully done.
Comment: What is the difference between "integrated something" and "fully integrated something"?
Comment: Here, you've "fully integrated something" when you've "integrated something"... just like you've "fully died" when you've "died."  By the way, here the answer is $\frac{\sec ^7(x)}{7}-\frac{2 \sec ^5(x)}{5}+\frac{\sec ^3(x)}{3}$.
Answer: I integrate it observing that$$\int\tan^5(x)\sec^3(x)\,\mathrm dx=\int\frac{\sin^5(x)}{\cos^8(x)}\,\mathrm dx=\int\frac{\sin(x)\bigl(1-\cos^2(x)\bigr)^2}{\cos^8(x)}\,\mathrm dx$$and using the substitution $\cos(x)=y$ and $\sin(x)\,\mathrm dx=\mathrm dy$. And I check my answer computing its derivative and seeing wither or not I grt $\tan^5(x)\sec^3(x)$.
Answer: 1) Try something like $u=\sec(x)$, recall $$du=\sec(x)\tan(x)dx$$
2) The integral "is fully done" when the symbol $\int $ no longer appears.
Comment: I would rewrite the integral as $$\int \sec^2(x)\tan^4(x)\sec(x)\tan(x)dx=\int \sec^2(x)\big(\sec^2(x)-1\big)^2\sec(x)\tan(x)dx$$ Then, this is equal to $$\int u^2(u^2-1)^2du$$


Tracking the point until when the code ran

Question: I need to track the point until when the code ran. Consider the program given below:
function f() throws Exception{
    statement 1 //can throw exception
    statement 2 //can throw exception
    statement 3 //can throw exception
}

I need a mechanism to identify at what point the exception occurred, one way is to do this using exceptions, i.e. creating a variable in exception itself, or pass something by reference to function f and use it to identify at what point did the function the ran successfully.
Which is the better way, or is there any more elegant way to do this?
Comment: do you throw these exceptions or API that you are using?
Comment: I throw at catch the exception at some upper level, at that level I need to figure out a way if the code ran at some point, so that I can take specific actions.
Comment: Do you have the hand on `f`? Can you change it? If so, some "try catch" around each statement can help you wrap exception thrown in a custom one and handle the custom one later. Some aspect is probably another solution
Answer: A common mistake is to not print out the stack trace, or not print out the exception at all.  Don't do that in most cases, because you are throwing away useful information.
I would use the debugger to step through the code or find the exact point an exception is thrown, or you could read the stack trace for the exception.
public static void f() throws Exception {
    statement1(); //can throw exception line 101
    statement2(); //can throw exception line 102
    statement3(); //can throw exception line 103
}

When the stack trace says it threw an exception on line 101, 102 or 103, this tells you which statement it was executing.
If you need to do this at runtime, doing something different each time I would put each one in a try/catch block.
public static void f() throws Exception {
    try {
        statement1();
    } catch (TheException e) {
        doSomething1();
        // return or throw
    }
    try {
        statement2();
    } catch (TheException e) {
        doSomething2();
        // return or throw
    }
    try {
        statement3();
    } catch (TheException e) {
        doSomething3();
        // return or throw
    }
}

Comment: @AkashdeepSaluja reading the stack trace can be done at runtime as well, however you need to know what the line numbers mean. A better approach is to use a different exception whenever you expect different behaviour, or place each statement in it's own try/catch block.
Comment: I need it at runtime, I guess the solution wont work.
Comment: @AkashdeepSaluja I have added an example of using multiple try/catch blocks.
Comment: using line numbers at runtime is pretty risky I guess, making custom exceptions is a viable option though.
Comment: @AkashdeepSaluja they could be different to imply a different actions should be taken.  You should look at what built in exceptions there are and use these or have custom exceptions sub-class the most appropriate exception.
Answer: I would like to do a little trick, but I'm not sure whether it is correct.
public class ExceptionLevel extends Throwable {
    private int value;

    public ExceptionLevel (int v) { value = v; }
}

Then, when you throw an exception (it need to have a Throwable(Throwable cause) constructor), you should
} catch (Exception e) {
    e.initCause(new ExceptionLevel(1)); // from the first statement
    throw new AnyException("message", e);
}

To handle all of this (inside of a global catch block)
int statement = e.getCause() == null ? 0 : ((ExceptionLevel)e.getCause()).getValue();

I think you understand my main idea. You may improve it a little bit by making ExceptionLevel as last cause in your chain of exceptions.
Comment: I would use a different exception for different behaviour or use a text `message` if I didn't want lots of Exception classes.
Comment: This is probably a solution but the original exception gets lost, and that's bad
Comment: @RC., we can build a chain of causes, there is nothing to loose


Action of a compact Lie group is a proper action

Question: I want to show that the usual action of $U(1)$ on $S^3$ given by $e^{i\theta}\cdot(z_1,z_2)=(e^{i\theta}z_1,e^{i\theta}z_2)$ is a proper action.
It seems that the following more general statement should be true

Any action of a compact Lie group is a proper action

Recall that the action of a topological group $G$ on $X$ is a map $G\times X\rightarrow X$ given by $(g,x)=g\cdot x$. The action is said to be proper if the map $G\times X \rightarrow X \times X$ given by $(g,x)\mapsto(g\cdot x,x)$ is a proper, that is the preimage of every compact set is compact.
I have having trouble proving this: Let $U\subset X\times X$ be compact.The projections $\pi_1,\pi_2:X\times X\rightarrow X$ onto the first and second coordinates are continuous. Therefore $\pi_1(U)$ and $\pi_2(U)$ are compact in $X$.
I am unsure what the preimage of $U$ is however. Obviously it is $\{(g,x)\in G \times X \text{ such that }(g\cdot x,x) \in U\}$ But I do not know how to continue.
Answer: Let $f:G\times X\rightarrow X\times Y$ defined by $f(g,x)=(gx,x)$ and $U$ be a compact subset of $X\times X$, $\pi_2(U)=V$ is compact since $\pi_2$ continuous. $f^{-1}(U)\subset G\times V$ and is closed thus it is compact since it is a closed subset of a compact set.
Answer: Knowing that the action is continuous then the orbit map $\mathcal{O}_x:G\to X$ is continuous.  Therefore assuming $U\subseteq X$ is compact and $X$ is Hausdorff (this is generally assumed for most applications, but please specify if this is not allowed) then we find that $U$ is closed in $X$.  Therefore $\mathcal{O}_x^{-1}(U) \subseteq G$ is closed, and thus compact since $G$ is compact.  Therefore $\mathcal{O}_x^{-1}(U)\times U$ will be compact in $G\times X$.
Comment: This is good enough for what I am doing since since $S^3$ is Hausdorff. Out of curiosity and for the benefit other people who make see this question in the future: Is the statement true if $X$ is not Hausdorff?
Comment: @Milkman From what I've seen in the literature, proper actions are generally only defined for Hausdorff or locally Hausdorff sets $X$.  I'm not sure it's technically defined for arbitrary topological spaces.  The main reason why I see this being an issue is that getting rid of the Hausdorff condition may generally yield pathological examples where we don't get nice quotients.  The only theorem which I feel is more general is the homogeneous space construction theorem where the group action needs to be transitive, but it can act on an arbitrary set.


I want to know how independent two variables are

Question: I have no formal training in statistics so please correct me if I use the wrong terms as I try to explain my problem.
I have a set of data (less than 80 points) with essentially 1 single outcome (a float we will call dcl) that can potentially depends on 10 of other variables, most of them floats maybe one or two boolean.
While I might ask some multi-variate regression question later, let's start with something simple.
Historically, people in my field have focused on the strongest correlation between dcl and variable J and some of my data suggests some other dependence on a float Re which is I'm sure at least weakly correlated with 'J' as they share some variables in their respective expressions. So my first question is how do I test the correlation and/or the independence of 'Re' and 'J' on the outcome 'dlc'? Intuitively and physically, I expect 'dlc' to depend strongly on 'J' and weakly on 'Re'. How do I prove this with a statistical analysis?
Here are a few graphs to illustrate the data:

Final point, in terms of software, I have python and R installed, I'm fairly proficient in python but I just installed R and know pretty much nothing about it.
EDIT 1:
Following gung's suggestion, I ran my dataset through R:
Call:
lm(formula = dcl ~ J + I(J^2) + Re + I(Re^2), data = df)

Residuals:
    Min      1Q  Median      3Q     Max
-9.0078 -3.7930 -0.4458  2.0869 21.2538

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)  1.648e+01  1.232e+00  13.380  < 2e-16 ***
J           -2.662e+00  3.773e-01  -7.054 6.58e-10 ***
I(J^2)       1.096e-01  2.071e-02   5.293 1.10e-06 ***
Re           1.966e-06  1.621e-05   0.121    0.904
I(Re^2)      2.191e-11  3.441e-11   0.637    0.526
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.369 on 77 degrees of freedom
Multiple R-squared: 0.4831, Adjusted R-squared: 0.4562
F-statistic: 17.99 on 4 and 77 DF,  p-value: 1.818e-10

So now I need some help to decipher this (but I will look into R documentation too). I don't know if it's relevant but on physical grounds only, it's probable the dependency in J is $dcl \sim \frac{1}{\sqrt{J}}$. Can I put this directly into the model? Does that already tell me something about the dependency on $J$ vs $Re$?
Call:
lm(formula = dcl ~ J + I(J^(-0.5)) + Re + I(Re^(-0.5)), data = df)

Residuals:
    Min      1Q  Median      3Q     Max
-7.8119 -3.0097 -0.8504  1.8506 12.1439

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)   8.175e-01  1.634e+00   0.500   0.6184
J            -2.946e-01  1.258e-01  -2.343   0.0217 *
I(J^(-0.5))   4.516e+00  7.053e-01   6.403 1.09e-08 ***
Re            3.332e-05  6.684e-06   4.985 3.72e-06 ***
I(Re^(-0.5))  6.009e+02  1.354e+02   4.438 2.98e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.426 on 77 degrees of freedom
Multiple R-squared: 0.6487, Adjusted R-squared: 0.6305
F-statistic: 35.55 on 4 and 77 DF,  p-value: < 2.2e-16

> model = lm(dcl ~ J+I(J^(-0.5)) + Re+I(Re^(-0.5)), data=df)
> summary(model)

EDIT 2: OK I'm starting to understand things better. Also, again based on physical grounds, I would think that the dependency is more something like $dcl ~ \frac{1}{\sqrt{J}} Re^{n}$ with possibly other variables in that product that I ignore. So when I enter such model in R (can I still use lm for something non-linear?), here is what I get:
Call:
lm(formula = dcl ~ I(J^(-0.5)) * I(Re^(-0.1)), data = df)

Residuals:
     Min       1Q   Median       3Q      Max
-10.5363  -3.0192  -0.2556   1.4373  17.1494

Coefficients:
                         Estimate Std. Error t value Pr(>|t|)
(Intercept)               -43.220      9.164  -4.716 1.03e-05 ***
I(J^(-0.5))                63.813     11.088   5.755 1.62e-07 ***
I(Re^(-0.1))              124.245     24.038   5.169 1.77e-06 ***
I(J^(-0.5)):I(Re^(-0.1)) -142.744     27.269  -5.235 1.36e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.668 on 78 degrees of freedom
Multiple R-squared: 0.6042, Adjusted R-squared: 0.5889
F-statistic: 39.68 on 3 and 78 DF,  p-value: 1.122e-15

Does that 4th line tell me something about the dependence between $J$ and $Re$? What kind of tools could I use to get an estimate on the exponent on Re? Because right now I'm just trying a few different numbers empirically to see how the errors evolve. Next for me is to plot the dcl vs the new model and see how well the data collapses visually...
EDIT 3:
In the end, I used nls to explore the possible exponents of my fit. I also removed some outliers in my data that used a different experimental method. I settled on a fit that gave me decent Pr(>|t|) and residuals and which visually produce a decent fit. The last outlier is actually another experiment with a different setup, but one that I trust. So in a sense it's good that it shows up as an outlier as it hints at other parameters that need to be explored. Thank you gung, I accept your answer as I believe it guided me in the right direction.
> model = nls(L.D ~ C*I(J^(c1))*I(Re_s^(c2)), start=list(C=10,c1=-0.25,c2=-0.25),data=df)
> summary(model)
Formula: L.D ~ C * I(J^(c1)) * I(Re_s^(c2))
Parameters:
   Estimate Std. Error t value Pr(>|t|)
C  57.20389   26.40011   2.167   0.0337 *
c1 -0.27721    0.05901  -4.698 1.27e-05 ***
c2 -0.16424    0.04936  -3.327   0.0014 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 4 on 70 degrees of freedom
Number of iterations to convergence: 8
Achieved convergence tolerance: 2.91e-06

Comment: All models can be approximated by a Taylor series, i.e. a polynom of sufficiently high order. However, if you know the model from the science, you should use it. In fact, the second fit shows that the `dcl ~ I(J^(-0.5))`relationship is significant. Now you need to consider how Re could factor into this. Could it possibly modify the relationship between dcl and J? Than look at interactions.
Answer: +1 for a clearly laid-out question.  Regarding terminology, people use terms in different ways--unfortunately, terms are not fully standardized.  However, multivariate regression usually means regression when there is more than one response variable, whereas multiple regression usually means regression when there is more than one explanatory / predictor variable.  Your case is clearly the latter, so the way you asked the question, and the tags you used, is correct.
From looking at your plots, you will need a multiple regression model with both $J$ and $Re$ included.  Moreover, it looks like the relationship between these and $dcl$ is curvilinear for both variables, so you will need to include quadratic terms for both variables as well (i.e., $Re^2$ and $J^2$).
As for software, I'm sure Python can do this, but I'm not savvy enough with Python to tell you how.  It's also pretty easy with R, something like the following code should do the trick:
df = read.table(file="<some_file_name>", header=TRUE, sep=",")
model = lm(dcl ~ J+I(J^2) + Re+I(Re^2), data=df)
summary(model)

I'm assuming here that your data are in a csv file where the first line lists column / variable names (headers).  There is also a library in Python that allows you to call R from within Python, which you may feel more comfortable with, but I'm not very familiar with it.
Update:
Something that occurs to me here is that creating squared terms will generate a little bit of multicollinearity.  What you could do is turn your variables ($J$ and $Re$) into z-scores first (you should be able to use ?scale) and then form squared terms.  It's perfectly reasonable that $dcl$ is a function of the reciprocal of the square root; there's no reason you can use that.  As for the results of your second model, they look pretty similar to the results from the first model to me, and even a little better.  You want to be careful to ignore the stars and focus on the residual standard error and the multiple R-squared instead, and both of those metrics improve ever so slightly (note that this would be more complicated if you had differing numbers of variables in the two models).
As for the interpretation of R's output, a one unit change in a covariate is associated with an Estimate units change in the response all things being equal.  (Note that it will not be possible for, say, $J$ to change without $J^2$ changing also, so you would need to do both.)  If you didn't do a power analysis in advance with the intention of being able to differentiate a specific Estimate magnitude from 0, the p-values probably mean little.
Update2:
(I may not be the best person to advise you; I also try to avoid saying things that are completely foolish, but my track record is middling. ;-)  Looking at your third model, and the path we've taken to get there, makes me think of a couple of things that are worth bearing in mind:  First, it is strongly advisable not to drop simpler terms because they are not significant or even because it leads to a 'better' model (see here: does-it-make-sense-to-add-a-quadratic-term-but-not-the-linear-term-to-a-model, and here: including-the-interaction-but-not-the-main-effects-in-a-model--@whuber's answers especially, for example).  Second, as we look at the data, decide on some covariates to try, model them, and then try something else, we are data dredging.  This is rather worrying.  (To see / understand this better, you may want to read my answer here: algorithms-for-automatic-model-selection.)  Doing the things we've been doing here, and running simulations as we discussed in the comments, can help you to work though how you are going to think about what you find in your next experiment / how you plan for it.  However, if you decide to draw conclusions / say something about these data on the basis of this, the risk of saying something completely foolish is very high.  This is true even for the first iteration where I looked at your top plot and suggested including both variables with squared terms.  You are probably on reasonable grounds to suggest there there may be a curvilinear relationship with both variables, but I would be cautious about firmly concluding more.  (Note, for example, that although the terms in the last model have lots of stars, the residual standard error is larger and the multiple R-squared is smaller.)  If, based on these data and scientific knowledge, you can come up with a couple of possibilities, you can design an experiment with your colleagues explicitly to differentiate amongst those possibilities.
As far as interpreting the final model, the fourth line is an interaction.  This does not mean that $J$ is dependent on $Re$  or vice versa (although, they are clearly correlated).  Rather, this means that the effect of, say, $J$ on $dcl$ depends on the level of $Re$.  This is a difficult and nuanced concept.  The way I typically explain it is to imagine if someone asked you a question about the effect of two variables on a third, would you use the term 'depends' or the phrase 'that doesn't matter'?  For instance, if someone asked you about the effect of someone taking the birth control pill, you would say something like, 'Well, it depends, if you're a woman, it stops you from ovulating, but if you're a man, it doesn't'.  Alternatively, if someone asked about how high a shelf someone can reach if they're 5'8" (173 cm) and being male versus female, you might say, 'that doesn't matter, if you're 5'8" you can reach a shelf that is 7' high whether you're male or female'.
Comment: OK I will need time to understand all that you said but on your last point, yes the experiments were not performed to explore the dependency in $Re$ so I understand this probably limits the amount of information one can extract from the data. I generated a few points myself using numerical simulations (where only $Re$ changes and not $J$) and I want to know if the trend I see is also present in the rest of the experimental data.
Comment: I'm a big fan of simulations. They can be a good way to explore your data & help you think about the possibilities that lay behind them. I would use them to plan a *future* experiment rather than to draw conclusions about *this* experiment, though. EG, they could guide you towards where to sample data from (in the $(J, Re)$ space) in your next experiment to best differentiate between the different possibilities. OADN, I'm not suggesting that you can't learn anything from these data, only that the p-values won't be very meaningful.
Comment: Unfortunately, I'm not the one doing the experiments, I'm a CFD guy . And yes my goal is to show that there could be a trend and that this will be worth exploring when they design the new experimental rig. So I understand that what I will be able to affirm is limited but I want to see if I can hint at something worth exploring and also avoid to say something completely foolish.


Infimum and supremum of set $A=\{\sqrt[n]{\frac{1}{n}}, n \in \mathbb{N}, n \ge 3 \}$

Question: I have to find the infimum and supremum of the set $A=\{\sqrt[n]{\frac{1}{n}}, n \in \mathbb{N}, n \ge 3 \}$. $  \sqrt[n]{\frac{1}{n}} = \frac{1}{\sqrt[n]{n}}$. $\lim_{n \to \infty}\sqrt[n]{n} = 1$ so  $\lim_{n \to \infty}\sqrt[n]{\frac{1}{n}} = 1$. So supremum of $A$ is $1$. I guess infimum of $A$ is $\frac{1}{\sqrt[3]{3}}$. Am I right?
Comment: If your sequence increase then your is right. so, verify this
Answer: Let $$L=\lim_{n\to \infty } \, \left(\frac{1}{n}\right)^{1/n}$$
We compute $$\log L=\log \left(\lim_{n\to \infty } \, \left(\frac{1}{n}\right)^{1/n}\right)=\lim_{n\to \infty } \, \log \left(\left(\frac{1}{n}\right)^{1/n}\right)=\lim_{n\to \infty } \, \frac{\log \left(\frac{1}{n}\right)}{n}=\lim_{n\to \infty } \, \left(-\frac{\log n}{n}\right)=$$
$=0$ and if $\log L=0$ then $L=1$
$$\lim_{n\to \infty } \, \sqrt[n]{\frac{1}{n}}=1$$
Which is  $$\sup \left\{\sqrt[n]{\frac{1}{n}}\right\}_{n\in\mathbb{N}}=1$$
Infimum is also minimum (because it is an element of the sequence, while $1$ is not) and it is $$\inf \left\{\sqrt[n]{\frac{1}{n}}\right\}_{n\in\mathbb{N}}= \sqrt[3]{\frac{1}{3}}$$
The sequence is increasing. Indeed
$$\left(\frac{1}{n+1}\right)^{\frac{1}{n+1}}>\left(\frac{1}{n}\right)^{1/n}$$
because taking $\log$ of both side, for $n\ge 3$, we have
$$\frac{\log \left(\frac{1}{n+1}\right)}{n+1}>\frac{\log \left(\frac{1}{n}\right)}{n}$$
$$-\frac{\log (n+1)}{n+1}>-\frac{\log (n)}{n}$$
$$\frac{\log (n+1)}{n+1}<\frac{\log (n)}{n}$$
$$n \log (n+1)<(n+1) \log (n)$$
$$\log \left((n+1)^n\right)<\log \left(n^{n+1}\right)$$
$$(n+1)^n<n^{n+1}$$
$$\left(\frac{1}{n}+1\right)^n n^n<n\cdot n^n$$
$$\left(\frac{1}{n}+1\right)^n<n$$
as $n\to\infty$ the RHS keeps less than $e$ while the RHS goes to $\infty$
We have finally proved that the sequence is increasing.
Answer: Let $a_n=n^{-1/n}$. Then $\ln a_n=-f(n)$ where
$$f(x)=\frac{\ln x}x.$$
Investigate this function for $x>0$. What are its maxima/minima?
Where does it increase? decrease?


Implement Realtime Barcode Scanner on Windows Phone 8.1 Runtime using ZXing and MFT

Question: I'm working on a Windows Phone 8.1 Runtime shopping application which needs barcode scanner feature. I'm using the ZXing lib, which is fine. My problem isn't about decoding the picture, ZXing does a great job, but to get the Camera Preview realtime, and feed it to ZXing. After a little research I found this forum https://web.archive.org/web/20150328233747/http://developer.nokia.com/community/discussion/showthread.php/247707-Windows-Phone-8-1-Windows-Media-Capture-API-and-Preview-Frames. Can someone give me a working sample of combining an MFT and ZXing? Or how can I get the preview and handle it in my C# code?
My project is close to the deadline, so please help me out!
Right now the barcode scanning is really messy, I have a "Scan" UI button, which calls the MediaCapture.CapturePhotoToStreamAsync method, but that's not a good solution. I need realtime, automatic scanning.
Thank you!
Comment: Which zxing library are you using? Most I've seen come with working samples that you can build upon.
Comment: I know they have working samples for Silverlight. But for Windows Phone 8.1 RUNTIME, their sample is very inefficient, slow, thus not suitable for realitme scanning. Their sample saves the photo to storage, than scans it. I found an improvment saving the photo to a stream, which is not bad, but still far-far away from the Windows Phone Silverlight version. In Windows Phone Silverlight you can access the camera preview very easily with PhotoCamera.GetPreviewBufferArgb32.
Comment: I finally found a solution. I Microsoft engineer, Matthieu Maitre, hacked together something very useful. The main purpose of his project was "Apply image effects from the Nokia Imaging SDK and DirectX HLSL pixel shaders to videos in Universal Store Apps..". He had an "effect" called "QrCodeDetector", which I tried out and worked, but was really slow. So I asked him if he could enhance the effect, and in two days he updated the nuget package, and it works, and it is lightning fast now: https://github.com/mmaitre314/VideoEffect#realtime-video-analysis-and-qr-code-detection
Answer: I finally found a solution. I Microsoft engineer, Matthieu Maitre, hacked together something very useful. The main purpose of his project was "Apply image effects from the Nokia Imaging SDK and DirectX HLSL pixel shaders to videos in Universal Store Apps..". He had an "effect" called "QrCodeDetector", which I tried out and worked, but was really slow. So I asked him if he could enhance the effect, and in two days he updated the nuget package, and it works, and it is lightning fast now: https://github.com/mmaitre314/VideoEffect#realtime-video-analysis-and-qr-code-detection
Comment: I think he'll update the code soon to support autofocus. On low-end devices, like the lumia 520, autofocus is not supported, so the solution is to trigger the focus in intervals, for example every 3 seconds. You should keep checking the github page to see if he updated it.
Comment: He has updated the code recently and it works great with the Focus. Thank you for your consideration.
Comment: Thanks for the solution. It works. But for 2D barcodes, it's really slow and mostly incorrect. The problem is that the code in the VideoEffect example can't focus the camera. I've added some focus codes but none of them works. Could you plz help with the problem?
Comment: I could be wrong but I thought that the imaging library does not support all architectures. Also, his code only seems to support QR type barcodes.
Comment: Yes, it supports arm only. But he uses zxing lib which supports 1D barcode types as well. I use it in my app, so trust me it does :)


Anonymous function in function composition

Question: While reading Function operator chapter in Advanced R by H. Wickham, I came across the compose function. Infix operator, "o" is used to create function composition:
library(pryr)
"%o%" <- compose

Now the question is, why does the following function works
mul <- sum %o% median %o% mean %o% length %o% function(x) x ^ 2
mul(1:10)
10
But this doesnt
mul <- sum %o% median %o% mean %o% function(x) x ^ 2 %o% length
mul(1:10)
Error in FUN(X[[i]], ...) :
  'list(...)[[1L]]' is not a function, character or symbol
where the only difference is the position of the anonymous function.
Answer: I think the anonymous function needs to be put in braces, otherwise length is composed as part of the function, and this (legitimately) returns an error. You can try:
mul2 <- sum %o% median %o% mean %o% {function(x) x ^ 2} %o% length
> mul2(1:10)
[1] 100

Is this what you want?


Is the garbage I'm seeing in /var/log/messages indicative of a problem?

Question: I've been seeing a lot of junk in /var/log/messages on one of my servers, lately. There don't appear to be any associated I/O errors and the server is still performing its intended tasks without any appearance of a problem, but I was wondering if this is indicative of some kind of other failure that I could be concerned about.
The garbage characters look like this:

SF??)?mq??JX??_?cS=??4?v???A?X~??Tk???$+]?k?"?MG
  T???\u?R????V  ??m????E????9?C???YK
  ??V?5. ????*D???[
                    YHwp?@I?? ~??????m  o f                                                                                G?F_vM'?b9??-31/?ˮ?(?q`?%1?h?/???a?H?+-?U0???yٹ h?^m[??uC?/R??S??5٣???\??L?pkr
  =v ?'?|?b?&?{ 5?)h?5?P_?q?;?G?? ???hZU   ???2??J?????iD???-?=??#
Comment: The last meaningful entry before this garbage is....? Tried shutting down syslog service, moving /var/log/messages and restarting the service?
Comment: To help you better we need a somewhat longer chunk of your syslog. That's definitely junk, but to rule stuff out (or in) we need what came before the junk :)
Answer: I would first look elsewhere to avoid an fsck & downtime.
Normally, the only thing that writes to /var/log/messages is the Syslog daemon. You can verify this with 'lsof':
$ sudo lsof /var/log/messages
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
rsyslogd 123 syslog   21w   REG   8,17  123123 123123 /var/log/messages

You should only see one COMMAND writing to this file. If you see more then one, then might be the source of your problem.
If this information came from the syslog service, each line will preceded by the timestamp, hostname and the name of the program which wrote the log. Something like "Mar  4 00:12:42 myhost kernel: ", and then other information.
If there is no such format, then this garbage was not passed through Syslog, and something else is writing garbage to /var/log/messages. You should be able to track that down if you shut down syslog, and then use lsof or fuser to look for open files.
Or, as others have said, syslog is buggy and needs to be restarted.
Answer: Try to track down where that stuff is coming from.  If it's being logged by something (and thus has the normal header that syslog adds), well, maybe that program has a problem.  If on the other hand syslog is writing that stuff out instead of what you expect, I'd get worried.  Any errors in dmesg?  Segfaults?  Have you done a memtest recently?
Answer: Check if your partitions overlap, then run fsck on your /var or /var/log filesystem (you do have a /var and/or /var/log filesystem, don't you?)
Answer: Is this all that's getting into syslog, or is it scattered among "normal" entries? I'd try shutting down the log daemon, move the syslog file, start it up again and see if it persists. If so, schedule a fsck and restart.
You do have an up-to-date backup, correct? Taking one now could risk backing up corrupted data...


yum history list + how to verify rpm historical status

Question: The rpm command gives every package installed a transaction ID. The transaction ID is a Unix time stamp (number of seconds since January 1, 1970). You can then perform some operations on packages based on the transaction ID.
but on our rhel machines when we try to get info from  yum history list $rpm_name
then we get the following errors
Bad transaction IDs, or package(s), given
Error: Failed history list

usually if rpm was removed the we should get from yum history list $rpm_name
ID     | Login user               | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    29 | root <root>              | 2020-11-24 00:54 | Erase          |   26
     1 | System <unset>           | 2019-12-15 14:05 | Install        | 1363
history list

and if rpm is installed then we should get from yum history list $rpm_name
ID     | Login user               | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    31 | root <root>              | 2020-11-26 01:06 | Install        |    1

but what is the meaning of the errors below ? that we get from yum history list $rpm_name
note - rpm_name - is rpm name
Bad transaction IDs, or package(s), given
Error: Failed history list

Answer: You must give the name of the package, not the name of a file.
So you would use libcgroup, not libcgroup-0.41-19.el7.x86_64.rpm.


switch não reconhecendo ENUM como constante

Question: public enum enumUpdateAction {
    NEW(0), CHANGE(1), DELETE(2), DELETE_THRU(3), DELETE_FROM(4);

    public int codigo;

    enumUpdateAction(int codigo) {
        this.codigo = codigo;
    }

    public int getCodigo() {
        return this.codigo;
    }
}

...
switch (Eventos.get(0).getUpdateaction()) {

            case enumUpdateAction.NEW.getCodigo():
                ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
                break;
}

Após criado o enum, estou tentando usar esse valor dentro de um switch (no caso, NEW corresponde a 0 e, portanto, estou tentando usar 0 dentro do case), mas recebo o erro "constant expression required". Alguém sabe me dizer o porque disso acontecer?
Answer: Acontece pelo fato de você estar tentando comparar o código do enum com o enum em si, pois o getUpdateaction() retorna o enum em si, porem você tenta fazer o case com o código do enum, assim ocasionando esse erro, basta você retirnar o enumUpdateAction.NEW.getCodigo() e colocar enumUpdateAction.NEW.
Comment: Não, não. O Eventos.get(0).getUpdateaction() retorna um número de 0 a 4. Portanto, para não colocar 0, 1, 2, 3 e 4 nos cases, criei um enum, pois o número 0, por exemplo, refere-se a NEW. Portanto, não preciso ficar sempre lembrando o que cada número se refere. Compreende? O ENUM facilita nessa parte mas não estou conseguindo pegar o int o qual o NEW se refere, que é o 0. o getUpdateAction() não tem a ver com o enum.
Answer: Um valor utilizado em um case precisa ser uma constant  variable, ou seja, uma variável final de tipo primitivo ou String inicializada em tempo de compilação, ou uma enum. Esse não é o caso do valor retornado pelo método getCodigo da sua enum.
Caso o método getUpdateAction retorne uma enum basta fazer isso:
Use o nome da enum no case :
switch(Eventos.get(0).getUpdateaction()) {
    case NEW:
        ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
        break;

}

Caso ele retorne o código da sua enum, mude sua enum para:
public enum EnumUpdateAction {
    NEW(0), CHANGE(1), DELETE(2), DELETE_THRU(3), DELETE_FROM(4);

    private static final EnumUpdateAction VALUES[] = EnumUpdateAction.values();

    private final int codigo;

    private EnumUpdateAction(int codigo) {
        this.codigo = codigo;
    }

    public int getCodigo() {
        return this.codigo;
    }

    public static final EnumUpdateAction deCodigo(int codigo) {
        for(EnumUpdateAction e : VALUES) {
            if(e.codigo == codigo) {
                return e;
            }
        }
        throw new IllegalArgumentException("codigo inválido: " + codigo);
    }
}

E seu switch para:
switch(EnumUpdateAction.deCodigo(Eventos.get(0).getUpdateaction())) {
    case NEW:
        ArrayEventos.add(InserirOrdenado(ArrayEventos, Ordem), Ordem);
        break;

}

Observação: por convenção, os nomes de classe em Java são escritas em CamelCase.


How should I include an image field from a taxonomy term in a node view?

Question: I'm creating a site with just one content type sorted in three categories and posted by three different organizations (no matter in which of the categories). The front page has to be three columns displaying the content of each category.
The nodes has to be distinguished by the logo of the organization. I'm trying to solve it by managing the organization as a taxonomy and creating an image field for each organization/term; when I deal with the view, I find that I just can use as field the name of the taxonomy and not the image (creating a view of node type of course).
How can I achieve it?
Answer: If you're using Drupal 7 then you will have to add a "Content: Taxonomy terms on node" relationship before attempting to add the term image field. When you add the relationship then in the Fields section you will be able to choose term fields (like the image field of your terms) to display them in your content view.


Missing URI template variable for method parameter of type String

Question: This is what my REST controller looks like
@RequestMapping(method = GET, path = "/type/{eventtype}/events")
@ResponseBody
public ResponseEntity<?> getEventsSpecificType(@PathVariable String eventType) throws InvalidRequestException {
    return ResponseRestBuilder.createSuccessResponse(
            portEventRepository.
                    findByEventTypeOrderByTimestampAsc
                            (eventType));
}

Calling it from Postman with the following URI
http://localhost:8181/type/default/events

gets me this error
{
"timestamp": 1518605163296,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.web.bind.MissingPathVariableException",
"message": "Missing URI template variable 'eventType' for method parameter of type String",
"path": "/type/default/events"

}
What am I missing? Isn't the String variable properly mapped?
Answer: You must give the name of the path variable, the name of the method parameter doesn't matter. And the name of the path variable must match exactly the name used in your Path (eventtype).
getEventsSpecificType(@PathVariable("eventtype") String eventType)

If you don't specify the @PathVariable, the name must match exactly the name used in the path. So change the eventType method parameter to eventtype.
Answer: I have also got same Issue and Resolved by **Changing Name of Path variable Like
@RequestMapping(method = GET, path = "/type/{eventType}/events")
@ResponseBody
public ResponseEntity<?> getEventsSpecificType(@PathVariable String eventType) throws InvalidRequestException {


Evaluating $\int_a^b \frac12 r^2\ \mathrm d\theta$ to find the area of an ellipse

Question: I'm finding the area of an ellipse given by $\frac{x^2}{a^2}+\frac{y^2}{b^2} = 1$. I know the answer should be $\pi ab$ (e.g. by Green's theorem). Since we can parameterize the ellipse as $\vec{r}(\theta) = (a\cos{\theta}, b\sin{\theta})$, we can write the polar equation of the ellipse as $r = \sqrt{a^2 \cos^2{\theta}+ b^2\sin^2{\theta}}$. And we can find the area enclosed by a curve $r(\theta)$ by integrating
$$\int_{\theta_1}^{\theta_2} \frac12 r^2 \ \mathrm d\theta.$$
So we should be able to find the area of the ellipse by
$$\frac12 \int_0^{2\pi} a^2 \cos^2{\theta} + b^2 \sin^2{\theta} \ \mathrm d\theta$$
$$= \frac{a^2}{2} \int_0^{2\pi} \cos^2{\theta}\ \mathrm d\theta + \frac{b^2}{2} \int_0^{2\pi} \sin^2{\theta} \ \mathrm d\theta$$
$$= \frac{a^2}{4} \int_0^{2\pi} 1 + \cos{2\theta}\ \mathrm d\theta + \frac{b^2}{4} \int_0^{2\pi} 1- \cos{2\theta}\ \mathrm d\theta$$
$$= \frac{a^2 + b^2}{4} (2\pi) + \frac{a^2-b^2}{4} \underbrace{\int_0^{2\pi} \cos{2\theta} \ \mathrm d\theta}_{\text{This is $0$}}$$
$$=\pi\frac{a^2+b^2}{2}.$$
First of all, this is not the area of an ellipse. Second of all, when I plug in $a=1$, $b=2$, this is not even the right value of the integral, as Wolfram Alpha tells me.
What am I doing wrong?
Comment: One can obtain the answer without doing much thinking: to obtain the ellipse, we stretch the circle $a$ units through one axis and $y$ units through the other, which amounts to $ab$ times the area of the unit circle, which is $\pi$, so $ab\pi$. Alternatively, the transformation $(x,y)\mapsto (ax,by)$ has Jacobian $ab$.
Comment: @Eric Auld: see http://math.stackexchange.com/questions/1933765/reconciling-x-mathrmdy-y-mathrmdx-x2y2-mathrmd-theta
Answer: There are already a lot of good answers here, so I'm adding this one
primarily to dazzle people w/ my Mathematica diagram-creating skills.
As noted previously,
$x(t)=a \cos (t)$
$y(t)=b \sin (t)$
does parametrize an ellipse, but t is not the central angle. What
is the relation between t and the central angle?:

Since y is bSin[t] and x is aCos[t], we have:
$\tan (\theta )=\frac{b \sin (t)}{a \cos (t)}$
or
$\tan (\theta )=\frac{b \tan (t)}{a}$
Solving for t, we have:
$t(\theta )=\tan ^{-1}\left(\frac{a \tan (\theta )}{b}\right)$
We now reparametrize using theta:
$x(\theta )=a \cos (t(\theta ))$
$y(\theta )=b \sin (t(\theta ))$
which ultimately simplifies to:
$x(\theta)=\frac{a}{\sqrt{\frac{a^2 \tan ^2(\theta )}{b^2}+1}}$
$y(\theta)=\frac{a \tan (\theta )}{\sqrt{\frac{a^2 \tan ^2(\theta )}{b^2}+1}}$
Note that, under the new parametrization, $y(\theta)/x(\theta) =
tan(\theta)$ as desired.
To compute area, we need $r^2$ which is $x^2+y^2$, or:
$r(\theta )^2 = (\frac{a}{\sqrt{\frac{a^2 \tan ^2(\theta )}{b^2}+1}})^2+
(\frac{a \tan (\theta )}{\sqrt{\frac{a^2 \tan ^2(\theta )}{b^2}+1}})^2$
(note that we could take the square root to get r, but we don't really need it)
The above ultimately simplifies to:
$r(\theta)^2 =
\frac{1}{\frac{\cos ^2(\theta )}{a^2}+\frac{\sin ^2(\theta )}{b^2}}$
Now, we can integrate $r^2/2$ to find the area:
$A(\theta) = (\int_0^\theta
\frac{1}{\frac{\cos ^2(x )}{a^2}+\frac{\sin ^2(x )}{b^2}} \, dx)/2$
which yields:
$A(\theta) = \frac{1}{2} a b \tan ^{-1}\left(\frac{a \tan (\theta )}{b}\right)$
good for $0\leq \theta <\frac{\pi }{2}$
Interestingly, it doesn't work for $\theta =\frac{\pi }{2}$ so we
can't test the obvious case without using a limit:
$\lim_{\theta \to \frac{\pi }{2}} \, \frac{1}{2} a b \tan
^{-1}\left(\frac{a \tan (\theta )}{b}\right)$
which gives us $a*b*Pi/4$ as expected.
Answer: Your question has been answered, so now we look at how to find the area, using your parametrization, which is a perfectly good one.
The area is the integral of $|y\,dx|$ (or alternately of $|x\,dy|$. over the appropriate interval.
We have $y=b\sin\theta$ and $dx=-a\sin\theta\,d\theta$. So the area is
$$\int_0^{2\pi} |-ab\sin^2\theta|\,d\theta.$$
Using $\sin^2\theta=\frac{1-\cos 2\theta}{2}$, we find that the area is
$$\int_0^{2\pi} ab\frac{1-\cos 2\theta}{2}\,d\theta.$$
This is indeed $\pi ab$.
Comment: Your integral is right. But we can't really blame poor Alpha for disagreeing, implicitly you told it $b=\sqrt{2}$.
Comment: Thanks, Andre. So the integral I set up was the wrong one. But can you see where is the error in my evaluation of the integral? Wolfram Alpha yields a different answer...
Comment: Thank you! That was really bothering me...
Comment: You are welcome. These kinds of minor typos can be the hardest to find, I got lucky.
Answer: HINT:
Putting $x=r\cos\theta,y=r\sin\theta$
$$\frac {x^2}{a^2}+\frac{y^2}{b^2}=1,$$
$$r^2=\frac{a^2b^2}{b^2\cos^2\theta+a^2\sin^2\theta}=b^2\frac{\sec^2\theta}{\frac{b^2}{a^2}+\tan^2\theta}$$
Comment: @EricAuld, clearly you can see the value of $r$ here in terms of $\theta$. We can't set polar equation in term of $\theta$ in that way. You can see some other methods here : http://en.wikipedia.org/wiki/Ellipse#Area
Comment: Great. So I see that $\vec{r}(t) = (a\cos{t}, b\sin{t})$ does *not* parameterize the ellipse by the angle. Can you spot my error in evaluating the integral as I set it up?
Answer: This is another way to do it when one know the area of a circle: Consider the area of a circle with radius 1 in coordinates $(\xi, \eta)$ this is:
$$
\int d\xi d \eta = \pi
$$
now if you define new coordinates in your ellipse equation $\xi = \frac{x}{a}, \quad \eta= \frac{y}{b}$ you obtain a circle of radius one: $\xi^2 + \eta^2 =1$
The area of the ellipse you want is  $ \int dx dy = ab \int d\xi d\eta = \pi ab$.
Answer: Here you go - this person even made your mistake, then someone else corrected it.
Link
Comment: Awesome! So I was wrong in assuming that that integral represented the area. Can you see how I have erred in evaluating the integral?


Sufficiency of Sample Mean for Laplace Distribution

Question: I recently started reading about sufficient statistics. I have the following questions:
1) Is sample mean a sufficient statistic for Laplace Distribution (aka Double Exponential) if we already know the scale parameter?
2) If not, is this also related to the fact that it is not an efficient estimator of the mean/location?
EDIT
For example sample median with known scale parameter is sufficient and efficient.
Thanks
Comment: I noticed you have deleted a few of your recent questions that were quite interesting. I will not vote to undelete, I will leave that for your discretion (at least for now). But would you care to at least post a comment under the OP or an answer before deleting? That way at least the users with sufficient reputation would see what solution you found or why you thought the question was no longer relevant. Thank you!
Comment: The one you deleted an hour ago and another recent one (I forgot what exactly it was about). If I were you, I would keep them a bit longer. By deleting them early you also discourage slow users who perhaps plan to answer when they find time. And the questions are quite good, IMHO (even if they do not get many upvotes).
Comment: I am not sure how to do that. But mine was a general comment applicable to future posts as well. Good luck with your statistical problems!
Answer: For on observation, the Laplace pdf is
$$f_X(x) = \dfrac 1 {2b} \exp(-\dfrac {|x-\mu|} b)$$
For multiple iid observations, the pdf is
$$f_\boldsymbol X(\boldsymbol x) = \dfrac 1 {(2b)^n} \exp(- \dfrac 1 b \sum_{i=1}^n {|x_i-\mu|})$$
The easiest way to determine what statistics are sufficient for $\boldsymbol X$ is to try to use the Factorization Theorem (https://en.wikipedia.org/wiki/Sufficient_statistic#Fisher.E2.80.93Neyman_factorization_theorem). However, if you start to work with this expression, you'll see that the absolute values in the sum make it impossible to do any simplification/factorization.
To answer your first question, the sample mean is not a sufficient statistic (event if $b$ is known). However, if $\mu$ is known, then $\sum_{i=1}^n |x_i-\mu|$ is a sufficient statistic for $b$. But $\mu$ will almost never be known unless it's assumed to be zero.
As for your second question, I don't believe there are any theorems which directly state for some conditions, inefficiency implies insufficiency or vice-versa. However, there are theorems which connect sufficient statistics to maximum likelihood estimators and MLEs are asymptotically efficient under certain regularity conditions. So in that sense, I suppose you could view the insufficiency and inefficiency of the sample mean as related results.
Comment: (+1) For independent observations from a Laplace distribution the minimal sufficient statistic for the location parameter (scale being known) is the order statistic - there's indeed no further reduction possible. You can separate this into the median (the maximum-likelihood estimate) & an ancillary complement, the configuration statistic.
Comment: Hm. Heuristically, that doesn't make sense to me. Suppose you have two distinct samples, x = {-1, 0, 1} and y = {-100, 0, 1}. If all you know is the sample median (0 in both cases), you certainly don't have a sufficient amount of info to make inference about b. Given x, we'd expect b to be much smaller than if we were given y. In both cases, you'd need the whole sample to make the best possible inference.
Comment: It's a special situation owing to the Gaussian distribution's being in the exponential family - see the Pitman-Koopman-Darmois theorem,
Comment: +1 for the first part. For the second question, I believe sample median is a sufficient statistic and it is efficient. That hints me of some connection.
Comment: Sorry about that. You did mention that you were assuming b was fixed and you wanted to make inference about $\mu$. Disregard my last comment.
Comment: @Scortchi interesting comment. In Gaussian setting with known variance mean is sufficient. It doesn't fit in the template you mentioned. Is it just a special situation due to symmetry?
Comment: @Scortchi-ReinstateMonica For Gaussian, order statistic is not minimal sufficient statistic for the location parameter.
Comment: @Tan: I know, I was referring implicitly to a Laplace distribution. I've edited my comment.
Comment: @Scortchi-ReinstateMonica Thank you for clarification. Do you know, or any hint, on how to prove it, that the order statistic is sufficient for Laplace?
Answer: The sample median is the maximum likelihood estimator of the mean if the scale is known, but it is not the sufficient statistics. I agree that the order statistics is the sufficient statistics. This can be seen using the factorization theorem and examining the dependence of the RN derivative, upon the examination of the absolute values therein, on the data across all mu values.


How to send email to all members when a post is updated by user?

Question: I am creating  a rules to send an email when a (node with content type update) is updated which has field_og_audience as field and it is placed on the groups page using advanced form block.
I want to send an email when node (with content type update) is updated by user then all the members of the group(selected in the field_og_audience) should recieve an email.
Comment: @tyler.frankenstein I added a rule for content as shown below to send mail to all members
Comment: Have you tried creating a custom action? https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_action_info/7 - This can be fired by rules and accept the OG ID, which you could use in turn to load the users and send off an e-mail. I'm not aware of a point-n-click solution.
Answer: EVENT
After saving new content
CONDITIONS
Entity is group content
Parameter: Entity: [node]
ACTIONS
Get group members from group audience
Parameter: Group content: [node]
Provides variables: Fetch a List of group members (group_members)
Loop
Parameter: List: [group-members]
List item: Get list of group members and their email ids (list_grp_members_emails)

Send mail Parameter: To: [list-grp-members-emails:mail], Subject: Notification: Content..., Message: Test