União de array multidimensional em PHP

Question: Tenho o seguinte array:
Array
(
    [0] => Array
        (
            [chamado_codigo] => 5
            [representante_id] => 1
            [data] => 2015-10-08
            [razaoSocial] => mineoro
            [cliente_cidade] => chapeco
            [tecnico_nome] => jacomasio
        )

    [1] => Array
        (
            [chamado_codigo] => 6
            [representante_id] => 2
            [data] => 2015-10-08
            [razaoSocial] => mineoro
            [cliente_cidade] => chapeco
            [tecnico_nome] => Eduardo
        )

)

Quero unir o array abaixo com o acima:
Array
(
    [0] => Array
        (
            [valor] => R$ 0,45
        )

    [1] => Array
        (
            [valor] => R$ 0,50
        )

)

Ou seja, quero deixar assim, é possível? Como eu faço?
Array
    (
        [0] => Array
            (
                [chamado_codigo] => 5
                [representante_id] => 1
                [data] => 2015-10-08
                [razaoSocial] => mineoro
                [cliente_cidade] => chapeco
                [tecnico_nome] => jacomasio
                [valor] => R$ 0,45
            )

        [1] => Array
            (
                [chamado_codigo] => 6
                [representante_id] => 2
                [data] => 2015-10-08
                [razaoSocial] => mineoro
                [cliente_cidade] => chapeco
                [tecnico_nome] => Eduardo
                [valor] => R$ 0,50
            )

    )

Comment: já tentou com `array_merge()` ? http://www.w3schools.com/php/func_array_merge.asp
Answer: Você pode tentar assim (cosiderando $a o array original e $b o secundário):
$i=0;
$novoArray = array();
foreach($a as $valor) {
    $novoArray[] = array_merge($valor, $b[$i]);
    $i++;
}

Veja funcionando aqui: http://ideone.com/cLwZ2H
Answer: Aparentemente a função array_merge_recursive deveria fazer o trabalho.
No entanto, quando os índices não estão definidos ou são números, a função não funciona.
Na página do array_merge_recursive existe uma função que funcionou bem.
veja o exemplo:

function my_array_merge ($arr,$ins) {
  if(is_array($arr))
  {
    if(is_array($ins)) foreach($ins as $k=>$v)
    {
      if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
      {
        $arr[$k] = my_array_merge($arr[$k],$v);
      }
      else {
// This is the new loop :)
        while (isset($arr[$k]))
          $k++;
        $arr[$k] = $v;
      }
    }
  }
  elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
  {
    $arr=$ins;
  }
  return($arr);
}

//aproveitando o exemplo do nosso amigo Jorge Campos
$a = array( array("chamado_codigo"=>5,"representante_id"=>1), array("chamado_codigo"=>6,"representante_id"=>2) );
$b = array( array("valor"=>"R$ 0,45"), array("valor"=>"R$ 0,50") );

print_r(my_array_merge($a,$b));

o que resultará em
Array
(
    [0] => Array
        (
            [chamado_codigo] => 5
            [representante_id] => 1
            [valor] => R$ 0,45
        )

    [1] => Array
        (
            [chamado_codigo] => 6
            [representante_id] => 2
            [valor] => R$ 0,50
        )

)

União de array multidimensional em PHP


Stargazer omits one row of coefficients when using keep or omit

Question: I've identified a bug in R's stargazer package that results in the last row of covariates being deleted when printing multiple models and using either the "keep" or "omit" function to suppress the printing of certain covariates (e.g. fixed effects for example, or the intercept).
data("mtcars")
names(mtcars)
mod<-lm(mpg~hp+wt+disp+carb+gear+vs+cyl+drat+am+hp*wt, data=mtcars)
mod1<-lm(mpg~hp+wt+disp+carb+gear+vs+cyl+drat+am+hp*wt, data=mtcars)
list1<-list(mod, mod1)
library(stargazer)
#Print multiple models, bug appears
stargazer(list1, type="html", omit=10)
#Print one model, bug does not appear
stargazer(mod, type="html", omit=10)

Comment: Can you be more specific what row you are missing? Should it be html output? Are you especially interested in the interaction?
Answer: When I ask stargazer to show 2 models with either the keep or omit option, it shows what I asked for:
library(stargazer)
data("mtcars")
mod1<-lm(mpg~cyl+wt, data=mtcars)
mod2<-lm(mpg~disp+wt, data=mtcars)

stargazer(mod1, mod2, type="text", keep = "wt", omit.stat=c("LL","ser","f", "n", "rsq", "adj.rsq"))

==================================
          Dependent variable:
      ----------------------------
                  mpg
           (1)            (2)
----------------------------------
wt      -3.191***      -3.351***
         (0.757)        (1.164)

==================================

stargazer(mod1, mod2, type="text", omit = "wt", omit.stat=c("LL","ser","f", "n", "rsq", "adj.rsq"))

=====================================
             Dependent variable:
         ----------------------------
                     mpg
              (1)            (2)
-------------------------------------
cyl        -1.508***
            (0.415)

disp                       -0.018*
                           (0.009)

Constant   39.686***      34.961***
            (1.715)        (2.165)

=====================================

If you like to see how to turn on/off the interaction term components, check out How to exclude interaction terms in stargazer?


How can I memorize all the notes in each usable key?

Question: Basically, I want to have all the notes in every usable key memorized so that I can instantly just call them to my memory and play them. By usable I mean any key that has 7 or less flats/7 or less sharps. For instance, if I just think "E♭ minor", I'll instantly be able to conjure up the major 6th, minor 4th, etc. I'd be memorizing the modes as well. Is there some website that I can use to practice this for myself?
Comment: What's a 'minor fourth' - in any key?  And, are you after *intervals*, *note names*, or *note positions*?
Comment: What do you need a website for? Pick 3 keys and work on them this week; pick three more next week; keep at it for awhile....
Comment: What defines a "usable key"?
Comment: @DavidBowling I guess I can pair it with my practice of the fretboard interval memorization. I'll start with C and C minor, practicing the diatonic notes and interval locations for each string.
Comment: On guitar, it's more about patterns and their positions. For me at least, that's more important than actually being able to name every singe note as you play it. And a pattern for, say, something in C will be the same pattern moved up 3 frets for Eb.
Comment: Lol I think I meant minor 5th. And all 3, I suppose.
Comment: *Minor fifth*? Let's clear up some misconceptions here first. In a minor key, the intervals in relation back to the tonic are: Perfect unison, major second, minor third, perfect fourth, perfect fifth, minor sixth, minor seventh (and repeats with perfect octave). There is no such thing as a minor or major fourth or fifth (or unison/octave); perfect intervals can only be augmented or diminished.
Comment: That's really not important to my point at all.
Comment: I come from a programming background and like to think of notes as matrices or progressions. For example, the "matrix" for a natural major key is `[1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1]` and for blues hexatonic minor it's `[1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0]`. 1's mean a note is present, and 0's mean it's not. Memorising the matrix means you can apply it to any set of 12-note octaves. And that's precisely what I do in my music automation software.
Comment: @コナーゲティ - it's not particularly important to the point, but it adds credence - or not... Still worth getting things right, surely?
Comment: Okay, but it's not a misconception, I just made a mistake. I already know that 4ths and 5ths can't be minor, I just misspoke. I don't think I'm able to edit my posts.
Comment: @OP - maybe you should accept an answer ?
Answer: Scales! By learning the scales of each key, you'll know the diatonic notes from each key. At the same time, by starting on different notes from each of those scales, the modes will gradually be revealed.
Arpeggios! By learning the arpeggios of each key, you'll understand what a m3, M3, P5 etc. is in those keys.
Then start transposing one line tunes into different keys, and you'll become conversant with facts like C>E in one key is the equivalent of F♯>A♯ in another.
Comment: In that case, you need to become a quicker learner, and/or dedicate more time to playing! There is no quick fix for this - as thousands of us realise. The more we play in different keys, the better our knowledge of those keys becomes. There is no quick fix! Maybe there are apps for that kind of thing, but an app isn't knowledge. Mere mortals have to practise - I think even Mozart et al did that! (No apps in their day..!)
Comment: @Tim That's exactly how I use it too. Classical pianists who are accompanists have to transpose often when working with singers, to accommodate the different ranges that they have. For an interesting and amusing discussion of this by the great Gerald Moore, see this excerpt from his *The Unashamed Accompanist*: https://youtu.be/ia7iOdRe9nk?t=3047. Which record, if I may say so, is well worth a listen in its entirety.
Comment: I already understand how scales are formed and I can find the diatonic notes in each key, the problem is that it takes too long, I need to get faster at it.
Comment: I still remember the last thing that my first guitar teacher told me at our last lesson: "If you remember anything that I taught you, make sure that you practice _everything_ in _every_ key." It is surprising how long it took for that lesson to really sink in (for me, at least: that was in 1985!)....
Comment: @DavidBowling - that was a wise thing to say! And something I've advocated since well before '85! Actually, on guitar, it's often an easy task - move everything up to the next fret, etc. On piano, a *completely* different ball game. But on guitar, is there a lot (or any) point in knowing what the name of each note is as it's played? On piano, it's very obvious, although often academic, but on guitar, I find I play most notes automatically - through knowing scales (!) so their name don't really matter at that moment.
Comment: @Tim Not a problem on piano these days. You just hit a couple of buttons, push an arrow key, and now you're playing a half step higher. LOL Seriously, transposing on piano is something that you have to work at for sure. A lot of us classical pianists are pretty bad at it, and it seems most jazz pianists are quite good at it.
Comment: @Tim -- and arpeggios (!) ;)  I don't see much point in knowing note names in the heat of _performance_, although that knowledge has gotten me out of a tight corner now and again. But, when _practicing_ I think it is very valuable to know note names on the fretboard. I use this as one way to get outside of familiar patterns when finding new things to practice; one hopes that deliberate practice will pay off at performance time....
Comment: @BobRodes - interesting! I tend to use the button the opposite way - when fed up with the umpteenth 12 bar in A, I may play the next one in F, while everyone else is bored silly still in A. Classical pianists don't ever get asked to transpose pieces, do they? Jazzers *have* to do it as part of the job!
Comment: @BobRodes - had a listen to that. Thanks!  I'm not convinced by transposition as portrayed there, though. Yes, the music did sound darker transposed by nearly half an octave (G>D), but what he *could* have done is played the accompaniment nearly half an octave *higher* - that theoretically should lift it even more - both sonically and metaphorically! Putting vox over may have been the cruncher there, but he didn't mention it...
Comment: @Tim I do agree with you that if he had played it up a fifth instead of down a fourth it would have had the opposite effect. If he were around to ask about that, I expect he would have said that, like Icarus, it was now lifted too high. Anyway, as I recall from the last time I heard this back in college 45 years ago, we sort of all sat around saying "interesting" and "never considered that before" and not being entirely convinced either.
Comment: @Tim What is interesting that it has an effect at all, and I like his story about listening to the song without realizing it has been transposed and not liking it as well. Also, it gives some background to Beethoven's assertions about the varying and specific emotional moods that different keys had for him. Now, I'm not sure what "putting vox over" is. What do you mean by that?
Comment: @BobRodes - the example was purely piano. 'Putting vox over' - I meant adding the vocal part - which may or may not change octave (with a big key change it could go either way), and that *would* make a big difference.
Comment: @Tim Oh yeah, "vox," Latin for "voice." I kept seeing the "Peter and the Wolf" record I had when I was three, which I could find in the rack because it was one of two that had a great big "VOX" on it. And I didn't realize that that was what I kept seeing. Senior moment. :) Thanks for explaining.
Answer: learn the circle of fifths rules and you can work them out in your head. Its then easy to memorise the more you do it. Its even better than counting sheep to get to sleep.
So, Start at C (C D E F G A B), move to the fifth G and sharp the fourth giving
G A B C D E F# .
repeat, taking D and sharping C gives you D major. Repeat ad somnolum.
Comment: you are clearly light years ahead of me in talent, but I thank you for the affirmation of my humble suggestion
Comment: "better than counting sheep"! yes, that's what I do to get to sleep: memorizing scales, chords, and entire music pieces e.g. the inventions or violon concertos by Bach ;)
Answer:
Basically, I want to have all the notes in every usable key memorized so that I can instantly just call them to my memory and play them.

