Defining intervals.

Question: There seems to be a lot of confusion over naming intervals. Some seem to think it involves major intervals being from major keys/scales, thus minor intervals need to follow from that. Some seem to think the number of semitones difference defines the interval. Neither are spot on. What is a simple way to define intervals, that works for all of them?
Comment: Haha, I was posting a similar question at the same time. Mine is about interval *names* as opposed to something like the amount of frequency separation.
Comment: I thought mine was too. But there is confusion (on internet sites in particular, about whether say C>D# or C>Eb is a min3, et al...We both know the answer!, but a simple explanation would maybe help clear up this confusion.I don't look forward to answers which quote Hz, etc... or even percentages of same.
Comment: Agreed--I also was thinking about what I actually wanted to ask, and I think the answers would be basically the same as those to this question.
Comment: My comment was in another thread where the OP was specifically talking about the size of major and minor thirds, not augmented seconds! It wasn't intended to be a *complete* discussion on intervals, just a comment pointing out that the OP's question was based on logical deduction starting from an incorrect assumption!
Comment: Is this even a question? I think it should be closed. There's gazillion of explanations in different places, they all require different amounts of assumed knowledge - there's no one-size-fits-all answer. People are wrong about it and will continue to be wrong about it, no matter what's written here.
Comment: just look at the answers: they are not a bit simpler than answers given anywhere else, and - in the whole - even more confusion is introduced by people using different approaches and even methodologies ("there exist only three basic intervals in Western music"?!).
Comment: @fdreger - one of the aims of this site is to provide as complete a compendium of all things musical - practice and theory wise. Yes, of course there are other places where information is obtainable. The answers so far are all good, and portray different ideas behind the naming of intervals. Point 1 - thank you for giving a dv reason. Point 2 - if you think it should be closed, there is a 'close' word to click on.
Comment: @Tim There's no "close" word to click on - that requires 3000 rep points. Dv is all I have.
Comment: @Tim and the fact that there are 4 different answers highlights the problem of this question (i.e. the fact that it does not fit the Q&A format of Stack Exchange). How I see this question is precisely this: https://xkcd.com/927/ (just replace "standard" with "authoritative answer").
Comment: @fdreger - is there a 'flag' available for you to bring it to the attention of mods? There are often different answers to the same question.
Comment: @Tim - flag - yes, but I wouldn't want to flag it :) It's not me wanting to change things by appealing to mods or something. It's just being a part of community, upvoting things I like downvoting and voting to close things I don't - that's how we move forward, both +1s and -1s are necessary, I think. This question strikes me as artificial - it's really a call for writing tutorials. And there can be no single "acceptable" answer, because the exact language depends on concepts that the reader already knows, everyone's "perfect answer" will be different. Good for a chat or a wiki, bad for Q&A.
Comment: @fdreger - o.k. Bearing in mind it's getting on for 3yrs old, and 'what the reader already knows' was my concern. There's a lot of misinformation out there, especially on 'official' sites, and I saw it as an opportunity to tidy up and make things clearer for all. As said previously, one main aim on this site is to be the 'fount of all knowledge (music-wise), and answers should help.
Comment: @Tim - since we already have this chat, you can take a look at the site's tour: https://music.stackexchange.com/tour. There's a box called "Don't ask about" and there are two negative qualities a question can have: "primarily opinion-based or recommendations" and "too many possible answers or that would require an extremely long answer". I think the fuzziness of this question falls under both.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107359/discussion-between-fdreger-and-tim).
Answer: I think it helps a lot, at first, to separate the two parts of an interval name and look at them in isolation, and then go back to combining them. The context for interval names that I will consider in this answer is strictly "Western" tunings and scales, meaning based on the notes A B C D E F G (or Do Re Mi, etc. if you prefer).
The Numerical Part
The most significant part of an interval name is the "numerical" part, e.g., third, fourth, ninth, fifteenth, etc. And here's something that I think confuses a lot of people: the name of this part of the interval name is based on the names used for the two notes that make up the interval.
To dive deeper into that last sentence, the interval name for the interval made up of C and E# is a different interval name from the one composed of C and F, even though E# and F are (generally) the same pitch (they are enharmonic).
That doesn't make a lot of sense when you are looking at the piano keyboard, because you are literally playing the same notes in both cases. It makes a lot more sense when you are looking at sheet music and arranging and transposing parts and generally working with music theory. Right off the bat, it's clear that writing E# in a score looks different from writing F.
So to determine what the numerical part of an interval name should be, you start by knowing/determining the note names of the two notes in the interval. Ignoring all accidentals (sharps, flats, double sharps, naturals, whatever), merely count the distance between the letters, starting with 1 for the same note (so C to the same C is 1, C to D is 2). When intervals are wider than an octave, you keep counting (it doesn't reset to 1), so that's how there are 9ths and 15ths, etc.
The Quality Part
Once the numerical part is determined, that forms the basis for the "quality", but the quality is determined using the number of half steps. Here's a table of sorts showing the most common interval name and then a less common name and the half steps between them:

0 half steps - Unison
1 half step - Minor second, augmented unison
2 half steps - Major second, diminished third
3 half steps - Minor third, augmented second
4 half steps - Major third, diminished fourth
5 half steps - Perfect fourth, augmented third
6 half steps - Tritone, augmented fourth, diminished fifth
7 half steps - Perfect fifth, diminished sixth
8 half steps - Minor sixth, augmented fifth
9 half steps - Major sixth, diminished seventh
10 half steps - Minor seventh, augmented sixth
11 half steps - Major seventh (not sure I've ever heard of "diminished octave" before)
12 half steps - Octave, Augmented seventh, diminished ninth

After that, the quality pattern repeats but with the numbers continuing to increase.
Comment: After a re-read, a small comment. In the 1st para it says ABC etc, or do re mi.The two aren't substitutes, unless it reads 'C D E or do re mi'. A B C# would do, but may confuse! A slight edit?
Comment: I guess, if an aug unison lives, then a dim octave ought to have a chance!
Comment: When determining the two letter names (numerical part above) do we *need* notation on staff to get the right spelling? I think the answer is yes, otherwise we need to state assumptions about key signatures and spelling tertiary chords in thirds. Ex. D# v. Eb. In C minor Eb would be the normal spelling unless D# was actually written in the notation.
Comment: @MichaelCurtis Good question. I think if I tried to dive into all the ways to know what the note names would be (e.g., just having a nominal key for a piece or section implies what note names should be used, even where there is no notation), this answer would have to be so long and involved that it would make the question seem too broad.
Comment: @ToddWilcox, it is hard to think of concise way to write it. I was trying to tease apart the 'confusion' some people have with the numerical part. I suppose that confusion is especially for folks who can't read the staff or don't know key signatures.
Answer: Intervals are two distinct measurements: distance in semitones and distance in letter name. The type of interval (unison, 2nd, 3rd, ect) is based off of the distance between the letter names. The quality (i.e Major, minor, perfect, ect) is based off of the "typical" space that the type of interval occupies. The following I have posted before on other questions asking about why a quality is named the way it is and I think it applies well to this question.

To better explain why the intervals ended up this way, let's look at this solely from a distance perspective at first. The distances from unison to octave are as follows in semitones:

 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12

In C these notes would map to:

 C - Db - D - Eb - E - F - F#/Gb - G - Ab - A - Bb - B  - C

As you can see, both 0 and 12 map to C and the furthest you could be away from a C in semitones is 6.  This leaves us with 5 notes on each side with 1 - 2 - 3 - 4 - 5 closer to 0 and 7 - 8 - 9 - 10 - 11 closer to 12.
Now let's look at the standard interval names. In this I will use M for major, m for minor, P for Perfect and tt for tritone (which is considered both an augmented 4th and a diminished 5th).

 P1 - m2 - M2 - m3 - M3 - P4 - tt - P5 - m6 - M6 - m7 - M7 - P8

I'll also group the typical groupings. Notice how the tritone is in both the 4th and 5th grouping:

 P1 - (m2 - M2) - (m3 - M3) - (P4 - [tt) - P5] - (m6 - M6) - (m7 - M7) - P8

Now looking at the whole interval spectrum, we notice

The tritone (or 6 semitones away and equal distance from both 0 and 12) has a perfect interval above and below (P4 - tt - P5) and can be described as both an A4 and d5 for this reason (because they both are "contesting" the tritone).
The note you are basing the name off of (C in this case which is both 0 and 12) is also perfect (P1 for unison P8 for octave) .
The other notes are group into twos (because of the two semitones typical max in scales) with the smaller one being minor and the bigger one being major (m2 - M2 - m3 - M3) and (m6 - M6 - m7 - M7).
The augmented and diminished intervals of the major and minor intervals are for when one of the  intervals stretches out of its typical designation.

Now taking a step back, if there is one "typical" space for the note the normal quality is prefect and if there are two the bigger one (going upward) will be major and the smaller one will be minor. Anything bigger than the normal interval (i.e. C to F♯, C to D♯, ect) is considered augmented in quality. Anything lower (i.e. C to G♭, C to B♭♭, ect) is a diminished quality.
Comment: "Theoretically" there's infinite, but I've never seen anything above "Tripply" and even that was just a theory exercise.
Comment: @Tim contemporary music notation sometimes includes triple-flat and triple-sharp accidentals on any note. An interval of Dbbb to A### should presumably be named as some sort of 5th, even though it's actually a semitone wider than an octave!
Comment: Good answer, as ever - haven't seen you post for a while - but what reasons are there for the Perfect intervals not being called maj/min?
Comment: @Tim because they have one defined space and one "contested" space. think of it like the 4th and 5th both can't claim it as there normal space.
Comment: Rather like the others have 4 derivitives, but they only have 3. That needs adding to the answer, not left in comments, I think.
Comment: @Tim "Doubly augmented" and "doubly diminished" are real terms that can be used for fourths and fifths. I'm not sure I've ever heard of triple augmentation or diminution but these days almost anything is possible. Point being, perfect intervals can have more than 3 flavors.
Comment: I wonder if there's even a technical reason why there should need to be more than 3. I'd have thought every possibility would have been catered for with M,m,dim, aug. and P. C>Gx doesn't occur in any pieces I've played - yet...
Answer: There exist only three basis intervals in Western music: octaves, fiths and major thirds. Everything else is compound. Ignore the naming for now, those intervals can be defined as pure mathematical ratios:

The octave is the simplest interval, created by doubling the frequency.
The fifth is created by multiplying the frequency with 3⁄2.
The (major) third is created by multiplying the frequency with 5⁄4.

All together, these form the classic narrow voicing of a 4-voice major chord, for example C3 - E3 - G3 - C4. That sounds nice but quickly gets boring; to enable leading actual melodies, we fill the gaps by stacking some of those intervals upon already-constructed notes. The conventional way to do this is to extend one extra major chord (the dominant) from the fifth, and one chord whose fifth is the original fundamental (the subdominant). This way, we end up with a diatonic scale.
https://gist.github.com/leftaroundabout/049faa0e9fb4841b71aefb2171f66283
This is a (Ptolemy-) diatonic scale, frequencies in log-domain:

If you plot all the ratios between two notes in that scale, you'll observe two pretty tight clusters, some rather diffuse blobs, and one lonely oddball:

About that loner we shall not speak, the other groups we give numbers (starting at, erm... 2), giving us the rough intervals. For the "blobs" we always still see a pretty clear division into two subgroups; these are the fine intervals.
We thus end up with the classification

E-F, B-c: minor second
C-D, D-E, F-G, G-A, A-B: major second
D-F, E-G, A-c: minor third
C-E, F-A, G-B: major third
C-F, D-G, E-A, G-c: pure fifth
C-F, D-G, E-A, G-c: pure fourth
E-c: minor sixth
C-A, D-B: major sixth
D-c: minor seventh
C-B: major seventh

Disclaimer: this derivation is historically debatable, because especially in the middle ages, the major third was not considered a basis interval, instead it was constructed by stacking four fifths on top of each other. But those Pythagorean thirds don't sound consonant at all, and the Pythagorean scale's ratios actually don't exhibit a "cloud patterns" structure (in fact, the Pythagorean minor third is closer to the major second than it is to the major third).
Answer: If we write out the scales, we see where the intervals get their name (or at least the numerical part of it.) This is done below (using the scales of natural notes A minor and C major for convenience.) All the intervals are named as the difference between the root note and the number of the degree. For example the Major 6th is the difference between the root and 6th note of the major scale (C and A in the scale of C major.)
Where necessary, an interval which exceeds the normal bounds can be described as "augmented" (1 semitone more than a perfect or major) or "diminised" (1 semitone less than a perfect or minor.)
In fact, the only way to name the 6 semitone interval in this system is to call it an augmented 4th or diminished 5th, as this "tritone" or "devils interval" does not feature as an interval between the root and another note in either the major or minor scale.
 Semitones Aminor Cmajor

      0    A     C       Unison
      1                  Minor 2nd***
      2    B     D       Major 2nd
      3    C             Minor 3rd
      4          E       Major 3rd
      5    D     F       (Perfect) 4th
      6
      7    E     G       (Perfect) 5th
      8    F             Minor 6th
      9          A       Major 6th
      10   G             Minor 7th
      11         B       Major 7th
      12   A     C       Octave

But WAIT! the Second note of both the major and minor scale is 2 semitones! Why is the 1 semitone interval called a 2nd at all?!
This is the ONLY exception (unless you count the 9th, which is the same thing an octave higher). I have heard that the Phrygian mode was more popular in the past, and if we change the B in A minor to a Bb, we obtain A Phrygian and everything falls into place.
For a long time I thought this little oddity of naming was done simply to conveniently fill in the gap and find a name for the 1 semitione interval. After all, the Italian "Minore secondo" simply means "lesser second" and "Maggiore segundo" means "greater second."
With this in mind however, here's a look at the different intervals which exist in all 7 modes:
                                       1 1 1
Semitones          0 1 2 3 4 5 6 7 8 9 0 1 2

Name               P m M m M P   P m M m M P
                   1 2 2 3 3 4   5 6 6 7 7 8

Ionian (Major)     C - D - E F - G - A - B C
Dorian             D - E F - G - A - B C - D
Phrygian           E F - G - A - B C - D - E
Lydian             F - G - A - B C - D - E F
Mixolydian         G - A - B C - D - E F - G
Aeolian (Minor)    A - B C - D - E F - G - A
Locrian            B C - D - E F - G - A - B

Total ocurrences   7 2 5 4 3 6 2 6 3 4 5 2 7

Looking at this, we see the 2-semitone interval occurs in 5 of the modes, functioning as a second, and the 1-semitone interval occurs in the other 2 modes, also functioning as a second. Hence major and minor second. If we check all possible modes, we see both the major and minor forms of the Second in use!
Similarly the 4-semitone interval occurs in 3 modes, functioning as a third, and the 3-semitone interval occurs in 4 modes, also functioning as a third. Hence major and minor third.
A similar thing happens with the 6ths and 7ths. Hence we have two equally valid standard forms of the 2nd, 3rd, 6th and 7th: a minor one, and a major one.
Note that the 6-semitone interval (the tritone) occurs twice. In the Lydian mode it functions as an augmented 4th, while in the Locrian mode it functions as a diminished 5th. Therefore this interval cannot be readily classified as a typical variety of 5th or a typical variety of 4th (though the term "diminished 5th is rather more often used than "augmented 4th", due to the way in which chords are constructed.)
So we see also why there is therefore only one "standard" form of the 4th and the 5th, given the name "perfect", with the tritone being an oddball.
Comment: Do you have any sources for this meaning behind interval names? As far as I know, some of this is incorrect.
Comment: @ToddWilcox Thanks for your comment. I think I had it backwards (but for years I didn't care because, with the exception of the minor second, it was working for me.) The truth is, the major and minor scale are most likely named after the major and minor intervals, and not the other way round. But as I say, the Major mode contains all four Major intervals, whereas the Phrygian (not the Minor) is the one that contains all four minor intervals. Checking all 7 modes reveals plenty of seconds of both the major and minor variety.
Comment: My initial intention was to provide a simple answer defining the more basic intervals (see my first table) as I thought it was missing from the page, but it has grown into something bigger!
Comment: Some of this answer is good, but the part where you state an interval's size as so many semitones is incorrect. The size of an interval can't be expressed *only* in semitones (except the minor second, if you call that a semitone). Even if we restrict attention to meantone temperaments, in order to say how big an interval of a given name is, you need both minor seconds (diatonic semitones) and major seconds (tones).
Answer: Everyone's answering the wrong question.   This is about NAMING intervals, not about analyzing their harmonic function
To understand the system of NAMING them, we could do a lot worse than the 'relate it to the major scale starting on the lower note' method.
The number is purely about how many letter names it contains.  C (natural, flat, sharp, double sharp, whatever) to E (same list...) is a 3rd.  C, D, E.  Three letter names.  Yes, it's a notation thing - sorry all you fret-counters out there.
If it's in the major scale (we're talking about the one that starts on the lower note of the interval, remember) it's major.  Unless it's a unison, 4th, 5th or octave when it's perfect.
If it's a semitone (half-step) smaller than that, it's minor.  Unless it started as perfect, then it's diminished.
Another semitone smaller, the minor ones become diminished.
One bigger than major/perfect, it's augmented.
And that's it.  How to name an interval.  Not WHY we name them that way.  Question answered.  I have no idea why @Tim feels this isn't an acceptable way of doing so.  It works.
Comment: Maybe not.  But the major scale has EVERYTHING to do with our system of naming them.
Comment: +1 The truth, and nothing but the truth. @Dom This is true, but this answer is about what name an interval has, not about why the names are what they are.
Comment: "If it's in the major scale, it's major. " this explanation is the source of a lot of confusion and why questions like this take more explanation. The major and minor scale have nothing to do with the definition of major and minor intervals.
Comment: They are different definitions. Lumping them together makes confusion for new people learning as the minor scale has major intervals in it and other scales that we would define as more major in nature like Mixolydian have minor intervals in them. The major scale has intervals in it that are major yes, but calling that the absolute reason for how we name them is not correct.
Comment: "There seems to be a lot of confusion over naming intervals. Some seem to think it involves major intervals being from major keys/scales, thus minor intervals need to follow from that. Some seem to think the number of semitones difference defines the interval. Neither are spot on. What is a simple way to define intervals, that works for all of them?" This answer IMO adds to the confusion mentioned by the OP and explicitly used a method the OP calls not correct.
Comment: However, it IS the simple method of naming any interval.

Defining intervals.


How to order a related table using list of ids in Django

Question: here is example of what I am trying to perform;
class GroupA(models.Model):
    name=models.CharField(max_length=250)

class GroupB(models.Model):
   category = models.CharField(max_length=250)
   group_a = models.ForeignKey(GroupA)

I have list of ids; [1, 2, 3]. How do I perform an order of GroupA through GroupB using the list of ids.
Currently, an example of data I am returning is;
[
{
"id": 3,
"category": "Category 1",
"group_a": [
   {
     "id": 2,
     "name": "John"
   },
   {
     "id": 1,
     "name": "Doe"
   },
   {
     "id": 3,
     "name": "Jane"
   }
]
}
]

What I am trying to archive is order the data of group_a using list of ids; [1, 2, 3]. So it would return something like this;
[
{
"id": 3,
"category": "Category 1",
"group_a": [
   {
     "id": 1,
     "name": "Doe"
   },
   {
     "id": 2,
     "name": "John"
   },
   {
     "id": 3,
     "name": "Jane"
   }
]
}
]

//Edit
Serializer.py
class GroupASerializer(serializers.ModelSerializer):
    class Meta:
       model = GroupA
       fields = "__all__"

class GroupBSerializer(serializers.ModelSerializer):
    group_a = GroupASerializer(read_only=True, many=True)
    class Meta:
       model = GroupB
       fields = "__all__"

views.py
class GroupBView(APIView):
    serializer_class = GroupBSerializer
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        group_trip = GroupB.objects.all()
        serializer = GroupBSerializer(group_trip, many=True)
        return Response(serializer.data)

Comment: show your current queryset
Answer: Maybe you should use ModelViewSet
class GroupViewSet(viewsets.ModelViewSet):
    queryset = GroupB.objects.all()
    serializer_class = GroupBSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return GroupB.objects.all().order_by('id')

I didn't check if it works


hook_form_alter doesn't load load my form_id

Question: I'm trying to hide a CCK field in my node-edit form. I followed this tutorial:
http://dominiquedecooman.com/blog/drupal-how-disable-form-element-cck-form-using-form-alter
but i'm stucked at the implementing hook_form_alter function, it seems that this hook doesn't recognize my form, i've tried this:
function video_tutorial_form_alter(&$form, &$form_state, $form_id) {
  print_r($form_id);
}

but it only prints "search_block_form search_theme_form";
Answer: You have 3 options if you wish to hide a form item:

Use .css and make your life simple using display:none;
create a custom module (see below)
Why even have the cck field if you are going to hide it? What's the point of that?

Please note that the above tutorial DISABLES the field and does not HIDE it. Disabled fields can not be edited, but they are still displayed!
To point 2:
Is this function in your themes template.php? If yes, I presume your theme is called 'video_tutorial', if not, you should rename your function so it is THEMENAME_form_alter.
However, since you're using the edit node form it will actually be using the admin theme, not your front end theme - unless you have changed permissions for certain usergroups not to be able to access the admin theme or you are using the front end theme as your admin theme (unlikely) -, so you're better off creating your own module to override the form rather than using the themes template.php file:
How to create your custom module:

Create a folder, call it whatever you like - but it should make sense - eg:
custom_admin_overrides

In it, create two blank text files:
custom_admin_overrides.info
custom_admin_overrides.module

Open custom_admin_overrides.info and add the basics so drupal can see your module:
name = Custom Admin Overrides
description = Custom Module that provides Admin Area Overrides
package = Custom
core = 7.x

Save the .info file and add the following to your custom_admin_overrides.module file:
<?php
function custom_admin_overrides_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'YOUR_FORM_ID') {
  $form['FIELD_NAME']['#disabled'] = TRUE;
 }
 // YOU CAN UNCOMMENT THE BELOW FOR EXTRA HELPFUL DETAILS
 // GET FORM ID UNCOMMENT BELOW
 drupal_set_message("YOUR_FORM_ID is : " . $form_id);
 // GET ALL FORM ELEMENTS UNCOMMENT BELOW
 // drupal_set_message(dprint_r($form, TRUE));
}

Note that we aren't closing the

Save and upload the folder to your site/all/modules/custom/ folder.
Now enable the module and from that point onwards you should see the form id's displayed on all admin pages in the drupal message box at the top.
Now go to your specific node create/edit page and make a note of the form id and the field name you wish to disable. Now reopen your custom_admin_overrides.module file and replace the values for
YOUR_FORM_ID

and
FIELD_NAME

Save and now your field should be uneditable. Uncomment the following line to stop displaying the form id's:
drupal_set_message("YOUR_FORM_ID is : " . $form_id);

Comment: Thank you tecjam for response, your solution is right. Problem was that hook_form_alter() didnt get form_id of form when i tried to submit it with not properly disabled cck field - i kept refreshing page with red "field is required" message. When i loaded edit form again everything works correctly


Generic Multiplication of Different Types

Question: In simple words, I want to implement a function like that:
let myfunction (scalar : float) (quantities : ''T list) =
    List.fold (fun acc quantity -> acc + quantity * scalar)
        LanguagePrimitives.GenericZero<_>
            quantities : 'T

Note that I am multiplying a value of generic type 'T and a float value (quantity * scalar) which should return a value of type 'T. For example, multiplying a Point by a scalar result in a Point.
I cannot make F# understand that the multiplication quantity * scalar should result in a value of type 'T. I tried LanguagePrimitives.MultiplyDynamic, but it seems that this function is reserved to be used by the F# compiler.
What should I do?
Answer: Is there any reason to specialize to the case where scalar is a float?  I think your best bet is to generalize even further:
let inline myfunction scalar quantities =
    List.fold (fun acc quantity -> acc + quantity * scalar)
        LanguagePrimitives.GenericZero<_>
        quantities

Comment: Nice, the inline resolved my problems. Amazing how easy you can write generalized code in F#! I am getting passionate for this language everyday!


Showing that the definition of a morphism from $V_1$ to $V_2$ in Silverman is well-defined

Question: Silverman (in Arithmetic of Elliptic Curves) defines a morphism between projective varieties $V_1$ and $V_2$ to be a map $\phi = [\phi_0, \dots, \phi_n]$ such that

the $\phi_i(X) \in \overline{K}[X] = \overline{K}[X_0, \dots, X_n]$ are homogeneous polynomials, not all in $I(V_1)$, having the same degree;
for every $f \in I(V_2)$, $f(\phi_0(X), \dots, \phi_n(X)) \in I(V_1)$.

Then says that if $P$ is a point of $V_1$ where all of the $\phi_i$ vanish, and we have a set of polynomials $\psi_0, \dots, \psi_n$ such that

$\psi_0, \dots, \psi_n$ have the same degree;
$\phi_i \psi_j \equiv \psi_i \phi_j \pmod{I(V_1)}$ for all $0 \leq i, j \leq n$;
$\psi_i(P) \neq 0$ for some $i$,

we take $\phi(P) = [\psi_0(P), \dots, \psi_n(P)]$.
I'm having trouble verifying from the definitions that $[\psi_0(P), \dots, \psi_n(P)]$ is guaranteed to be in $V_2$. I think that the requirements on the $\psi_i$ and $\phi_i$ should force $f(\psi_0(X), \dots, \psi_n(X)) \in I(V_1)$ just algebraically, which would be enough, but I can't figure out how to use $\phi_i \psi_j \equiv \psi_i \phi_j \pmod{I(V_1)}$ for all $0 \leq i, j \leq n$ to get this to come out. Can anyone help me find the trick?
Answer: Figured this out with the help of a peer so I'll post this to get the question off of the unanswered queue.
Since $I(V_2)$ is a homogeneous ideal, we need only check that $f(\psi_0, \dots, \psi_n) \in I(V_1)$ for the homogeneous generators of $I(V_2)$. Letting $f$ be such a generator, and $i$ be some index such that $\phi_i$ is not in $I(V_1)$, we have that $\psi_i^{\deg f} f(\phi_0, \dots, \phi_n) \in I(V_1).$ But since $f$ is homogeneous, we get that $\psi_i^{\deg f} f(\phi_0, \dots, \phi_n) = f(\psi_i \phi_0, \dots, \psi_i \phi_n) \in I(V_1)$. Looking modulo $I(V_1)$, we have that $f(\psi_i \phi_0, \dots, \psi_i \phi_n) \equiv f(\psi_0 \phi_i, \dots, \psi_n \phi_i) \equiv \phi_i^n f(\psi_0, \dots, \psi_n) \equiv 0$. But $I(V_1)$ is prime, and $\phi_i \not\in I(V_1)$, so $f(\psi_0, \dots, \psi_n) \in I(V_1)$. Since this is true for the homogeneous generators of $I(V_2)$, it holds for all $f \in I(V_2)$, so $[\psi_0(P), \dots, \psi_n(P)] \in V_2$.


What does "con piu fuoco possibile" mean?

Question: Towards the end of Chopin's Etude No. 4 in C# minor, Op. 10 No. 4, it says "con più fuoco possibile." What does this mean?
Answer: Word by word:

con - with
più - more
fuoco - fire
possibile - possible

In Italian, "possibile" stuck on the end of a phrase means "as much [preceding thing] as possible".
So translated as a phrase: "With as much fire as possible"
Answer: Definition of con fuoco
: FIERILY, IMPETUOUSLY —used as a direction in music
possibile = as possible
https://www.merriam-webster.com/dictionary/con%20fuoco
Con fuoco Definition and background:A musical directive to the performer to play a particular passage with vehement energy or fervid emotion. with fire, in a fiery manner
this means: most fierly
but not hot sexy!

this was only con fuoco! you can't imagine like it would be:
con piu fuoco possibile piu = even more!
edit! the commentors are right:
this conductor explains much better
what con fuoco means:
Comment: That has to be the sickest interpretation of Dvorak I've ever seen.  Eye bleach please!  (and in all seriousness, that team lap dance would go with any 2/4 or 4/4 tune)
Comment: Second YouTube link is dead. No description, so can't find a replacement.
Comment: I actually find Dvorak's 9-4 to be triumphant and heroic, as if I were in a war between a large amount of villains and I have triumphed over them.
Comment: @Aaron If you google the end of the youtube link, you can usually find mirrors on facebook and shady Russian-hosted websites.  It looks like that one pointed to "Gustavo Dudamel _ Dvorak - Symphony no. 9 - 4th movement - Allegro con fuoco".


PHP JSON does not work, can anyone tell me why?

Question: myfile.php
header('Content-type: application/json');

echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );

