Add Meta tags and Title on hook_menu "page callback"

Question: How to add Meta and Title tags to the document head on hook_menu "page callback"?
Drupal 7
Comment: Why do you think adding meta tags have anything to do with menu hooks?
Answer: Assuming Drupal 7...
For the title you can use drupal_set_title().
For the meta tags you can use drupal_add_html_head(). Example from geerlingguy in the comments of those docs:
$element = array(
  '#tag' => 'link', // The #tag is the html tag - <link />
  '#attributes' => array( // Set up an array of attributes inside the tag
    'href' => 'http://fonts.googleapis.com/css?family=Cardo&subset=latin',
    'rel' => 'stylesheet',
    'type' => 'text/css',
  ),
);
drupal_add_html_head($element, 'google_font_cardo');


Executar método que esta dentro do evento "onclick"

Question: Ao responder essa pergunta, me deparei com a seguinte situação. Note que onclick em x é um objeto com dois métodos, quando o elemento recebe o clique executa o método click que por sua vez era pra executar o método funcao_a, mas retorna o seguinte erro:

TypeError: x.onclick.funcao_a is not a function at HTMLHeadingElement.click

var x = document.getElementById("title");
x.onclick = {
  funcao_a: function() {
    console.log('Função A');
  },
  click: function() {
    console.log('Click');
    x.onclick.funcao_a();
  }
};

x.onclick = x.onclick.click;

Somente alguns testes em JS

Mas não acontece o mesmo quando tenho um objeto com um nome diferente, como por exemplo: x.objeto.

var x = document.getElementById("title");
x.objeto = {
  funcao_a: function() {
    console.log('Função A');
  },
  click: function() {
    console.log('Click');
    x.objeto.funcao_a();
  }
};

x.onclick = x.objeto.click;

Somente alguns testes em JS

Minha pergunta é: É possível acessar esse método como no primeiro exemplo? Se sim como ?
Answer: Na verdade o problema está no que assumiu que ficou em x.onclick

Note que onclick em x é um objeto ...

O onclick em x ficou na verdade com uma função, algo que consegue comprovar com o operador typeof

var x = document.getElementById("title");
x.onclick = {
  funcao_a: function() {
    console.log('Função A');
  },
  click: function() {
    console.log('Click');
    x.onclick.funcao_a();
  }
}.click;

console.log(typeof x.onclick);

Somente alguns testes em JS

Porque quando construiu o objeto apenas ficou com a função click ao fazer .click no final.
Comecemos por considerar outro exemplo simples:

let usuario = {
    nome: "Carlos",
    idade: 25
};

let nome = usuario.nome;
console.log(nome);

Aqui torna-se claro que a variável nome vai ter o valor "Carlos".
Mas podemos construir um exemplo semelhante ao seu sem guardar o objeto numa variável:

let nome = {
    nome: "Carlos",
    idade: 25
}.nome;

console.log(nome);

A diferença é que neste caso construímos o objeto todo mas apenas ficamos com o nome, o que faz com que o resto da informação não seja acessível. Na verdade o objeto foi instanciado e utilizado apenas naquela linha, não ficando com nenhuma referência para ele, e por isso não sendo acessível no resto do código.
É exatamente este o problema que o seu primeiro exemplo tem.
Se quisesse tornar ainda mais claro poderia formatar ligeiramente o exemplo e acrescentar parêntesis reforçar visualmente que sobre o objeto criado irá ficar apenas com o nome:

let nome = ({nome:"Carlos",idade: 25}).nome;
console.log(nome);
Comment: Até aqui entendi, mas mesmo assim o erro persiste. Veja que alterei na pergunta, chamando `x.onclick = x.onclick.click;` quando executa a função `click` a função `funcao_a` chamada nela não funciona. Retorna o erro.
Comment: Agora o problema é ligeiramente diferente. Pois primeiro guarda o objeto com `x.onclick = { .... };`. Mas depois tira o objeto de lá e mete apenas a função com `x.onclick = x.onclick.click;`, deixando o objeto anterior novamente inacessível. No final do dia se `onclick` é função não vai poder fazer `onclick.qualquercoisa()`. Se ainda assim não tiver ficado claro é só avisar que eu extendo a minha resposta para contemplar esse outro cenário também.
Comment: Neste caso somente o segundo exemplo funcionaria corretamente. Obrigado pelo esclarecimento, isso nem passou pela minha mente.
Comment: @wmsouza Exatamente só o segundo exemplo é que funciona corretamente. Fico contente de ter ajudado.
Answer: No primeiro código, o click sublinhado na imagem abaixo não representa nada além de uma instância do objeto x.onclick:

Eu poderia usar qualquer nome, por exemplo abc:

var x = document.getElementById("title");
x.onclick = {
  funcao_a: function() {
    console.log('Função A');
  },
  abc: function() {
    console.log('Click');
    x.onclick.funcao_a();
  }
}.abc;

Somente alguns testes em JS

No primeiro exemplo você não consegue acessar funcao_a() porque o objeto x.onclick está apontado apenas para click (no meu exemplo, abc) em:
}.click;

No seu segundo exemplo, você não atribuiu o objeto a nenhuma instância, logo você consegue acessar qualquer instância dentro dele chamando pelo nome:
x.onclick = x.onclick.click;

ou
x.onclick = x.onclick.funcao_a;

Veja o que o console mostra dentro de x.onclick do primeiro exemplo, apenas a função dentro de click::

Já no segundo exemplo, o console mostra todas as instâncias disponíveis no objeto:

Logo, não tem como você acessar a instância funcao_a: no primeiro exemplo porque ela não está visível para o onclick em questão.


DADDAD chord progression on guitar