To me, recalling 'the notes' - (plural) - sounds slow, because it sounds like you need to remember and think about more than one thing before you've even touched the instrument.
Personally, if I want to play in E minor, I recall, as a single entity, the intervallic shape of the minor scale - and mentally 'map' that pattern on to the instrument I'm playing, so that I 'see', in my mind's eye, the intervals of the scale on the physical layout of the instrument.
Once I've practiced a bit on that instrument, I the mapping becomes automatic, and I can play the 'minor shape' on the instrument (from some given root) pretty directly, with no obvious 'process' of recall. Practicing scales and arpeggios, as Tim suggests, is one way to get this happening instantly. It will probably happen more automatically the more you practice, and to some extent, the less you consciously try to think about the notes in each key. Just let your brain be the pattern-matching machine that it is!
Answer: This site has a lot of good information about scales, as well as diagrams of where they fall on a piano keyboard. This site is a good reference for notation, intervals, etc.
The way to get faster at it is to keep studying it until it becomes automatic. To get to where you want to be, study what intervals fall where in the different modal scales. Start with the "big two": major (ionian mode) and minor (aeolian mode). You should know the intervals between each scale degree in each of these modes before moving on, including all three variations of the minor scale.
I would also recommend that you know the quality of the triad built on each scale degree. For example, in a major scale, using C as an example, C-E-G is major, D-F-A is minor, E-G-B is minor, and F-A-C is major. And so on: going from the first scale degree, the triads are major, minor, minor, major, major, minor and diminished. In a natural minor scale, they are minor, diminished, major, minor, minor, major and major. In other words, the same order as the major scale triads, moved down two. (You'll find that the quality of triads for each scale degree occurs in the same order in every mode, but with a different starting point.)
This is a good overview of modes in general.
Comment: @Tim I can see that for sure. I expect that's an example of the reason that, where I went to school, all music majors, regardless of instrument, had a required "piano proficiency" course, in which they had to demonstrate the ability to play all 36 major and minor scales on the piano in two octaves at 120 bpm. As it is now, I find that anyone playing any instrument who wants to advance their knowledge of theory can benefit from enough knowledge of piano to be able to pick out chords and scales and so on.
Comment: A lot of people find intervals don't translate easily on guitar. On piano, obviously, yes, but with guitar, you can go up 4 frets on the same string, or down a fret and onto the next string for the same note. Defies logic for some!
Answer: It's not that hard to memorize all the notes as each of the scales is in alphabetical order (well it wraps after G back to A). But that means that you never skip notes, and you never repeat notes. But see how they are in order starting from the root back to the root:
E♭ Major: E♭, F, G, A♭, B♭, C, D, E♭
A Major: A, B, C♯, D, E, F♯, G♯, A
So as long as you know the alphabet you're good. The only thing you need to remember is which ones have flats/sharps. Refer to the circle of fifths for that.
Answer: Wach  major scale is built by 2 equal tetrachords (ladder of 4 tones WWH WWH (Wholetone and Halftones, between the 2 tetrachords  is also a wholetone.
Do-Re-MiFa - So-La-TiDo.
If you take the 2nd tetrachord of a scale (So-La-TiDo) and think the root tone of this one is now the root tone Do-Re-MiFa of a new scale and construct the 2nd tetrachord WWH -scales of the circle of 5ths.
e.g.
C-D-EF - G-A-BC take the 2nd (upper) tetrachord and start a new scale with G:
G-A-BC - D-E-F#G (notice that F will become the leading tone (Ti)  of the major scale of G. (G was So in C and is now Do in G. The root tone Do defines the name of the scale.
Continue with the 2nd tetrachord of G (D-E-F#G) developing the new scale of D (with 2 sharps: F# and C#), go on and you can construct all major scales of the circle of 5ths' right side. (G,D,A,E,B,F#)
To construct the b-flat side of the circle (F,Bb,Eb,Ab,Db,Gb) we go down step the scale of C and take the  2nd tetrachord (the lower one now) and build a new scale where we have to flatten the 4th degree of the new scale for having a Fa (halftone to the new Mi)
CB-A-G - FE-D-C (the lower tetrachord of C becomes the upper tetrachord of F:
FE-D-C - BbA-G-F (we have now a new scale: F with 1 flat:Bb
If you continue we'll get all flat-scales and the you can always be sure that the system is transparent to you.
The minor scales can be deduced from the major scales - as related scales:
The 6th degree of a major scale is the 1st degree of the relative scale:
e.g.: La of C remains la of a minor, note that the root tone of a minor scal is la (la-ti-do-re-mi-fa-so-la). This is the natural minor scale, the whole and half tone steps stay as they are in the relative scale C major but the tetrachord are quite different and it would be more complicate to mind them.
(It is much easier by imaging them as the names of the doremi.)
la-tido-re-mifa-so-la (you can see that the tetrachords are not identical regarding the W- and H-tones: so the concept of interchangeable tetrachords would be more confusing than helpful!)
Now what we have developed is the natural minor a (aeolian mode) which is also the melodic minor scale downwards ...)
There are namely 3 kind of minor scales:

harmonic, 2. melodic up, and 3. melodic down (aeolian up  and down)
Harmonic scale (minor)

To emphasize the root tone La (A) of the minor scale, the 7th degree (So) in music history has been altered a halftone up to get a leading tone (G#=Se).
Now we've got a new scale a-bc-d-ef-g#a with a step of one and a half between the 6th and 7th degree (Fa-Se) that was terribly difficult to sing.

melodic minor upward:

To make this terrible step between the 6th and 7th degree more singable the 6th degree has been augmented too and we get a new 2nd tetrachord E-F#-G#A (mi,fe,sela) which is identical with the 2nd tetrachord in tha parallel major scale (A).

melodic minor downward:

As it is not necessery to augment the 7th degree in the minor scale downwards (it has not the function of a leading tone) the So and also the Fa isn't altered (normaly) in the minor scale downwards. ("normaly" as composers also can use the harmonic scale down in certain situations of counterpoint compositions.) But in folk songs usually we find the aeolic mode.
So far the theory of the scales, how you can develope and learn to understand them. As you see, the development of the minor scales is more complicated and needs a lot of practice. The best is here to have it in the ear and play by ear. But it will be very helpful to write them down as schema, notation, keyboard and guitar patterns.
Comment: That's not the issue, the issue is being able to instantly recall any degree from any scale.
Answer: There is no mystery to this.
Play major and minor scales, along with basic cadences in all twelve major/minor keys.
Use the circle of fifths, up to 6 sharps or flats, to get the various key signatures.
You can play the scales in various broken intervals like broken thirds and fourth. This will help build a "map" of intervals on the fretboard. Adam Neely has a video about practicing this way. You probably don't need to do it as completely as he doesn't in terms of all intervals and all directions, but it's a nice example to work from.
For learning note names you can sing tone names aloud, like "E flat" or by degree, ex. "mediant", or solfege, like "mi re do." Scale practice usually is too fast for singing these names, but you can do it while playing cadences. For each practice repeat you can change the voice you sing from soprano, alto, tenor, to bass. (Move them into your comfortable octave.) That will give you 4 repeats per cadence pattern and you will be learning scale tone names in musical context.
On piano I like to practice all 12 keys moving up/down chromatically, but on guitar I think moving between keys by ascending/descending fourths is better.
Answer: I invented a simple way to do that but the last time I posted the method it was flagged as being 'commercial content' despite that it's not anything I'm selling.
Instead of detailing the steps to derive it I'll post what you need to know.
Alternate letters starting at F ... add a space between. F _ G _ A _ B
Alternate letters starting at C ... add a space between. C _ D _ E
Weave them together ...
F C G D A E B ... These are fifths.
Now assign numbers to them ... the number alternate like the letters. 1 _ 2 _ 3 _ 4 and 5 _ 6 _ 7.

F C G D A E B
4 1 5 2 6 3 7

These are the positions of each note in the key of Cmajor (C=1).
Suppose you slid the numbers one position to the right? (up one fifth)

 F C G D A E B
   4 1 5 2 6 3 7

Now you have the notes in the key of Gmajor ... G is first, E is sixth ... and after B you have F# because the seven note pattern starts again but is sharp ... we're going up fifths.

 F C G D A E B F#
   4 1 5 2 6 3 7

On the other side the F gets a ♭7 because the number pattern repeats as well, but going left is flat.

 F C G D A E B F#
   4 1 5 2 6 3 7

 F C G D A E B F#
♭7 4 1 5 2 6 3 7

The seventh note in Gmajor is F# (and the ♭7 must be F).
Lets move the numbers a few more spots to the right.
Now we're calculating with a fifths slide rule in Bmajor.

 F C G D A E B F#
        ♭7 4 1 5 2 6 3 7

The FCGDAEB letter pattern repeats right but sharpened.

 F C G D A E B F# C# G# D# A# E# B#
        ♭7 4 1 5  2  6  3  7

The letter pattern repeats left but flattened.

   B♭  F  C  G  D  A  E  B  F# C# G# D# A# E# B#
   ♭1 ♭5 ♭2 ♭6 ♭3 ♭7  4  1  5  2  6  3  7  #4 #1

As you can see B has five sharps ... the first five letters of the FCGDAEB pattern.

E  B  F# C# G# D# A#
4  1  5  2  6  3  7

It's five sharps because the numbers were shifted five spots ... moving the "1" from under C to under B.
Which key has three flats?
Here's three octaves with C = 1 (zero flats or sharps)

   F♭ C♭ G♭ D♭ A♭ E♭ B♭  F  C  G  D  A  E  B  F# C# G# D# A# E# B#
   ♭4 ♭1 ♭5 ♭2 ♭6 ♭3 ♭7  4  1  5  2  6  3  7  #4 #1 #5 #2 #6 #3 #7

Shift the numbers to the left ... one shift gives you F=1 with B♭=4  ... F has one flat, B♭.

       F♭ C♭ G♭ D♭ A♭ E♭ B♭ F  C  G  D  A  E  B  F# C# G# D# A# E# B#
   ♭4 ♭1 ♭5 ♭2 ♭6 ♭3 ♭7  4  1  5  2  6  3  7  #4 #1 #5 #2 #6 #3 #7

Shift the numbers to the left ... next shift gives you B♭=1 with E♭=4 ... B♭ has two flats, B♭, E♭.

       F♭ C♭ G♭ D♭ A♭ E♭ B♭ F  C  G  D  A  E  B  F# C# G# D# A# E# B#
♭4 ♭1 ♭5 ♭2 ♭6 ♭3 ♭7  4  1  5  2  6  3  7  #4 #1 #5 #2 #6 #3 #7

Shift the numbers to the left ... next shift gives you E♭=1 with A♭=4. E♭ has three flats, B♭, E♭, A♭ (A♭ is the 4 in E♭).

             F♭ C♭ G♭ D♭ A♭ E♭ B♭ F  C  G  D  A  E  B  F# C# G# D# A# E# B#
   ♭4 ♭1 ♭5 ♭2 ♭6 ♭3 ♭7  4  1  5  2  6  3  7  #4 #1 #5 #2 #6 #3 #7

Do you play guitar? ... imagine the strings are not tuned in "Standard Tuning" but instead in all-fourths tuning ... E A D G C F ... all-fourths is all-fifths backwards.
On the first fret, F string, is F# ... it's the first sharp of G major (one fifth up from Cmajor).
The next lower string is C, first fret is C#. The key a fifth up from Gmajor is Dmajor and it has two sharps ... F# and C#.
The first fret gives you the accidentals for sharp keys going high string to low string.

F# - Gmajor     (F#)
C# - - Dmajor   (F# + C#)
G# - Amajor     (F# + C# + G#)
D# - - Emajor   (F# + C# + G# + D#)
A# - Bmajor     (F# + C# + G# + D# + A#)
E# - - F#major  (F# + C# + G# + D# + A# + E#)

Again, every two letters, every two strings, increments by a whole note, it's going up two fifths ... G, A, B ... D, E, F#.
Now lets go back to 4152637.

F C G D A E B
4 1 5 2 6 3 7

These are the notes in Cmajor.
If you built chords for each note you'll find the 415 is major, the next three, 263, are minor and 7th is diminished.  (The first three are the most consonant, the next are a less...minor, and the last is the most dissonant chord of the group, diminished.)
Now suppose we want to work with minor keys?
Well why not start here.. with the 1 under the A, the relative minor of C.
Here's C plus a few extra notes.

C D E F G A B C D E F
 W W h W W W h W W h W

The interval combination for a major chord is M3+m3.
M3, major third, is four half-steps ... (W + W).
m3, minor third, is three half-steps ...(W + h) or (h + W).
So we can build minor chords starting at D, E and A.
However ... if you build a minor scale starting at D or E, using the minor scale pattern of WhWWWhW, you'll get a flat in Dminor (B♭, as Dminor is the relative minor of Fmajor, which has a B♭) and a sharp in Eminor (F#, as Eminor is the relative minor of Gmajor, which has an F#.)
So the relative minor is Aminor ... put the "1" under A and I'll leave the rest to you!

F C G D A E B
      4 1 5 2 6 3 7

There's actually more tricks with this method but they're not as directly relevant to the OP question.
The name of this method is Two Handed Easier Music Theory - "T.H.E. Music Theory" – because when I show it to kids I assign numbers to my fingers, mesh them, and read the finger numbers from top to bottom to get the "41526374" pattern.
2) The "San Francisco" method as it starts with 415, area code for SF.
Please ask for permission before reposting.


Use congruence to show that the output of a natural number function is always divisible by 6

Question: I have been asked to show that for any natural number $n$, $(7n+30)(13n+7)(n+2)$ is divisible by 6. I can show that this function is congruent to $n(n+1)(n+2)$. I noticed that this function is the sequence of tetrahedral numbers multiplied by 6 which already proves it but I have been told by a tutor that introducing a sequence that is not discussed in the course is insufficient. I am not sure if I am able to use induction as the question only asks for me to use congruences to show that it is divisible by 6. I would like to know if this is possible without induction in a way that specifically uses modulo congruence techniques.
Comment: +1 and thank you so much for providing context! This site has been around for a while and many of the common questions have already been asked, so unfortunately there is a duplicate of your question.
Comment: Well I would prefer to know if there is a way to answer this question without the use of induction, i.e., only with the use of congruences.
Answer: You know that in any triple of consecutive integers, say $n$, $n+1$, and $n+2$, at least one is divisible by $2$ and at least one is divisible by $3$. Since $2$ and $3$ are coprime, the product $n(n+1)(n+2)$ is divisible by $2\cdot 3=6$.
Comment: @Arthur The OP pointed out that $$(7n+30)(13n+7)(n+2)\equiv n(n+1)(n+2)\pmod 6$$


Writing Server stored procedures in c#

Question: I am new to c# and am having a difficult time figuring this out,
public UserNotificationFeed GetNotificationFeed(TenantInfo tenant, List<int> notificationId)
{
    UserNotificationFeed userNotificationFeed = new UserNotificationFeed();

    string sql = "select " + NotificationFieldList + " from UserNotificationFeed where MsgId = @MsgId";

    Database databaseObj = SocialDB.GetDataBase(tenant.ConnectionString, tenant.ProviderName);
    DbCommand commandObj = databaseObj.GetSqlStringCommand(sql);

    databaseObj.AddInParameter(commandObj, "MsgId", DbType.Int64, notificationId );

    using (IDataReader reader = databaseObj.ExecuteReader(commandObj))
    {
       while (reader.Read())
       {
          userNotificationFeed = new UserNotificationFeed();
          this.PopulateObject(userNotificationFeed, reader);
       }
    }

    return userNotificationFeed;
}

What I want is that the
string sql = "select " + NotificationFieldList + " from UserNotificationFeed where MsgId = @MsgId";

to take a list of MsgIds passed on by a List<int> notificationId.
Any help is really appreciated .
Comment: That isn't a "stored procedure", btw - it is just a command. Not an important point - just a bit of terminology.
Comment: Random question: if there are multiple ids, your code currently only returns the **last** row. What did you intend to do in that scenario?
Comment: are you getting exceptions?is it not running
Answer: A simple approach, since the data is int (and therefore injection safe) would be to just use:
string sql = "select " + NotificationFieldList +
    " from UserNotificationFeed where MsgId in (" +
    string.Join(",", notificationId) + ")";

(and don't add the parameter)
If you want it to be fully parameterized, that is possible too, but harder (it requires a flexible number of parameters). There are tools that can help, though. For example, with dapper that would be:
var rows = connection.Query("select " + NotificationFieldList +
    " from UserNotificationFeed where MsgId in @MsgId",
    new {MsgId = notificationId}).ToList();

here dapper will automatically tweak the SQL and add the correct number of parameters. But: dapper won't work directly with your IDataReader-based PopulateObject method (since it has already populated some objects).

Writing Server stored procedures in c#


Suppose $G$ is a group and $H,K \trianglelefteq G$. If $H \cap K =1$ the $hk=kh$ for all $k \in K, h \in H$?

Question: Suppose $G$ is a group and $H,K \trianglelefteq G$. If $H \cap K =1$ the $hk=kh$ for all $k \in K, h \in H$?
Here is what I have so far:
Take $h \in H$ and $k \in K$ we wish to show $hk=kh$ or equivalently $hkh^{-1}=k$. Now I know $hkh^{-1} \in K$ since $K$ is normal in $G$ but I don't know how to show that $hkh^{-1}=k$ i.e. it is the element we want it to be not some other element of $K$. I haven't used the fact that $H \cap K=1$ yet so I guess it follows as a consequence of that but I'm not seeing how at the moment.
Answer: Hint: It suffices to show that $hkh^{-1}k^{-1}=1$.  Using the fact that $H$ and $K$ are both normal, what can you say about $hkh^{-1}k^{-1}$?
Comment: It belongs to $H \cap K$ thus we must have it is equal to $1$ and we are done.
Answer: Sketch Proof:
It is shown here that $[H,K]\le H\cap K$. In particular $hkh^{-1}k^{-1}\in H\cap K$.
Comment: I got it now I think: $hkh^{-1}k^{-1} \in H \cap K$ so $hkh^{-1}k^{-1}=1$ then premultiply on the right first by $k$ then by $h$ yields $hk=kh$ for arbitrary $k \in K$ and $h \in H$. As we want. Thanks for the help.


Facebook JS SDK Issue with Logout - Expected Suspicious Login detection

Question: We have a kiosk/terminal style solution wherein we follow the following flow:

User identifies himself in our system.
User lands on his profile page on our system & clicks on add FB account.
User gives permissions.
User is redirected to our logout page.
User is given an option to like a page before logging out.

In the case of this problem, the small iframe of the FB Like Social Plugin redirects to a Connection Error page
Apparently, as pretty much expected, even the Logout link stops working.

In the cases where there is no error, the user logs out using the logout link on our logout page.
User is logged out of Facebook & redirected to his profile page on our system.
User logs out of our system.

The above repeats for multiple users present at the venue.
The overall flow used, that is relevant to the issue can be found here.
Comment: can you edit in the code please.
Comment: Are all the URLs in question https-enabled? That'd be my first wild guess.
Comment: @JimmySawczuk Yes. They are https enabled.
Answer: refer to the new js sdk:
first glance, if the like button is breaking this may be due to your document settings, or a timing issue...  I would suggest loading the like button from within js sdk async and parse it with xfbml


Como eliminar textos entre parênteses com regExp?

Question: Estou desenvolvendo um aplicativo em HTML5 que utiliza a API da Wikipédia para dar a definição do que pedimos. Usei o código que disponibilizaram em um fórum de outra língua do Stack e, nele, percebi a presença do uso de expressões regulares para eliminar certas partes do texto extraído (links, referências, tags, etc.).
Porém, eu gostaria de remover também textos entre parênteses como no exemplo abaixo:
O que ficasse assim

Software aplicativo (aplicativo ou aplicação) é um programa de computador que tem por objetivo ajudar o seu usuário a desempenhar...

Ficaria assim

Software aplicativo é um programa de computador que tem por objetivo ajudar o seu usuário a desempenhar...

Pois bem, tenho o código abaixo e gostaria de uma ajuda na parte das expressões regulares (que ainda não aprendi, mas tô tentando) para resolver meu problema:

if(d.getElementById('q').value !== "") {
algo = d.getElementById('q').value
}
var definir = function(algo) {
startFetch(algo, 1, 1000);
d.getElementById("feedback").value = "Definir > " + algo; // Palavra ou sentença a ser definida
d.getElementById('q').value = algo;
search();
d.getElementById("resposta").value = "Só um momento...";
voz();
}

var textbox = d.getElementById("resposta");
var tempscript = null, minchars, maxchars, attempts;

function startFetch(algo, minimumCharacters, maximumCharacters, isRetry) {
if (tempscript) return;
if (!isRetry) {attempts = 0;
minchars = minimumCharacters;
maxchars = maximumCharacters;
}

tempscript = d.createElement("script");
tempscript.type = "text/javascript";
tempscript.id = "tempscript";
tempscript.src = "https://pt.wikipedia.org/w/api.php?action=query&titles="
+ algo // Palavra ou sentença a ser definida
+ "&redirects="
+ "&prop=extracts"
+ "&exchars="
+ maxchars // Máximo de caracteres a ser "puxado"
+ "&exintro"
+ "&format=json"
+ "&callback=onFetchComplete"
+ "&requestid="
+ Math.floor(Math.random()*999999).toString();
d.body.appendChild(tempscript);
}

function onFetchComplete(data, algo) {
d.body.removeChild(tempscript);
tempscript = null
var s = getFirstProp(data.query.pages).extract;
s = htmlDecode(stripTags(s));
if (s.length > minchars || attempts++ > 5) {
d.getElementById("resposta").value = s;
d.getElementById("feedback").value = "Definindo...";
voz(); // Lê em voz alta a definição da palavra ou sentença
espera(); // Delay para se aproximar do carregamento do áudio
d.getElementById("log").value += "Definir > "
+ algo // Palavra ou sentença a ser definida
+ "\n"
+ s // Definição carregada
+ "\n\n";
saveHist(); // Salva a definição no log de conversa
}

else {
d.getElementById('resposta').value = "Não encontrei a definição, "+nomeDoUsuario+".";
voz();
}
}
function getFirstProp(obj) {
for (var i in obj) return obj[i];
}
function stripTags(s) {

// Abaixo está meu problema ***************************************************
return s.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, "");
// Acima está meu problema ****************************************************

}
function htmlDecode(input){
var e = document.createElement("div"); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Answer: Vejo que na tua regex já tens outros casos que queres tratar. Sugiro juntares (\s\(.*?\))| no inicio da tua regex.
Eu costumo usar este site para trabalhar com regex, é muito util.
De qualquer maneira o que esta sugestão faz é:
O parêntese exterior cria um grupo de captura (...). Depois de abrir esse grupo de captura juntei "um espaço em branco" que se escreve com \s. Isto porque antes de um parêntese há sempre um espaço em branco. Numa regex quando se usa a barra \ isso escapa o próximo caractere. Como viste antes os parenteses têm uma função num regex (grupo de captura), a barra \( "desliga" essa função e aponta para o próprio caractere (.
Depois uso .*? que quer dizer qualquer caractere, zero ou mais vezes, excepto novas linhas. E termino com | que é o "ou" da regex e que quer dizer caso A | caso B | caso C (caso A ou caso B, etc)

var s = 'Software aplicativo (aplicativo ou aplicação) é um programa de computador que tem por objetivo ajudar o seu usuário a desempenhar..';
document.body.innerHTML = s.replace(/(\s\(.*?\))|<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
Comment: @VictorRibeiro ótimo! Fico contente de ter ajudado. Votei `+1` na sua pergunta também por ter dado exemplo do que procurava.
Comment: Era exatamente disso que eu precisava. Resposta muito bem explicada, aprendi aqui o que venho tentando aprender há muito tempo. Muito obrigado, @Sergio.


how to find what libraries are installed/available on a machine for C or CPP?

Question: this is not a outright tech question but i wanted to know if there is a easier way to find what all libraries are present in a system for a particular language and its facilities .... something like a man page would be great , but to look for info you got to know what exist there first. (3rd party libraries for example....)
my way : for C or CPP - i know if there is a compiler like gcc or g++ all the standard libraries that are installed as part of the compiler itself so i can simply look into the section 2 - 3 of the manual , but those are standard libraries , you can also read about them as part of a book for C and CPP .
What i was really interested in was to find a way to discover libraries i dont know off and try and learn about them .
like 3rd party libraries like boost  could/might be found in places like /usr/bin ...  so i was doing a find for libXXX.a or a .so file , then doing google to find what it is and where and how i can use it ....... but this is feels stupid  :(
there must be a easier way to find things ?
PS : i am not owner of the machine so i dont do installations myself , think of a Work/University server .... lot of guys access that. , by the way the OS is Solaris 9
Comment: Almost every dynamic library on a Unixy system is written in/for C and/or C++. `ls /usr/lib` should be fine.
Comment: This is probably not a good way of discovering libraries. I have over 1000 library files in `/usr/lib` alone, very few of which I would care to learn about.
Comment: then how would you decide/find out on what else you should be knowing other than stdlib's of C or CPP which are mentioned in books ?
Answer: If you are on linux you can do at the terminal:
pkg-config --list-all

On my system this gives the following output:
gmodule-no-export-2.0          GModule - Dynamic module loader for GLib
xrender                        Xrender - X Render Library
#many many more
xcb                            XCB - X-protocol C Binding
gnome-mime-data-2.0            gnome-mime-data - Base set of file types and applications for GNOME

So the name of libray and a short description.
Comment: Very concise and straight to the point
Comment: Actually `dpkg --list` lists all the packages
Comment: @RubemPacelli Yes, dpkg --list list all packages, however it also list packages that have nothing to do with libraries, and pkg-config does excactly that. You can use it to list packages, but also to obtain extra information about the libraries, such as compilation and linking flags. It's very usefull for C(++) programmers.
Comment: That is strange because I've just installed the [`libpoppler-cpp-dev`](https://packages.ubuntu.com/kinetic/amd64/libpoppler-cpp-dev/filelist) package, which contains C/C++ libraries, and `pkg-config --list-all` wasn't able to list it to me. On the other hand, I found it using `dpkg --list`
Comment: @hetepeperfan Ok, I just find out that this packages is properly listed by the name `poppler-cpp`, as it is mentioned in the `.pc` (pkg-config) file `/usr/lib/x86_64-linux-gnu/pkgconfig/poppler-cpp.pc`. That actually makes sense since we omit the prefix `lib` and the suffix `.so` when linking a library. However, `pkg-config` does not provide the Linux package name (in my case, `libpoppler-cpp-dev`) used to install the library, which might be useful.
Answer: If you're just browsing for something interesting to learn about, it might be more worthwhile to either browse the rpm database for your distro, or rpmfind.net.
Answer: We choose to learn those libraries that we intend to use. It sounds like you want to know which packages are installed on the system by querying the package manager. Without knowing which operating system is in use, it's difficult to be any more specific.

http://en.wikipedia.org/wiki/Package_manager
http://en.wikipedia.org/wiki/List_of_software_package_management_systems


Graceful pod termination

Question: I need to let the container to run 5 minutes after the kubectl ' termination. It needs to do some work before it's destroyed. It seems that kubernetes contains exactly what I need:
terminationGracePeriodSeconds: 300

so I defined it within my yaml. I've updated running RCs, delete current pods so new ones were created and now I can see that a pod contains exactly this setting via get pod xyz -o=yaml.
Unfortunately, when I tried to do rolling-update, the original pod was killed after exactly 1 minute, not after 5 minutes. I does ssh to the target machine and I could see that docker termineted the container after this time.
I tried to do some investigation how the feature works. I finally found the documentation to kubectl delete where there is a notion about graceful termination period:
http://kubernetes.io/docs/user-guide/pods/

By default, all deletes are graceful within 30 seconds. The kubectl delete command supports the --grace-period= option which allows a user to override the default and specify their own value. The value 0 indicates that delete should be immediate, and removes the pod in the API immediately so a new pod can be created with the same name. On the node pods that are set to terminate immediately will still be given a small grace period before being force killed

So I took one pod, nginx, and try to delete it with grace-period=30. It turned out, that original pod was immediately delete and get pods showed that new one was being started.
So no 30 seconds. What am I doing wrong? It seems that all pods kubernetes does not take these values into account.
Note that I'm using kubernetes v1.2.2
I also found this issue https://github.com/kubernetes/kubernetes/issues/24695 where the reporter had same problem and he solved it in the same fashion. So e.g. 300 seconds is not too much for kubernetes.
Answer: You can use the container lifecycle hook preStop to have your pod sleep before terminating. This hook will be executed prior to kubectl sending SIGTERM to your container.
Example configuration from the docs:
apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: nginx
    lifecycle:
      preStop:
        exec:
          command: ["/bin/sleep","300"]

Answer: https://pracucci.com/graceful-shutdown-of-kubernetes-pods.html
may this can help you.
There're some circumstances where a SIGTERM violently kill the application, vanishing all your efforts to gracefully shutdown it. Nginx, for example, quickly exit on SIGTERM.
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.

Graceful pod termination


Rewrite directory names to php files with htaccess?

Question: Basically folder etc has files:
contact.php
help.php
news.php

How can I make /etc/contact direct to /etc/contact.php?
Comment: [Multiviews](http://httpd.apache.org/docs/2.2/content-negotiation.html) should do this - can you enable it for that directory?
Answer: RewriteCond %{REQUEST_URI}.php -f
RewriteRule (.*) $1.php

Comment: The _condition_ `%{REQUEST_URI}.php -f` will never (very unlikely) be successful, since `REQUEST_URI` is a URL-path, not a file-path. It should be something like: `RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f` instead. (And you should also include the `L` flag on this rule.)
Answer: I solved this by using the code below. first you need to head over to cPanel and in the directory, create a new .htaccess file or open for edit the one you already have, then insert the following code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

However, I still have issues with the PHP sections. for example, domain.com/dashboard now works but domain.com/dashboard/users still shows a 404 but when I manually enter domain.com/dashboard/?pg=users it works.


Calcular porcentagem

Question: Largura * Complemento = Subtotal + Porcentagem = Total

subtotal.Text = (Convert.ToDouble(largura.Text) * Convert.ToDouble(complemento.Text)).ToString();
total.Text = (Convert.ToDouble(subtotal.Text) % Convert.ToDouble(PercaTextBox3.Text)).ToString();

Onde estou errando a porcentagem?
Comment: `Largura * Complemento = Subtotal + Porcentagem = Total` é uma formula? Isso não faz parte do código não é?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: O símbolo de porcentagem não calcula a porcentagem, tem que usar a matemática básica para fazer isso. Alias sugiro aprender a programar de forma mais estruturada. Aprender na tentativa e erro sem saber o que está fazendo é mais difícil, mesmo que não pareça, gasta mais tempo, pula coisas importantes, e principalmente ensina errado causando tragédias.
Tem um erro extra no seu código que vou aproveitar para resolver. A conversão de dado vindo externamente não é garantida e pode quebrar sua aplicação, você tem que ter certeza que foi digitado algo que pode ser convertido.
Eu fiz em Console porque é mais fácil demonstrar, mas você adapta para Windows Forms. Até fiz uma última conversão para string que só fará sentido no Windows Forms.
Tem conversões sem sentido no código. Por isso reforço para entender o que está fazendo, na forma atual não está aprendendo programar. Uma frase que sempre digo:

Se você não sabe tudo o que seu código faz, inclusive o espaço em branco, você ainda não sabe programar

using static System.Console;

public class Program {
    public static void Main() {
        var larguraText = "2.00";
        var alturaText = "1.00";
        var percText = "30";
        var total = 0.0;
        if (double.TryParse(larguraText, out var largura) && double.TryParse(alturaText, out var altura) && double.TryParse(percText, out var perc)) {
            total = largura * altura * (perc / 100);
        }
        var totalText = total.ToString(); //só para fins didáticos do exemplo
        WriteLine(totalText);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.

Calcular porcentagem


Topologically equivalent metric

Question:
Show that in $\mathbb{R}$ the distance
$d'(x,y)=\left|\frac{x}{1+|x|} - \frac{y}{1+|y|} \right|$ is topologically equivalent to the usual metric in $\mathbb{R}$, $d(x,y)=|x-y|$ But $(\mathbb{R},d')$ is not complete.

Im not being able to show that they are topologically equivalent. I've tried to show that if $A \subset \mathbb{R}$ is open with $d$ then it should be open with $d'$. However, when dealing with the $\delta$ and $\varepsilon$, I don't know how to proceed. Any hint is more than welcome!
Answer: One way of playing with this is to note that $d'(x,y) = d(f(x),f(y))$ where $f(t) = t/(1+|t|)$ maps $\mathbb{R}\to (-1,1)$.  In other words, $d'$ is the standard metric on the interval $(-1,1)$ pulled back by the homeomorphism $f$. So this problem boils down to showing that $f$ is continuous and continuously invertible.
Comment: That's a nicely elegant way to show it.
Answer: Show that an open ball wrt d is an open ball wrt d' (not necessarily of the same radius), and vice versa. Then, since the open balls form a basis for the topology, the topologies are the same.
Answer: Here's what you will do:
First you will show that $d'$ is a finer metric that $d$ on $\mathbb R$.
To do it, first pick a point $x \in \mathbb R$ and let $\varepsilon >0$ be a fixed positive number.
Now, you want to find $\varepsilon'>0$ ( which may depend on $\varepsilon$ and $x$ ) satisfying
$$B_{d'}(x,\varepsilon') \subseteq B_d(x,\varepsilon) \tag{1}$$
So, you will say that for $\varepsilon'= f(\varepsilon,x)$ the relation (1) holds.
Then similarly, you will show that $d$ is a finer metric than $d'$ on $\mathbb R$ and this will complete the proof that these metrics are topologically equivalent.
Comment: But if I show that $d$ and $d'$ are topologically equivalent, as you said, then there is a contradiction in what you are saying or there is a contradiction in the problem, since they ask me to show that $(\mathbb{R},d')$ is actually not complete. (I think that the objective of this exercise is to actually show that completeness is not a topological concept)
Comment: Yes, sorry. You are right. I deleted the edit part.

Topologically equivalent metric


My django form is not working when i iterate through it using for loop

Question: Basically if I tried to use this code
{% for field in form %}

        {{field.label}}
        {{field}}

{% endfor %}

the form data wont make it pass is_valid().But it renders out the form fine. and if I use this code
<form action="" method="post"> {% csrf_token %}
 {{form}}
<input type="submit" value="">

it worked perfectly fine. How do I get the first code to work because I want to add classes between the label and the input field
and here's my view
def booklist_view(request):

  bkff = BookListForm()

  if request.method == 'POST':

      bkff = BookListForm(request.POST)

      if bkff.is_valid():

          bkff.save()
          bkff = BookListForm()

  context = {
      'form': bkff,

  }
  return render(request, 'booklist1st/booklist.html', context)

Comment: please add your view
Answer: Please try this.
views.py
def booklist_view(request):
  form = BookListForm(request.POST or None)
  if request.method == 'POST':
      if form.is_valid():
          form.save()
  context = {'form': form }
  return render(request, 'booklist1st/booklist.html', context)

Here we render field according according to field type(hidden_fields,visible_fields).
html template:
<form method="post">
    {% csrf_token %}
    {% for hidden in form.hidden_fields %}
      {{ hidden }}
    {% endfor %}
    {% for field in form.visible_fields %}

         {{field.label}}
         {{field}}

    {% endif %}
    <input class="btn btn-primary" type="submit" name="add_book" value="Save and add book" />
</form>

Comment: It worked thanks. But if you don't mind can you explain `form.hidden_fields` please?
Comment: If you want to render hidden field in your form then give this code. similarly visible field.
Answer: You need to specify each field relate data like for=, id=, etc. To have maximum control over how your form is rendered, specify each field and control its style, for example, as we can't see your Form definition, this is an example on how it would be for a title field:
<form method="post">{% csrf_token %}
    {# Include the hidden fields #}
    {% for hidden in form.hidden_fields %}
    {{ hidden }}
    {% endfor %}
    {# Include the visible fields #}
    {{ form.non_field_errors }}

    {{ form.title.errors }}
    Title
    {{ form.title }}
    {% if form.title.help_text %}
    {{ form.title.help_text|safe }}
    {% endif %}

    <input class="btn btn-primary" type="submit" name="add_book" value="Save and add book" />
</form>

Answer:     <form method="post">
        {% csrf_token %}
        {% for hidden in form.hidden_fields %}
          {{ hidden }}
        {% endfor %}
        {% for field in form.visible_fields %}

             {{field.label}}
             {{field}}

        {% endfor %}
        <input class="btn btn-primary" type="submit" name="add_book" value="Save and add book" />
    </form>

View.py
 from django.views.decorators.csrf import csrf_protect

    @csrf_protect
    def booklist_view(request):

      bkff = BookListForm()

      if request.method == 'POST':
          bkff = BookListForm(request.POST)
          if bkff.is_valid():
              bkff.save()
      context = {
          'form': bkff,
      }
      return render(request, 'booklist1st/booklist.html', context)


Return a JSON Array to a View in Laravel

Question: I am using Laravel 4to build an applicaiton.
This is my code:
public function handleCreateCandle(){
        $candle = new Candle;
        $candle->name = Input::get('name');
        $candle->body = Input::get('body');
        $candle->user_id = Sentry::getUser()->id;
        $candle->save();
        return Redirect::action('User_BaseController@getPrayerSpace')->with('message', 'Thank you for lighting candle');
    }

The issue is rather than returning a message I would like to return a json array to the view with a success code and the name and body of $candle. Can anyone advise me on how to do this?
Comment: however do you mean? do you want a json string instead of just a plain text? then just use the json_encode? ->with('message', json_encode($candle))
Answer: Instead of using save() function you can use create() function to create a new row.
Create() function returns you the last inserted row, which you can use to show it in your message.
Example:
$user = User::create(array('name' => 'John'));

Please refer:
http://laravel.com/docs/eloquent


My module adds a CCK field to an existing content type. How do I then modify an existing view to sort using the new field?

Question: I am building a new module ('best_answer') that builds on the functionality an existing module ('answers').
The new module adds a new CCK field ('best_answer_p') to a CCK content type ('answer') that was defined in the original module.
The original module also defined a view ('question_answers') which lists answer nodes, sorted by several factors. I'd like to modify this view so that it also sorts by the new field 'best_answer_p'.
I could do this by simply overriding the view, using the Views UI. However, what this means is that if any other module also wants to override the view in some way, my 'best_answer' sort will be lost.
So, I'd like to do this in a way that programmatically alters the existing view instead of overriding it. I am trying to do this using Hook_views_query_alter. But I run into an error.
Could anyone point me in the right direction?
Here is my code:
<code>function best_answer_views_query_alter (&$view, &$query) {

  if ($view->name == 'question_answers') {

    // add the best answer field to the query
    $query->tables['node']['node_data_field_best_answer_p'] = array(
      'count' => 1,
      'alias' => 'node_data_field_best_answer_p',
    );

    // sort answers so that the best answer is displayed first
    $new_orderby[0] = 'node_data_field_best_answer_p_field_best_answer_p_value DESC';
    foreach ($query->orderby as $key => $value) {
      $new_orderby[$key+1] = $value;
    }
    $query->orderby = $new_orderby;

  }
}
</code>
Here is the error:

user warning: Unknown column 'node_data_field_best_answer_p_field_best_answer_p_value' in 'order clause' query: SELECT node.nid AS nid, votingapi_cache_node_points_vote_sum.value AS votingapi_cache_node_points_vote_sum_value, node.created AS node_created FROM node node LEFT JOIN votingapi_cache votingapi_cache_node_points_vote_sum ON node.nid = votingapi_cache_node_points_vote_sum.content_id AND (votingapi_cache_node_points_vote_sum.content_type = 'node' AND votingapi_cache_node_points_vote_sum.value_type = 'points' AND votingapi_cache_node_points_vote_sum.tag = 'vote' AND votingapi_cache_node_points_vote_sum.function = 'sum') LEFT JOIN content_type_answer node_data_field_answer_question ON node.vid = node_data_field_answer_question.vid WHERE (node.status <> 0 OR (node.uid = 1 AND 1 <> 0) OR 1 = 1) AND (node.type in ('answer')) AND (node_data_field_answer_question.field_answer_question_nid = 2) ORDER BY node_data_field_best_answer_p_field_best_answer_p_value DESC, votingapi_cache_node_points_vote_sum_value DESC, node_created DESC LIMIT 0, 10 in D:\xampp\htdocs\drupal\sites\all\modules\views\includes\view.inc on line 771.
Answer: You should override the view and change the sort. I have never seen a module that attempted to alter a view defined by another module.
Comment: Thanks for this answer. It turns out I had planned to take your advice ... but want to do it programmatically and am struggling to figure out how. I ran across this stackexchange question http://stackoverflow.com/questions/4566682/rewrite-default-drupal-view-programmatically which seems to offer a way forward. I'll try that next.
Comment: Yep, hook_views_default_views_alter() did the trick. I also ran across a nice write-up here: http://drupal.org/node/744450#comment-3899464 . Thanks!


Python: Maintaining original order when zipping two lists into a dictionary

Question: I am reading a CSV file and combining rows into dictionaries, with the first row containing the keys and the subsequent rows containing the values.
I want my dictionary keys to be in the same order as the original csv file, but the dict(zip)) function seems to order them randomly. I tried OrderedDict and that didn't work.
If there is a better way to produce my dictionaries I'm open to suggestions, but I would really like to know how i can do this while keeping my existing code, just because I am very new to Python (and programming in general) and I would like to be able to understand my own code at this point.
import csv     # imports the csv module

with open("csvfile.csv", "r") as file_var:
    reader = csv.reader(file_var)
    my_list = []
    for row in reader:
        if (len(row)!=0):
            my_list = my_list + [row]

for i in range(1, len(my_list)):
    user = dict(zip(my_list[0], my_list[i]))
    print "----------------------"
    print user['first_name'], user['last_name']
    for key in user:
        print key, user[key]

Answer: Dictionaries have an arbitrary order. You should use an OrderedDict instead.
from collections import OrderedDict

user = OrderedDict(zip(my_list[0], my_list[i]))

etc.
I note you say it didn't work, but I see no reason why it wouldn't. In what way did it fail?
Comment: Honestly not sure. Is OrderedDict a thing in python 2.7? It wasn't even highlighted as a function in my editor.
Comment: It's a class in the collections module (in the standard library), and yes it was introduced in 2.7.
Comment: You're right - I didn't import the module when I tried it. It worked! Thanks much.


How many real roots does the following polynomial equation have?

Question: $P_n(x)=1+2x+3x^2+4x^3+....+(n+1)x^n$
 Also given: n is an odd number.
Well; from the polynomial equation, it is clearly understood that all the roots have to be negative.
Also, there has to be at least 1 root; that is clear if we put $x=1$.
It would help if you could tell me how to proceed...
Comment: Change the title of the question, because the equation that you want to solve is not quadratic
Comment: Your polynomial is the derivative of $$1+x+\cdots+x^{n+1} = \frac{x^n-1}{x-1}$$ That right-hand side really ought to be easier to handle, in my opinion.
Comment: We have $P_n(1)\ne 0$ and the polynomial is not quadratic for $n\ge 3$. You probably mean that $P_n(1)>0$ shows that there is at least one real root but this is guaranteed for a polynomial with odd degree anyway. Additionally : What is the question ?
Comment: You might mean $P_n(-1)=(1-2)+(3-4)+...+(n-(n+1))=-(n+1)/2<0$ to get the existence of at least one real root (in $[-1,0]$). But then again, every odd degree polynomial has at least one real root by the intermediate value theorem.
Comment: Why do you think that there is at least 1 root at $x=1$? This is a polynomial of $\mathbb{N}[X]$ of degree $n$ so it has exactly $n$ roots counted with multiplicity.
Comment: @BillO'Haran "exactly $n$ roots" is true in the complex numbers, I do not think this is the intent here, it seems that the real roots have to be determined (and perhaps the number of (negative) real roots)
Comment: @Peter My point is that the third sentence makes no sense.
Comment: @BillO'Haran It is unlucky formulated, but it makes sense if it is interpreted correctly, namely that $P_n(1)>0$ guarantees the existence of a real root because the function tends to $-\infty$, when $x$ tends to $-\infty$. However, this existence follows already from the odd degree.
Answer: Since all coefficients of $P_n(x)$ is non-negative. $P_n(x) \ge P_n(0) = 1 > 0$ for all $x > 0$.
Independent of whether $n$ is even or odd, $P_n(x)$ doesn't have any non-negative root.
For odd $n$, notice
$$(x-1)^2 P_n(x) = (n+1)x^{n+2} - (n+2) x^{n+1} + 1$$
At $x = -r < 0$, we have
$$(r+1)^2 P_n(-r) = 1 -((n+1)r + (n+2))r^{n+1}$$
Notice RHS is strictly decreasing as $r$ increase from $0$.
Together with the fact RHS is $1$ at $r = 0$ and goes to $-\infty$ as $r \to \infty$. There is one and only one $r > 0$ where $(r+1)^2P_n(-r)$ vanishes.
From this, we can conclude $P_n(x)$ has exactly one real root for odd $n$.
Answer: As your function is a partial sum for the binomial series of $(1-x)^{-2}$, consider
\begin{align}
(x-1)P_n(x)&=-(1+x+x^2+...+x^n)+(n+1)x^{n+1}\\
(x-1)^2P_n(x)&=1-(n+2)x^{n+1}+(n+1)x^{n+2}
\end{align}
From the last form you can see by the Descartes rule of signs that there is exactly one negative root for odd $n$.
In a first, rather heuristic, approximation, the roots of the last expression are close to the roots of the two binomials in it, that is, close to $\frac{n+2}{n+1}$ and the roots of $x^{n+1}=\frac1{n+2}$. Remove from this root set the first one and $\sqrt[n+1]{\frac1{n+2}}$ as these correspond to the double root at $1$ of the factor $(x-1)^2$. Then there remains a real root around $x=-1$ with a closer approximation to $-\sqrt[n+1]{\frac1{2n+3}}$ while the other are close to complex unit roots.
More precisely, set $x=qv$ with $q^{n+1}=1$, $q\ne 1$ and $v\approx 1$. Then one approximation of the equation is $$0\approx 1-(n+2-(n+1)q)v^{n+1}$$ which has a solution close to $1$ of approximately
$$
v\approx ((n+2)-(n+1)q)^{-1/(n+1)}\approx(2n+3)^{-1/(n+1)}(1+\frac1{2n+3}(q+1))
$$

<code>phi=np.linspace(0,2*np.pi,160);
for k in range(4,22):
    n=2*k-1; rts = np.roots(range(n+1,0,-1));
    plt.plot(rts.real, rts.imag, '+', label="n=%d"%n);
    r=(2*n+3)**(-1./(n+1)); q = np.exp(1j*phi);
    x = r*q*(1+(q+1)/(2*n+3));
    plt.plot(x.real, x.imag, lw=0.2)

plt.plot(np.sin(phi),np.cos(phi), lw=0.4); plt.legend(); plt.grid(); plt.show()
</code>


Google Sheets: Formulas over multiple sheets

Question: Is it possible to grab the contents of a cell from one sheet and display them on another?
I have 4 sheets. And I want the cells of the third sheet to display the first column of the second sheet on the second column.
Answer: if you want to get range from another sheet just use:

Replace 'Sheet' and 'A2:C8' with title and range you want to refer

={Sheet!A2:C8}

For multiple sheets

Replace ';' with ',' for horizontal view:

={Sheet!A2:C8;Sheet1!A2:C8;Sheet2!A2:C8}

Answer: Google Sheets allows reference between sheets. the syntax is pretty simple. consider a single cell: =<sheetname>!A2 for example. From there, you can drag down with the bottom right corner, and your your column will now be a copy of an arbitrary column in , in this case A
Answer: Add the sheetname exclamation point to your cell reference
e.g. sheet!A:1
Then drag from the first cell down to as many rows as you need.
Answer: These are the annotations for cells in google sheets
Sheetname!A:1 For Relative Cells
Sheetname!$A:1 For Absolute Columns
Sheetname!A:$1 For Absolute Rows
Sheetname!$A:$1 For Absolute Cells
Answer: Yes.  For specific ranges you can use IMPORTRANGE.
Answer:
Is it possible to grab the contents of a cell from one sheet and display them on another?

Yes. It's even possible to get entire columns of data.
In sheet 2 A1,
 =ARRAYFORMULA('Sheet1'!A:A)

The single quotes ' can be omitted, if the sheet name doesn't have a space . In other words, if you use Monthly Budget as a sheet name, then single quotes is mandatory.


IIS 7.0: Why does Require Client Certificates cause error 500 and "page cannot be displayed"

Question: I have two Windows 2008 x86 servers running IIS 7.0, one site on each server; both sites are SSL-enabled, using DoD-issued certificates.  Both sites are accessible via https over port 443, but fail the moment Client Certificates are set to Require or Accept. IIS log records error 500.0.64 but nothing else.
I have several Windows 2008 IIS 7 x64 servers that require client certificates and they are working as expected; it's just the two x86 servers that are being problematic.
Comment: Do you need client certificates?

Your description sounds like you are just wanting SSL-encryption.
Comment: Yes, I need to configure the servers to Require Certificates from clients. The servers in question have a valid SSL-cert installed; that part is working. It's just when the Client Certificates option is enabled that users can no longer access the site.
Comment: Unless there is a genuine fault, it sounds like the server can't validate the client's cert (e.g.: chaining issue), or it can't perform a CRL check, or it can't access the signing CA.  This could be me barking up the wrong tree...
Answer: The solution can be found here and is related to MS KB977377. The choices are

Remove MS update KB977377

or

Change the vlaue of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\DisableRenegoOnServer to 0


Twitter typeahead not working after upgrade

Question: I upgraded twitter typeahead using the nuget package manager from 10.2 to 1.11 and the remote query is no longer being called to get the autocomplete results in my ASP.Net MVC 5 project. There are no errors reported.
var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('FullName'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    remote: '/Person/GetPeople?q=%QUERY'
});

engine.initialize();

$('#Person').typeahead({
    hint: true,
    highlight: true,
    minLength: 1,
}, {
    display: 'FullName',
    source: engine.ttAdapter()
}

Answer: I found the answer before I finished typing my question out, so here is what I found. I just had to change the remote declaration in the following:
var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('FullName'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    remote: {
        url: '/Person/GetPeople?q=%QUERY',
        wildcard: '%QUERY'
    }
});

Furthermore, the CSS was broken for Bootstrap 3 - I am using typeahead.js-bootstrap3.less. The temporary fix for this was to replace dropdown-menu with menu in typeahead.css (until a new release).


Rsync fails to update

Question: I have a script running on several computers that mounts a remote directory and transfers from the local disk to that mounted directory. I have rsync running with the -a tag, but for some reason files aren't getting updated.
From my understanding, if you put "rsync -av  " then anything that is different on the local will be moved to the remote. When I run with a -vv tag it shows the files being listed and it says they are "uptodate", but if I run a diff on the two locations I can see that they are not(They differ by one line).
Is there something I'm missing?
It should't matter, but I'm running rsync  version 2.6.8  protocol version 29
Answer: By default rsync only looks at file size and lost modification time to figure out if a file is up to date or not. While not perfect, it's usually a good performance trade off.
You might want to start by examining the modification time and file size value. There is also the option of using the -c parameter, which actually compares checksums.
Comment: It randomly started working... I started by rsyncing the specific file, then deleting that change and rsyncing the directory above that, etc, and now it's working, without the -c flag... I'm double checking by running my script.
Comment: Okay, so it doesn't initially do a diff, but when you say it checks if it is up to date, if the file is older, or the file size is smaller, will it still move it?
Comment: +1 I was just typing the same thing. - Never mind as long as someone answers! I suggest running again with the --checksum flag
Comment: checksum isn't a viable options, as I have several thousand files and some can be quite large. I'm wondering how exactly the difference engine works based on file size and mod time. I would assume that if the file is newer, and the size is different then it will transfer. If so, then my files are meeting that criteria, I'm just not sure why it's not transfering.
Comment: Does ramping up verbosity to -vvv show anything useful?
Comment: Could you not do a test rsync of just that one file using the --checksum option?

Rsync fails to update


google maps android studio does not show my polyline

Question: I don't know why this polyline won't show, I already put the google maps api and enabled the directions api as well
PolylineOptions rectOptions = new PolylineOptions();

    rectOptions.add(new LatLng(24.009115, -104.699933));
    rectOptions.add(new LatLng(24.009115, -104.699933));
    rectOptions.width(5);
    rectOptions.color(Color.RED);

   Polyline polyline = mMap.addPolyline(rectOptions);

Answer: Add(), width() and color() all return a PolylineOptions with the new settings added.
PolylineOptions rectOptions = new PolylineOptions();

rectOptions =rectOptions.add(new LatLng(24.009115, -104.699933));
rectOptions =rectOptions.add(new LatLng(24.009115, -104.699933));
rectOptions =rectOptions.width(5);
rectOptions =rectOptions.color(Color.RED);
Polyline polyline = mMap.addPolyline(rectOptions);

or
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(24.009115,-104.699933),
new latlang(24.009115,-104.699933))
.width(5)
.color(Color.red);
Polyline polyline = mMap.addPolyline(rectOptions);

Source:https://developers.google.com/android/reference/com/google/android/gms/maps/model/PolylineOptions


Swap elements of a diagonal matrix

Question: Suppose you have a diagonal matrix, e.g.,
$$\begin{bmatrix}
3 & 0 & 0 & 0 \\
0 & 2 & 0 & 0 \\
0 & 0 & 9 & 0 \\
0 & 0 & 0 & 1
\end{bmatrix}$$
What linear transformation (or any method, really) could you apply to get a different matrix, e.g.,
$$\begin{bmatrix}
2 & 0 & 0 & 0 \\
0 & 3 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 9
\end{bmatrix}$$
Where we swap every odd indexed diagonal with the element at (that index + 1)
I think this problem is equivalent to rearranging the eigenvalues and eigenvectors of a matrix with each other. For example moving the eigenvalue $3$ from the vector $$\begin{bmatrix} 1 \\  0 \\ 0 \\ 0\end{bmatrix}$$ to $$\begin{bmatrix} 0 \\ 1 \\ 0 \\ 0\end{bmatrix}$$
This seems like a trivial question, but I can't find a solution myself.
Comment: Hint: permutation matrix.
Comment: To permute rows and columns you can multiply on the left and right by a permutation matrix. You can model all position swaps that way for any matrix, even rectangular.
Answer: To swap the $i$th and $j$th entires along the diagonal of a diagonal matrix: Using $E_{ij}$ to denote the matrix with $1$ in the $i$th row and $j$th column and $0$ in all other positions, multiply your matrix on both sides by $I - E_{ii} - E_{jj} + E_{ij} + E_{ji}$. (Since this matrix is involutory, this can be viewed as conjugation.)
The matrix for swapping adjacent entries in pairs would look like
\begin{pmatrix}
 A & 0 & \cdots & 0 \\
 0 & A & \cdots & 0 \\
 \vdots & \vdots & \ddots & \vdots \\
0 & 0 &  \cdots & A
\end{pmatrix}
in block form, where $A = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}$.

Swap elements of a diagonal matrix


Bootstrap Dropdownlist Issue in angular JS

Question: I am trying to use ng-repeat in bootstrap dropdown menu, but it does not display the list of elements in drop down. am i missing anything in populating the elements of drop down list from a method defined in controller.
<button type="button" class="btn btn-default btn-sm" title="Results Per Page">

      {{Temp.obj.pageSize}} Results Per Page

                 {{result}}

</button>

Answer: You are simple missing the dropdown-menu directive in the ul list.
As a reminder, here is the (simplified) example from the angular-ui bootstrap doc.

  <button id="single-button" type="button" class="btn btn-primary" uib-dropdown-toggle>
    Button dropdown
  </button>

Action

Another action

It looks like you are using an old version of angular-ui bootstrap when the directive were not prefixed by uib-. I recommend updating your version if you can. Otherwise, just remove the prefixs from the example.
Edit: As you are using the version 1.1.2 of angular-ui bootstrap, you need to prefix the directives as shown in this answer. And here is the doc for reference
Comment: I added the directive but still the data is not populated on the dropdown list...
Comment: which version of angular-ui bootstrap do you use?
Comment: I have multiple versions in the scripts folder for angular 1.2.2, 1.3 and 1.5.and  bootstrap version 3.2.0.
Comment: 1.5 seems to be the angular version, not the angular-ui bootstrap. It is important to know your angular-ui bootstrap version because as I explained the directive names have changed with the versions.
Comment: ok, so now we need to know the version of the angular-ui bootstrap library: https://angular-ui.github.io/bootstrap/
Comment: ui bootstrap-tpls-1.1.2.js is the version .
Comment: ok so according to the doc for that version, you need to prefix the directive: http://angular-ui.github.io/bootstrap/versioned-docs/1.1.2/#/dropdown If you copy/paste the snippet of the answer the dropdown menu should work as expected. Then you will be able to test with your ng-repeat in order to isolate the cause of the issue. But using the updated template with prefixed directives should be enough.
Comment: now that i changed to use uib- as prefix to dropdown-menu, its working but when ever i click on the dropdown or make a selection, its displaced to either left or right. and also the dropdown when it is populated it doesnot populate exactly under the button. how should i fix these position issues. Thank you so much.


Does a guitarist need to know staff notation?

Question: There is a notation called Tablature for guitar. Most of the keyboardists I have seen, use the staff notation.
Is staff notation useful for guitarists?
Will it help the guitarist in learning guitar?
Comment: "Knowledge is Power."  In this case, that's actually true: the more ways you can read music, the more flexible or adaptable you can be.
Comment: @Tim no, I'm advocating learning both.  Weak analogy, but as a cellist I'm comfortable reading bass, tenor, and treble clefs. If, as a guitarist, you can read a classical score and read tablature, you have more sources of "sheet music" available to you.
Comment: The standard notation is designed to write down music, the tab notation is designed to write down fingerings.
Comment: @Carl - so are you advocating tab?
Comment: I find that the two kinds of notation compliment each other. Often if I am learning a new piece, I use both together, because each has its strong points and its weak points.
Comment: Q: How do you get a guitarist to turn down the volume?  A: Put sheet music in front of him.
Answer: A guitarist will benefit from learning staff notation. Depending on music style and ambition level, this benefit will vary. For someone starting out, I would recommend to try to learn staff at the same time. It is the common written language of music, after all. There will be vastly more material available compared to tabs.
That being said, the notation isn't as good match for guitar as for piano, and it is quite hard. Sight reading guitarists are a rarity for a reason. But you need to learn some of the staff notation for the rhythm, so it can't hurt to try and pick up the other stuff as well.
To summarize: Knowing staff notation is a benefit, so try it. On the other hand, a great host of guitarists has managed to do fine without it, so it's not something one is expected to know.
Answer: If you want to play classical guitar it is obligatory.
If you want to play jazz, it is VERY preferable.
If you want to play rock/pop in a garage, you'll survive without it.
In the end, if you want to be a professional musician, knowing staff notation will make you much more competitive, to say the least.
Answer: Personally I find the classical notation ill suited to a guitar, and while I understand it for playing piano I find it hard to use for the guitar.
However, it does provide some key information that most tabs do not - the rhythm is perhaps the most important of the things that are missing. Most official published scores will provide both the classical notation and a tab. I use the tab to find out what to play, and the classic notation to determine to rhythm.
This has suited me fine for 20 years, and may well suit you, depending on what you want to do with the instrument. I like to play blues and rock and jam with my friends. If you are learning Classical guitar and want to play in an orchestra I would recommend that you learn the staff notation.
Comment: You are correct that most tablature lacks rhythmic notation. There's quite a bit more information in staff notation that's not included in guitar tab than just rhythm, though. Key signatures, and dynamics, for example.  Perhaps most important, intervals are much easier to read on staff notation than tablature.
Comment: Good point, there are many things missing from tabs, especially those posted online.
Answer: Staff notation is important for guitarists, once they have mastered it. The trouble with tab is that it doesn't tell the timing, unless, of course, the proper stave is there as well. It also tells where the author has played it, or thinks it should be played. This is very subjective, unless it's produced by the very same person who played a particular solo that you're trying to get.Many solos/tunes can be played in several different places on the fingerboard - I prefer to  make my own decisions.
If you think you may end up playing in a reading band, or be a session guy, reading dots is probably essential.If, later you want to play another instrument, tab won't help at all - unless it's bass guitar...
If lack of timing marks is not a problem, 'cos you know the tune, why would you use the tab anyway ?
Another problem I find, as a teacher, is that so many downloaded tabs seem to be made by people still wet behind the ears, so are just inaccurate.
On the other hand, so to speak, tab can be invaluable to distinguish things like slurs - is it a bend up, slide up or hammer-on? Not available in standard notation - just shown as 'slur'.Harmonics, etc. Open strings as opposed to fretted - sometimes an important piece of information for the player. So, having both is the best solution, as they complement each other. One on its own is probably not actually sufficient. But that means to get the best out of it, you need to be able to read BOTH !!
Comment: I agree that a lot tabs posted online are incorrect, but some of them are good transcripts. There are always the official scores that are normally fairly close. However I disagree with your comment 'If lack of timing marks is not a problem.. why would you use the tab anyway?' - well most music fans would be able to hum their favourite tune with roughly correct timing, but the leap from there to being about to listen to a song and then play it by ear is huge. Tabs will help people along that path.
Comment: Fair comment. But I prefer to spend time giving players the facility to hear something and play it, rather than relying on something which, at the end of it all, could be giving wrong info. anyway.Folks do tend to think tab is gospel.
Comment: Yes some people do, and you are right to warn about the inaccuracies posted online. I tend to seek out a few different versions and use it as starting point rather than treating it as if its set in stone. That, or I buy the official version.
Answer: Tablature is idiomatic notation, i.e. a style of notation that is specific to a particular instrument, and it can be useful in communicating information that is specific to an instrument.
It's particularly useful for guitar in that the guitar is a relatively difficult sight-reading instrument. Much of the sight-reading difficulty guitarists face stems from the simple fact that virtually any note on the guitar can be found on multiple strings. Well-written tablature can clarify what positions one should use to execute a particular passage.
That said, because it is idiomatic notation, it also has limitations. Staff notation is a remarkably efficient means for conveying a lot of musical detail in a small space, and it has the advantage of being applicable to any non-transposing instrument without modification. Compared to staff notation, tablature is actually fairly difficult to sight-read in performance situations.
So, yes, it will be useful in learning the guitar, but, if your goal is to be a working musician, you will need to learn to read sheet music, as you will almost certainly find yourself in situations where tablature is either not available or not ideal for the situation.
Comment: Good point about non-transposing instruments using standard notation.When learning the trumpet, I learnt to read 'wrongly', so I could play any ordinary music at concert pitch.I.e. read a C, but play a 'trumpet D'. Going off on a tangent here, though, as transposing is often very easy on guitar - move up or down a number of frets.
Answer: Violins and other string instruments are no different re having multiple note locations.
Disagree with kiprainey that guitar is not suited to sight reading, it's an education thing - and most people learn to read tab instead. It's taking the easy way out, and it has been continually successful because there is less demand for session musicians who can read than the number of able guitarists out there. Chicken or egg? It's stupid anyway, and I don't think anyone in their right mind should encourage tab, or discourage classic notation.
Learning to read (classic notation) is something every musician should do, regardless of instrument.
Comment: On piano, each note maps to one key. For guitar, a phrase can be played in multitude of ways. Tab was developed out of a need. While I do think one should learn staff, a casual player will do fine with tab, and will likely play more music rather than try to figure out fingerings. Different strokes...
Comment: Yes, but it encourages the casual player aspect and many find it hard to then move on to staff reading
Answer: Scrowler's answer is on the money. Staff notation is the standard way of reading music and applies to every instrument. It is the only way in which music is presented in professional contexts like the studio or bandstand. It contains much more information than tablature, allows one to play music written for other instruments, allows one to communicate with other instrumentalists in the written form. As for apparent difficulty, this is indeed a matter of education. For the most part, classically trained guitarists have no problems reading. It is those without a formal education which focuses the appropriate amount of time on learning to read that have a hard time. The argument that, it is too hard on guitar, is woeful. It's like saying that reading a foreign language is too hard and therefore a waste of time.
Answer: I'd say need is a subjective term in this case.
Arguments For
It's beneficial in that it helps you understand the language of music overall, it can be used as a medium by which most instruments can play.  You give tablature to a piano player and they'll have no idea what to do with it, but sheet music they'll be able to understand a lot more.
Arguments Against
On the other hand there are a handful of guitarists, like Jimi Hendrix, who managed to get by remarkably well without being able to read music, because they make up for it in musical ear, feel, passion, whatever you want to call it.
It's like language.  You don't strictly need to write in order to speak it and understand, but for getting things down it's a very good medium.
So in conclusion, you don't need to learn staff notation, though it is highly beneficial to take the time to learn it.
Answer: Having the ability to read both types of notation is beneficial because of the wider ranger of sheet music that will be available to you.  I often find it easier to read rhythm and chords when looking at staff notation.  The downside of staff notation is that there isn't a one-to-one correspondence for a given note and it's representation on paper.  Tablature eliminates this ambiguity and for that reason can make sight reading moving lines much easier (as long as adequate rhythm notation is provided).  Ideally, both staff and tablature notation are provided when reading music.  So yes, staff notation is useful for guitar if you take the time to learn it, but it is not a necessity to be a great guitar player.  As far as staff notation helping someone learn to play guitar, I think it is.  It helps a new guitar player to think of the frets as notes instead of numbers.  However, as long as a new guitar player spends time learning the theory of music and how it applies to a guitar, this shouldn't be a problem.


addEventListener() by the second argument "function" push array value to a globally declared array and then I can't use the array at a time

Question: WELL, I have globally declared an array and in second line the document.addEventListener("click",function1);  inside the function1 I have inserted an array value and then I want to use the globally declared array data outside the addEventListener()  function1 using if statement but the problem is that if statement dose not working at a time. I want to show a alert message by the if statement as if I can use the counterAll array in another place
var counterAll = new Array();
var f1 = document.getElementById("f1");
f2.addEventListener("click",function1);
function function1(){
    counterAll[0] = 13;
}
if(counterAll[0]===13){
alert("It work's");
}

Answer: Seems like you need real understanding of javascript here, first of all your code f2.addEventListener("click",function1);
just register a function to be executed, but doesn't do anything.
function function1(){
        if(counterAll[0] == 13){
           alert('works');
        }
    }

Above code is function declaration,(its not executed till this point)
if(counterAll[0]===13){
alert("It work's");
}

Above code executes straight away, but counterAll[0] is undefined, because the function which is setting the value has not been called yet, so try below code and understand it
var counterAll = new Array();
var f1 = document.getElementById("f1");
f2.addEventListener("click",function1);
function setValue(){
    counterAll[0] = 13;
}

function function1(){
    if(counterAll[0] == 13){
       alert('works');
    }
}

setValue();

I have created a separet function setValue() in which I am setting the value. Now when i will click the Dom element with the id 'f1', the alert will show up


Appending file to zip in nodejs

Question: I'm making an application in which you edit a file, and it should append the edited file to zip archive and make it downloadable. It should be cross platform (Windows and Linux).
My goal is to programmatically generate the edited file and append it to static archive (which is always the same, around 3-4MBs, but around 40-50 files).
I've looked at the following post on how to zip archives in node.js, however the answer by Eliseo Soto is OS dependent.
I've also found daraosn/node-zip, but as I understood it's not able to append a file to the archive, without remaking it.
Any suggestions on how I can complete my goal without rebuilding the whole archive from scratch for each request?
Answer: node-zip is using JSZip. According to JSZip documentation, the archive is not recreated in yout case. (if the zip file exists, the files are added to it).

Appending file to zip in nodejs


Custom WPF ProgressBar To Include Upper Limit Indicator

Question: I would like to make a custom progress bar with upper limit property (this must be different then the maximum value of the control). When you set a value to this property a simple red line appears on the progress bar at the specified location.
Something like this would do it:
Answer: You can Inherit From ProgressBar class in a new one, add your new DependencyProperty to it of new maximum value.
Set a new style and template for it to show the new line:
https://wpftutorial.net/HowToCreateACustomControl.html
Comment: I get this... the problem is that i don't really understand how to draw a line or rectangle or whatever at a specified value on the progress bar.
Comment: When you edit the Template of your new inherited control, you can insert this Rectangle/Border/etc. and set its Margin(or any clever positioning method you can come up with).
We Bind to new property we mentioned before, ActualHeight/ActualWidth of our control, and converter to return the value you need.
Comment: (or any clever positioning method you can come up with), this is what i'm looking for. The clever method -_-
Comment: Thats why I added the tutorial. you edit the Template of your control.
You put a Red rectangle with margin that is binded to both your new property and the actual width of the control and multibinding converter. the logic in the converter should return a thickness relative to the width of the control which should position the rectangle where you need it.

https://www.codeproject.com/articles/328978/introduction-to-multi-binding-and-multi-value-conv


print observable array in console is not working in angular2 nativescript

Question: I tried to print the observable array in console.log. But it prints like object, object for all array items.
I have posted the codes below:
ts file:
   private stuArr: ObservableArray<StudentData> = new ObservableArray<StudentData>();

  ngOnInit() {

        this.fileReader.getArrayDataFromLocalFile('/json/students.json')
            .subscribe(data => {

              this.stuArr.push(data.students.map(item => new StudentData(item.name, item.id, item.address)));
              console.log("PrintData :", this.stuArr);

            });
    }

Comment: ObservableArray is a class. You can call its toString() method, and see if it won't print the elements in sequence. If it doesn't, then you may have to iterate through the object's elements with a forEach
Comment: you need to use `console.log("PrintData :", JSON.stringify(this.allFeedItems));`
Comment: @RahulSingh I tried stringify already.getting typeerror converting circular structure to json error in console at runtime
Comment: you need to log this in console or template ? if not you can try iterating thought the entire array and then show the objects
Comment: @RahulSingh console only not template
Answer: console.log("*** PrintData start ***", );
console.dir(this.stuArr);
console.log("*** PrintData end ***", );

Comment: console.dir takes an object as argument, so console.dir("PrintData :", this.stuArr) for instance wont work.
Answer: we can print the observable array using for loop iterator or else by tns debug android or ios using chrome devtools:
  printArr(stuData:ObservableArray<StudentData>){
    for(let i=0; i<stuData.length; i++)
    console.log("PrintData:", stuData.getItem(i));
    }


Parse.com JavaScript SDK - How can I refresh the cached user object?

Question: The cached Parse user object in local storage is only updated on login or signup. I'd like to refresh it when my app loads to make sure any modifications are in sync. How can I do that?
According to this thread from the Parse.com forums archive, there should be a method Parse.User.current().refresh() to do just that, but in the latest version of the JS SDK that method doesn't seem to exist.
Thanks! Any help appreciated!
Comment: Try [fetch](https://parse.com/docs/js/symbols/Parse.Object.html#fetch)
Answer: Fetch the model from the server
Parse.User.current().fetch()

https://parse.com/docs/js/api/symbols/Parse.Object.html#fetch


The limit of the ratios of terms from a converging and a diverging series

Question: Suppose $(a_n)$ is a decreasing sequence such that $\sum_1^{\infty} a_n < \infty$
Suppose $(b_n)$ is a decreasing sequence of positive numbers such that $\sum_1^{\infty}b_n = \infty$.
Is it true that $\lim_n \frac{a_n}{b_n} =0$?
I've been trying to prove this but I've failed. I think that it is plausible because it is certainly true whenever $b_n$ is asymptotically larger than or equal to $\frac{1}{n}$ , i.e, it is a well-known fact that $na_n \to 0$.
Here is a counterexample when $a_n$ is not decreasing:
let $a_n=\left\{
     \begin{array}{}
       \frac{1}{n} & \text{if } n \text{ is a power of 2}\\
       0 & \text{otherwise}
     \end{array}
   \right.$
Let $b_n=\frac{1}{n}$. Then clearly, $\limsup_n \frac{a_n}{b_n} =1$, so the claim fails.
Answer: The original question did not specify that the sequence $(b_n)$ is decreasing. There is then a simple counterexample: Let $a_n=\frac{1}{n^2}$, and let $b_n=1$ when $n$ is odd and $\frac{1}{n^2}$ when $n$ is even.
We now show how to  construct a counterexample for the modified problem where the sequence $(b_n)$ is also decreasing.  More precisely, we produce non-increasing sequences $(a_n)$, $(b_n)$ that do the job. One can perturb these by an extremely quickly decreasing sequence if we want strictly decreasing sequences.
Let $(F_n)$ be a very rapidly increasing sequence of positive integers. For concreteness and fun, let $F_n=2^{2^{n-1}}+1$, but we could use the slower growing $F_n=(n!)^2$.
For the $b_i$, use $F_1$ copies of $\frac{1}{F_1}$, followed by $F_2$ copies of $\frac{1}{F_2}$, followed by $F_3$ copies of $\frac{1}{F_3}$, and so on. The divergence of $\sum b_i$ is clear.
We now describe the $a_i$. Let $n_1=1$ be the index of the first occurrence  of $\frac{1}{F_1}$ in the sequence $(b_n)$. Let $n_2$ be the index of the first occurrence of $\frac{1}{F_2}$. Define $n_3$, $n_4$, and so on analogously.
Let $a_1=\frac{1}{F_1}$. For $i=n_1+1$ to $n_2$, let $a_i=\frac{1}{F_2}$. For $i=n_2+1$ to $n_3$, let $a_i=\frac{1}{F_3}$, and so on. Note that $a_i=b_i$ at $i=n_1,n_2,\dots$, ensuring that $\frac{a_i}{b_i}$ does not have limit $0$.
Finally we show that $\sum a_i$ converges. This is because for $k\ge 2$ the sequence $(a_n)$ has only $F_{k-1}$ copies of $\frac{1}{F_k}$, and $\sum \frac{F_{k-1}}{F_{k}}$ converges.
Comment: Nice! I didn't think it was true, but this is convincing.


Is Cyclic cohomology a Weil cohomology?

Question: Simply stated question...

Is the cyclic homology theory of an algebra a Weil cohomology theory, given the appropriate reformulation of the Weil axioms?
Comment: Cyclic homology is Hochschild homology on cyclically invariant chains, and a Weil cohomology theory is a cohomology theory on a class of projective varieties which satisfies some natural set of axioms.
Answer: I don't think you could make sense of this, given that cyclic homology of the base is periodic. Moreover, if you extend cyclic homology to schemes (and on quasicompact, quasiseparated schemes there is only one way to do this), then the cyclic homology of projective space is also periodic as calculated by Beckmann, so it doesn't satisfy being zero outside zero to twice the dimension.
Comment: Cool, perfect answer :D  Thanks alot Jason :)

Is Cyclic cohomology a Weil cohomology?