the above code works.
but when I alter it it stops working:
if( isset( $_GET['customerID'] ) ){

       // do something else error

} else {

   header('Content-type: application/json');
   echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );

}

both outputs are correct:
{"error":"jkfshdkfj hskjdfh skld hf."}

but I get an ajax error:
myfile.phtml
        <?php
            if( isset( $_GET['custID'] ) )
               echo "var custID = " . htmlentities( $_GET['custID'] ) . ";";
            else
               echo "var custID = null;";
        ?>

        $.ajax({

            url: 'php/viewCustomer.php',
            type: 'GET',
            data: {customerID: custID},
            dataType: 'json',
            cache: false,
            beforeSend: function(){

                $('#display').append('
 Lodaing ...
');

            },
            complete: function(){

                $('#loader').remove();

            },
            success: function( data ){

                if( data.error ) {

                    var errorMessage = "";

                    $.each( data, function( errorIndex, errorValue ){

                        errorMessage += errorValue + "\n";

                    });

                    alert( errorMessage );

                } else {

                    //$('div#customer-content table tr td').eq(0).text( '1234' );
                    //$('div#customer-content table tr td').eq(1).text( '1234' );
                    //$('div#customer-content table tr td').eq(2).text( '1234' );
                    //$('div#customer-content table tr td').eq(3).text( '1234' );
                    //$('div#customer-content table tr td').eq(4).text( '1234' );
                    alert( data );

                }

            },
            error: function( jqXHR ){

                alert( 'AJAX ERROR' );

            }

        });

    });