Question: I have a chord progression:
Verse:
Dm9 D9#5 Dm9 D9#5 Dm9 A7#5 D
Chorus:
Gm9 F6/9 G D9 D7 D
When going from the last D in the chorus to the first Dm9 in the verse, it sounds incongruous. Any ideas how to bridge that?
Comment: (My first impulse would be: the same way you got from Dm to D at the end of the verse: via the dominant, A.)
Comment: I don't see how the alternate tuning relates to the question here. I would suggest either removing the tag or specifically discussing fingering issues with your progression, depending on which you feel is more important.
Comment: Welcome! Please read about [the topics that are covered here](https://music.stackexchange.com/help/on-topic) and [how to avoid subjective answers](https://music.stackexchange.com/help/dont-ask), then please use the "Edit" button to tell a bit more about the problem and target the question more.
Answer: Two time tested ways. One is the obvious V>I, as in A(7)>D(m9). The other would be to use the tritone substitution of the A7, which would be E♭7.

DADDAD chord progression on guitar


Algorithm for Transposing Chords Between Keys

Question: I'm writing software that transposes sheet music between keys and I'm still new at music theory so I was hoping someone who knows more could let me know if my approach is correct. Here's my process for each note:

Find the degree of the note's letter name in the current key's scale.
Find the number of semitones raised or lowered the note is from the actual note in the scale. I'll call this the offset.
Find the note in the new key's scale that is the same degree.
Raise or lower the new note by the offset.

Here's an example. Say we are transposing the note E# from C major to D major. Then we would do the steps above as follows:

E# would be third degree of the scale.
The offset would be +1 because E is actually the third degree of the C major scale, and E# is one semitone above that.
The third degree of the D major scale is F# so that's the new note.
Adding our +1 offset to that would make it F##.

So F## is the result of transposing E# from C major to D major. I realize you wouldn't normally have an E# in the key of C major but I think it's possible and it works to explain the algorithm.
Is this algorithm correct? Should I be approaching this differently?
A secondary question: is it necessary to know the mode of the keys when executing this kind of algorithm? The results seem the same whether I'm using major or minor scales for the degree/offset calculations. Thanks in advance!

Update: Solution
It sounds like the above algorithm is correct, but can be simplified. The piece of the puzzle I was missing was that you can determine the interval without referring to the scale. Here's the updated algorithm. Steps 1 and 2 find the interval between the current key and the new key. Steps 3 and 4 apply that same interval to the note we are transposing.

Find the distance between the current key's letter name and the new key's letter name in the list of all letters (not including sharps or flats): A, B, C, D, E, F, G.
Find the distance in semitones between the current key and the new key.
The new note's letter will be the letter distance (Step 1) above the current note.
Add sharps or flats to the new note's letter until it is the correct number of semitones (from Step 2) above the current note.

Repeating the original example we'll have:

D is 1 letter above C
D is 2 semitones above C
The new letter will be 1 letter above E#, which is F
The new note will be 2 semitones above E#, which is F##

Thank you to everyone who answered, and especially to @MattL and @Dom. All the answers and comments have been very enlightening!
Comment: @CarlWitthoft Thanks for the suggestion, but this question is about correctness, not efficiency. I have the programming skills to optimize it myself; I just don't have the music theory knowledge to know that I'm producing correct results. If you'd like me to state that in the question I can add it.
Comment: @BobRodes I think triple-sharps are perfectly valid (in the theoretical sense). If we stick to the example I used in my question, but we transpose an E## instead of E# then that would be a doubly augmented second interval (I think) and the only way to preserve the same interval during transposition would be the result of F###. As far as I can tell, whether to have double or triple flats/sharps is a matter of preference. So it will have to be left up to the user, not the algorithm.
Comment: I was planning to edit my answer once I got a response, but perhaps this is a better way to go about it.  Now Jonathan, suppose you want to transpose from C minor to G# minor.  Input note is a B natural.  Output note is therefore Fx (F##).  What are the logical steps?  We have C+4 is G, and G# is 8 semitones up from C.  So we know that we need the note 8 semitones up from B natural, and we know that we need to call it an F.  What are the logical steps to determine that it is a double sharp, as opposed to, say, a flat?  ...
Comment: ... I'm asking because there appear to be rather more of them than the steps  in my suggested algorithm (below) that uses Caleb's idea.  But I could be wrong, so perhaps we should look at both.
Comment: Other things that your solution has to address: what do you do if you find a Cx in a piece in C that you are transposing to F#?  That note would need to be F###, and triple sharps aren't allowed.  It would have to read G# instead.
Comment: I would recommend you write your algorithm -- what language are you using?  -- and then post to SO to see if people can recommend refactoring for speed.  There are a lot of ways to run a look-up-table, which is essentially what you're writing here.   --  Oh, and watch out for enharmonics, as the performer probably would prefer not to have a ton of triple-flats :-)
Comment: I think the algorithm that you have selected as your answer is correct as far as it goes.  However, I would suggest that you take the test scenarios that I've suggested and work through them.  I think that you will find that when it becomes necessary to decide which enharmonic note to select that your algorithm will become rather unwieldy.  (In case you don't know the term "enharmonic notes", they are two notes of the same pitch that are written differently, such as A# and Gb.)
Comment: I'll be interested to see your code when you're done with it.
Comment: Yeah, but people prefer generally not to use them.  Here's an interesting article on how MuseScore handles transposition.  http://davidbolton.info/articles/musescore_interval_transposition.html  It mentions that Finale keeps a triple sharp and Sibelius respells it.
Comment: p.s. If you're interested in a free program that has a good transposition feature, you might want to download and install MuseScore.
Comment: @BobRodes That's an amazing article, thanks for pointing that out! It's nice to know that I'm on a beaten path since Finale does it the same way. I've finished implementing the algorithm and you can view the source code here: https://github.com/jpotterm/google-apps-chord-transposer. The bulk of the work is done in the transpose function of the server/note.gs file (it may move if I refactor in the future). I hope you find it useful, and thanks for all your help!
Comment: Here's another article on musical notational oddities: http://homes.soic.indiana.edu/donbyrd/InterestingMusicNotation.html .  The author mentions that there are "at least five" examples of triple sharps/flats in the entire music literature!  If you are transposing sheet music, you may want to do something to avoid them.
Answer: It is indeed not relevant which scale is used. What counts is the interval from the root note to the current note. Using your example, an E# is an augmented third from the root note C. So if the root changes to D, the transposed note is an augmented third from D, which is an F##.
Instead of working with semi-tones (which will give you ambiguity in naming the notes), you need to work with intervals, which allows you to distinguish an E# from an F (for C as the root, the first is an augmented third, the latter a perfect fourth).
Comment: @JonathanPotter: Yes, apart from using "the current key's scale", which is not necessary. Take the interval between the original root note and the new root note, and shift the current note by that same interval. This will keep the interval between the note and the root note identical.
Comment: Very informative, thanks! I think that's what I'm doing. So the algorithm I'm using looks correct to you?
Comment: I'd like to mark both this and @Dom's answer as correct, but I can only do one :( So you have my thanks and my upvote.
Answer: Matt's right you want to think in intervals when you think about transposition as it will result in you being able to know what you should name the note along with the distance in semitones you need to move the note.
So in this specific case, you are transposing up all the notes by a Major second which means you move every note up two semitones and the name of the note is based on the next letter name up.
Let's say just for simplicity that the value of the note were enumerated like this:

0    1     2     3     4    5     6    7     8     9    10    11
C  C#/Db   D   D#/Eb   E    F   F#/Gb  G   G#/Ab   A   A#/Bb   B

And let's also say that we have the note letters enumerated like this:

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

So back to your example the E# would map to the note value of 5 (F) and the note letter of E (2) regardless of what key you are in. When you want to move this note up by a Major Second, you would then increase the note value by 2 and the note letter by 1 giving a note value of 7 (G) and note letter of F (3) from these two values you can assign a new name for the note.
Comment: Yes, but especially if you are to continue to make musical based software I would try and keep the algorithm in musical terms. Step 1 & 2 are combined if you just denote the interval as a major 2nd (which you know the distance in semitones and the letter name you want to move to) which you could create an infrastructure to do with a little  bit of extra work.
Comment: I've updated the question with a new algorithm based on your (and @MattL's) answer. Does it look like I've understood correctly?
Comment: Yes, in my code I've created an abstraction for intervals, but I thought it was helpful in this question to specify explicitly how one would go about finding the interval and then applying it. But I've updated the question to give a better explanation of the intervals.
Answer: If I may suggest a simpler alternative: use a "Line of Fifths" approach to ensure the proper note spelling while not requiring any knowledge of scale degree.
The Line of Fifths is constructed similarly to the better-known Circle of Fifths, but it does not assume enharmonic equivalence, so it does not close in on itself, and stretches to infinity in both directions. It's a convenient structure to use with algorithms that care about spelling notes properly.
...
B♭
F
C
G
D
A
E
B
F♯
C♯
G♯
D♯
A♯
E♯
B♯
F♯♯
...
The algorithm then becomes:

Find out how many spaces along the line you are transposing. In this case, going from C to D is two fifths.
Find the note you want to transpose, and then go that many spaces further. In this case, going two fifths beyond E♯ brings you to F♯♯.

If you'd like to read more, I introduced the Line of Fifths concept in my first-ever stack exchange answer, regarding an algorithmic way to determine interval names: General procedure for determining the name of an interval given a major key / diatonic collection.

Update:
Since it isn't quite obvious, and BobRodes asked about it, I'll mention that in this scheme, any note can be represented by a single number -- it's position along the line. Though you could conceivably put the origin anywhere, I find the math works best if F = 0 and numbers increase as you go towards the sharps (C = 1, G = 2).
There is no need to store an entire array of note names, because there is a simple one-to-one mapping between a note's name and it's position on this line. You do need to explicitly store 7 pairs (mapping the range F-B to the numbers 0-6), but once you have that, the position of any pitch name can be found (and vice versa).
The key is to realize that any pitch name can be represented by the pair {letter, numberOfSharps} -- where a negative numberOfSharps means to use flats. For example F♯♯♯ is (F, 3) while G♭♭ is (G, -2). To convert this to a position along the line, you use the formula:
<code>7 * numberOfSharps + letterToNumber[letter]
</code>
So for C♯♯♯, since C=1 and there are 3 sharps, the position along the line would be 7*3+1 = 22.
The inverse relation (convert a position to a pitch name) can be found using a combination integer division by 7 to get the number of sharps, and modular division (position mod 7) to get the letter.
Comment: Thanks! After trying multiple strategies for the problem, I found and implemented this one, and it seems to have worked great. The edit was particularly useful, I was about to create the full array until you pointed how to easily map to a number. It worked great as-is for chords, but I also used the same algorithm to transpose notes on the sheet. For that I needed to add some extra logic in order to handle octave information (e.g. E5 vs E6). I also ended up implementing triple-sharp and triple-flat on my application, at least so I could verify the correctness of some edge cases.
Comment: Very interesting Caleb.  While I understand that you can theoretically stretch to infinity, in practice we don't go beyond ## and bb as I'm sure you know.  So, if you were writing an algorithm, where would you go up from a B## or down from an Fbb?  Not that you'll run into either of these 99.9% of the time, but what would you do if you did?  I'm thinking you might just go up or down a diminished sixth instead of a fifth, making B## go to G# and Fbb go to Ab.  What do you think?
Comment: I don't see any reason why wrapping would be necessary, and have updated my answer accordingly. Though if you wanted to, you could just add/subtract 12 to the note's position, in order to move closer to 0.
Comment: The reason is practical.  Nobody uses more than double sharp/double flat in notation (nearly nobody).  If you're actually trying to make a piece of software that transposes actual music, you hit a hard boundary at Bx and Fbb.
Comment: Sure, you'd have trouble displaying it or printing it, but there's no theoretical reason that the transposition algorithm should be inherently  limited.
Comment: Well, part of the transposition algorithm would be what actual note to output, wouldn't it?  I mean, I take your point, but it sounds like a matter of how you define limitation.  An algorithm that can't output the notes that are actually used in transposition in the name of being unlimited sort of is a contradiction in terms, isn't it?
Comment: I do see your point.  But does that mean that you need another algorithm to figure out what note to print?
Answer: You only have 12 keys to worry about (even minor keys are just duplicates note-wise of the relative major) so it would be very simple to create a 2-dimensional String array to use as a look up table for the names of each of the notes for each key. This will allow you to specify what each note will be called for all 12 keys and you can determine whether to call a note an "A#" or a "Bb".
In addition, you can also decide what to call notes outside of the key (many songs contain chords/notes from outside of the key). For example, you might choose to use the name D# in the key of G major (since G major has one sharp), while you might choose to use the name Eb in F major (since F major has one flat).
This will make key changes super simple as all you have to do is change the root and everything else dealing with chords/notes internally within the key will stay exactly the same.
Comment: Well, I'm another programmer too, and your algorithm doesn't explain how "you can determine" what to call a note.  It needs to include this if it is to be considered a solution.
Comment: ???...why the down vote? Jonathan is writing software and asked for an algorithm for transposing keys so I offered him a suggestion as to how to code what he is trying to do. I'm a programmer as well as a musician and I have experience with this topic as I have created music software myself which included the option of transposing keys. My response was directed at another programmer who will likely understand my suggestion. :)
Comment: But what you call a note is dependent on the key you're in, so what you actually call a note will be different. The note names can be found from googling the 12 different major keys and then manually entered into the look up table. This will eliminate oddities like "E#" from showing up in the key of C major as the array will always point to the name "F" and not "E#". I guess more info is needed from he op as to what kind of scenarios he's trying to account for.
Comment: I agree that more info is needed.  But if the OP needs to actually write transposed sheet music, the "oddities" that you mention have their place and use in music.  See here: https://www.youtube.com/watch?v=A3j57AdHSvg (it's a bit blurry, sorry, best I could find).  Look on the third line, first measure, last beat, top note of the chord.  It's an E#.  If you wrote it F, you'd have to write a natural on it (because the previous F is sharped), and then put a sharp on the next F.  That's not as easy to read.
Comment: p.s. If both the input and output of the program are actual music, then enharmonic names of notes don't matter as you say. If they are sheet music, your idea is an unworkable oversimplification, as my example should demonstrate.  Most of the software development failures in our business occur from incomplete understanding of the requirements; this is a fine example of that.  :)
Comment: The key is one of many factors that determines what you call a note. If you are in the key of C you may see C# and/or Db depending on the context you are in its even the case for E# and F as in this case. The key alone is not enough, you need the context and more information and in this case, just using the key you would end up with an F instead of the desired E# which is not what the OP wants.
Comment: The sheet music part was the piece that was missing in the original post, but he's updated the post and clarified that part now. :) Yes, in sheet music there's also the visual aspect of how it appears on paper to make it easier to read, which can trump standard chordal/key theory as Bob's example does. I was expecting chord chart conversion given that the he stated he was new to music theory and sheet music conversion is quite an ambitious task to take on.
Comment: @Tekkerue: amazing how some company will spend 5 million working out requirements, and when everyone is waist deep in the development phase and the stakeholders are going that isn't what I meant at all, 20 people will sit around a table and say well, I was expecting this because of that very reasonable and logical "given", etc, etc, etc.  It's why half of all software development initiatives fail.  Please understand this isn't a personal criticism, but an observation about something that we IT people all do and have to be careful to avoid (and often aren't) when the money is on the table.
Comment: BobRodes, sure, but this is a free web forum where someone asked a question who stated they were new to music theory and didn't initially specify what kind of software they were writing. So in the case of someone new to theory, assuming the simpler approach was a reasonable one. But if this were a job I would have riddled him with questions to determine what he wanted and I certainly wouldn't have coded anything without getting more direction. Also, I'm actually developing my own software where there's no room for confusion as to what my requirements are, so no worries there. :)
Comment: It's clear that you understand very well why I said it wasn't s criticism but an observation.  LOL
Comment: Not going to get into an argument over this, but you did paraphrase my comment about "expecting" a certain outcome because it was reasonable given the initial information. So your "observation" clearly was directed at my response and I explained why it was unnecessary...let's leave it at that. :)
Answer: IMHO, the most efficient way to do what you want from an IT perspective is Caleb Hines' solution.  There are fewer moving parts than Dom's solution (sorry Dom).  Just create an array (a zero-based array) containing his "Line of Fifths" in it.  You'll need to handle the boundary condition of where to go from the ends of the line, which are Bx and Fbb.  Absent a better suggestion from him, I would change the fifths to diminished sixths: G# follows Bx, Ab follows Fbb.  It's most unlikely that you will ever see either of these notes (or have to transpose across them) but you have to account for them.  If you don't and they come up, your program will fail spectacularly and the reason won't be very obvious.
So, your algorithm will look something like this.  First (assuming that you have already created the array with the "Line of Fifths" in it), determine the distance between the input key and the output key:

Start with the first array element.
Iterate the array until you find either of the two keys.
Continue iterating the array until you find the other key.
Let X equal the difference between the two offsets.
If the first value found is the target key, let X = -X.

Next, iterate through all the notes in the piece (a non-trivial proposition!).  To determine the transposed pitch of one note:

Iterate the array until you find the element containing the note.  Let Y equal the offset of this element.
If Y + X is greater than the upper bound of the array (we'll call the upper bound U), let A = the offset of C#.  Output the element whose offset is A + Y + X - U.
If Y + X is less than zero, let A = the offset of Ab.  Output the element whose offset is A + Y + X.
If otherwise than 2 or 3 (non-boundary condition), output the element whose offset is Y + X.

That should get you started.  If you can poke holes in my logic, by all means do so.
Comment: There's no need to waste all that valuable memory, or limit yourself to the bounds of a finite array! Just represent a note as a single number, and create a mapping from that number to the note name. I've updated my answer with more details. With a 32 bit integer, this lets you get at least up to F with 306,783,377 sharps. Which should be more than enough to appear infinite under any possible transposition...
Comment: That isn't useful, though, in practical terms.  You don't generally go above two sharps or flats.  As such, you need to work out an enharmonic note to transpose to if the algorithm outputs a triple sharp or flat.  You're going to need to do that to solve the problem at hand.  http://homes.soic.indiana.edu/donbyrd/InterestingMusicNotation.html has some interesting material on this.
Answer: There is a slight flaw in that would probably never be an E# in the key of C, but the concept seems to be on the right lines. You need to be more musically aware.
Re-reading your question, it's obvious I misunderstood what you were aiming at. I apologise.
Comment: The OP mentioned that he knows that there wouldn't normally be an E# in the key of C major, but in theory it could happen. And the example was deliberately chosen to be a bit weird, in order to "challenge" the method.
Comment: Any fairly chromatic passage in the key of C might have one.  For example, Chopin's Etude Op. 10, number 2 is in C, and bar 7, fourth beat, top note is an E#.  Perhaps your criticism of the OP's lack of musical awareness is misplaced, Tim?
Comment: @BobRodes, from looking at the piece it appears the E# is so the performer can quickly see at a glance that it's chromatic (all the notes in a nice slope). This isn't a theoretical issue but a visual issue of how it appears on sheet music to make it easier on the performer. A blind algorithm converting to a different key could very well screw up that nice visual slope on the sheet music indicating that it's chromatic. That kind of thing probably won't work to well with a blind algorithm as the algorithm wouldn't know the reason why the E# was used instead of the "theoretically correct" F.
Comment: I'll refer you to my comment on your post.  You are quite correct, it is primarily a visual issue.  But there are algorithms that will always show this interval as a minor second rather than an augmented unison.  Caleb Hines' idea looks like it will, for example, although I would want to test the boundary conditions more thoroughly before making such a pronouncement.


Fastest Net::HTTP/Net::HTTPS wrapper for Ruby

Question: What is the fastest way to download a webpage for parsing in Ruby? I've tried using open-uri and HTTParty both seem to take roughly about 25 seconds to download simple webpages (I've tried multiple sites).
I'm passing the sites to Nokogiri but the latency takes place prior to passing any parameters to Nokogiri.
Answer: i prefer to use gem 'http' (https://github.com/httprb/http). It is fast, clean api.
Also you can take a look on the http clients comparison table:
https://github.com/httprb/http#another-ruby-http-library-why-should-i-care


Is it valid to take the midpoint of discrete outcome variables that express a range e.g. (1-20%, 21-40%) then calculate the mean of those midpoints?

Question: I work in a health service and have a PhD student who was told by my boss (her primary supervisor) to measure clinicians' responses concerning what proportion of their clients had a certain condition via a discrete outcome variable expressing the proportion as either 0% or a range: 0%, 1-20%, 21-40%, 41-60%, 81-100% (and 'do not know').
My boss suggested this then went on long service leave for six months. While he was away my student collected the data and then started to analyse it. The form we chose for this outcome has presented us with considerable difficulties in reporting descriptive statistics. Histograms work quite well but I have found it very difficult to express the descriptive statistics verbally in a meaningful or comprehensible way (e.g. "40% of clinicians reported that 21-40% of their clients had the condition, 25% reported that 61-80% of their client had the condition" Huh?).
I expressed these difficulties to my boss who wondered what all the fuss was about and told my student to just transform the variable to a numeric variable, with the midpoint of each range as the value, then report the mean and sd of those values. i.e. '1-20%' becomes 10%, '21-40%' becomes 30%, '41-60%' becomes 50% etc. My boss is very smart but not a statistician and instinctively his workaround just seems wrong to me; however, I wouldn't know where to begin looking to find out whether this is the case or not.
Can anyone give me advice about whether or not his approach - to take the midpoint of a range response in order perform mathematical operations on that midpoint - is valid? Or alternatively point me to some literature?
Comment: Your data are binned (interval censored). https://en.wikipedia.org/wiki/Censoring_(statistics)#Types ... this doesn't solve your problem but may help when searching the site.
Comment: Another solution is to use interval arithmetic.
Comment: Thank you @whuber. What is interval arithmetic.
Comment: https://en.wikipedia.org/wiki/Interval_arithmetic
Answer: This approach, as implemented, assumes that, within each category, the mean is actually at the midpoint. This is not necessarily the case.
Far better to get the median, which only assumes things about the category that the median is in. Then you can make different guesses as to how that is distributed, and see how much it matters. But the simplest way is to assume that the distribution within that category is uniform. You can, if you wish, also calculate the quartiles in the same way.  Just know that they will all be based on certain assumptions, but that those are reasonable.
Comment: Thanks so much @Peter Flom. So, if I understand you, you are saying it *is* valid to transform each categorical 'range response' (e.g. '1-20%', '61-80%') into the midpoint (10% and 20% respectively) then take the median and interquartile range (for example) of those midpoints? Is that right?
Comment: "Valid" isn't really a "yes/no" thing in this context.  It is a reasonable thing to do, and many people do it. But it won't give you exact answers.
Comment: Ok thank you, 'it is a reasonable thing to do' was exactly what I needed to hear. Will make life much easier.
Comment: Typo above. I meant ' (e.g. '1-20%', '61-80%') into the midpoint (10 and 70% respectively)'
Answer: you can take a weighted average of the ranges given by the doctors to give an overall range. If half the doctor say 40-60% and the other half say 60-80%, you can be sure that 50-70% of the patients overall have the condition. I hope the math is obvious enough with this simple example.
you can use middle values of the range if you declare so, but this may just as well be reason for more confusion.


Why ++ becomes -+-+-+- : string.gsub "strange" behavior

Question: Why ++ becomes -+-+-+- ?
I'd like to clean a string from double operating signs. How should I process ?
String = "++"
print (String ) -- -> ++
String = string.gsub( String, "++", "+")
print (String ) -- -> + ok
String = string.gsub( String, "--", "+")
print (String ) -- -> +++ ?
String = string.gsub( String, "+-", "-")
print (String ) -- -> -+-+-+- ??
String = string.gsub( String, "-+", "-")
print (String ) -- -> -+-+-+- ??? ;-)