Comment: You are passing a customerID with the ajax request, so it's going into the if - what output are you expecting?
Comment: What error do you get? What happens when `customerID` is set?
Comment: The error is 'AJAX ERROR' from the error: function( jqXHR ) { alert( 'AJAX ERROR' ); }
Comment: data: {customerID: custID} = where is the custID coming from?
Comment: Chad, if customerID is set I do nothing at the moment. empty if block.
Comment: Oli, it is currently NULL.
Comment: Tim, json data, but its currently empty.
Comment: So then your php isn't sending back to your ajax script, if that PHP snippet is complete, right?
Comment: @TimFountain Has answered this. Although the value might be null or undefined in javascript, the if condition in php is met. So what do you expect?
Comment: Oli the browser out of myfile.php is {"error":"jkfshdkfj hskjdfh skld hf."}
Comment: hek2, I am getting the output {"error":"shdkfj hskjdfh skld hf."} in myfile.php in the broswer.
Comment: According to your question, myfile.php has 2 different sets of code in it. However you haven't shown us what is in 'php/viewCustomer.php' and this is the script being called by the AJAX routine.
Comment: but you're referencing 'php/viewCustomer.php' in your script..
Comment: Oli, thats not an error, Ive just called it myfile for simplicity.
Comment: Ok glad the 'empty()' is working for you..don't understand how you could still see the error if this fixed it though!
Comment: Oli, I did a bit of amending my self the if block contains   header('Content-type: application/json');
   echo json_encode( array( 'data' => 'jkfshdkfj hskjdfh skld hf.' ) );