Comment: Look at each result separately.
Comment: `-` in [lua patterns](http://www.lua.org/manual/5.1/manual.html#5.4.1) is a metacharacter.
Comment: @Tarass But now you know *which* exact pattern(s) causes the non-expected results - and can formulate a hypothesis/question with specific context. Always try to break down the problem. See [string.gsub](http://lua-users.org/wiki/StringLibraryTutorial) - as at this point, with a single function returning 'unexpected results', the hypothesis should be about incorrect assumptions about usage of gsub - and follow the linked resources to read up about patterns.
Comment: I agree with you. I read about string.gsub a short synthesis, I didn't imagine there could be magic characters. As you said to that there is, looked further and found %. I didn't see, at first, the link you gave me and I found % and other explanaition that will be very helpfull for what I have to do. Thank you very much for your consern and your advices.
Comment: Ok, I put each step in my example. I don't understand why `+` becomes `+++` at second step ? I missed something ?
Comment: I will use a `%`. Thank you.
Answer: The core problem is that gsub operates on patterns (Lua's minimal regular expressions) and your string contains unescaped magic characters. However, even knowing that I found myself surprised by your results.
It's easier to see what gsub is doing if we change the replacement string:
string.gsub('+',   '--', '|') => |+|
string.gsub('+++', '--', '|') => |+|+|+|

- means "0 or more occurrences of the preceding atom". Unlike +, it's non-greedy, matching the fewest characters possible.
I just tested it and apparently "fewest characters possible" mostly means 0 characters. For instance, my intuition about this:
string.gsub('aaa','a-', '|')

Is that the expression a- would match each a, replace them with '|', resulting in '|||'. In fact, it matches on the 0-length gaps before and after each character, resulting in: '|a|a|a|'
In fact, it doesn't matter what atom we precede with -, it always matches on the smallest length, 0:
string.gsub('aaa','x-', '|') => |a|a|a|
string.gsub('aaa','a-', '|') => |a|a|a|
string.gsub('aaa','?-', '|') => |a|a|a|
string.gsub('aaa','--', '|') => |a|a|a|

You can see that last one is your case and explains your results. Your next result is the exact same thing:
string.gsub('+++','+-','|') => |+|+|+|

Your final result is more straightforward:
string.gsub('-+-+-+-','-+','|') => |+|+|+|

In this case, you're matching "1 or more occurances of the atom -", so you're just replacing the - characters, just as you'd expect.


Drupal vs Options Indexes?

Question: I have an .htaccess file with Options Indexes FollowSymLinks, my /apache2/sites_available/default file also has these options and AllowOverride All.
If I do these things outside of Drupal it's working (if I go to a directory without an index file, I see a file directory listing), but inside Drupal I'm getting

The requested page "/sites/default/files/" could not be found.

Also, I am able to to access files within the files directory. For example if I went to /sites/default/files/someFile.pdf... it would be able to access it fine. I want to have it so that if I link to a directory within the files directory and that directory does not have an index file... it will display a directory listing of all the files/folders within. Something like:
http://3.bp.blogspot.com/_rhuioznu6Us/TBmeWAr_G2I/AAAAAAAAAFE/tKCclPXdq2M/s1600/apache.png
I think Drupal is doing something based on the fact that I get my Drupal headers above the message that the page couldn't be found. How do I stop this?
The files below show some of the things I've tried...
apache2/sites_available/default contains:
DocumentRoot /var/www/default
<Directory />
  Options Indexes FollowSymLinks
  AllowOverride All
</Directory>

<Directory /var/www/default/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  Allow from all
</Directory>

default/files/.htaccess contains
Options +FollowSymLinks
Options +Indexes
RewriteEngine Off

Answer: You don't need the Indexes on your web server. Its actually not recommend on a live environment. For testing purpose it can be useful sometimes.
If you don't have your files directory I would recommend you to created a files directory
sudo mkdir sites/default/files # Creating files directory
sudo chmod a+w sites/default/files # Permissions

After that you can you try  this on your default configuration file...
<DIRECTORY />
      Options FollowSymLinks
      AllowOverride None
 </DIRECTORY>

 <DIRECTORY /var/www/drupal_site/>
     Options +FollowSymLinks
     AllowOverride All
 </DIRECTORY>

Source: https://github.com/darol100/lazydubuntu/blob/master/bin/includes/skeleton
And then re-start your server.
If this does not solve your problem here is a similar question (with the same error)
And here is the answer.

This is a known problem, a natural result of clean URLs

When you are on http://example.com/?q=node/15 and the browser sees a relative "files/filename" path it resolves it as
  http://example.com/files/filename. The ?q= part does not pretend to be
  a path, so the browser does not use it.
When you are on http://example.com/node/15 and the browser sees a relative "files/filename" path it resolves it as
  http://example.com/node/15/files/filename because it considers node/15
  as a real path.

So, when you use clean URLs the file links must have a front slash
  (and possibly a path if Drupal's home page contains an URL path). The
  browser sees the absolute path "/files/filename" and resolves it using
  the bare domain name. You need to edit all the file paths in the
  content and add a front slash.
Alternatively, try the http://drupal.org/project/pathologic module
  which tries to be smart about it (or one of the other modules
  mentioned there).
Comment: I already have the files directory, and some files within. Also, I am able to to access files within the files directory. For example if I went to /sites/default/files/someFile.pdf... it would be able to access it fine. I want to have it so that if I link to a directory within the files directory and that directory does not have an index file... it will display a directory listing of all the files/folders within. Something like: http://3.bp.blogspot.com/_rhuioznu6Us/TBmeWAr_G2I/AAAAAAAAAFE/tKCclPXdq2M/s1600/apache.png

Drupal vs Options Indexes?


NullPointerException no Android

Question: Estou com um problema ao listar as fotos da pasta DCIM no Android. Ele dá erro no laço for, lançando um java.lang.NullPointerException? O que pode ser?
Veja o código que pego as informações da pasta:
public class MainActivity extends Activity  {

    private ListView listView;
    private List<String> minhaLista;
    private File file;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //carrega o layout onde contem o ListView
        setContentView(R.layout.layout_arquivos);

        minhaLista = new ArrayList<String>();

        String root_sd = Environment.getExternalStorageDirectory().toString();
        file = new File(root_sd + "/DCIM");
        File list[] = file.listFiles();

        System.out.println(file);

        for( int i=0; i< list.length; i++)
        {
                minhaLista.add( list[i].getName() );
        }

        AdapterListView adapter = new AdapterListView(this, minhaLista);
        listView = (ListView)findViewById(R.id.list);
        listView.setAdapter(adapter);
    }
}

A classe adapter:
public class AdapterListView extends BaseAdapter {

    private Context mContext;
    private List<String> mArquivos;

    public AdapterListView(Context context, List<String> arquivos) {
        // TODO Auto-generated constructor stub
        mContext = context;
        mArquivos = arquivos;
    }

    public int getCount() {
      return mArquivos.size(); // Retorna o número de linhas
    }

    public String getItem(int position) {
      return mArquivos.get(position); // Retorna o item daquela posição
    }

    public long getItemId(int position) {
      return position;
   }

    // Classe responsável por guardar a referência da View
    static class ViewHolder {
        TextView hTextView;
    }

   public View getView(int position, View convertView, ViewGroup p) {
      ViewHolder holder = null;
      String item = this.getItem(position);
      if (convertView == null) {
         convertView = LayoutInflater.from(mContext).inflate(R.layout.item_escolher_pasta, p, false);
         holder = new ViewHolder();
         holder.hTextView = (TextView) convertView.findViewById(R.id.txtNomePastas);
         convertView.setTag(holder);
      } else {
         holder = (ViewHolder)convertView.getTag();
      }

      holder.hTextView.setText(item);

      return convertView;
   }

}

Comment: http://pt.stackoverflow.com/help/mcve
Comment: Mudei a pasta para SDCARD e mesmo assim o problema persiste no FOR.
Comment: Felipe quando voce faz isso 'String root_sd = Environment.getExternalStorageDirectory().toString();' você recebe o caminho do seu sdcard tenho do aparelho se as suas imagens estão dentro do  DCIM mantenha dessa maneira, mas se não existir a pasta no seu sdcard vai acontecer como o @VictorStafusa falou.
Answer: Felipe, veja se isso te ajuda
    //verifica se o SDCARD está no aparelho
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    {
        Toast.makeText(this, "Erro, SDCARD Não Encontrado!", Toast.LENGTH_LONG).show();
    } else
    {
         //cria
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM");
        file.mkdirs();
    }
    //verifica se existe o diretorio
    if (file.isDirectory())
    {
         File list[] = file.listFiles();

        for (int i = 0; i < list.length; i++)
        {
             minhaLista.add( list[i].getName() );

        }

        }
    }

Answer: Eis o seu laço for:
    File list[] = file.listFiles();

    System.out.println(file);

    for( int i=0; i< list.length; i++)
    {
            minhaLista.add( list[i].getName() );
    }

O NullPointerException poderia ser lançado no for apenas se list for null ou se algum dos elementos list[i] for null.
Vamos ver um pequeno trecho do javadoc do método listFiles():

If this abstract pathname does not denote a directory, then this method returns null.

Traduzindo para o português:

Se este nome de caminho abstrato não denotar um diretório, este método retorna null.

Além disso, o array retornado por listFiles(), quando o caminho existe, nunca contém null, logo a causa do seu problema é que a sua referência file não corresponde a um diretório existente. Portanto Environment.getExternalStorageDirectory().toString() + "/DCIM" não corresponde a um diretório existente no seu caso.
Comment: Victor a criação da pasta caso não exista resolveria o problema do @felipe?
Comment: @WellingtonAvelino Talvez. Mas pode ser que ele simplesmente esteja olhando para o lugar errado, e neste caso ele estaria criando a pasta errada.
Comment: entendi, talvez o que eu tenha postado não seja util para ele.

NullPointerException no Android


Differing conclusion on a coin's side given two logically equivalent pieces of information

Question: The following scenario was posed by my philosophy professor:

Consider the scenario where one day God decided to flip infinitely many fair coins (not stated if countably or uncountably infinite), with each flip being independent. Exactly one of this coin has your name on it. After He is done, He sent an angel to provide you the following information: miraculously, out of all the coins, only a finite number of them turned out to be heads. If you have to bet whether the coin with your name has head or tail facing up, what would you bet on?

By classical or naive probability, one would be tempted to say "tail", as the probability of the coin being a head is $``\frac{k}{\infty} = 0"$, where $k$ is the (finite) number of heads in total. Those who have studied probability theory may argue that the scenario forms an immeasurable space, so the probability of the coin being a head cannot be established. On the other hand:

Suppose the angel told you the following information instead: out of all the coins except yours, only a finite number of them turned out to be heads. Now, what would you bet on?

In that case, one would easily conclude that the probability of the coin being a tail is $\frac{1}{2}$, by fairness of coin and independence of tosses.
At first glance, these two conclusions seem reasonable. However, even though the two pieces of information seem different, they are logically equivalent - there are finitely many heads in all coins except yours iff there are finitely many heads in all coins including yours.
What is the logical fallacy here? Could it perhaps be that the problem was phrased in a (subtly) paradoxical way? Any insights provided would be appreciated.
Comment: If I were told that infinitely many "fair" coins were flipped and only finitely many of them landed on heads, I'd conclude that whoever said the coins were fair was a liar.
Comment: @JMoravitz please explain why.
Answer: The word "tempted" is doing a lot of work here. We are being "tempted" to forget that the coin is fair (i.e. $p=\frac{1}{2}$ where $p$ is probability of heads, and, in this case, also tails).
First off, there is no problem with measurability if the number of flips $X_i$ is countable. In that case, we identify the sequence of heads and tails with the digits after the decimal point in the binary number $X=0.X_1X_2X_3\dots$. Then $X$ is a normal number (there is an interesting discussion on this random variable for general $p$ here: Derivative and calculus over sets such as the rational numbers). The normal numbers are a set of full measure in $[0,1]$, so equivalently we consider $X$ to be uniformly distributed on $[0,1]$.
The probability that only finitely many $X_i$ are 1 is the same as the probability that $X$ is rational (since the binary expansion terminates). This event has probability 0, since the rationals have Lebesgue measure $0$. This is why JMoravitz states in the comments that one would be tempted to consider it unlikely that $p=\frac{1}{2}$: the likelihood that that is the case, given our one observation, is $0$. Apparently, we are meant to make the leap that $$``\mathbb{P}(p=\tfrac{1}{2}\mid X\text{ is rational})=0.''$$
But wait, that actually makes no sense. We never said that $p$ was a random variable and that it has any chance of being anything other than $\frac{1}{2}$. We are told $p=\frac{1}{2}$ deterministically. There is no Bayesian update of priors. So in this model, actually $$\mathbb{P}(p=\tfrac{1}{2}\mid X\text{ is rational})=\mathbb{P}(p=\tfrac{1}{2})=1.$$
In other words, $p$ does not depend on $X$ at all. It's just the constant $\frac{1}{2}$.
So, there is no problem. If $p=\frac{1}{2}$, then in both of the scenarios above, the probability of your coin coming up heads is $\frac{1}{2}$.
In general, there is usually something like this going on in these kinds of "philosophical" "probability" questions. The professor is either confused or trying to confuse you. If $p=\frac{1}{2}$, why are we suddenly being asked to consider changing that? Are we supposed to construct a new model of the coin from empirical facts? If so, that would be a different model of the coin than the one we started with, and the paradox here is just the conflation of these two different model coins.
The narrative aspect adds an element of smoke and mirrors to a simple question. There would be no confusion if instead the question was written:

Let $X_i$ be independent Bernoulli($\tfrac{1}{2}$) random variables
  for $i\in\mathbb{N}$. What are:

$\mathbb{P}(X_1=1)$,
$\mathbb{P}(X_1=1\mid \sum_{i>1}X_i<\infty)$,
$\mathbb{P}(X_1=1\mid \sum_{i} X_i<\infty)$?
Comment: +1 great explanation esp. with the last example, identifying "your coin" with $X_1$.  I think that actually is the key.  If "your coin" is always the $1$st coin (or the $1073$rd one, etc), then the ${k \over \infty} = 0$ argument doesn't apply.  However, like (haha) Monty Hall, if you're offered a chance to switch to a random coin (uniform $n \in \mathbb{N}$??) before betting H/T, you should!  ;)
Comment: Excellent explanation. Thank you.


OpenBSD 6.5 /etc/mail/aliases correct format?

Question: What is the correct entry format for an alias?
Right now I have
root:  firstname.lastname@example.com

Running newaliases -f /etc/mail/aliases yields a syntax error. Are there examples in the manual page for aliases?
Answer: Your alias file format is correct but you are using the wrong file with the -f option, that's why its giving an error.  See the relevant man page here:
https://man.openbsd.org/newaliases
-f file
    Use file as the configuration file, instead of the default /etc/mail/smtpd.conf.

As you can see there, -f option is to use a configuartion file other than the default one and not the alias file itself.
You can just run newaliases without any parameter and it should work.


How do i view information of bmp image

Question: Im new to c++ and its developing. I'm going to develop image based algorithm. in order to do that i wish to use .bmp (bitmap image). i want to grab the pixel values of that image to compare with other pixel values of another bmp image. to do that i followed Wiki link -bitmap there i have noticed that there are other info of bitmap as well.
My problem is how do i take a information of the my bitmap image. The above link they mentioned some are optional , how do i see in my image all the sections such as Color Table, Extra bit masks etc. please help me thank you.
Answer: please refer the following PDF. It will help you.
http://www.di.unito.it/~marcog/SM/BMPformat-Wiki.pdf
Answer: I recommend you start here:
http://www.imagemagick.org/Magick++/
However, I don't think bitmaps have a "color table", that's more of a GIF thing.  Bitmaps just describe (typically 8-bit each) RGB(A) values.

How do i view information of bmp image


Multilingual "labels" in views fields?

Question: Is there any way to setup multilingual labels in views' fields.
Let´s say I have the ´title´ field and it shows the label ´My Title:´. Then as my site is bilingual (english-spanish) I need to have that label to ´Mi Titulo´ depending on user language.
How can I solve this?
Any module to expand views module?
Answer: You want to look into Internationalization Views, which allows you to translate labels and such in a view.
Comment: I come almost 6 years late to this thread but maybe this will help someone: It's in the dropdown menu at top right of the Views admin page (the one that has 'edit view name/description' as first option). There is an item that says 'Translate view'. There you will will translation for every field and field label on the view.
Comment: thanks berdir, I just enabled the i18nviews module. I was expecting to see language options in field´s settings but nothing... where do I find the place to translate my labels.
Answer: All the standard module care about printing title, labels and string and keep them translatable using t().
I think Translation Interface (example.com/admin/build/translate/search) can help you to search strings and define their translations.
Comment: thanks shoaib, but I am a drupal beginner, can you show how to use t() please?
Comment: I am not recommending you to use it but I am guessing standard module developer always use it to make sting translatable. e.g. If it is to print 'Title' then they use print t('Title'). t() function will first check for available translation of string 'Title' for the selected language in current session. If not found the original string is returned. What you need to do is to search your desired string via Translation Interface and then edit it for translation(s) and check if this works in your view?
Comment: ok, don't know where to write the t() function inside views. I tried with "Rewrite the output of this field" but didn´t work. I have the module 'Php filter' enabled. Take a look a this picture: http://img850.imageshack.us/img850/2947/screenshot01t.jpg
Comment: I think you had not tried Translation Interface :(
Comment: solved.  I saved the label as 'Custom'. Then the label is available for translation.
Answer: If I understand you correctly, what you want is done by the Field Translation module, which is part of the Internationalization (i18n) package. Once enabled, there will be a translate tab when you edit a field (from manage fields). You will also have to enable more languages, so they are offered as translation targets.
Answer: I used this method which is probably bad practice, but I couldn't find another solution.
With your file manager/FTP go to core language file: Example is for the installed German language
[mysite]\profiles\standard\translations\drupal-7.0.de.po
Open in a utf-8 reader.
You will be able to see a list of all English strings and their German counterparts: Example
msgid "Countries"
msgstr "Lände"
Add your labels (strings) and their translations and save.
[-all good but this library must now be reread in-]
Using your web interface go to www.mysite.com/admin/config/regional/language
Delete the language you are editing. This will clear the DB of the translations but the edited file will remain untouched.
Now select "Add Language" and select your language again. The system will now read-in your updated list.

Multilingual "labels" in views fields?


show that the equation $3z^3+(2-3ai)z^2+(6+2bi)z+4=0$has exactly one real root

Question:
show that :
the equation $3z^3+(2-3ai)z^2+(6+2bi)z+4=0$ (where both $a$ and $b$ are real numbers) has exactly one real root.

let $x_{1},x_{2},x_{3}$ be root,and $$x_{1}x_{2}x_{3}=-\frac{4}{3},x_{1}+x_{2}+x_{3}=\dfrac{3ai-2}{3},x_{1}x_{2}+x_{1}x_{3}+x_{2}x_{3}=\dfrac{2bi+6}{3}$$
Comment: For this Complex coefficient I can't deal it
Comment: Well, you know that $x_1, x_2, x_3$ are the three roots of the cubic. You also have 3 equations relating these roots. So you might be able to solve these three equations for  $x_1, x_2, x_3$ say using substitution? And you should find that only one of them is real.
Comment: Parallel to method which @okrzysik said, If you want the answer just for polynomials of degree 3, you can solve them and reach to your real root. (There is a formula for degree 3 roots like degree two.)
Answer: If we had exactly 3 real roots, then the sum of all roots would be real, but it is not.
If we had exactly 2 real roots, then the product of all roots would not be real, but it is.


Determine which of the following rings are fields.

Question: Have I done it correctly?

Determine which of the following rings are fields:
a) $(\mathbb{Z}/2\mathbb{Z})[x]$/$\large_{(x^2+1)}$
b)$(\mathbb{Z}/3\mathbb{Z})[x]$/$\large_{(x^2+1)}$