Answer: From the comments it sounds like you are passing a null customerID and are not expecting it to go into the if condition. But even if the value is null, $_GET['customerID'] is still set. Change the check to empty() instead and it will work as you expect:
if( !empty( $_GET['customerID'] ) ){
    ....


How to store an image in a subfolder in a Sdcard in Android?

Question: I want to store my images in an sdcard subfolder. I have done the following but my images are not getting stored in the subfolder.How can I save my images in the subfolder?
My codes are as follows:
 final File wallpaperDirectory = new File("/sdcard/Wallpapertask/");
 wallpaperDirectory.mkdirs();
 myImageView1.setImageBitmap(circleBitmap);
 BitmapDrawable drawable = (BitmapDrawable)myImageView1.getDrawable();
 Bitmap bitmap = drawable.getBitmap();
 File sdCardDirectory = Environment.getExternalStorageDirectory();
 File image = new File(sdCardDirectory, "test2.png");

Comment: possible duplicate of [Android Camera - Save image into a new folder in SD Card](http://stackoverflow.com/questions/8588838/android-camera-save-image-into-a-new-folder-in-sd-card)
Answer:
How can I save my images in the subfolder?

Your code does not save any images. You can use the compress() method on Bitmap to write a Bitmap to an OutputStream.
Also note that you should not be hardcoding paths, like /sdcard/Wallpapertask, as that path will not work on all devices or for all users.


Linear Algebra questions on terminology and concepts

Question: If my reduced row echelon of the matrix looks like
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 &0\\
0 & 1 & 0 & 0 &0 &0\\
0 & 0 & 0 & 0 &0 & 0\\
0 & 0 & 0 & 0 &0 & 0\\
0 & 0 & 0 & 0 &0 &0\end{pmatrix}
then using the linear algebra terminology I would say that the dimension or the degrees of freedom is two correct?
What is meant by $Ker(M) \neq 0$? I don't understand this and would need an example. Also if the $Ker(M) = 0$ is the matrix $M$ invertible? Does the converse of this statement hold? Please help I want to get this material to pass my linear algebra class
Comment: Dimension of *what* is two? The dimension of the row space is two; the dimension of the column space is two; the rank is two. The kernel is the nullspace. the zero-vector is always in the nullspace. Kernel not zero means the zero vector isn't the only element of the nullspace. If the kernel is zero, *and the matrix is square*, then, yes, it is invertible.
Comment: The dimension of the matrix that I put up.
Comment: A matrix doesn't have a dimension. If you like, it has *two* dimensions, a height and a length --- your matrix has dimensions $5\times6$.
Comment: @depressed Dimension has a very specialized meaning in linear algebra. By "degrees of freedom" do you mean the number of _free variables_?
Comment: Could you give me an example of a matrix $M$ where the kernel is not zero? And if the kernel is zero how many vectors are there in the nullspace?
Comment: I have written down in my notes that the "dimension of a space is the number of degrees of freedom of the space."
Comment: The matrix you have given has kernel not zero. Do you know what the nullspace of a matrix is?
Comment: @depressed: That is an extremely vague statement. Did your instructor talk about vector spaces at all?
Comment: By kernel being zero, we really mean that $\ker(M) = \{\mathbf{0}\}$, so by definition, if the kernel is zero (or more technically _trivial_) then it contains only the zero vector. And that is a horrible definition of dimension.
Comment: @depressed: Do you realize that nullspace is another name for kernel?
Comment: @wj32, yes I do know that the nullspace is another name for kernel. I had to study that for a midterm. The professor asked us to study the terms.
Comment: @depressed Can you outline briefly what exactly you have learned so far? It doesn't have to be very detailed, just the general ideas so we know how to approach your problem.
Comment: @EuYu: We have studied the kernel (nullspace), dimension, rank, span, eigenvalues, basis, gaussian elimination and discussed something about free variables.
Comment: @depressed: Can you tell us what a basis is, according to your instructor?
Comment: A basis is a set of linearly independent vectors that can form any vector in the vector space roughly speaking.
Comment: @ Gerry: What other vector is in the nullspace  of the matrix besides the zero vector?
Comment: $\begin{pmatrix}0 & 0 & 0 & 0 & 0 & 1\end{pmatrix}^\mathrm{T}$ for example.
Comment: $(0 0 0 1 0 0)^T$ is another. Thanks.
Answer: You could say that the dimension or the degrees of freedom "is two" for this matrix, but you'd be being pretty vague. Here are some more precise things you could say:
The dimension of the column space is two, i.e. there are two linearly independent vectors which span the space spanned by the columns. Similarly for the row space.
The nullspace or kernel has dimension $3$. The kernel is the space that your matrix sends to $0$. You can see that it has dimension three in this case because
$$\left( \begin{matrix} 0\\0\\1\\0\\0\end{matrix}\right),\left( \begin{matrix} 0\\0\\0\\1\\0\end{matrix}\right),\left( \begin{matrix} 0\\0\\0\\0\\1\end{matrix}\right) $$
are all send to $0$, while all nonzero combinations of the other two basis vectors are not.
The image has dimension $2$. This is the dimension of the space your matrix maps onto. It's got the same dimension as the column space, because each column is the image of a basis vector.
A central fact in linear algebra is the rank-nullity theorem. This says that for any linear transformation $T$ from $V$ to $U$ the dimension of the kernel and the dimension of the image sum to the dimension of the domain, $V$. So if $V=U$, or more generally if they have the same dimension, then if $\ker T=0$ the rank-nullity theorem tells us the image of $T$ has the full dimension of $U$, which does mean that $T$ is invertible.
However, if $U$ and $V$ have different dimensions, $T$ can have no kernel but $0$ and still not be invertible: consider the map from $\mathbb{R}^2\to\Bbb{R}^3$ that sends $\left(\begin{matrix}1\\0\end{matrix}\right)$ to $\left(\begin{matrix}1\\0\\0\end{matrix}\right)$ and
$\left(\begin{matrix}0\\1\end{matrix}\right)$ to
$\left(\begin{matrix}0\\1\\0\end{matrix}\right)$. This isn't invertible, because for instance nothing maps to $\left(\begin{matrix}0\\0\\1\end{matrix}\right)$.
Comment: I appreciate the depth you gave and the understanding really came through
Answer: Let me address a few concepts here, my apologies that this answer got so long. It is not too clear what exactly your question is (since you seem to be confused on the terminology a bit) so hopefully I'll be able to address most of your issues.
First let me begin with the concept of a basis. A basis is a set of vectors in a vector space. A basis is defined as a set which is both linearly independent and spanning. Every element in the vector space can be written in a unique linear combination of a set of basis vectors.
Next, the concept of dimension in linear algebra is very specific. Formally, dimension is a number associated with a vector space. If $V$ is a vector space (if you are uncomfortable with arbitrary vector spaces,  then just replace all my $V$s with $\mathbb{R}^n$) then the dimension of $V$ is the number of vectors in a basis of $V$. It turns out that this definition is well defined since all basis of a vector space have the same size.
Very informally, dimension addresses the size (or "degree of freedom" if you will) of the vector space. In $\mathbb{R}^2$ we have the standard basis
$$\left\{\begin{pmatrix}1 \\ 0 \end{pmatrix},\ \begin{pmatrix}0 \\ 1\end{pmatrix}\right\}$$
which spans the space. Any vector in $\mathbb{R}^2$ can be written uniquely as
$$a\begin{pmatrix}1 \\ 0 \end{pmatrix} + b\begin{pmatrix}0 \\ 1 \end{pmatrix}$$
for scalars $a,\ b\in\mathbb{R}$, so I guess you can say that the "degree of freedom" is $2$ since you may vary the two scalar coefficients $a$ and $b$ (be careful with this "degree of freedom" idea though since it is very ambiguous, it is useful as an intuitive aid but make sure you know the proper definition of dimension). Similarly, the dimension of $\mathbb{R}^3$ would be $3$ and in general $\dim\left(\mathbb{R}^n\right) = n$.
Finally, let me address your actual question. From the above, you can see that dimension is a term reserved for a vector space. It makes no real sense to ask about the dimension of a matrix. If you are referring to the height and width of the matrix, then I would simply talk about the size of the matrix. That being said, there are several very special and very important vector spaces which are associated with each matrix. The three you may have been exposed to are the rowspace, columnspace and the nullspace (or kernel). It turns out that the dimension of the columnspace and the rowspace are always the same and we give it the name rank. The rank of a matrix is the dimension of its rowspace and columnspace.
The dimension of the nullspace is called the nullity of the matrix. If you look at your matrix in reduced row echelon form and count the number of pivot entries (leading $1$s) then that gives you the rank of the matrix. The remaining non-pivot columns each correspond to a variable which is free to be adjusted. We call these free variables and each free variable gives one "degree of freedom" to the nullspace; more formally, the nullity of the matrix is the number of free variables. The matrix you posted has $2$ pivot columns (columns one and two) and $4$ non-pivot columns (columns three to six). That means it has rank $2$ and nullity $4$. I'm not sure if you know how to find the nullspace of the matrix by inspecting its reduced row echelon form, I will assume you do and move on.
When we say the kernel is zero (or trivial), we really mean that the dimension of the kernel is $0$, i.e. it contains only the zero vector. From the above, this can happen if and only if each column of the matrix is a pivot column. If the matrix happens to be square (invertible is a term normally reserved only for square matrices, it's a bit tricky to talk about rectangular inverses), then a trivial kernel implies that the matrix is row equivalent to the identity matrix which of course means that it is invertible. The converse also holds. In fact, a square matrix has trivial kernel if and only if it is row equivalent to the identity matrix if and only if it is invertible. This is only three conditions of a long chain of equivalencies sometimes termed the invertible matrix theorem which you will eventually (or may have already) be exposed to.


i need code for hyperlink that is activated while clicking on nodes?

Question: I have to view my data as a visual network format so used cytoscape web. I have used example link http://lekshmideepu.blogspot.in/2012/03/cytoscape-web-examples.html for my drawing a network with different colored nodes and edges,It works color and size for node/edge. I need to set one more event hyperlink for each node. please need on-click event node as hyperlink in network?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

                Cytoscape Web will replace the contents of this div with your graph.

Answer: Bind to the click event and set window.location.href appropriately in the handler.
Comment: Please i didnt get clear please give simple sample code for hyperlink that is activated while clicking on nodes
Answer: Assuming the network data has a node attribute called "link", you can do something like this:
vis.addListener("click", "nodes", function(evt) {
    var node = evt.target;
    var link = node.data.link;
    window.open(link);
});

See:
http://cytoscapeweb.cytoscape.org/documentation/visualization#section/addListener
http://cytoscapeweb.cytoscape.org/documentation/events#section/EventType
Of course, you can get the links from anywhere you want, like your own data cache stored in a JavaScript object, for instance. You don't need to store them in Cytoscape Web, as node attributes, but that may be more convenient.
Answer: I created a function which goes to a link by a right-click (obviously you can change that part to whatever you want:
 cy.on('cxttap','node', function(e){
  var url=this.data('link');
   window.open(url);

});
And the "data" part of the element looks like this:
{ data: { id: 'a', name: 'a',link:'http://google.com' },classes:'a'},


Google Cloud Healthcare API search by date with time zone on FHIR resource returns error

Question: I'm using Google Healthcare API and trying to search a FHIR resource by date with time zone, like example below:
https://healthcare.googleapis.com/v1/projects/project-id/locations/us-central1/datasets/dataset/fhirStores/fhirstore/fhir/Appointment?date=2020-01-23T08:29:00+03:00

And i'm getting this error:
{
    "issue": [
        {
            "code": "value",
            "details": {
                "text": "invalid_query"
            },
            "diagnostics": "error parsing date \"2020-01-23T08:29:00 03:00\": invalid dateTime: 2020-01-23T08:29:00 03:00",
            "severity": "error"
        }
    ],
    "resourceType": "OperationOutcome"
}

According to the documentation both FHIR and Google:
Date searches on any type of date, time, or period. The date parameter format is yyyy-mm-ddThh:mm:ss[Z|(+|-)hh:mm], and the same prefix modifiers used for number also apply here.

It should work, but when the timezone signal is "plus +". It throws an error.
When is "minus -" ex: /Appointment?date=2020-01-23T08:29:00-03:00. it works.
Am I missing something? It looks like a bug to me.
Thanks!
Answer: Looks like a URL escaping issue - plus is one of the special characters in URLs.
Try date=2020-01-23T08:29:00%2B03:00, this works when I try it.


Como obter posição de uma sub-lista dentro de outra lista?

Question: Tenho uma lista de bytes e preciso verificar se ela contém uma sub-lista de bytes em uma ordem específica.
Como posso fazer essa verificação obtendo a posição da sub-lista de uma maneira simples, usando os recursos do Linq ou da própria List, ou seja, sem a necessidade de ter que fazer um for verificando posição a posição.
Exemplificando:
List<byte> bytes = new List<byte> { 10, 20, 30, 40, 50, 60, 70, 80  };
List<byte> pattern = new List<byte> { 30, 40, 50 };

int indiceInicioSublista = ???

Answer: Você pode aninhar dois loops para fazer isso: para cada posição válida da lista principal, verificar se cada item da lista sendo buscada bate. Se chegar até o final sem achar, então retorna um valor negativo, indicando que não achou.
A versão LINQ, equivalente está no final da resposta.
public static int FindSubList<T>(IList<T> mainList, IList<T> subList)
{
    for (int it = 0; it <= mainList.Count - subList.Count; it++)
    {
        bool allEquals = true;
        for (int it2 = 0; it2 < subList.Count; it2++)
        {
            if (!mainList[it + it2].Equals(subList[it2]))
            {
                allEquals = false;
                break;
            }
        }

        if (allEquals)
            return it;
    }

    return -1;
}

Usando o LINQ ficaria assim, que é o equivalente ao código acima:
public static int FindSubList<T>(IList<T> mainList, IList<T> subList)
{
    for (int it = 0; it <= mainList.Count - subList.Count; it++)
        if (!subList.Where((t, it2) => !mainList[it + it2].Equals(t)).Any())
            return it;

    return -1;
}

Outra alternativa usando LINQ sobre IEnumerable, entretanto essa solução é mais lenta do que a de cima:
public static int FindSubEnumerable<T>(IEnumerable<T> mainList, IEnumerable<T> subList)
{
    return
        Enumerable.Range(1, mainList.Count())
            .FirstOrDefault(it => mainList.Skip(it - 1).Take(subList.Count()).SequenceEqual(subList)) - 1;
}

Comment: Obrigado, mas estou procurando uma versão mais simples sem usar for. Usando for eu já consegui fazer.
Comment: Eu indiquei uma solução LINQ! Está no final da resposta.
Comment: Agora eu indiquei outra alternativa, usando LINQ puro, sobre `IEnumerable` ao invés de listas.
Comment: A versão com `IEnumerable` é mais lenta, eu recomendo a segunda solução, que é usando LINQ sobre `IList`.
Comment: @MiguelAngelo no código seu não deveria ser  em vez de  ?
Comment: @FCCDias: Realmente! Fiz os códigos ficarem genéricos de forma que qualquer tipo de dados seja suportado.
Comment: A versão LINQ com IList ainda está com problemas, vou arrumar isso.
Comment: Testei a última opção, e funcionou corretamente. Obrigado.
Comment: Corrigido, ao converter para genérico, inverti sem querer a condição de teste.
Answer: Pega a igualdade de elementos independente da posição.
List<byte> result = bytes.Where(e => pattern.Contains(e)).ToList<byte>();
IEnumerable<byte> result1 = bytes.Intersect(pattern);
IList<byte> result3 = bytes.Intersect(pattern).ToList<Byte>();

Retornar true, se bytes estiver dentro de pattern, que foram convertidos em String.
bool retorno = String.Join("", bytes).Contains(string.Join("", pattern));

Referências
1 - Getting Started with LINQ in C#
2 - 101 LINQ Samples
Comment: Dessa forma, mesmo que o pattern mude, ele continuar trazendo o resultado. A ordem do pattern é importante.
Comment: Então, @RenatoDinhaniConceição, no caso ele vai trazer os elementos que se repete independente da ordem !!! é isso !!! ou entendi errado
Comment: Então, na verdade, a ordem é importante sim.
Comment: O pattern é um cabeçalho de um protocolo, e quando ele é encontrado, todo o conteúdo depois dele tem um significado diferente.
Comment: Mude o pattern para `{ 30, 50, 40 }`. Não é pra retornar nada.
Comment: Caro @RenatoDinhaniConceição, porque, você não forneceu isso na pergunta, que os dados tem sequencia ?
Comment: Primeira linha da pergunta: "se ela contém uma sub-lista de bytes em uma ordem específica."
Comment: @RenatoDinhaniConceição isso não ta claro


Find the sum $\sqrt{5+\sqrt{11+\sqrt{19+\sqrt{29+\sqrt{41+\cdots}}}}}$

Question: Okay so this can be written as $$\sqrt{5+\sqrt{(5+6)+\sqrt{(5+6+8)+\sqrt{(5+6+8+10)+\sqrt{(5+6+8+10+12)\cdots}}}}}$$
Putting it as $y$ and squaring both sides doesn't seem to help, and I don't know what else can be done.
Comment: Please give the rule for the coefficients $5, 11, 19,  \ldots$ in your formula (which, by the way, is not a sum).
Comment: The terms seem to be given by $n^2 + 3n + 1$ for $n \geq 1$.
Comment: Just a nitpick on the title: this is not actually a sum.
Comment: Numerically, it seems to converge to 3.
Comment: Thanks, but I actually need to compute it theoretically.
Answer: Heuristic Idea. We may adopt the technique for Ramanujan's infinite radical.
Let $p(x) = x^2 + 3x + 1$ and define $F : [0, \infty) \to [0, \infty)$ by
$$ F(x) = \sqrt{p(x) + \sqrt{p(x+1) + \sqrt{p(x+2) + \cdots }}} $$
Then $F$ solves the functional equation
$$ F(x)^2 = p(x) + F(x+1). $$
Now we make an ansatz that $F(x)$ takes the form $F(x) = ax + b$. Plugging this into the functional equation and comparing the coefficients shows that
$$ F(x) = x + 2. $$
Finally, since $(p(1), p(2), p(3), \ldots) = (5, 11, 19, \ldots) $, the infinite radical in question corresponds to the case $x = 1$. Therefore we conclude
$$ \sqrt{5 + \sqrt{11 + \sqrt{19 + \cdots}}} = F(1) = 3. $$

Justification. Fix a constant $a \in (1, 2) $. Also, let $\mathcal{C}$ denote the set of all continuous functions $f : [0, \infty) \to \mathbb{R}$ such that $f(x) = \mathcal{O}(a^x)$ as $x \to \infty$. Then $\mathcal{C}$ is a Banach space with respect to the norm $\|\cdot\|$ defined by
$$ \| f\| := \sup_{x \geq 0} \left( a^{-x} |f(x)| \right). $$
Now, write $p(x) = x^2 + 3x + 1$ and define the subset $\mathcal{A}$ of $\mathcal{C}$ by
$$\mathcal{A} = \{ f \in \mathcal{C} : f(x) \geq 0 \text{ for all } x \geq 0 \}. $$
This is a closed subset of $\mathcal{C}$. Now define the operator $\Phi : \mathcal{A} \to \mathcal{A}$ by
$$ \Phi[f](x) = \sqrt{p(x) + f(x+1)}. $$
$\Phi$ is indeed a well-defined operator on $\mathcal{A}$, for if $f \in \mathcal{A}$, then we have
$$ \limsup_{x\to\infty} a^{-x} |\Phi[f](x)|
\leq \lim_{x\to\infty} a^{-x} \sqrt{p(x) + a^{x+1}\|f\|}
= 0 $$
and hence $\| \Phi[f] \| < \infty$. Moreover, if $f, g \in \mathcal{A}$, then
\begin{align*}
a^{-x} \left| \Phi[f](x) - \Phi[g](x) \right|
&= a^{-x} \cdot \frac{\left| f(x+1) - g(x+1) \right|}{\sqrt{p(x) + f(x+1)} + \sqrt{p(x) + g(x+1)}} \\
&\leq a^{-x} \cdot \frac{a^{x+1} \| f - g \|}{2} \\
&= \frac{a}{2} \| f - g \|.
\end{align*}
By the choice of $a$, $\Phi$ is a contraction mapping on $\mathcal{A}$. So, by the contraction mapping theorem, we conclude:

There exists a unique $F \in \mathcal{A}$ for which $\Phi[F] = F$, and
Such $F$ is realized as the limit $\Phi^{\circ n}[f]$ as $n\to\infty$ for arbitrary initial choice $f \in \mathcal{A}$.

Finally, we already know that $F(x) = x+2$ is an element of $\mathcal{A}$ that solves $\Phi[F] = F$. Therefore, for any $ f \in \mathcal{A}$, we have
$$ \lim_{n\to\infty} \Phi^{\circ n}[f](x) = x+2. $$
Answer: Maybe works, $$3=\sqrt{3^{2}}=\sqrt{5+4}=\sqrt{5+\sqrt{16}}=\sqrt{5+\sqrt{11+5}}$$
$$=\sqrt{5+\sqrt{11+\sqrt{25}}}=\sqrt{5+\sqrt{11+\sqrt{19+6}}}=\sqrt{5+\sqrt{11+\sqrt{19+\sqrt{36}}}}$$
$$=\sqrt{5+\sqrt{11+\sqrt{19+\sqrt{29+7}}}}=\sqrt{5+\sqrt{11+\sqrt{19+\sqrt{29+\sqrt{49}}}}}=\sqrt{5+\sqrt{11+\sqrt{19+\sqrt{29+\sqrt{41+8}}}}}=\ldots$$
This is just a beautiful way of writing 3.
Comment: Last line should have $\sqrt{41+8}$ not $\sqrt {41+7}.$
Comment: Needs more argument.  Note, starting with any value larger than $3$, we can do this...\begin{align}4 &= \sqrt{5+11}\\&=\sqrt{5+\sqrt{11+110}}\\& =\sqrt{4+\sqrt{11+\sqrt{19+12081}}}\\&=\dots\end{align}
Answer: This is a slightly more rigorous form of @Pablo_'s excellent insight. @Sangchul Lee covers the full, analytic answer.
Set $a_n = n^2 + 5n + 5$ for $n \geq 0$. This sequence gives the coefficients of the "infinite radical." Rather than consider the full infinite radical, consider the "partial radicals," defined as $$r_n = \sqrt{a_0 + \sqrt{a_1 + \cdots + \sqrt{a_n + (4 + n)}}}.$$
As Pablo_Lee notes, $r_n = 3$ for all $n$. To see this, observe that $a_n + (n + 4) = (n + 3)^2$. This allows us to "unroll" the radical back to $a_0$. For example, $$a_{n - 1} + \sqrt{a_n + (n + 4)} = a_{n - 1} + n + 3 = a_{n - 1} + ((n - 1) + 4) = ((n - 1) + 3)^2.$$ Therefore,
$$
\begin{align*}
    r_n &= \sqrt{a_0 + \sqrt{a_1 + \cdots + \sqrt{a_{n - 1} + \sqrt{a_n + (n + 4)}}}} \\
        &= \sqrt{a_0 + \sqrt{a_1 + \cdots + \sqrt{a_{n - 1} + ((n - 1) + 4)}}} \\
        &= \sqrt{a_0 + \sqrt{a_1 + \cdots + \sqrt{a_{n - 2} + ((n - 2) + 4)}}} \\
        &\vdots \\
        &= \sqrt{a_0 + \sqrt{a_1 + 5}} \\
        &= \sqrt{a_0 + 4} \\
        &= \sqrt{(0 + 3)^2} \\
        &= 3.
\end{align*}
$$
(There is likely a snappy way to do this by induction, but I don't see it yet.)
If we are willing to define the full radical as $\lim_{n \to \infty} r_n$, then this should also be an acceptable answer.
Now canonically, the expression $\sqrt{a_0 + \sqrt{a_1 + \sqrt{a_2 + \cdots}}}$ (note that the ellipsis appears in a sum) would refer to the sequence $$r'_n = \sqrt{a_0 + \sqrt{a_1 + \cdots + \sqrt{a_n + 0}}}.$$  But since $r'_n \le r_n$, convergence follows immediately from the monotone convergence theorem.

Edit: For any integer $r \geq 2$, setting $p_n = n^2 + (2r - 1)n + r^2 - r - 1$ and $q_n = n + r + 1$ should yield, through the same arguments, $$r = \sqrt{p_0 + \sqrt{p_1 + \cdots + \sqrt{p_n + q_n}}}$$ for all $n \geq 0$. Note that $p_n$ is merely a shifted form of the Fibonacci polynomial $n^2 - n - 1$ at integer values.
For example, $$4 = \sqrt{11 + \sqrt{19 + \sqrt{29 + \sqrt{41 + 8}}}}.$$
Answer: Set
$ p(x) = x^2 - 3x + 1$
and observe that
$ p(x) + x = (x - 1)^2.$
Then for $r \ge 0$,
$$r = \sqrt{r^2} \\
= \sqrt{p(r + 1) + r + 1} \\
= \sqrt{p(r + 1) + \sqrt{(r + 1)^2}} \\
= \sqrt{p(r + 1) + \sqrt{p(r + 2) + r + 2}} \\
= \sqrt{p(r + 1) + \sqrt{p(r + 2) +  \sqrt{(r + 2)^2}}} \\
= \sqrt{p(r + 1) + \sqrt{p(r + 2) +  \sqrt{p(r + 3) + r + 3}}} \\
= \sqrt{p(r + 1) + \sqrt{p(r + 2) +  \sqrt{p(r + 3) + \sqrt{p(r + 4) + r + 4}}}} \\
= \sqrt{p(r + 1) + \sqrt{p(r + 2) +  \sqrt{p(r + 3) + \sqrt{p(r + 4) + \sqrt{p(r + 5) + r + 5}}}}} \\
= \ldots
$$
Now define for $q \ge 0$:
$$ F(r,q,x_0) = \begin{cases}
\sqrt{p(r + 1) + F(r + 1, q, x_0)}, & \mbox{if } r + 1 \le q\\
x_0, & \mbox{if }  r + 1 \gt q.
\end{cases}
$$
So in particular:
$$\begin{array}{llll}
 & F(r, r + 1, 0) &=& \sqrt{p(r + 1) + 0} \\
<& F(r, r + 2, 0) &=& \sqrt{p(r + 1) + \sqrt{p(r + 2) + 0}} \\
<& F(r, r + 3, 0) &=& \sqrt{p(r + 1) + \sqrt{p(r + 2) + \sqrt{p(r + 3) + 0}}} \\
<& \lim_{n \rightarrow \infty} F(r, r + n, 0) &=_{\mbox{def}}& \sqrt{p(r + 1) + \sqrt{p(r + 2) + \sqrt{p(r + 3) + \ldots}}}
\end{array}$$
and also
$$\begin{array}{llll}
F(r, r + 1, 0) &< F(r, r + 1, r + 1) &= \sqrt{p(r + 1) + r + 1} &= r\\
F(r, r + 2, 0) &< F(r, r + 2, r + 2) &= \sqrt{p(r + 1) + \sqrt{p(r + 2) + r + 2}} &= r \\
F(r, r + 3, 0) &< F(r, r + 3, r + 3) &= \sqrt{p(r + 1) + \sqrt{p(r + 2) +  \sqrt{p(r + 3) + r + 3}}} &= r \\
F(r, r + n, 0) &< F(r, r + n, r + n) &= \ldots &= r.
\end{array}$$
So by the monotone convergence theorem, the limit
$$F(r, \infty, 0) =_{\mbox{def}} \sqrt{p(r + 1) + \sqrt{p(r + 2) + \sqrt{p(r + 3) + \ldots}}}$$
actually exists (and it's at most $r$). As it exists, it must satisfy the equation
$$F(r, \infty, 0) = \sqrt{p(r + 1) + F(r + 1, \infty, 0)}.$$
Now this is clearly satisfied for $F(r, \infty, 0) = r$, but that doesn't mean (yet) that $r$ is the answer. For $r = 0$, of course, we know
$$0 \le F(0,\infty,0) \le 0.$$
We also know
$$F(r + 1, \infty, 0) = F^2(r, \infty, 0) - p(r + 1).$$
If we use $F(r, \infty, 0) = r$ as an induction hypothesis, we obtain
$$\begin{array}{ll}
F(r + 1, \infty, 0) &= r^2 - p(r + 1)\\
&= r^2 - ((r + 1 - 1)^2 - (r + 1))\\
&= r + 1\\
\end{array}$$
for $r\in\mathbb N$ #.
Note on $0 \le r \lt \frac{1 + \sqrt 5}{2}$. When $p(r + 1) < 0$, we have to resort to the complex square root to make everything work. In that case, the monotonous convergence theorem has to be applied separately to the real and imaginary part of $F$. In particular (after a few terms), the real part increases towards $r$ (as expected), while the imaginary part decreases towards $0$.
$$\begin{array}{rcl}
F(0,1,0) &=& i\\
F(0,2,0) &=& e^{3\pi i/8}\\
F(0,3,0) &=& i\\
F(0,4,0) &\approx& 0.3259i\\
F(0,5,0) &\approx& 0.1062i\\
F(0,6,0) &\approx& 0.04115i\\
F(1,2,0) &=& i\\
F(1,3,0) &=& 0\\
F(1,4,0) &\approx& 0.8938\\
F(1,5,0) &\approx& 0.9852\\
F(1,6,0) &\approx& 0.9983
\end{array}$$
A key observation here is that $-1 + \sqrt{1 + \sqrt 5} > 0$.


Running shell command using shell_exec

Question: Im using an ajax call to execute "shell_exec" on the server (centos).
The line that im executing is the following
echo shell_exec("php -q /websockets/timedactions.php");

This is the server response:
X-Powered-By: PHP/5.5.16
Access-Control-Allow-Origin: http://myIpAddress
Access-Control-Allow-Credentials: true
Content-type: text/html

0

After running this command it seems that the process that it supposed to activate is not running.
Calling the same command on shell with root access
php -q /websockets/timedactions.php

works perfectly.
How can i make the script work using shell_exec ?
Comment: php binary may not be in the path, try it with full path name like  `shell_exec("/path/to/bin/php ...")`
Answer: There can be errors, while the command is executed. You can redirect STDERR to STDOUT, to see if there are any, like this(Sample 3.5).
echo shell_exec("php -q /websockets/timedactions.php 2>&1");
Also there could be something preventing shell_exec from printing (link).

Running shell command using shell_exec


Loading specific bootstrap mode in hook_menu

Question: There is a way to define a specific bootstrap mode for a hook_menu URL (MENU_CALLBACK)?
I just want the request returns to me a result of a simple query in JSON and for that, I don´t need load the Drupal bootstrap in full mode, damaging the response performance.
Thanks!
Answer: It's not possible, because hook_menu() is invoked when Drupal is completely bootstrapped, also because only when Drupal has been completely bootstrapped, all the modules are loaded; only in this case all the menu callbacks defined in hook_menu() are available.
If you really need to limit the bootstrap to a phase, then you can write a file that is similar to index.php, for example.
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

An example of file used for a specific task is cron.php.
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  drupal_cron_run();
}

Generally, there isn't the need to limit the bootstrap, only to serve data in JSON format. Creating a file like cron.php should be done for a dedicated task that is time consuming, or for limiting the pages being served, as with install.php.
Answer: Try this module: https://www.drupal.org/project/js
It does not let you choose the bootstrap level, but it allows you to define a callback that only loads the bare bone of drupal.


What transfer function should I use to model a gradual permanent step positive intervention with increasing rate of growth?

Question:
Hello,
I want to ask what transfer function I should use to model a gradual permanent step intervention with increasing rate of growth. The relevant graph is presented at the attached image.
I want to model a step intervention that leads to an increase in the level of the series. I consider three cases, an abrupt (sudden) permanent step intervention, a gradual permanent positive intervention with decreasing rate of growth and a gradual permanent positive intervention with increasing rate of growth (see graph). In all the cases I create a binary dummy variable to model the intervention.
1)  In the simple case of the abrupt (sudden) permanent step intervention I run the regression Yt = intercept + [omega] * Dummy. Example data are as follows:
… 20 20 33.5 33.5 33.5 33.5 33.5 33.5 33.5…
2)  In the case of a gradual permanent step positive intervention with decreasing rate of growth I run the regression  Yt = intercept + [omega/ (1-delta*B)] * Dummy. Example data are as follows:
… 20 25 28 30 32 33 33.5 33.5 33.5 …
3)  In the case of a gradual permanent step positive intervention with increasing rate of growth what transfer function should I use to model it?
Yt=intercept+[Transfer Function] * Dummy
Example data are as follows:
… 20 20 20.25 21.5 23 25 29 33.5 33.5 …
Thanks in advance,
Andreas
Comment: Andreas, could you share some information about the purpose of this modeling?  Absent that, you will only get generic answers that might or might not be appropriate for the question, which makes it difficult (if not impossible) for people to provide the great answers we look for here.
Comment: It is not clear to me what this graph is showing. Is it the desired impulse or step response of the system for which you'd like a transfer function? Or, something else? It seems clear that if the graph is intended to be either an impulse or step response, then no rational transfer function should exist. Indeed, I could be mistaken, but I do not see how a linear system could produce such a response function at all. (But, I will give it some more thought. Please update your question in the meantime.)
Answer: I have edited this and tried to meet some of Cardinal's sage and continually positive and mature advice regarding postings/answers.
The question is how to efficiently convert/characterize an observed series in terms of a Transfer Function/ARMAX Model.There are four possible ways to include a deterministic/dummy 0/1 variable and the OP wishes to create a map between data and a possible representation. The 4 ways are Pulses, Level Shifts , Seasonal Pulses and Local Time Trends. A step/level (St) 0 before intervention and 1 after intervention) and a pulse Pt (1 at intervention and 0 elsewhere) interventions, the model then can be expressed as
Yt=β1St+β2Pt+ηt where nt is an ARIMA process
Also because there may different responses to the interventions, say graduate change in
level is by ωSt1−δB or decayed responses ωPt1−δB.
Your three examples reinforce the idea that all models are wrong but some are useful. It is possible to represent your three series with and wthout incorporating ARIMA structure. In
1)  20 20 33.5 33.5 33.5 33.5 33.5 33.5 33.5…  might be handled by two pulses followed by a level shift
y(t)=b1*x1 + b2*x2 + b3*x3
No ARIMA structure needed
where x1 and x2 are pulse series and x3 is a step/level series
2)  20 25 28 30 32 33 33.5 33.5 33.5 … can be approximated by a combination of memory/ARIMA and dummy series.
[(1-B*1)]Y(T) = +[X1(T)][(1-B*1)][(+  .417)]        :PULSE               5
<code>              +[X2(T)][(1-B**1)][(-  .114)]        :PULSE               8

              +[X3(T)][(1-B**1)][(+  .229)]        :PULSE               6

             +     [(1-  .635B** 1)]**-1  [A(T)]
</code>
Alternatively if one wanted to supress the ARIMA component. Note that a step = [1-B]trend thus a trend = step/[1-B] . REstated a step is a difference of a trend and a pulse is a difference of a step
Y(T) =  19.784                              gradual
<code>   +[X1(T)][(+ 2.6434)]   :TIME TREND          1

   +[X2(T)][(- 2.5298)]   :TIME TREND          6

   +[X3(T)][(-  .123)]    :TIME TREND         11

   +[X4(T)][(- 2.4278)]   :PULSE               1

   +[X5(T)][(- 1.0012)]   :PULSE               5

  +       [A(T)]
</code>
OR in terms of step/level variables and pulses
Y(T) =  19.784                              gradual
<code>   +[X1(T)][(+ 2.6434)]/[1-B]   : STEP/LEVEL   1

   +[X2(T)][(- 2.5298)]/[1-B]   : STEP/LEVEL   6

   +[X3(T)][(-  .123)]/[1-B]    : STEP/LEVEL  11

   +[X4(T)][(- 2.4278)]   :PULSE               1

   +[X5(T)][(- 1.0012)]   :PULSE               5

  +       [A(T)]
</code>
3)… 20 20 20.25 21.5 23 25 29 33.5 33.5 . In terms of no ARIMA and no differencing operators
Y(T) =  18.336                              gradual-perm
<code>   +[X1(T)][(+  .932)]    :TIME TREND          1

   +[X2(T)][(+ 1.2098)]   :TIME TREND          6

   +[X3(T)][(- 2.1723)]   :TIME TREND         11

   +[X4(T)][(+ 4.0747)]   :PULSE               8

   +[X5(T)][(+ 1.9325)]   :PULSE               9

  +       [A(T)]