My resolution:

a) We know that $(\mathbb{Z}/2\mathbb{Z})$ is a field. Then, $(\mathbb{Z}/2\mathbb{Z})[x]$ is a PID. We know that $(x^2+1)$ is maximal if the polynomial $x^2+1$ is irreducible. We have to search for the roots of the form $[a]\in (\mathbb{Z}/2\mathbb{Z})$, such that $[{p(a)]}=[a^2+1]=[0]$. The elements of $(\mathbb{Z}/2\mathbb{Z})$ are $[0]$ and $[1]$:$$
[p(0)]=[0+1]=[1]\neq[0],
$$$$
[p(1)]=[1+1]=[2]=[0]
$$
so $x^2+1$ is reducible.
b) We know that $(\mathbb{Z}/3\mathbb{Z})$ is a field. Then, $(\mathbb{Z}/3\mathbb{Z})[x]$ is a PID. We know that $(x^2+1)$ is maximal if the polynomial $x^2+1$ is irreducible. We have to search for the roots of the form $[a]\in (\mathbb{Z}/3\mathbb{Z})$, such that $[{p(a)]}=[a^2+1]=[0]$. The elements of $(\mathbb{Z}/3\mathbb{Z})$ are $[0]$, $[1]$ and $[2]$:$$
[p(0)]=[0+1]=[1]\neq[0],
$$$$
[p(1)]=[1+1]=[2]\neq[0]
$$
  $$
[p(2)]=[4+1]=[5]=[2]\neq[0]
$$
so $x^2+1$ is irreducible $\implies (\mathbb{Z}/3\mathbb{Z})[x]$/$\large_{(x^2+1)}$ is a field.
Comment: @AdamHughes I don't know if there are shadow edits that I missed, but what's written seems perfectly alright to me.  It would be good to conclude part a) with "therefore $(\mathbb{Z}/2\mathbb{Z})[X]/(X^2 + 1)$ is not a field", but from my reading, he seems to understand this fact perfectly.
Comment: @Slade Huh, I don't see any edit trail either. Perhaps my brain added the letters "ir" to his "reducible." Thanks for the catch!
Comment: @AdamHughes  I didn't edit anything. Thank you both for your comments.
Answer: Yes! $F[X]/(f(x))$ ($F$ field ) is a field if and only if $f(x)$ is irreducible in $\mathbf{F}[X]$. Then what you've done is correct!
Answer: More concisely, for part a), observe that $\mathbb{Z}/2\mathbb{Z}[x]/(x^2+1)$ is not an integral domain, because $(\overline{x+1})(\overline{x+1})=\overline{x^2+2x+1}=\overline{x^2+1}=0$ in the quotient ring. And $\overline{x+1}$ is non-zero element. If it is not an integral domain, it surely cannot be a field.