</code>
If one wanted to represent this time series using a combination of ARIMA and dummies
[(1-B*1)][(1-B*1)]Y(T) =  .73605E-08      gradual-perm
<code>     +[X1(T)][(1-B**1)][(1-B**1)][(+ 4.2000)]   :PULSE               8

     +[X2(T)][(1-B**1)][(1-B**1)][(+ 1.8333)]   :PULSE               7

     +[X3(T)][(1-B**1)][(1-B**1)][(+ 2.3000)]   :PULSE               9

     +[X4(T)][(1-B**1)][(1-B**1)][(+  .833)]    :PULSE              10

    +       [A(T)]
</code>
Andreas, these models were easily/automatically developed by commercially available software that I have had a role in developing (AUTOBOX). SAS and others attempt to form similar models but often fail, in my opinion. I am sure that some of this could be duplicated in other programming languages.
Comment: I think some attention to the formatting of this answer would be very helpful. Right now it looks to me more or less like a bunch of screen dumps from a piece of software that I'm not familiar with, with little surrounding context. I don't mean that to sound too critical; I just feel that providing some context and words in between the software output would be helpful.


Determinar tamanho dos círculos na legenda de um gráfico do GGPLOT2

Question: Olá!
Eu inseri esses comandos lá no R:
library(ggplot2)
lm_smooth <- geom_smooth(method = lm, size = 1)
qplot(percwhite, percbelowpoverty, data = midwest,
weight = popdensity, size = popdensity) + lm_smooth