Jest obsolete snapshot warning causes test failure: ignore warnings when exiting Jest

Question: I have a test suite/file that I have disabled. It has an associated snapshot file. For my particular situation I do not want to delete or update the snapshot file (long-story-short: it is used elsewhere).
So, Jest logs out just a warning, rather than a failure, for the obsolete snapshot. However Jest then exits with code 1 and my build fails. This happens despite no test actually failing.
Can I tweek the config to ignore obsolete snapshots? Or is there some other way to have Jest exit with code 0 after only a warning?
Comment: would it be possible to peep your package.json file?
Comment: Sorry @MarioPerez, I no longer have access to that repo.
Answer: Add --silent to your test-ui script in the projects package.json
Comment: For others, the documentation says "Prevent tests from printing messages through the console." If this causes "Jest exit with code 0 after only a warning" then I'd be surprised.


This row already belongs to another table

Question: I have a problem with my asp.net website, I am trying to copy a data row from one data table to another data table, but every time I am trying to do this i am getting an error:
This row already belongs to another table.

Answer: As the error states, a DataRow instance is tied to its owning DataTable and cannot be added to another table.
Instead, use the ImportRow() method to make an actual copy of the row.
Comment: Ok, Microsoft... you realize that is the case, why not, instead of throwing a smug exception, you run ImportRow in that case for us?  *sigh*
Comment: @SeanKendle: No; having add sometimes make a copy of the row with no indication would be a very bad idea.
Comment: Is there a case where saying "add row" *wouldn't* mean make a copy?  Or, where you can even use add row if it's already a member of another table?
Comment: @SeanKendle: `table.NewRow()`.  Or, remove, then re-add.
Comment: Ok, so, in my mind, my point stands.  In the case where you're saying "add this existing row (member of another table) to this other table", the language should be intelligent enough to know what you mean is "make a copy of the existing row, and add the copy to this table."  Just my opinion.  Sometimes VB.net isn't very intuitive.
Comment: @SeanKendle: No; that's exactly the opposite.  The `Add()` method everywhere adds an _existing_ instance to a collection.  Silently creating copies, especially only sometimes, is a horrible idea and is likely to lead to bugs.  To put it differently, you don't want to write `a.Add(b)`, then discover that `b` is still not in `a`.
Answer: For Example
You need to create a new Row with the values from dr first. A DataRow can only belong to a single DataTable.
You can also use Add which takes an array of values:
myTable.Rows.Add(dr.ItemArray)

Or probably even better:
myTable.ImportRow(dr);

Link
Comment: This won't work directly first you need to clone the source table with destination data table


How to Re-size Divs Without Stretching or Squishing Them?

Question: I'm at a loss. I've literally tried to figure this out for four hours straight and I give up. I can't figure out how to actually use bootstrap (or just regular CSS) to prevent the elements from stretching or squishing on a page re-size. I figure there's some other sort of javascript involved, but I can't figure it out. Here is an example of what I'm talking about: http://premiumlayers.com/demos/kappe/?storefront=envato-elements
Please explain this. I'm very discouraged right now because I'm trying so hard to get good and I can't even figure this out...
Edit:
Here is some of my code:
HTML:

.box {
  width:33.333%;
  height: calc(100vw / 3);
  display: block;
  float: left;
  background: lightblue;
  border:1px solid #111;
  box-sizing: border-box;
  color:#222;
}

@media (min-width: @screen-md-min) {
  .box {
    width: 20vw;
    height: 25vh;
  }
}

@media (min-width: @screen-lg-min) {
  .box {
    width: 30vw;
    height: 35vh;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

            Box

I also tried using this without bootstrap but the issue continued.
Comment: Can you provide some sample code that illustrates your problem? Regular CSS elements are not resizing if they have a given width.
Comment: I edited my question to include some of my code.
Comment: Did the answers provided not help with your question?
Answer: The example you provided is using a masonry style plugin to layout the items, but for what you want you can just use viewport units.
Set the width of the div to a fraction of the viewport width and it will keep the aspect ratio the same when scaling down.
e.g height: calc(100vw / 3);

.item {
  width:33.333%;
  height: calc(100vw / 3);
  display: block;
  float: left;
  background: lightblue;
  border:1px solid #111;
  box-sizing: border-box;
  color:#222;
}

@media (max-width: 1200px) {
  .item {
      width:33.333%;
    }
}

@media (max-width: 800px) {
  .item {
      width:50%;
    }
}

@media (max-width: 480px) {
  .item {
      width:100%;
    }
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Comment: This kind of does, but I wanted it to respond in a way that it would be 4 boxes for a larger screen, 3 boxes for a medium screen, etc.
Comment: You need to use media queries for that to change the width of the item depending on the screen size. https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Comment: I was doing that in my code, but it was stretching/squishing it.
Comment: I'm so confused, I'm sorry. Why are you taking the height and calculating it via dividing the vw by 3? Also, I put it into my code and it still doesn't work, but it works if I run it it via your snippet...sigh...
Answer: This could be handled to an extent using flexbox, however the images wouldn't take up the full width of the container until they were able to fully fit on.
In your example the boxes are resizing slightly to fit the available space and this is handled with JS.
Here is a simple example of how to handle this type of resizing:
JS
const wrap = document.querySelector('.wrapper');
const box = wrap.querySelectorAll('.box');
const boxWidth = 250;

let calcBoxWidths = (function calcBoxWidths() {
  let wrapWidth = wrap.offsetWidth;
    let fitWidth = Math.round(wrapWidth / boxWidth);
    let allBoxes = Array.prototype.slice.call(box);

  allBoxes.forEach((thisBox)=>{
    thisBox.style.width = 100 / fitWidth + "%";
  });
  return calcBoxWidths;
})();

window.onresize = () => calcBoxWidths();

In the above JS a floored value is found for roughly how many images can fit in the width of the container. This is then turned into a percentage value to set the width of each box.

Fiddle:
http://jsfiddle.net/4sa9b5y8/3/


Call stored procedure for each Row with/without using a cursor

Question: I want to a run a stored procedure for almost 1000 records (P_SHIPMENT_GID) in one go and below is the pseudo code.
DECLARE
    P_SHIPMENT_GID VARCHAR2(200);
    BEGIN
    P_SHIPMENT_GID := NULL;
    ULE_PKG_UNPLANNED_ICT_CALC.UNPLANNED_ICT_CALC(
    P_SHIPMENT_GID => P_SHIPMENT_GID
    );
    END;

How can I achieve this with or without using cursors?
Answer: It is not all that clear what you want to do (where are the 1000 records from?) but here is a "pattern" I am pretty sure you can use :
BEGIN
   FOR i IN (SELECT table_name, status FROM user_tables) LOOP
      dbms_output.put_line('name : ' || i.table_name ||
                           ' status : ' || i.status);
   END LOOP;
END;

This creates a loop on an implicit cursor and allows you to use the returned rows/column in a readable way.
Comment: Hi Thanks for your reply!! 1000 records exists in a table called shipment
Comment: Actually in my code in place of NULL I can pass a value of one shipment like(1246876) and I can run my procedure ,my procedure will do all the calculation for that one Shipment but point is I want to run my procedure only once and it should take all the 1000 shipments values in one go so in that case i would not have to pass single shipment ID 1000 times
Comment: Can you modify the called procedure? If you want to pass a "list" of shipments you will need to either change its type for a structure instead of a `VARCHAR2` or pass all the shipment values in some kind of comma separated list within a varchar.
Comment: If I got you right you are asking me to pass shipment vales as comma separated if yes then I tried the same by passing the values with comma separated and it has thrown me the error so I closed that point:( and it is very important for me as I need to execute this proc for 1000 records.
Comment: Hello guys can anyone please help me on this!!
Answer: You can write this anonymous block for your requirement. Although its not clear from where you are storing your SHIPMENT_GID values which you wanted to pass to your procedure/pkg.
BEGIN
   FOR rec IN (               --Assuming your shipmentid are stored in a table
               SELECT SHIPMENT_GID
                 FROM Your_TABLE)
   LOOP
      ULE_PKG_UNPLANNED_ICT_CALC.UNPLANNED_ICT_CALC (
         P_SHIPMENT_GID   => rec.SHIPMENT_GID);
   END LOOP;
END;


Disable creation of a page for a content type and just use teasers?

Question: So on my website I have Content Type: Level 3 - Article Page. This page has two node reference fields where you can set Call to Actions, these display teaser versions of other articles, downloads etc and are shown below the body text of the page. See this screenshot:

I now want to also allow users to set Call To Actions on the Level 3 pages for specific Giving/Donations.
So I've created a new Content Type: Giving CTAs. Here a user can add text, a thumbnail, title, default donation amount etc.
The issue is that I only ever want to use these Giving CTAs as teasers rendered as in the screenshot. They will forward to a giving checkout page carrying the donation amount value.  I don't really want full pages to be rendered for each one. So is there a way to cancel the rendering of pages or disable it for this content type? Maybe it's actually disabling the creation of a URL and default node/id URL? I'm not sure :S
Answer: As far as I'm aware, every Drupal node created has a "page" created for it, no matter what. You can disable the creation of a user-friendly URL, but all nodes have a node ID, and since the node/id URL path is in reality just a simple query, all nodes can have "pages" generated for them by querying against their node IDs in this way.
I would say as long as you just refrain from placing these content types into a menu, you won't need to worry about it. It's highly unlikely that a user would manipulate a URL on their own in order to find the content's page.
Comment: Could I use `drupal_goto()` to send to Page Not Found or give it that status?
Comment: Yeah I guess you could, but I'm not sure I'd go to the trouble myself to be honest.


Como pegar o tempo de ping com o módulo https do nodejs

Question: Como posso realizar o cálculo do ping entre cliente e servidor usando o módulo http/https do node.
OBS: Uso esse modulo em especifico pois o objetivo do script é gerar log de disponibilidade deum site a cada meio minuto com o seguinte output:
200 | www.site.com | 350 ms | 19-08-2019 12:10:29

Fiquem a vontade para indicara algum módulo pronto para isso.
const https = require('https');
const hostname = 'www.site.com';

setInterval(()=>{
  const req = https.request({
    hostname: hostname
  }, function (res){
    console.log(`${res.statusCode} | ${hostname} | ${new Date().toISOString().slice(0,19).replace('T',' ')}`);
  });
  req.on('error',(e)=>{
    console.log('Erro: '+e);
  });
  req.end();
},3000);

Output atual:
200 | www.site.com | 19-08-2019 12:10:29

Tentei usar listenners para capturar o tempo atual no ato do ínicio da requisição e subtrari com o tempo no final da mesma, porém não achei o evento que é disparado nomomento em que o request é executado, e não sei se essa é a maneira correta para calcular o tempo do ping.
Comment: Da uma olhada nisso aqui -> https://stackoverflow.com/questions/4737130/how-to-ping-from-a-node-js-app
Comment: Acredito que isto não seja válido para fazer log. Pois eu teria de fazer uma requisição para validar se o server http responde 200 e outra para validar o tempo do ping.
Answer: Tente :

const https = require('https');
const hostname = 'www.site.com';

setInterval(()=>{
  let startRequest  =  new Date().getTime();
  const req = https.request({
    hostname: hostname
  }, function (res){
 const pingTime =  new Date().getTime()- startRequest;
    console.log(`${res.statusCode} | ${hostname} | ${pingTime} | ${new Date().toISOString().slice(0,19).replace('T',' ')}`);
  });
  req.on('error',(e)=>{
    console.log('Erro: '+e);
  });
  req.on('connect',(e)=>{
   startRequest  =  new Date().getTime();
  });
  req.end();
},3000);
Comment: Eu alterei a minha sugestão, tente usar o evento connect presente no httpClientRequest . Pela documentação em ( https://nodejs.org/api/http.html#http_class_http_clientrequest ) ela serve para interceptar o início da conexão entre o cliente e o servidor, veja se funciona.
Comment: Será que essa técnica é a mais precisa possível? Dado que momento em que ele registra "o disparo da requisição" o corre antes de realmente ser disparado ?
Answer: Usa o morganjs, ele eh um middleware e ele faz logs de cada requisição.
Exemplo Expressjs:
const express = require('express');
const app = express();
const morgan = require('morgan');

app.use(morgan('dev')); // Essa eh uma forma de declarar um middleware "global" para todas as rotas

app.listen(3333);

Na linha onde tem app.use(morgan('dev')) esse 'dev' é o padrão do log q ele vai mostrar no console, tem varios tipos, porem ja que não se deve fazer logs em producao, so para desenvolvimento ent esse padrão('dev') serve para 90% dos casos
const express = require('express');
const app = express();
const morgan = require('morgan');

app.get("/", morgan('dev'), (req, res) => {
    res.send("
Hello World!
");
} // Nesse caso o morgan ira mostrar e monitorar os dados dessa rota somente, onde tem o app.get pode ser qlq metodo(app.post, app.put, app...)

app.listen(3333);


How do I properly encode a form in php

Question: On my site users can add content to the database via a form. I want the users to be able to type anything in the form and for it all to be added to the database how they have entered it. At the moment I'm getting problems with a number of characters, namely slashes, &, ? etc.
What is the best way to allow all characters to be added to the database correctly?
Also, do you have to decode them when displaying them for it to work correctly? If so, how do I do that?
Comment: There's no need for any encoding. You can insert any character into the database as long as you run the correct escaping method on the data. For the `mysql_*` family of functions, that is `mysql_real_escape_string()`. Show the code you're using to input and output data, and describe what goes wrong at which point exactly.
Comment: What database are you using?  What character set are your databases/tables created using in the DDL?
Answer: When saving, use mysql_real_escape_string (or PDO) to protect against SQL injection attacks. This will make it possible to write quotes and backslashes without destroying the SQL query.
<?php
$text = mysql_real_escape_string($_POST['text']);
mysql_query('INSERT INTO table(text) VALUES("'.$text.'")');
?>

When printing the data to a browser (with echo), first run it through htmlspecialchars to disable HTML and solve your current problem:
<?php
// ...fetch $text from db here...
echo htmlspecialchars($text);
?>

Answer: htmlentities() may help you encode and decode html characters:
You can also use nl2br() to preserve line breaks from textarea elements:
Also you should use PDO for your database needs as it is much more secure than the old method of escaping data, mysql_real_escape_string()

How do I properly encode a form in php


How to use AWS SDK for iOS with Objective-C instead of Swift?

Question: I'm connecting my Objective-C based app to AWS S3 filestore by doing this by following this AWS-amplify tutorial . It's using the AWS Amplify CLI and the AWS SDK for iOS (AWSAppSync). My problem is that a Swift snippet needs to be added to the appDelegate file. However, my appDelegate is Objective-C and I don't know what's the best way to add it correctly.
[1] Is this extra code snippet in the delegate file really necessary? I'm only going to upload images to the S3 filestore.
[2] If necessary, what's the best workaround? (making a separate swift file and bridging it to the appDelegate file feels a bit too hacky)
Here's the snippet:
import AWSAppSync

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var appSyncClient: AWSAppSyncClient?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        do {
            // You can choose the directory in which AppSync stores its persistent cache databases
            let cacheConfiguration = try AWSAppSyncCacheConfiguration()

            // AppSync configuration & client initialization
            let appSyncServiceConfig = try AWSAppSyncServiceConfig()
            let appSyncConfig = try AWSAppSyncClientConfiguration(appSyncServiceConfig: appSyncServiceConfig,
                                                                  cacheConfiguration: cacheConfiguration)
            appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
        } catch {
            print("Error initializing appsync client. \(error)")
        }
        // other methods
        return true
    }

So far I've tried using this piece of code:
#import <AWSAppSync/AWSAppSync.h>
#import <AWSCore/AWSCore.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:DefaultServiceRegionType credentialsProvider:credentialsProvider];
    AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
}

But I get the errors:
Use of undeclared identifier 'DefaultServiceRegionType'
Use of undeclared identifier 'credentialsProvider'

Answer: You can use AWSCore
Import the AWSCore header in the objective c app delegate.
@import AWSCore;

And Create a service configuration in the
application:didFinishLaunchingWithOptions:

application delegate method.
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:CognitoRegionType
                                                                                identityPoolId:CognitoIdentityPoolId];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:DefaultServiceRegionType
                                                                     credentialsProvider:credentialsProvider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;

Import the appropriate headers for the services(May be inside your view controller) you are using. The header file import convention is @import AWSServiceName; as
@import AWSS3;
@import AWSDynamoDB;
@import AWSSQS;
@import AWSSNS;
@import AWSCognito;

And implement a call to the AWS services.
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = yourBucket;
uploadRequest.key = yourKey;
uploadRequest.body = yourDataURL;
uploadRequest.contentLength = [NSNumber numberWithUnsignedLongLong:fileSize];

[[transferManager upload:uploadRequest] continueWithBlock:^id(AWSTask *task) {
    // Do something with the response
    return nil;
}];


What is it called when the Test Set and Training set is the same?

Question: Normally when evaluating a model,
the training data is split into a test set and a training set.
I want to evaluate the best possible performance of the classifier on my task.
So I have Trained it on all my data, and tested it on all my data.
The results are not all 100% for all variation on the model I am investigating, which is worth reporting on.
Comment: You may have to provide more detail on how you developed your model (or whether it was a pre-existing model, for which you estimated the parameters on the training set) and what you did to avoid overfitting. Some approaches have well recognized names (e.g. leave-one-out cross-validation, x-fold cross-validation etc.).
Comment: I am also doing various forms of cross-validation. But not here.
Here I *want* the classifier to overfit.  The purpose of setting the test and training set to be the same is to assess if the classifier has the power to apply to this data at all.
Comment: If your main approach to avoid overfitting is cross-validation, then I guess people would know what you did, if you wrote e.g. "naively applying the classifier without cross-validation".
Answer: Since you mention you're doing that as a comparison for methods of cross-validation, it can be called "not doing cross-validation". One can also say that you don't have test set (unseen data) at all, only training set.


SQL query showing element more than once

Question: I have the following SQL query but it doesn't entirely work because it shows each element more than once.
select c.name, c.director, c.title, count(c.title) as numfilms
from casting c
join casting c1 on c1.name = c.name
Group by c.name, c.director, c.title
Having count (c.title) > 1
order by numfilms

So what it does it shows which actors have made more than 1 film. But unfortunately, this query shows each actor as many times as the number of movies he made. Using distinct doesn't work as actor may have been in different movie with same title and different director.
Answer: select c.name, count(c.title) as numfilms
from casting c
Group by c.name
Having count (c.title) > 1
order by numfilms

If you are just looking for the actors names and the number of films they are in you can remove the title and director from the grouping and select.
EDIT: From reading the comment below clarifying the question Richard's first query should be the correct solution.
Answer: The question is not making sense - the join of casting back to itself is the confusing part- it is completely unnecessary unless you need the full record as shown below.
select c1.name, c1.director, c1.title, numfilms
from
(
    select c.name, count(c.title) as numfilms
    from casting c
    Group by c.name
    Having count (c.title) > 1
) c
join casting c1 on c1.name = c.name
order by c1.name

This query shows: for each actor who appears in more than one film, show all the actors' films.
On the other hand, if you are only after actor names who have appeared in more than one film, a single pass through casting is all you need.
select c.name, count(c.title) as numfilms
from casting c
Group by c.name
Having count (c.title) > 1

The confusing part is, if you wanted names only, why add the director and title to the SELECT? Which film of the actor's films to show?
Comment: Will this query not return multiple rows as well? This query will return the films and the directors for each movie the actor has been part of. The wording of the original question could have been a bit better.
Comment: I've just reread my question. Sorry about being a bit too inexplicit. What I have to do is show each actor who played in more than one film and the films he played in. In this case, is my initial query correct? For some reason I thought it was wrong showing, something like the following: actor1 film1 director 1 count; actor1 film2 director2 count.
Comment: Ok so with the clarification of the issue Richard's first query will be what you are looking for.
Comment: @Sorin Your query should **also** work, but will be slower because it is first exploding the result set then grouping for the counts.


Split DNS Issue - Configuring a new domain controller with an existing Apache web HTTP services using the same domain name "example.com"

Question: We have a problem configuring a new domain controller with an existing Linux server hosting an Apache web HTTP services using the same domain name "example.com".
The Ip address for the first Domain controller 192.168.234.5 the Second Domain controller 192.168.78.5 Apache Web server 192.168.234.232 All using BIND DNS Server.
How we can configure this? Where is the configuration will be set?
enter image description here
Answer: There are already several questions and answers on this forum regarding this concept. Generally, it is not a good practice to use a TLD for an existing DNS zone, but rather create a new sub zone for AD. E.g., ad.example.com.
However, it is and has always been possible for Active Directory to co-exist with existing DNS zones, and even using Bind DNS servers.
Normally an Active Directory domain controller creates and manages the DNS records for Active Directory DNS domains, and clients may also register their own DNS records using a process known as DNS Dynamic Update.
Given that Active Directory is usually a secondary in these scenarios, dynamic update is usually not an option.
The following article describes the steps for creating the records required for Active Directory implementation and operation.
Integrating Windows DNS into an existing DNS namespace
https://learn.microsoft.com/en-us/troubleshoot/windows-server/networking/integrate-windows-dns-into-existing-dns-namespace

Summary
One feature of Windows Domain Name System (DNS) is its support for dynamic host updates (documented in RFC 2136). To take advantage of this feature, Windows DNS can be deployed in environments that have no other DNS servers, as well as in environments that already have non-dynamic DNS servers implemented (such as BIND 4.9.7 and earlier, and so on). When you're deploying Windows DNS in an environment that already has BIND servers implemented, you have several integration options:

Migrate zones from non-dynamic authoritative DNS servers to servers running Windows DNS.
Delegate child DNS domains under a parent DNS domain. For Active Directory domain names that don't have the same name as the root of a zone, delegate the subdomain to Windows DNS. For example, if the name of the Active Directory domain is dev.reskit.com and the zone that contains this name is reskit.com, delegate dev.reskit.com to a Windows-based server running DNS.
Delegate each of the subdomains used by the domain controller (DC) locator records (SRV records) to a Windows-based server. These subdomains are _msdcs.reskit.com, _sites.reskit.com, _tcp.reskit.com, and _udp.reskit.com. This option would be used where Active Directory domain names (for example, reskit.com) that are the same as the name of the root of a zone (for example, reskit.com), can't be delegated directly to a Windows-based server running DNS. Optionally, clients may be members of the Active Directory domain called reskit.com, but can register in the DNS zone called dynamic.reskit.com.

This article documents the fourth option listed above, how to integrate Windows DNS into an organization that already has a DNS namespace implemented in which the DNS server that is authoritative for the zone with the name of the Active Directory domain doesn't support RFC 2136 (dynamic updates). This article also discusses a scenario in which domain members use a primary DNS suffix different from the name of the Active Directory domain to allow dynamic registration of DNS records by Windows-based computers when the DNS server authoritative for the zone with the name of the Active Directory domain doesn't support dynamic DNS updates.
More information
To integrate Windows DNS into an existing namespace based on non-dynamic DNS servers, you can delegate the subdomains used by the locator records (SRV records) so that dynamic updates (as per RFC 2136) may be used. Follow these steps:

On the non-dynamic DNS server that is authoritative for the zone with the name of the Active Directory domain, delegate the following zones to a Windows 2000-based server running DNS:
_udp. DNSDomainName
_tcp. DNSDomainName
_sites. DNSDomainName
_msdcs. DNSDomainName
For example, if the root zone is called reskit.com, delegate _udp.reskit.com, _tcp.reskit.com, _sites.reskit.com, and _msdcs.reskit.com to the Windows-based server.
You must delegate also two additional subdomains:
ForestDnsZones. ForestDNSName
DomainDnsZones. DNSDomainName

On the Windows-based server, create the forward zones delegated in step 1, and enable the zones for dynamic update.
To create the new zones:

Start DNS Manager on the Windows server.

Expand the appropriate DNS server within DNS Manager.

Right-click the Forward Lookup Zones folder, and then click New Zone.

When the New Zone Wizard starts, click Next, select "Primary Zone" and maybe select Store the zone in Active Directory check box, and then click Next.

For AD-integrated zones, select where the zone data should go, either to all DNS servers in the domain or forest, or to all DCS in the domain (only option in Windows 2000).

Type the name of the zone in the name box. For example, type _msdcs.reskit.com.

Click Next. After reviewing the wizard's summary, click Finish.

To enable the zone to accept dynamic updates:

Using DNS Manager on the Windows server running DNS, right-click the new zone, click Properties, and then click the General tab.
In the Allow Dynamic Updates box, click Only Secure Updates (recommended) or Yes. The Only Secure Updates option is only available after the server has been promoted to a domain controller. Repeat this process until all four of the zones described in step 1 have been created and allowed dynamic updates. This allows domain controller locator records to be dynamically registered and de-registered in DNS.

Additionally, a single zone or several zones may be created and configured to allow clients and servers to dynamically register themselves with the Windows server. For example, a zone called dynamic.reskit.com could be used to register all clients and servers on a network via dynamic updates. To configure such a zone:
On the non-dynamic DNS server that is authoritative for the parent zone (for example, reskit.com), delegate a new zone to the Windows-based server running DNS. For example, delegate the dynamic.reskit.com. zone to the Windows server.
On the Windows server, create a forward lookup zone for the zone delegated above (dynamic.reskit.com).
On the Windows server, enable the zone(s) for dynamic updates.

When Windows domain controllers start up, the Netlogon service attempts to register several SRV records in the authoritative zone. Because the zones in which the SRV records are to be registered have been delegated (in steps 1 and 2) to a Windows server where they can be dynamically updated, these registrations will succeed. Additionally, a DC will attempt to register the A record(s) listed in its Netlogon.dns file in the root zone (for example reskit.com). In this case, because the root zone is located on a non-dynamic DNS server, these updates won't succeed. The following event will be generated in the system log on the DC:
<code>Event Type: Warning
Event Source: NETLOGON
Event Category: None
Event ID: 5773
Date: <DateTime>
Time: <DateTime>
User: N/A
Computer: DC
Description:
The DNS server for this DC does not support dynamic DNS. Add the DNS records from the file %SystemRoot%\System32\Config\netlogon.dns to the DNS server serving the domain referenced in that file.
</code>

To correct this behavior:

Every Windows DC has a Netlogon.dns file located in its %SystemRoot%\System32\Config folder. This file contains a list of DNS records that the DC will attempt to register when the Netlogon service starts. It's a good idea to make a copy of this file before making the following changes so that you'll have a list of the original records that the DC tries to register with the DNS server. Note that each DC will have different records because these records are specific to each network adapter on each DC. Examine the Netlogon.dns file to identify all A records in the file. You can identify A records by the record type following the "IN" class descriptor. For example, the following two entries are A records:
<code> reskit.com. 600 IN A 10.10.10.10
 gc._msdcs.reskit.com. 600 IN A 10.10.10.10
</code>

The number of A records in the Netlogon.dns file depends on the number of adapters the DC has, the number of IP addresses that each adapter has been configured with, and the role of the DC. DCs register:

One A record per each of its IP addresses for the name of the domain.

If the DC is also a global catalog (GC) server, it registers gc._msdcs. DnsForestName for each of its IP addresses.

Because the non-dynamic DNS server won't accept the domain controller's attempts to dynamically register the A records, the A records have to be manually configured on the authoritative DNS server (in the example in this article, the DNS server authoritative for the zone reskit.com). Addition of the A record corresponding to the name of the domain (for example, reskit.com) isn't required for the Windows deployment and may be needed only if third-party LDAP clients that don't support SRV DNS records are searching for the Windows DCs.

On the Windows server, create the GC server-specific A records that were identified in step A, in the appropriate zone. For example, create an A record for the GC server in the _msdcs.reskit.com zone.
On the non-dynamic DNS server that is authoritative for the root of the zone, create A records in the root zone (for example, reskit.com) for the non-GC server-specific A records that were identified in step A. For example, create an A record for reskit.com in the reskit.com zone.

The following registry key should be used to disable the DC from attempting to register the A records seen in the Netlogon.dns file. Set the REG_DWORD RegisterDnsARecords value to 0 (zero) under:
<code> HKLM\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters
</code>

To correct this behavior: Once you have an Active Directory forest and domain in place, you should integrate Active Directory with the DNS domains that the Windows server running DNS is responsible for. Also, you should reconfigure zones that have been configured to accept dynamic updates to accept only secure dynamic updates.


8 - How do a get a view then save it with a new value

Question: In an update_hook() I need to search all views' displays for a value, then resave them with a new/extra one.  How do I go about this?  What command can I use?
$views = Views::getEnabledViews();
foreach ($views as $view) {
  $source_value = '';
  $config = \Drupal::config('views.view.' . $view->id());
  $rawData = $config->getRawData();

  $master = FALSE;
  // Get the display with the draggableviews field.
  // It is a little tricky because the 'default' display is the master.
  foreach ($rawData['display'] as $display_key => $display) {
    $field = isset($display['display_options']['fields']) ? $display['display_options']['fields'] : [];
    if ($display_key == 'default' && array_key_exists('draggableviews', $field)) {
      $master = TRUE;
    }
    if ($display_key != 'default' && array_key_exists('draggableviews', $field)) {
      $source_value = $view->id() . '|' . $display_key;
    }
    if ($master && empty($display['display_options']['fields'])) {
      $source_value = $view->id() . '|' . $display_key;
    }
  }
  if ($source_value) {
    // Save the view with the source value in the sort handler.
    foreach ($rawData['display'] as $display_key => $display) {
      $sorts = isset($display['display_options']['sorts']) ? $display['display_options']['sorts'] : [];
      if (array_key_exists('weight', $sorts)) {
        // **************
        // SAVE VIEW HERE
        // **************
      }
    }
  }
}

Comment: I think I might have it now calling Views::getView($view->id()) as it returns an ViewsExecutable class, instead of a Views class
Comment: Have you considered a [views sort handler plugin](https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21sort%21SortPluginBase.php/group/views_sort_handlers/8.4.x) instead?
Comment: It's a temporary thing I need to put in an update_hook().  I do not want to create a permanent file to accomplish this.
Comment: Perhaps you're looking for [ConfigEntityBase::save()](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Config%21Entity%21ConfigEntityBase.php/function/ConfigEntityBase%3A%3Asave/8.4.x)?
Answer: Replace
// **************
// SAVE VIEW HERE
// **************

with
$view_exec = Views::getView($view->id());
$view_exec->setHandlerOption($display_key, 'sort', 'weight', 'source', $source_value);
$view_exec->save();

When you call Views::getEnabledViews() it gives you an array of View classes.  What you need is the ViewsExecutable class.   Views::getView($id) returns this.
ViewsExecutable

An object to contain all of the data to generate a view, plus the member functions to build the view query, execute the query and render the output.

Views vs ViewsExecutable
Another good example of using setHandlerOptions is in the TestCase
FieldGroupRowTest