E o R me retornou esse gráfico:

Alguém saberia me dizer como posso determinar os valores que aparecem na legenda? Por exemplo: ao invés de 4 tamanhos de círculos diferentes, eu gostaria de determinar quantos eu quisesse.
Answer: Você pode usar scale_size() para definir os tamanhos.
qplot(x = percwhite, y = percbelowpoverty, data = midwest,
      size = popdensity) +
      scale_size(range = c(1,4),
             breaks = c(10000, 20000, 30000, 40000, 50000, 60000, 70000),
             labels = c("10000","20000","30000", "40000", "50000","60000", "70000"),
             guide = "legend") +
      lm_smooth


Redirect to /user upon login

Question: I can't figure out why users are redirected to http://example.org/user (the domain is just an example) when they log in. I don't see a rule anywhere. I have written rules to redirect somewhere else upon login, and the rules do not work. I suspect the Logintoboggan or the Drupal Commerce, but I can't find any settings that would cause this. I don't have any other redirect modules installed.
Why are user redirected to their user profile after they log in?
Comment: You don't specify Drupal 7 or 8, but assuming 7 have you looked at [Login Destination](https://www.drupal.org/project/login_destination)??
Comment: Bleen's answer is probably good but I have not tried it This can certainly be achieved with https://www.drupal.org/project/rules React on event "user: user has logged in"
and add Action "System: Page Redirect"
Comment: The OP is not asking what to use to redirect users, but why users are redirect to http://example.org/user (the domain is just an example).
Answer: The redirect is specified in the login form forst_state array under the redirect key, that's why. You can change that by altering the user login form.

Redirect to /user upon login


Error When Building APK From Flutter Project

Question: I faced a problem when I am trying to build the APK from my flutter project.
I used appicon.co to create the app icons.
<code>You are building a fat APK that includes binaries for android-arm, android-arm64.
If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
    To generate an app bundle, run:
        flutter build appbundle --target-platform android-arm,android-arm64
        Learn more on: https://developer.android.com/guide/app-bundle
    To split the APKs per ABI, run:
        flutter build apk --target-platform android-arm,android-arm64 --split-per-abi
        Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
Initializing gradle...                                              1.4s
Resolving dependencies...                                           6.4s

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeReleaseResources'.
> java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  Output:  D:\projects\e-cal app\ECAL appication\ecal\android\app\src\main\res\mipmap-hdpi\ic_launcher.png: error: failed to read PNG signature: file does not start with PNG signature.

  Command: C:\Users\DELL\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\dc6524cdbb29b6d93306387944c512dd\aapt2-3.2.1-4818971-windows\aapt2.exe compile --legacy \
          -o \
          D:\projects\e-cal app\ECAL appication\ecal\build\app\intermediates\res\merged\release \
          D:\projects\e-cal app\ECAL appication\ecal\android\app\src\main\res\mipmap-hdpi\ic_launcher.png
  Daemon:  AAPT2 aapt2-3.2.1-4818971-windows Daemon #1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                      76.4s
*******************************************************************************************
The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
*******************************************************************************************
Gradle task assembleRelease failed with exit code 1
</code>
How to fix that issue? Can someone help please.
Answer: I not to sure, but when building you should try to build app bundle, as it doesn't take up as much room and will make people more likely to get your app.


Question related to probability density function

Question: A continuous random variable X has the probability density function
$f(x)=
\begin{cases}
 px+q & 1 \leq x \leq 4 \\
 0 & \text{otherwise}
\end{cases}$
If $P(X<2)=\dfrac{1}{9}$ , find the values of $p$ and $q$. $\left[ans: p= \dfrac{1}{9},\ q=\dfrac{1}{18}  \right] $

This is my attempt,
\begin{aligned}
P(X < 2) &= \dfrac{1}{9}\\
P(X \leq 2) &= \dfrac{1}{9} \\
\int_1^2 (px+q) \,dx &= \dfrac{1}{9} \\
\left[\dfrac{px^2}{2}+qx \right]_1^2 &= \dfrac{1}{9} \\
2p+2q- \left( \dfrac{p}{2}+q\right) &= \dfrac{1}{9} \\
\dfrac{3}{2} +q &= \dfrac{1}{9} \qquad(1) \\
\end{aligned}
\begin{aligned}
\int_{-\infty}^{\infty} f(x) \,dx &= 1 \\
\int_{1}^{4} (px+q) \,dx &= 1 \\
\left[\dfrac{px^2}{2}+qx \right]_1^4 &= 1 \\
8p+4q- \left( \dfrac{p}{2}+q\right) &= 1 \\
\dfrac{15}{2} +3q &= 1  \qquad(2)  \\
\end{aligned}
By solving both $(1)$ and $(2)$, I get $p=\dfrac{2}{9} \text{ and } q=- \dfrac{2}{9}$
Can someone check my work? Thanks.
Comment: I find the same answers as you. So I think you are correct.
Answer: Hint:please check (1) and (2)
$$\frac{3p}{2}+q=\frac{1}{9}(1)$$
$$\frac{15p}{2}+3q=1(2)$$
$$p=\frac{2}{9} , q= \frac {-2}{9}$$
same answer


PHP/MySQL Concurrency - Write dependent on Read - Critical Section

Question: I have a website running PHP+MySQL. It is a multiuser system and most of the MySQL tables are MyISAM-based.
The following situation got me puzzled for the last few hours:
I have two (concurrent) users A,B. Both of them will do this:

Perform a Read Operation on Table 1
Perform a Write Operation on another Table 2 (only if the previous Read operation will return a distinct result, e.g. STATUS="OK")

B is a little delayed towards A.
So it will occur like this:

User A performs a read on Table 1 and sees STATUS="OK".
(User A Schedules Write on Table 2)
User B performs a read on Table 1 and still sees STATUS="OK".
User A performs Write on Table 2 (resulting in STATUS="NOT OK" anymore)
User B performs Write on Table 2 (assuming STATUS="OK")

I think I could prevent this if Reading Table 1 and Writing to Table 2 were defined as a critical section and would be executed atomically. I know this works perfectly fine in Java with threads etc., however in PHP there is no thread communication, as far as I know.
So the solution to my problem must be database-related, right?
Any ideas?
Thanks a  lot!
Answer: The Right Way: Use InnoDB and transactions.
The Wrong-But-Works Way: Use the GET_LOCK() MySQL function to obtain an exclusive named lock before performing the database operations. When you're don, release the lock with RELEASE_LOCK(). Since only one client can own a particular lock, this will ensure that there's never more than one instance of the script in the "critical section" at the same time.
Pseudo-code:
<code>SELECT GET_LOCK('mylock', 10);
If the query returned "1":
    //Read from Table 1
    //Update Table 2
    SELECT RELEASE_LOCK('mylock');
Else:
    //Another instance has been holding the lock for > 10 seconds...
</code>
Comment: Thx, I read something similar. The only thing I am not sure about is how "blocking" will be handled in this case. I don't want other concurrent operations to be blocked and thrown away, instead I'd like MySQL to put them into a queue. Are you familiar with how this works?
Comment: @InnoDB: I was also thinking about switching to that engine. However can this really solve my problem of executing several DB queries in a block / critical section ? I thought InnoDB could "just" solve any other concurrency issues, but mine :D
Comment: With InnoDB, you can wrap your DB operations in a transaction. This will in effect make them an atomic block. As for locks, if you try to get a lock while another client is already holding it, your script will pause for up to $timeout seconds (10 seconds in my example). If the lock gets released during this time, it will take the lock and proceed as normal. If the timeout expires, well, it's up to you to decide what happens then. You could just retry.


Derivation when priori probability is Unknown

Question: I want to derive an expression for the Bayesian classification risk $L(r^*)$ when the priori $\tau_1\in[0,1]$ is unknown.
For this problem, let:
$X\in\mathbb{X}=[0,1],Y\in\{ 0,1 \}$
$\pi_y=P(Y=y)=1/2$ for $y\in{0,1}$
Also, conditional distributions are characterised by:
$[X|Y=y]$ are characterised by $f(x|Y=0)=2-2x$ and $f(x|Y=1)=2x$.
In a binary classification case, $L(r^*)=E(min\{\tau_1(X),1-\tau_1(X)\}=1/2-1/2E(|2\tau_1(X)-1|)$, so I'm assuming I need to replace the $\tau_1$ somehow, but I'm not exactly sure what else the classification risk would rely on.
Comment: You are provided with $P(Y=y)$ and $P(X|Y)$, $Y$ is binary so $P(X)$ is easily found. Please explain  **(a)** what does $\tau_1$ stand for? **(b)** how does this question differ from your previous one? (https://stats.stackexchange.com/questions/549134/explicit-form-and-function-of-posteriori-probability-when-y-1) and **(c)** which textbook are you taking these question from?
Comment: $\tau_1(x)$ is $P(Y=1|X=x)$ I believe.  The question from $(b)$ was looking for the explicit form of $\tau_1(x)$ and its graph. This question is looking for the derivation of $L(r^*)$ or the classification risk. In regards to $(c)$, these are challenge questions from my university course. The main problem I'm having is the lecturer uses notation that is varies from what I've seen in textbooks and the internet, and secondly, I don't understand this material very well. I'm from a machine learning background and I'm doing a stats elective. Second half of course has just thrown me in the deep end.
Comment: $\tau_1$ is the posteriori probability. I've seen it referred to as $\mu$ in other literature.
Comment: No offence intended - Do you feel comfortable enough with the definitions of prior & posterior, or do you need some clarification?
Comment: No offence taken. Any explanations would be greatly appreciated. I don't understand Bayesian statistics at all.
Answer: First, let us define what are prior and posterior: Assume that a variable $x$ "belongs" to a distribution $F$ with parameter $y$. For example, $x$ could be the result of a coin toss, with probability $y$ for getting "head". Given a specific value of $y$, say $y=\theta$ we have enough information to construct the PDF, CDF and everything else related to $x$:
$$P(x=1|y=\theta)=\theta,\qquad P(x=0|y=\theta)=1-\theta$$
Note that these probabilities are conditional on the value of $y$.
But what if the probability $y$ is itself a variable? In general, that's the basic idea behind Bayesian methods. Going on with the coin toss example - before flipping the coin, we take an assumption regarding the probability which the parameter $y$ "comes from". That is, we assume its probability of having certain values prior to conducting our experiment. That's why it is called the prior distribution.
Next, we conduct our experiment and collect the results. We would like to obtain an estimate of the distribution of $y$ given the results of $x$ we have obtained. This could be only done after conducting our experiment. That's why it's called posterior. This is the probability of $y=\theta$ given our results of $x$, so it is denoted $P(y=\theta|x)$.
Now, let's look at the Bayes theorem, which connects $P(X|Y)$ with $P(Y|X)$:

Back to your question: we are provided with $P(Y), P(X|Y)$ so we can find the marginal distribution for the denominator and then the posterior (see my previous solution), which is $\tau_1(X)=P(Y=1|X)=X$.
The loss function is $L(r^*)=E\left[\min\{\tau_1(X),1-\tau_1(X)\}\right]$, but we know nothing about how $E[\tau_1(X)]=E[X]$ looks like. Surprisingly enough, it doesn't matter at all.
In the case of $\tau_1(X)<1-\tau_1(X)$, we take $L(r^*)=E\left[\tau_1(X)\right]$, but there's more: $\tau_1(X)<1-\tau_1(X)$ so $2\tau_1(X)<1$, which means $|2\tau_1(X)-1|=1-2\tau_1(X)$, then:
$$0.5-0.5E[|2\tau_1(X)-1|]=0.5-0.5E[1-2\tau_1(X)]=0.5-0.5+E[\tau_1(X)]=E[\tau_1(X)]$$
...which is exactly $E\left[\min\{\tau_1(X),1-\tau_1(X)\}\right]$. It's easy to show that the complementary case also holds.


Running an underpowered test

Question: Perhaps someone could help me with an issue.
I have a new product that some users might be interested in, and would like to email them an offer seeing if they sign up for it.
The problem is that some groups barely have any signups to the service (CR < 0.01%) and it is not realistic to run the test in a timeframe that will allow for enough traffic to gain a statistically significant audience.
What would be the best course of action to proceed with testing on something like this?
Comment: It is not so much the _percentage_ of users that matters as the _number_ of user that do. // There is nothing illegal about running an underpowered test. The risk is that you might not detect a real difference. [And for a group of users with very low traffic, it might not matter much to the bottom line if their opinion isn't crystal clear.]
Answer: As Bruce pointed out, running the tests without sufficient power increases type II errors (false negatives) but it also increases type I errors (false positives).
To avoid this you could only run the tests on the groups that are large enough to give you sufficient power for your statistical tests. Alternatively, you could perhaps bin some of the small groups together so that you have larger groups that give you sufficient power. Other than that, I think I'd need to know more about your problem to be able to suggest any thing else.

Running an underpowered test


NFS server as a client of itself performs very poorly

Question: I have set up an NFSv4 server. I am sharing files with Linux machines in a VM farm and Windows 7, 8, and 10 machines, so I need to share files with both NFS and Samba1. In the past, I have done this by configuring an NFS machine with direct access to the underlying ext4 file system and configuring a separate Samba server that mounts the NFS exports and shares them2.
I would like to unify the file sharing onto one server. Critically, I need to be sure that NFS and Samba are not stepping on each other's files, blissfully ignoring locks. As a result, I must continue using Samba on top of NFS and not in parallel with NFS.
This seems trivial. The NFS server should simply mount its own share, just as the Samba server would have done, and then that same machine must run Samba and export that mounted share. The only different would seem to be that traffic need not travel over the network between two machines. I would expect better performance.
Instead, the NFS server saturates the CPU on the machine while giving only 2.5 MB/s performance!
top - 11:34:57 up 15 days,  1:18,  1 user,  load average: 32.09, 8.07, 2.74
Tasks: 101 total,  13 running,  88 sleeping,   0 stopped,   0 zombie
%Cpu(s):  5.6 us, 93.7 sy,  0.0 ni,  0.0 id,  0.0 wa,  0.0 hi,  0.7 si,  0.0 st
KiB Mem :   899776 total,   124840 free,   184624 used,   590312 buff/cache
KiB Swap:        0 total,        0 free,        0 used.   261184 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
11058 root      20   0       0      0      0 R 11.5  0.0   5:53.84 nfsd
11061 root      20   0       0      0      0 R 11.5  0.0   5:53.88 nfsd
11057 root      20   0       0      0      0 R 11.2  0.0   5:53.72 nfsd
11059 root      20   0       0      0      0 R 11.2  0.0   5:53.78 nfsd
11060 root      20   0       0      0      0 R 11.2  0.0   5:53.80 nfsd
11062 root      20   0       0      0      0 R 11.2  0.0   5:53.86 nfsd
11064 root      20   0       0      0      0 R 11.2  0.0   9:23.40 nfsd
11063 root      20   0       0      0      0 R 10.9  0.0   6:00.00 nfsd

The only other sign I know of that something is wrong is that countless lines get written to /var/log/messages that look something more or less like that.
Apr 25 11:35:01 nas kernel: nfsv4 compound op #4/4: 9 (OP_GETATTR)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dbf606a080 opcnt 4 #4: 9: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound returned 0
Apr 25 11:35:01 nas kernel: --> nfsd4_store_cache_entry slot ffff88db7bbae000
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dac5072080 opcnt 4 #2: 22: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #3/4: 38 (OP_WRITE)
Apr 25 11:35:01 nas kernel: nfsd: write complete host_err=131072
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dac5072080 opcnt 4 #3: 38: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #4/4: 9 (OP_GETATTR)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsd_dispatch: vers 4 proc 1
Apr 25 11:35:01 nas kernel: nfsv4 compound op #1/4: 53 (OP_SEQUENCE)
Apr 25 11:35:01 nas kernel: __find_in_sessionid_hashtbl: 1555688119:2835816624:106:0
Apr 25 11:35:01 nas kernel: nfsd4_sequence: slotid 5
Apr 25 11:35:01 nas kernel: check_slot_seqid enter. seqid 9615 slot_seqid 9614
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dbf606a080 opcnt 4 #1: 53: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #2/4: 22 (OP_PUTFH)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88db7b529080 opcnt 4 #4: 9: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound returned 0
Apr 25 11:35:01 nas kernel: --> nfsd4_store_cache_entry slot ffff88db7bbaf000
Apr 25 11:35:01 nas kernel: nfsd_dispatch: vers 4 proc 1
Apr 25 11:35:01 nas kernel: nfsv4 compound op #1/4: 53 (OP_SEQUENCE)
Apr 25 11:35:01 nas kernel: __find_in_sessionid_hashtbl: 1555688119:2835816624:106:0
Apr 25 11:35:01 nas kernel: nfsd4_sequence: slotid 1
Apr 25 11:35:01 nas kernel: check_slot_seqid enter. seqid 9626 slot_seqid 9625
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88db7b529080 opcnt 4 #1: 53: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #2/4: 22 (OP_PUTFH)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dbf606f080 opcnt 4 #4: 9: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound returned 0
Apr 25 11:35:01 nas kernel: --> nfsd4_store_cache_entry slot ffff88db291eb000
Apr 25 11:35:01 nas kernel: nfsd_dispatch: vers 4 proc 1
Apr 25 11:35:01 nas kernel: nfsv4 compound op #1/4: 53 (OP_SEQUENCE)
Apr 25 11:35:01 nas kernel: __find_in_sessionid_hashtbl: 1555688119:2835816624:106:0
Apr 25 11:35:01 nas kernel: nfsd4_sequence: slotid 2
Apr 25 11:35:01 nas kernel: check_slot_seqid enter. seqid 9614 slot_seqid 9613
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dbf606f080 opcnt 4 #1: 53: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #2/4: 22 (OP_PUTFH)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dac507e080 opcnt 4 #2: 22: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #3/4: 38 (OP_WRITE)
Apr 25 11:35:01 nas kernel: nfsd: write complete host_err=131072
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dac507e080 opcnt 4 #3: 38: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #4/4: 9 (OP_GETATTR)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dac5072080 opcnt 4 #4: 9: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound returned 0
Apr 25 11:35:01 nas kernel: --> nfsd4_store_cache_entry slot ffff88dbf65cc000
Apr 25 11:35:01 nas kernel: nfsd_dispatch: vers 4 proc 1
Apr 25 11:35:01 nas kernel: nfsv4 compound op #1/4: 53 (OP_SEQUENCE)
Apr 25 11:35:01 nas kernel: __find_in_sessionid_hashtbl: 1555688119:2835816624:106:0
Apr 25 11:35:01 nas kernel: nfsd4_sequence: slotid 4
Apr 25 11:35:01 nas kernel: check_slot_seqid enter. seqid 9584 slot_seqid 9583
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dac5072080 opcnt 4 #1: 53: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #2/4: 22 (OP_PUTFH)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dbf606a080 opcnt 4 #2: 22: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #3/4: 38 (OP_WRITE)
Apr 25 11:35:01 nas kernel: nfsd: write complete host_err=131072
Apr 25 11:35:01 nas kernel: nfsv4 compound op ffff88dbf606a080 opcnt 4 #3: 38: status 0
Apr 25 11:35:01 nas kernel: nfsv4 compound op #4/4: 9 (OP_GETATTR)
Apr 25 11:35:01 nas kernel: nfsd: fh_verify(36: 01070001 00060001 00000000 9509b6fe 7a49ad56 5a4d5dbc)

I am not mounting the NFS shares locally via 127.0.0.1. The local NFS mount uses the private IP address of the machine itself. I could change that, but it would require additional complexity in the NFS exports definition, and I would actually prefer that this machine sees itself exactly the same way as the other machines that will be mounting the NFS shares3.
Footnotes

I know of ways of using NFS clients on Windows and Samba clients on Linux. Such options are not workable in this case.
I am aware of admonishments about re-exporting NFS shares with Samba, but I and many other sysadmins I know regularly do this without problems. The issue seems to have arisen here rather because the NFS server is mounting its own share. Nonetheless, I am curious about the exact reasons for such warnings, so if you know please share.
If anybody has some reason why this entire architecture is fundamentally flawed, I am open to hearing that. I have years of experience serving Samba on top of NFS using two machines, so I supposed that I could cut out the Samba machine and move Samba to the NFS server machine with an NFS self-mount.
Answer: It's very likely that your workload is dying a scheduling death. You're asking for a ton on context switches on the same system when exporting a filesystem back to itself and then exporting that export again.
You may see that splitting this workload out across more than one kernel (kernels that do not share the same CPU core) results in a performance increase, despite the involvement of a network link between those systems.
This could easily be accomplished with a collocated VM set; one running NFS, one running Samba. Collocating these on the same hypervisor should eliminate most network latencies, and should work well provided that these VMs do not share the same CPU cores.
There are also userspace implementations for NFS - NFS Ganesha being a very common one. However, Samba is also going to be responsible for a non-trivial amount of this repetitive userspace-kernel switching. NFS Ganesha may be worth testing if these workloads absolutely must share a kernel for some reason.
In short, reducing context switching within the same system should help significantly with this.
Comment: Brilliant. Adding a second core to the VM increased the transfer rate to 35 MB/s with 5% CPU usage by nfsd (only 2 nfsd processes working) and 25% CPU usage by smbd. I'll keep testing various sides of this, but I'm one happy customer. Haha! Thanks!
Comment: In general, increasing the message size sent to NFS *should* accomplish that, at the cost of more memory utilization. I would encourage playing with rsize and wsize parameters of the client connection to find a "sweet spot" of performance anyways, since the use case of this mount is so specific and narrow. You could also increase the MTU size of the interface you're using for this, and that should help to alleviate context switching on TCP's behalf. This could potentially be a good argument for using a loopback interface, which has a very high MTU "out of the box".
Comment: Huh! Context switching as an explanation is consistent with the high "sys" CPU usage in top, right? Could I alleviate the problem just by passing another core into the existing VM. The entire idea of moving from two VMs for these services to one was to *reduce* resource usage, so I would like to avoid moving back to two if possible. Is mounting the NFS share through 127.0.0.1 likely to improve the situation at all? I don't know what additional context switching might be necessary for the NFS traffic to potentially involve traffic outside the machine.
Comment: I don't think serving on localhost will help with this, since the traffic in question doesn't leave even a virtual network phy already. The main reason I brought up using separate machines entirely was to keep these schedule-heavy workloads from stomping on each other, resource utilization aside. You might have some luck with adding more CPUs to this one machine, and that's probably the most reasonable first step.
Comment: By the way, do you think adjusting NFS parameters to higher-than-usual transfer chunks could decrease context switching significantly in this case?


How to resolve gitbook-cli Maximum call stack size exceeded error?

Question: I install ubuntu18 server and node, npm, gitbook-cli on it, version info:
node -v:
v8.10.0
npm -v:
3.5.2
gitbook --version:
CLI version: 2.3.2
GitBook version: 3.2.3
My gitbook repository: https://github.com/linrongbin16/Way-to-Algorithm
When I build pdf with gitbook pdf ./ ../algo.pdf --debug
It output error message:
RangeError: Maximum call stack size exceeded
Answer: My case, I'm trying this & IT's working for me...
npm rebuild

And than try your command...