Como fazer desaparecer os     ?

Question: Tenho uma div que vai servir de menu.
O problema é que aparecem-me este caracteres esquisitos a formatar o código e eu não os coloquei lá:
Esses caracteres não são visíveis pelo código, mas são visíveis através do "Inspecionar Elemento" da internet.

Criei este FIDDLE para mostrar o erro.
HTML/JQuery

Opções

        <button type="button" class="ui-btn-b" ></button>
        <button type="button" class="ui-btn-b" ></button>
        <button type="button" class="ui-btn-b" ></button>
        <button type="button" class="ui-btn-b" ></button>

JS que fazem referencia ao menu
//atribuir largura ao menu das opçoes
$('#menuOpt').css({
   'width': nav_width + 'px',
// 'atributo':'Valor',
    });

    $("#menuOpt").slideToggle("slow");

Pergunta
Porque é que aparecem esses caracteres? Como é que os removo?
Comment: @JorgeB. Se clicares para inspecionar elemento naquele espaçamento entre as 4 `divs` consegues ver isso no código HTML. Eu penso que isto esteja a ser implementado propositadamente pelo código `JS` para criar esses espaçamentos, pois se reparares em todos os lugares em que existem espaçamentos esse código está lá presente.
Comment: http://jsfiddle.net/d38a9dhk/1/
Comment: Tem como dar mais informações? que aplicação é esta, que tecnologia usa
Comment: @msm.oliveira eu não sei se foi o JS pode ter sido o teu editor de HTML, pode ter sido muita coisa.
Comment: Não consigo reproduzir. Aqui está direitinho.
Comment: @JorgeB. aí não aparecem esses carqacteres? Eu estou a usar o google chrome. Pode ser por isso? eu estou a achas esquisito é que é a primeria vez que isto me aparece e tenho muito mais código
Comment: É o teu JavaScript que está a criar os ` `
Comment: @JorgeB. como é que pode ser o JavaScript? Estas são as únicas referencias que faço a esse menu no **JS**       `$('#menuOpt').css({
          'width': nav_width + 'px',
//          'atributo':'Valor',
      });` e

       `  $("#menuOpt").slideToggle("slow");`. O resto é **HTML** e **CSS**
Comment: Você copiou o código do seu site/app e trouxe os ` ` consigo. Continuo a dizer que é o JS que estás a usar.
Comment: @JorgeB. esse fiddle funciona bem. Mas então não percebo porque é que é o **JS** está a fazer isso? Mas se o passo para a app volta a aparecer os caracteres
Comment: Vê os JS que estás a usar, deves ter um que faz adicionar isso. Se quiseres colocar o código.
Comment: Só tens isso de JavaScript mesmo?
Comment: @JorgeB. passei o teu codigo uma vez e não deu depois de fazer refresh. Voltei a tentar, mas desta vez esvaziei a cache e fiz um refresh pesado e já resultou e resolveu. mas se tento fazer com o meu código não da. Muito obrigado e desculpa pela confusão. Vou usar o fiddle que disponibilizaste e altera-lo para o que eu quero :P
Comment: @msm.oliveira mas resolveu o problema?
Comment: @ricardo usei o fiddle do JorgeB. na minha app e só depois de esvaziar a cache e fazer um refresh pesado é que aquilo começou a funcionar. com o  meu codigo continua a aparecer aquilo, mas vou alterar o fiddle que o JorgeB. disponibilizou para o que eu quero. Desculpa as dores de cabeça que te causei, mas muito obrigado pela ajuda
Comment: @JorgeB. resolveu sim. só continuo a não perceber como é que aquele pedaço de **JS** causou isso
Comment: O ` ` é representação de espaço em branco. Eu não entendi qual é a necessidade de apagar isso, mas você pode simplesmente deletar o espaço vazio e quebrar a linha novamente manualmente que esses elementos irão sumir.
Answer: Não foi possível reproduzir. Provavelmente é algo que o JSFiddle fez e você não deve se preocupar com isto. Note que você está inspecionando um site que você não fez.
Se aparece em outra situação, era ela que você deveria ter postado.
De qualquer forma isto não é erro. Estes caracteres estão aí por algum motivo e eles são importantes. Eles representam um espaço em branco. Se você os remover terá um conteúdo diferente.
Se você não colocou na sua página e está nela (o que não parece ser o caso), elas não irão aparecer do nada. Alguma coisa está colocando e você tem que analisar o todo para descobrir o que está colocando. Ainda assim deve existir um motivo e retirar esses caracteres trará problemas. Você não colocou nada que dê para dizer porque eles estão sendo colocados. Sem mais informações, só você pode descobrir porque eles estão aí.
Comece fazer as coisas um passo de cada vez para descobrir o que está colocando isto.
Coloquei no GitHub para referência futura.
Comment: Estás errado ele copiou o HTML do código dele, se apagares os espaços entre os botões manualmente os ` ` deixam de aparecer.
Comment: A única coisa que eu sei é que nada é colocado sem um agente fazer isto. As informações não estão batendo. Se ele não mostrar de forma clara onde está o problema, fica difícil ajudar. Vamos ficar aqui chutando coisas. Tem que criar uma forma de reproduzir o problema de forma clara.
Comment: Eu não postei o site, pois isto é uma aplicação e não um site. Não consigo  postar aqui a aplicação. Mas eu copiei exactamente o código que estou a usar a aplicação relativamente a este menu. Como disse num comentario na pergunta, eu não percebo porque é que poderá ser no **JS** se lá eu apenas faço referencia a esse menu para lhe atribuir uma altura e para o fazer aparecer/desaparecer
Comment: Aplicação ou site, dá na mesma. O código que você postou não consta estes caracteres.
Comment: @JorgeB. exactamente: "ele copiou o HTML do código dele, se apagares os espaços entre os botões manualmente os   deixam de aparecer"
Comment: @bigown vê isto então: http://jsfiddle.net/d38a9dhk/1/
Answer: Este carácter   representa o carácter "espaço" (o mesmo como se você pressionar o espaço no teclado.) Ele esta a ser posto por algum de seus javascripts. Estes conjuntos de   são inofensivos, obs. eles devem ser considerados como um único carácter.
Comment: Sao inofensivos, mas estão a alterar-me o visual da aplicação :P
Comment: Esta adicionando alguns espaços (do tananho de um carácter) isto não chega a ser _perigoso_ à aplicação.
Comment: Mas se é colocado pelo **JS** porque é que no [**FIDDLE**](http://jsfiddle.net/d38a9dhk/), onde não uso **JS**, também me aparecem esses caracteres?
Comment: há sim: jQuery Mobile 1.3.0b1 (esta marcada esta opção) porém o browser pode estar inserido também.
Comment: @ricardo o problema é que ele copiou o HTML e colocou no FIDDLE olha vê: http://jsfiddle.net/d38a9dhk/1/
Comment: Vê o link que eu pus @ricardo
Comment: Apaguei os ` ` do código, ou seja, juntei o código todo (apaguei tudo que estava entre código) e os ` ` desapareceram.
Comment: @ricardo Não, apaguei da caixa do fiddle, juntei todo o código em uma linha e depois dei os `enter` lá.
Answer: O @JorgeB. tem razão, você ao ter copiado esse código, trouxe também os espaços   juntamente no markup.
O problema está mesmo no código HTML, se você reescrever o código linha por linha, ou simplesmente selecionar o texto HTML todo usando os atalhos do teclado - ctrl + A e enquanto o texto estiver selecionado apertar shift + Tab (para reorganizar o código e remover espaços desnecessários) e clicar run para correr o código novamente no jsFiddle você irá ver que estes espaços irão desaparecer.
Aqui está um exemplo no jsFiddle: http://jsfiddle.net/go35c5zy/
Siga as intruções que estão na janela JavaScript

Como fazer desaparecer os     ?


Ruby on Rails: Checkbox gets unchecked when trying to edit a post

Question: When i create a new post (passengerride), it is successfully storing multiple value in database. But, when i try to edit the post (passengerride), the checkboxes are getting unchecked.
This is my form:
apps/views/passengerrides/_form.html.erb:
<%= form_for @passengerride do |f| %>
        ......

              <%= f.label :okwithgender, 'Driver should be:' %>
              *

                  <input id="okwithgender"  type="checkbox" value="Male" name="passengerride[okwithgender][]">Male

                  <input id="okwithgender"  type="checkbox" value="Female" name="passengerride[okwithgender][]">Female

                  <input id="okwithgender"  type="checkbox" value="Other" name="passengerride[okwithgender][]">Other

                  <input id="okwithgender"  type="checkbox" value="Any Gender" name="passengerride[okwithgender][]">Any Gender

   ....
<% end %>

app/controllers/passengerrides_controllers:
  def passengerride_params
      params[:passengerride][:okwithgender] = params[:passengerride][:okwithgender].join(', ')
      params.require(:passengerride).permit(:origin, :destination ... :okwithgender)
  end

I guess using this <%= f.check_box ... %> will solve the problem, but i'm not sure how to write something equivalent to
<input id="okwithgender"  type="checkbox" value="Male" name="passengerride[okwithgender][]">
Answer: You should start using rails form helpers for form fields. http://guides.rubyonrails.org/form_helpers.html.
In your case, I think you should try and achieve this using radio buttons as any person will choose just one of these options.
<%= f.radio_button :okwithgender, 'Male' %>
<%= f.label :okwithgender, 'Male', value: 'Male' %>
<%= f.radio_button :okwithgender, 'Female' %>
<%= f.label :okwithgender, 'Female', value: 'Female' %>
<%= f.radio_button :okwithgender, 'Other' %>
<%= f.label :okwithgender, 'Other', value: 'Other' %>
<%= f.radio_button :okwithgender, 'Any Gender' %>
<%= f.label :okwithgender, 'Any Gender', value: 'Any Gender' %>

To achieve this via checkboxes multiple selection,
f.check_box :okwithgender, {multiple: true}, 'Male'
f.label :okwithgender, 'Male', value: 'Male'
f.check_box :okwithgender, {multiple: true}, 'Female'
f.label :okwithgender, 'Female', value: 'Female'
f.check_box :okwithgender, {multiple: true}, 'Other'
f.label :okwithgender, 'Other', value: 'Other'
f.check_box :okwithgender, {multiple: true}, 'Any Gender'
f.label :okwithgender, 'Any Gender', value: 'Any Gender'

Comment: I'm building a carpool app, where a user must select the gender of the driver (could be male or both male and female).
I tried this: <%= f.check_box :okwithgender,{},'Male' %>
But its equivalent to:

I need something like this
Comment: @SainathReddy Edited my answer. Let me know if this works for you.
Comment: When i check a value, it is storing the string and the unchecked values are stored as 0. It's storing 0,Male,0,0,0 when i checked male. And it's getting unchecked when i try to edit the form.
Answer: I would probably agree that this is easier with Rails form helpers. However, if you don't want to use them, you have to extract the values. So, in your models/passengerride.rb I would add:
def okwithgender_separate
  okwithgender.split(',')
end

and then in your view, each of the inputs would have to have something like:
<input
  id="okwithgender"
  type="checkbox"
  value="Any Gender"
  name="passengerride[okwithgender][]"
  <%= 'checked="checked"' if @passengerride.okwithgender_separate.include? 'Any Gender' %> >

or you could add that function to a controller helper to clean it up.
Comment: I tried this, but only the first box is checked, the rest of the selected boxes are getting unchecked in edit page. If I checked female and other, only female is checked in the edit page.


Anacruses, Bar Lines, and Line Breaks

Question: I am an amateur composer.
Page layout is important to me; I like the line breaks to be significant punctuation to the score.
i.e. the end of: sections, parts, phrases, lines of verse/lyrics, are all good places for a line break.
When composing a piece with an anacrusis this is not so straight forward.

I have adopted the practice of splitting measures midway through as can be seen in the below example:

  (In my favourite scorewriter (LilyPond), this is simple to achieve.)

I've never seen this done before so I suppose that my questions are:

Is this a good practice; is it breaking any engraving guidelines or rules?
Would musicians reading such a score, prefer this technique; or does it impair readability/functionality?
Are there other professional scores that also follow this practice?
Comment: I've actually seen split measures more commonly in scores *without* anacruses.
Comment: I don't really read a lot, so I don't have an authoritative answer for you but I would note that I didn't really see this at all when I was in school, so it's certainly not common practice.  I particularly like when charts are split out into phrases as you're describing and I've found that isn't necessarily very common either.
Comment: This is a nightmare if you sight-read the piece.
Answer: It's great that you're thinking about where your line breaks should go, and putting them at natural "punctuation" points is generally a good idea. Breaking mid-measure though is pushing this too far. While it may fit the phrase better, it's a bit disrupting to read. Experienced musicians are very good at identifying phrases, especially when they're 4 or 8 bars like this, and the existence of an anacrusis doesn't disrupt this identification at all.
Mid-measure breaks are sometimes used in professional scores, but usually only when the length of the measure (either the number of beats, or when a measure gets stretched because it's full of 32nd notes) leaves no other good option. It should be thought of as a last resort.
Comment: I prefer the line breaks that show e.g.  the up beat. I think modern digital layouts of music writings should much more respect the poetic aspect of  a composition showing the verses and phrases.  Of course a musician is able to recognize the phrases but if we consider that a song is like a poem an artwork the note lines should be set analog to the text.
Comment: Some of the other answers have noted that hymns often use this technique.
If you could add a small paragraph mentioning this, I can accept your answer.
Comment: I'm accepting this answer albeit reluctantly. Reluctantly, because _I_ still find it easier to write and read with the split measures.  But I do understand that it's certainly not standard engraving practice.
Answer: What you're doing is doubling up on the phrase marking, which is there just for the purpose you propose. Is there any extra point in breaking up bars? Not for me. It seems an amateur thing to do, as the phrasing marks already do the job. Even without phrasing marks, most musos would be able to translate how the line of music should scan, and for me, looking at the next line for the rest of a bar doesn't help any flow, it hinders it.
Comment: +1 - Agreed.  It's heavy-handed, particularly when phrases are already marked with slurs.  I also wonder what level of musician this would actually be helpful for: beginners would likely find split bars confusing, as they may still have difficulty counting and sorting out rhythms, while more advanced musicians will likely already understand phrasing without the visual cue of split bars.
Answer: I would consider breaking measures like this, but only when:

the music starts with an anacrusis (say one quarter note for the sake of this example) and
there's a repeated section which requires you to go back to the beginning and repeat the anacrusis.

In these circumstances you have to put the end-repeat :| bar line one quarter note before the end of an actual bar.  I've seen this in some of the Bach and Handel I've played.
As already noted, if the bar contains lots of 16th or 32nd notes, or a cadenza passage, and starts towards the right-hand end of the stave, you might consider breaking the line like this. I've seen this too, but far less frequently.
I've also seen old hymn books which have this style of layout. Very often any eighth notes are not beamed so it's missing the visual cues you expect from modern, thoughtfully typeset music.
So it's not completely forbidden, but it should be the exception rather than the rule.
In general, I think it's best to avoid anything that will make your reader go "Huh?" when they see it. The music should be as clear as it possibly can be.
Answer: There is a convention that scores for music theater (particularly on Broadway) are always written with four bars per line. Of course that only makes sense because the music is rhythmically boring with nothing but four-bar phrases!
It does boost the wages of music copyists whose union rates are per page, not per note. More empty space on the page means more money, but that's a digression.
Even then, bars are not split up at an anacrusis. In general this simply doesn't work. In the OP's example, if the bass player has a single note for the whole bar 4, how do you write it? If you put it at the end of the first line, there is an empty space at the start of the second like which looks like a mistake. If you split the single note into two notes tied together, that is making the notation more complicated without a good reason.
The reason nobody has done this for hundreds of years is not because they weren't smart enough to think of it, but because they were smart enough to realize that it doesn't make music easier to read.
You don't see printed books where every line ends with a punctuation mark either, for the same reason.
Comment: Was going to upvote, except for "the [musical theatre/Broadway] music is rhythmically boring with nothing but four-bar phrases".
Comment: Agree, except for the last para. Music is far more like poetry, which is usually written in specific lines (not talking prose here - that's different). A story when written out, has no stanzas, so can be written to the end of each available space. So, possibly, music *ought* to be written in four bar lines. Actually, when I write chord charts, that's exactly what I always do, but then those contain full bars and there's no splitting which is where OP comes in.
Answer:
Is this a good practice; is it breaking any engraving guidelines or rules?

Oh, yes, this would be a good practice. It helps to understand the musical structure and would support to learn a piece by heart.

Would musicians reading such a score, prefer this technique; or does it impair readability/functionality?

This may be opinion based and individual. But it would help to read and interpret a song and composition, and the most phrasing bows would be superfluous.

Are there other professional scores that also follow this practice?

look up a church choir book or a song book: you'll find this break when ever it was possible.
In a solo album and concert sheet music the layout doesn't show this structure. The main purpose is to save space and paper! But today in digital settings could help to keep the structure and emphasize the formal aspects of an musical artwork  (where it exists!)
I prefer the line breaks that show e.g. the up beat. I think modern digital layouts of music writings should much more respect the poetic aspect of a composition showing the verses and phrases. Of course a musician is able to recognize the phrases but if we consider that a song is like a poem an artwork the note lines should be set analog to the text
Comment: The difference with church choir/hymn books and song books is that this sort of line-breaking is almost always used with *exceptionally regular* poetic meters that correspond to *exceptionally regular* rhythms in the songs. Hymns that have varying length of anacrusis and/or varying phrase lengths frequently are typeset with whole bars, as the split bars get increasingly confusing without a regular pattern.  And while a quarter-note anacrusis in 3/4 may cause no confusion when split off, with more complicated (and inconsistent) rhythms, it can become increasingly difficult to read.
Comment: The hymnal is as much a presentation of poetry as it is a presentation of music.  The break ensures that lines of music correspond directly to the lines of the metrical poem.  However, this is a practical, functional, and stylistic decision specific to hymnals and other similar publications, and does not necessarily carry over to other musical genres.
Answer: It's a bit unconventional, but it can work.
About three years ago someone brought to my viola da gamba trio an In Nomine by John Bull. It was handwritten and had loads of linebreaks in the middle of bars, or three-quarters of the way through a bar, or wherever it wanted to have a linebreak.
To start with we thought this was very strange and we really struggled with it. I actually went as far as to write the two complex parts out without this feature (the cantus firmus was fine, consisting largely of one note per bar). And then we found that it was harder to read with line breaks only happening at the bar line, because the line breaks were on phrase boundaries, and the spacing the original editor had used really helped once we got into analysing the music and playing it according to its real structure, not just the one imposed by the bar lines (which, as usual in consort music of the period, one should largely ignore and may not have been in the original notation anyway).
So in conclusion I'd say it can certainly help in some cases, regardless of whether there's an anacrusis or not, but you're probably going to confuse some people who sit down to try to play it - at least until they figure out why you did it.
Answer: This is common practice in strophic songs and hymns.  But it's invariably notated with a double barline at the line break, not just an open end.
Comment: I question the assertion that "it's *invariably* notated with a double barline at the line break, not just an open end."  I've seen the open end more frequently in modern hymnals and songbooks, since, say 1900.  This strikes me as something I might see in an older hymnal, from perhaps pre-1800?

Anacruses, Bar Lines, and Line Breaks


How to name SQL FOREIGN KEY Constraint on CREATE two tables columns into a relationship TABLE

Question: i was just wondering if there is a way to name a foreign key on create table
FOREIGN KEY (uuid) REFERENCES employee(uuid));

i tried to do this and name my foreign key as fk1 but i've got syntax errors
FOREIGN KEY fk1 (uuid) REFERENCES employee(uuid));

error
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is com.jda.cloudsql.common.MigrationException: org.flywaydb.core.internal.dbsupport.FlywaySqlScriptException:

  FOREIGN KEY FK1[*] (UUID) REFERENCES EMPLOYEE(UUID)) "; expected "("; SQL statement:

Comment: Are you trying to _add_ a foreign key to a table which already exists, or are you asking how to do this from a `CREATE TABLE` statement.  You may certainly name a foreign key when adding it during create table.
Comment: @TimBiegeleisen from a CREATE TABLE, i actually dropped my previous table and recreate it
Comment: [See here](http://www.mysqltutorial.org/mysql-foreign-key/) for how to do this.
Answer: You can write:
ADD CONSTRAINT `customized_foreign_key_name` FOREIGN KEY (`uuid`) REFERENCES `employee` (`uuid`)

Comment: i am doing a create table, not an alter. I dont know if that will work in this case. it expects a type instead of a constraint?
Comment: Why don't you create the table first and then start creating foreign keys?
Comment: yeah that is exactly what i am about to do . thank you
Comment: Glad I could hep.


Java volatile modifier and synchronized blocks

Question: Does a variable that is accessed by multiple threads, but only inside synchronized blocks, need the volatile modifier? If not, why?
Comment: You may also be interested in this question:  http://stackoverflow.com/questions/3103204/difference-between-synchronization-of-field-reads-and-volatile
Comment: No. Refer to this relaled SE question: http://stackoverflow.com/questions/3519664/difference-between-volatile-and-synchronized-in-java/34355995#34355995
Answer: You do not need to use volatile inside of synchronized, synchronized already guarantees the correct behavior for local caching of variables when used consistently (on every access).
volatile works on primitive values, and can be a nice shortcut for atomic accesses to a primitive type. Note that the behavior of volatile has changed in JDK 5 from 1.4.
More information can be found here
Answer: No.  When you work within a synchronized block, all cached variables are synchronized on access, since it creates a memory barrier.
For details, see this comparison (with discussion) of volatile to synchronized.
Answer: Blocks that synchronize on the same object (or method) are guaranteed to not be run at the same time.  So as long as you synchronize to the same object, your variable will never have concurrent accesses, so it doesn't need special treatment.
If your accesses aren't synchronized, then you have a race condition.  Making the variable volatile can be correct for some primitive variables (I defer to other posts for better info on volaitle).  If that isn't useful, you almost certainly have a bug.
Comment: To be pedantic, synchronizing in other languages does not imply consistent memory - the value may be cached in a register or local memory, and even though the access is synchronized, it may not be atomic/consistent. However, in Java, synchronized turns on an automatic volatile.
Comment: To be equally pedantic, the other languages you're probably thinking of (C/C++) don't have an intrinsic notion of synchronizing threads, or even a `synchronized` keyword; you have to construct something similar out mutexes.  There you're right: there is no runtime to manage memory consistency for you.  Those languages don't even specify any semantics for concurrent memory accesses!  Thankfully Java is nice and just does what you expect it to do.
Comment: @YannRamin As in, the variable you synchronize on is effectively volatile for the purpose of modifications to it made within that synchronized block?  Not sure if I interpreted you correctly, but I can't find a description of that effect elsewhere.


Can a player be sent off while still on the substitute bench?

Question: Can a referee caution or send off a substitute or substituted player?
Comment: @Don_Biglia - no, "sent-off" is the correct terminology. The red card is just a signal
Comment: ..."be given a red card"... would be more clear( and given the circumstances more appropriate)
Comment: Well I'll mail to FIFA then that their terminology is off. I still find mine clearer
Comment: @Don_Biglia - cards weren't used as a signal until 1970. I don't see what's unclear about the terminology "cautioned" or "sent-off". They're completely unambiguous.
Answer: Yes.
From page 39 of the 2015/16 FIFA Laws of the Game (emphasis mine):

The yellow card is used to communicate that a player, substitute or substituted player has been cautioned.
The red card is used to communicate that a player, substitute or substituted player has been sent off.
Only a player, substitute or substituted player may be shown the red or yellow card.

While a substitute or substituted player can technically be sent-off for any of the seven sending-off offences a player is subject to, there are only three offences for which they may be cautioned.
p. 40 of the 2015/16 FIFA Laws of the Game:

A substitute or substituted player is cautioned if he commits any of the
  following three offences:

unsporting behaviour
dissent by word or action
delaying the restart of play

The team will continue to play with the same number of players they had on the field at the time the substitute or substituted player was sent off.
If a substitute is sent-off before the match begins, they cannot be replaced with a reserve player who was not named in the line-up.
p. 21 of the 2015/16 FIFA Laws of the Game:

A named substitute who has been sent off, either before the kick-off or after play has started, may not be replaced.
Answer: Yes. Although the team won't lose a man, the team won't be able to use that substitute, and the player will be subject to the same disciplinary sanctions as if they'd been sent off while on the pitch.
Additionally, players can be sent off after the game has finished. They can also be sent off before the game starts, though if this happens the team can replace them and won't be a man short.
Comment: @Don_Biglia - no, "sent-off" is the correct terminology. The red card is just a signal.
Comment: Same remark actually; ..."be given a red card"... would be more clear, and given the circumstances more appropriate I feel ;)
Comment: Only in this season, in my support team (Taranto FC - Italy) the referee has given 2 red cards to players on bench ;(
Comment: @Don_Biglia technically the term "given a red card" is more unclear as the player is "SHOWN" a red card he doesn't receive it he receives a "sending off" along with the sanctions... so studro is correct in this instance.


Can you use row and column operations interchangeably?

Question: Is it possible to use row and column operations "at the same time" on a matrix $A$? So, for example, first subtracting $row_1$ from $row_2$, and then choosing to multiply $column_3$ by a constant $c$? Or do you have to "stick to one method" when reducing a matrix? If so, can somebody explain why?
Edit: so let me put this more clearly. Suppose you have $$\left( \begin{array}{ccc}
a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a_{23}  \\
a_{31} & a_{32} & a_{33} \end{array} \right)$$
First I multiply row 2 by $\frac{a_{11}}{a_{21}}$, row 3 by $\frac{a_{11}}{a_{31}}$, then subtract row 1 from row 2 and row 3 so you end up with a matrix of a new general form:
$$\left( \begin{array}{ccc}
a_{11} & a_{12} & a_{13} \\
0 & b_{22} & b_{23}  \\
0 & b_{32} & b_{33} \end{array} \right)$$
with $b_{ij}$ the new coefficients which were attained by our row operations. My question is: could you then say, subtract column 1 from columns 2 and 3 in order to get:
$$\left( \begin{array}{ccc}
a_{11} & 0 & 0 \\
0 & b_{22} & b_{23}  \\
0 & b_{32} & b_{33} \end{array} \right)?$$
Edit2: How come that, according to the answers, this is incorrect, even though this is the exact same thing Serge Lang does in his book "Introduction to Linear Algebra"? What's happening here? Are you telling me Serge Lang doesn't know how to reduce a matrix? Reminder: this is NOT a linear system we're solving for, and this is NOT an augmented matrix. It's just a matrix $A$.
Edit3: here is some more context.
Comment: Dr. Lang makes it clear here the reason why row and column operations work in this case.  It's because he *doesn't care* if he loses information about the linear transformation under consideration -- he only wants to find the **rank** of the matrix.  Because the column rank and row rank are equivalent, you can use col or row or both operations to reduce the matrix.  Again, you *lose information* about the transformation (always try to remember that matrices are just representations of linear transformations) -- but no information is lost about the rank.
Comment: It depends on WHY you're wanting to reduce it.  If you're trying to determine if a matrix is invertible -- then yes (that is you're checking to see if the matrix is similar to the identity matrix).  You can use either one or both together.  In general, though, row and column reduction are 2 different things.
Comment: This is often done. For example the calculation of Smith normal form of a matrix requires both row and column operations. It all depends on the context of what you are doing. If you are calculating the determinant, you can do either. If you are solving a linear system, you cannot. A blanket answer is impossible. The following is the best I can say: A row operation amounts to a change of basis in the range - a column operation amounts to a change of basis in the domain. It depends on the task which (may be both, may be neither) is ok.
Comment: When we do row reduction without an augmented matrix, we wind up with a $U$ such that $Ax=0 \Leftrightarrow Ux=0$. When we do column operations, the $U$ we get at the end does not have this property. For example, $\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix} \begin{bmatrix} 1 \\ -1 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix}$ but $\begin{bmatrix} 1 & 0 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 1 \\ -1 \end{bmatrix} = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$
Comment: Certainly you cannot do all those things if you have any division by $0$ going on.
Comment: You can't even if you don't. My example merely subtracts column 1 from column 2 without any rescaling.
Comment: On your most recent edit: what does it mean to "reduce a matrix", in this sense? To me if one "reduces" $A$ to an upper triangular matrix $U$, then we should have $Ax = 0 \Leftrightarrow Ux=0$. With column operations this does not happen.
Comment: Alright, let me use the word "change" or "edit" the matrix.
Comment: In this particular instance, he was trying to reduce some arbitrary matrix $A$ to a block-matrix of the form: $$\left( \begin{array}{cc}
I & 0 \\
0 & 0 \end{array} \right)$$
Comment: Either add in a picture of that section of his book or type it up -- we need to see the source to know what Dr. Lang was trying to show you.
Comment: [Here](http://imgur.com/sn2zJ7A) are the pages in question.
Comment: The OP still hasn't made clear what Lang's end goal is, i.e. why he wants to end up with such a block-matrix, but here's a guess. Perhaps the claim is that for any linear map $\mathbb R^n \to \mathbb R^n$ there exists a basis for the first copy of $\mathbb R^n$ and a basis for the second copy relative to which the matrix of the linear map has the required block form. Using row and column operations together essentially amounts to changing bases of both the domain and codomain to obtain this, but this is far removed from the ordinary sense in which row operations are used to "reduce" a matrix.
Comment: I've uploaded a link with the appropriate pages.
Comment: To add onto @Bye_World's comment, the answer to your question in this case is simply "yes you can use row and column operations interchangeably in this case because that is what Lang's Theorem explicitly asks for." This doesn't say anything about whether you can or cannot use them interchangeably in other scenarios.
Comment: Thank you all: you've been very, very helpful. I understand what's going on now.
Answer: What "reducing a matrix" means
One issue here is what is meant by "reducing a matrix". The only purpose I can see for reducing a matrix is to decide if the matrix has some specific property. Whatever property you are interested in has to remain unchanged under the operations you do or you have not succeeded in your purpose.
If you investigate Serge Lang's book closely, you will find that he had a specific purpose for reducing the matrix,(to find the rank, discussed below) which allows him to use column operations to achieve his aim.
It is important to note that for most people, the phrase "reducing a matrix" refers specifically to finding the Reduced Row Echelon Form (also known as RREF). As the name implies, RREF is defined using the rows of the matrix:
 1. The leftmost nonzero entry in any row is a 1 (called a "leading 1").
 2. Leading 1's on lower rows are further to the right than leading 1's on higher rows.
 3. Other entries in a column with a leading 1 are zero.
 4. All rows consisting entirely of zeros are at the bottom of the matrix.
Since you are defining this matrix in terms of rows, you must do row operations to achieve it. In fact, if you do use row operations, then given a particular starting matrix (which may or may not be square, by the way), there is precisely one RREF that it will reduce to. If you do column operations you will not arrive at this same matrix.
Relationships to solutions of equations
The point others have made about finding solutions is valid. Every matrix can be used to represent the coefficients of a system of linear equations, regardless of whether you want it to or not. Many of the important properties of matrices are strongly related to this system of linear equations, and so it is a good idea to have methods that preserve these properties.
For example, the set of solutions to $A\mathbf{x} = \mathbf{0}$ is the same as the set of solutions to the (homogeneous) linear equations, and the nonzero rows of the RREF form a basis for the space perpendicular to this space of solutions. Neither of these properties are preserved by column operations, but they are preserved by row operations.
Most importantly, just to reiterate: the solution to your homogeneous linear equations is definitely not preserved by column operations, and this is an important consideration regardless of whether you want your matrix to represent linear equations or not.
Note that there are things that column operations do preserve, such as the range of the linear transformation defined by your matrix. However a mixture of row and column operations will not preserve this, nor most of the properties you care about.
The inverse of a square matrix
One property that a mixture of row and column operations does preserve is invertibility. You can see this from the idea of elementary matrices.
Doing elementary row operations corresponds to multiplying on the left by an elementary matrix. For example, the row operation of "new R2 = R2 - 3R1" is produced on a 3 by n matrix when you multiply on the left by $\begin{pmatrix} 1 & 0 & 0 \\ -3 & 1 & 0\\ 0 & 0 & 1 \end{pmatrix}$. Column operations, on the other hand, are produced when you multiply by a matrix on the right hand side. The column operation of "new C2 = C2 - 3C1" is produced on an m by 3 matrix when you multiply on the right by $\begin{pmatrix} 1 & -3 & 0 \\ 0 & 1 &  0 \\ 0 & 0 & 1\end{pmatrix}$.
The process of finding the inverse of a square matrix by augmenting an identity and doing matching row operations on both works because of these elementary matrices. If you perform row operations on $A$ to get $I$ and the elementary matrices corresponding to these operations are $E_1$, ..., $E_k$, then we have $E_k ... E_1 A = I$ and so the inverse of $A$ must be $E_k ... E_1$. But this is equal to $E_k ... E_1 I$, which is what you get when you do all those row operations on the identity!
This would work perfectly well if you did column operations, however a mixture of the two is a bit harder to understand. Suppose you did row operations with matrices $E_1$, ..., $E_k$ and column operations with matrices $F_1$, ..., $F_h$ and you produced the identity as a result. Then
$$
\begin{align}
E_k \dots E_1 A F_1 \dots F_h &= I\\
A &= (E_1)^{-1} \dots (E_k)^{-1} I (F_h)^{-1} \dots (F_1)^{-1}\\
A^{-1} &= F_1 \dots F_h I E_k \dots E_1
\end{align}
$$
This is not the result of doing the matching column operations and row operations on $I$ because the matrices are on the wrong side!
So if you can row-and-or-column reduce a matrix to the identity, then this proves that the matrix is invertible, but it is tricky to tell what the inverse actually is unless you do only row or only column operations.
Finally note that row and column operations simultaneously will allow you to calculate the determinant of a square matrix easily, and so there is a certain advantage to doing this. In particular a row/column operation of the type "new Ri = Ri + k Rj" or "new Ci = Ci + k Cj" will not change the determinant, so if you restrict yourself to those operations, you can get your matrix into a form where it is clear what the determinant is more quickly than restricting yourself to just one. However, it is worth stressing that this relates to my original comment about the purpose you are trying to achieve -- this is only really an advantage in the situation where you are finding determinants.
The rank of a matrix
Finally, this row-and-or-column reduction also does preserve the rank of your matrix. If you do this kind of reduction on any matrix, what you are guaranteed to produce eventually if you try is a matrix with some 1's down its main diagonal (but not necessarily all the way down) and zeros everywhere else. Something like these:
$$
\begin{pmatrix} 1 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 1 & 0& 0\end{pmatrix} \quad \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0& 1 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix}
$$
The number of 1's on that diagonal is the rank of your matrix. That is, it is the dimension of the column space and row space, and the dimension of the range of the linear transformation defined by your matrix, and n minus the dimension of the solution space to your system of equations. So the two matrices above have rank 3 and 2 respectively.
However, there is nothing in the final reduced form that tells you what the actual solutions to the equations are or what the bases for the spaces are. These can all be changed in ways that are not easy to follow if you do both row and column operations. If you did just column operations, then the leading-1 columns would be a basis for the range of the linear transformation, but with both row and column operations, these columns are all standard basis vectors and won't necessarily be correct. If you did just row operations, then the non-leading-1 columns would appear as the first several coordinates of the vectors in a basis for the null space of the matrix, but with both row and column operations these columns are all zero.
Summary

Most people mean Reduced Row Echelon Form when they say "reduced matrix", which is defined by doing only row operations.
Row operations preserve many useful properties of matrices and tell you certain information about matrices.
Column operations preserve some useful properties of matrices and tell you certain information about matrices.
Mixtures of row and column operations preserve only a small number of properties. In particular, a mixture will preserve the rank and the invertibility of a matrix (but will not provide bases for associated subspaces or the actual inverse itself).
Comment: Yes. I mean for every matrix A there is a system of equations that has that matrix A as the coefficient matrix.
Comment: When you say " Every matrix can be used to represent the coefficients of a system of linear equations, regardless of whether you want it to or not." you mean every matrix represent the coefficients of some or the other system of matrix right? (regardless of whether the matrix is intended as coefficient matrix in that context.)
Comment: "Neither of these properties are preserved by column operations, but they are preserved by row operations." ---

Why do row operations preserve the solution set of the matrix?
Comment: @information_interchange One reason is that doing a row operation is the same as multiplying on the left by an elementary matrix, and elementary matrices are invertible. So Ax=0 <=> EAx=E0 <=> (EA)x=0.
Answer: Say you have a system of equations:
$$\begin{cases}
a_{11} x_1+\ldots +a_{1m}x_m =b_1\\
 \vdots  \\
a_{n1}x_1+\ldots + a_{nm}x_m = b_n
\end{cases}$$
Then the corresponding augmented matrix is
\begin{pmatrix}
a_{11} & \ldots & a_{1m} & | & b_1 \\
\vdots & \ddots & \vdots & | & \vdots \\
a_{n1} & \ldots & a_{nm} & | & b_n\end{pmatrix}
Row operations correspond to adding and scaling equations or reordering them, which--by the force of regular algebra--doesn't change the overall system. Column operations however, DO change the system, because if we scale say the last column with all the $b$s, we see that this changes what we're trying to solve for.
In particular:  say your first set of equations is just:
$$\begin{cases} x + y = 1 \\ x-y = 0\end{cases}$$
then the matrix is
$$\begin{pmatrix} 1 & 1 & | & 1 \\ 1 & -1 & | & 0\end{pmatrix}$$
It's easy to see that the solution is $x=y=1/2$, however, if we can scale the columns as well, we get $x=y=1$ just by scaling the last column by a factor of $2$, and if we could add columns, we would get the matrix:
$$\begin{pmatrix} 1 & 2 & | & 1 \\ 1 & -1 & | & 0\end{pmatrix}$$
by adding the last column to the second one. This gives us the system:
$$\begin{cases} x + 2y = 1 \\ x-y=0\end{cases}$$
where we see that $x=y=1/3$, a different solution.
Comment: Yes, I see, but I wasn't talking about finding a solution to a system of linear equations, or an augmented matrix. Just suppose you have a real-numbered matrix $A$; wouldn't it be possible to use column and row operations interchangeably? As long as it's _just_ a "normal" matrix, without an added solution set, and I'd be interested in reducing it, wouldn't that be possible?
Comment: Here, I made an edit to clarify some things. If you could just take a look, I'd be very grateful!
Comment: Yes, assume that there's no division by zero going on. Is the presented method in my edit correct?
Answer: When you perform column operations rather than row operations, you change the solution rather than the right hand side. For brevity, let's say we are solving $Ax=b$; denote the new solution after a certain column operation by $x'$.

If you multiply column 1 by 2, $x'_1 = x_1/2$.
If you interchange columns 1 and 2, $x'_1=x_2$, $x'_2=x_1$.
If you add column 1 to column 2, $x'_1 = x_1 - x_2$. (Check this, I only tried this on a $2 \times 2$ example.)

These problems aside, yes, you can use both column operations and row operations in a Gaussian elimination procedure. There is fairly little practical use for doing so, however. About the only use is performing pivoting using both row and column exchanges (so-called "total pivoting", rather than "partial pivoting"), but one finds that in practice row exchanges alone are sufficient.
By the way, total pivoting is quite slow, because it requires scanning the entire matrix, rather than just one column, when finding each pivot. This increases the running time by a constant factor, whereas partial pivoting adds only quadratic time to a cubic procedure.
Comment: Thank you, that's a great answer, but I'd ask of you to read my reply to the other comment. I'm not interested in row-reducing an augmented matrix, I was interested in just reducing an arbitrary matrix $A$ without a specific solution set added to it.
Comment: But how come that Serge Lang, in his "Introduction to Linear Algebra", does exactly what I did in the edit?
Answer: Suppose we want to perform row and column operations on the matrix $A$. Performing a row operation is the same as multiplying on the left by a certain elementary matrix $E_R$; performing a column operation is the same as multiplying on the right by a certain elementary matrix $E_C$. Since $(E_R A)E_C = E_R(A E_C)$ (i.e., since matrix multiplication is associative), the order in which you perform a row operation and a column operation does not matter: you end up with the same matrix in either case.


Problem about a process with bins of balls

Question: A friend of mine give me this problem for fun:
Given $\frac {n(n+1)}{2}$ balls, first we divide arbitrarily these balls in baskets, after that we make another basket with one ball of each basket e do this procedure infinitely.
I want to prove that one time this stabilizes with 1 ball in one basket, 2 balls in another basket, ..., n balls in another basket.
It seems easy to solve, he says we can use some concept of energy (???), I'm trying with some concepts of combinatorics without any success.
Thanks in advance.
Comment: Please give your question a meaningful title.
Comment: @RossMillikan Then, the problem is, if, in the initial configuration, there were the entire $n(n+1)/2$ balls in the first basket of the first set, and none in the others, we do not run out of all the balls in the first basket of the first set of baskets after only "one pass." In fact, in this case the system will oscillate.
Comment: user85493, you're really going to have to explain this better.
Comment: @LordSoth the number of basket is arbitrary.
Comment: @RossMillikan the initial condition is with an arbitrary number of baskets
Comment: Hi, welcome to MSE. You second paragraph where you explain what you do with the balls is unfortunately not clear (at least to me). How many baskets are there? How do you divide the balls into baskets?, etc.
Comment: It sounds like you have $n$ baskets and distribute the balls in any way.  Then you have another set of $n$ baskets.  Into the first basket of the second set you put one ball from each of the first set of baskets that has one.  Then into the second basket of the second set you put one ball from each of the first set that still has one, and keep going.  Now repeat the process from the second set into the first.  Is that what you are thinking?
Comment: Then, as Lord Soth says, if the number of baskets is at least $n(n+1)/2$ and we start with all the balls in one basket, after one move we have one ball each in $n(n+1)/2$ baskets and we oscillate.  What you are trying to prove is then false.
Comment: I've edited the title to at least slightly reflect the content - 'Interesting Problem' says nothing useful about the question.  Feel free to edit it further, obviously, but I definitely recommend giving at least some description of the problem in the title.
Answer: I believe what you are discussing is known as Bulgarian solitaire. This is a theorem of Jorgen Brandt, i.e., that the game ends as you have described when the number of balls (or cards) is a triangular number,  i.e., of the form $n(n+1)/2$.

Here is a nice source to read over: (paywall)
Solution of the Bulgarian Solitaire Conjecture
Kiyoshi Igusa
Mathematics Magazine
Vol. 58, No. 5 (Nov., 1985), pp. 259-271
Published by: Mathematical Association of America
Article Stable URL: http://www.jstor.org/stable/2690174

Note this is also the subject of a problem in the June/July 2013 AMM: Problem 11712.
Comment: This is exactly what I presume the OP was talking about.  Very nicely done.
Comment: Thanks; was just lucky to recognize it from glancing at the most recent AMM.
Comment: No problem. If you can get a hold of the most recent issue of the American Mathematical Monthly (June/July '13) you (or your friend) might check out the problem on Bulgarian solitaire.
Comment: I didn't find this problem in the magazine of june/july '13, what's the name of the article?
Comment: Check the Problems and Solutions section of AMM June/July 2013 and look at the first problem listed (i.e., AMM Problem 11712).


Why does my front page only work in one language?

Question: I have problem with language of Drupal. When I click in home page in English language, the front page contains all content, nodes and blocks. When I click on other language, the front page doesn't show any contents and shows this message:

No front page content has been created yet

How can I make 1 front page that contains the same blocks and content and is also translated in different languages?
Answer: This is the way I use it for a website with one single language in the front end (Spanish), and backend in english.

And..

All nodes are created using default language.
Answer: You could create a node with some static content to display as homepage, and then set this node as your default front page for default language in

admin/config/system/variable/edit/site_frontpage.

and then translate this node for other languages.
In order to display some views blocks especifically in your frontpage and in all languages, first make sure your block settings are

Show block on specific pages : Only the listed pages : <front>

Then in view advanced settings, set Field Language as Current user's language
To complete, you can use Internationalization views to translate not dynamic content in your view, like views header, labels...


Como incrementar o campo código do tipo varchar() automaticamente no MySQL?

Question: Eu preciso fazer um controle de estoque, onde o código dos produtos deve ser varchar, pois o código será formado pelo nome abreviado da categoria do produto seguido de um número sequencial, então não vou usar a coluna product_ID que é do tipo int, mas vou usar a product_codev, que é varchar, e preciso que ela seja auto incrementável. Como faço, tem como com triggers?
Answer: Deixe product_ID como auto_increment e faça uma trigger de after insert. Assim você pode montar o product_codev da forma que achar conveniente.
Agora se eu puder te dar uma sugestão, acho que este product_codev poderia ser montado na aplicação, já que aparentemente é algo para apresentar para o usuário e não para garantir a consistência dos dados.
Comment: Ok, muito obrigado pela resposta, acho que vou fazer o product_code na aplicação, o product_id já está funcionando mesmo! Não posso votar ainda na sua resposta porque sou usuário novo
Comment: Você pode aceitar como a resposta correta ;p


How to display a BACK button but ONLY if the user came from somewhere else on my site

Question: I'd like to display a BACK button on my node--resource.tpl.php file but ONLY if the user came to the node from another part of my site. If they copied and pasted the URL for the node directly into their browser's address bar and got to it that way I do NOT want the button to appear.
Here' the button in my tpl:
<input type="button" value="Go Back" onclick="history.go(-1)" />

Anyone know how to do this with PHP (or another Drupal method)?
Comment: This is an off-topic question, here: How to detect from where a user comes to your page is a plain PHP question. In fact, `$_SERVER['HTTP_REFERER']` is not handled by Drupal.
Answer: There are many ways to do this.
One of it would be to use $_SERVER['HTTP_REFERER'] to detect where the user comes from.
Put the following code in your template file.
if (strstr($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
     // Facebook brought me to this page.
     print 'Go Back';  }


Reverse Proxy redirection based on hostname

Question: Here's my setup:
Windows Server (2003) receives all traffic for *.mydomain.com, which (up to now) redirects all incoming port 80 traffic to a Linux VM (using VMWare virtual network manager).
I now need to setup another website on this server, using IIS6, to handle subdomain1.mydomain.com.
How do I separate the HTTP traffic as such:
  subdomain1.mydomain.com -> IIS
  everything else (*.mydomain.com, domain.com, raw IP) -> Linux VM

I thought of setting up an Apache server on Windows as Reverse Proxy. But can ProxyPass handle hostnames? (all examples I see handle directories).
Is there another/easier solution? Would lighttpd help?
TIA for your help.
[FWIW: Changing the architecture is not an option. Else I wouldn't ask ;-). An acceptable option if it helps (I doubt though) is to setup a 2nd public IP)]
Answer: You can set up VirtualHosts in Apache, and then use ProxyPass for the subdomain1.mydomain.com to reverse proxy into IIS, and have a default VirtualHost that reverse proxies into your Linux VM.
You'd want a configuration that was something like this:
<Virtualhost *:80>

    ServerName subdomain1.mydomain.com

    ....
    # Reverse proxy into IIS
    ProxyRequests off
    ProxyPass / http://ip.of.IIS.machine/
    ProxyPassReverse / http://ip.of.IIS.machine/
</VirtualHost>

<VirtualHost _default_:80>
    ....
    ProxyRequests off
    ProxyPass / http://ip.of.linux.machine/
    ProxyPassReverse / http://ip.of.linux.machine/
</VirtualHost>

Those configs are missing most of the configuration, but the important bits are that the first VirtualHost definition matches on subdomain1.mydomain.com, and this then does a reverse proxy into the IIS machine.  The second definition matches everything else, and reverse proxies into the linux machine.
Note, I haven't tested the above as it is written, but I have definitely got an apache setup with multiple virtualhosts where one vritualhost is a reverse proxy into another machine, so the basic theory is fine.
Comment: Glad it worked for you. Also, setting up a second public IP probably does help - you should (assuming windows does sane things here, I don't know) be able to bind IIS to one of the IPs, and serve it directly, and then forward everything on port 80 on the other IP through to your linux VM, and no apache+reverseproxy needed.
Comment: Daniel, thanks! It works. Oddly though, I had to put a ServerName in the _default_ vhost or everything would go to the other one. The only problem is that IIS (localhost, different port) thinks the client is localhost hence, in case of application error, returns a detailed explanation of the error :-(
Comment: I know it's super late to suggest this, but maybe adding `ProxyPreserveHost On` above the `ProxyPass` config would fix the problem with IIS thinking its serving clients on localhost?
Comment: That worked flawlessly! In my scenario, I only needed the `ProxyPass` directive tho. I had 1 apache proxy + 1 webserver with 2 VirtualHosts. I created 2 different VirtualHosts as you described in my apache proxy, redirecting them to the webserver, and it worked!.  *PS: I didn't need a default VirtualHost, I used 2 regular VirtualHosts*


Cant use document.getElementById() with createElement();

Question: Why can't I use cant use document.getElementById(); with createElement(); ? I'm getting this error: Uncaught TypeError: document.getElementById(...).createElement is not a function. I got createElement from this. FYI: I'm not using any javascript apis like jquery, and im not planning on either.
The code I have:
document.getElementById('container1').createElement("input")

Comment: Look `createElement()` creates an element. Then you `append` the element to the `document.getElementById('container1')`
Comment: Oh. I must have mis understood that wrong from the docs
Comment: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
Answer: getElementById returns a HTMLElement, and HTMLElement doesn't have a createElement method
This may be what you're after:
var parent = document.getElementById('container1')
var child = document.createElement('input')
parent.appendChild(child)

Or
document.getElementById('container1').appendChild(document.createElement('input'))

Answer: The Fix it Pretty simple.
const element = document.createElement('input')
document.getElementById('container1').append(element)

The create Element returns an element. The secounds appends the newly created element to another element which is already rendered to the user
Comment: Thanks. I just misunderstood what I read from the documentation


Joomla 2.5 content plugin with Ajax

Question: On my Joomla 2.5.x site, I want to add links, that opens Fancybox window, with mail form, in which the user enter mail and address. On submit, the plugin will validate and send the mail to the correct recipient.
I wrote the plugin, and stumble into a problem: How to get Ajax to call the php script that is doing the db staff and sending the mail.
If I use the following url:
<code>$.ajax({
    type: 'POST',
    url: ''/my_site/plugins/content/my_plugin/sendmessage.php',
        ...
</code>
The php script is out of Joomla reference, It closes due to:
<code> defined('_JEXEC') or die();
</code>
And Joomla functions are not working.
There are workaround for this like adding the following staff to the php script:
<code><?php
define( '_JEXEC', 1 );

// JPATH_BASE should point to Joomla!'s root directory
define( 'JPATH_BASE', realpath(dirname(__FILE__) .'/' ) );
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
$user =& JFactory::getUser();
$session =& JFactory::getSession();
?>
</code>
But I am not sure about the security of this workaround. And I prefer clean solutions.
I searched a lot, and found out that the right way is to create a php function, add it to the controller and call it from Ajax in the following way:
<code>    $.ajax({
    type: 'POST',
        url: 'index.php?option=com_mycomponent&format=raw&task=mytask';
         ...
</code>
But is this way is possible only for a Component ? What I need is a Plugin. How can I run a simple ajax call to a php function/script in a Plugin ? Any help will be appreciated, I am looking for a solution for quit some time.
Answer: This has been implemented in Joomla 3.2, there is a new Ajax functionality. If you need to use it in a previous version, check https://github.com/betweenbrain/Joomla-Ajax-Interface which has been added to 3.2, you can also install it to Joomla 2.5+ and use it.

Joomla 2.5 content plugin with Ajax


Is it Possible to Change "Edit Permissions" Based on a Field Value on that Node?

Question: I have users that need to be able to edit a piece of content they created until the status field on the piece content is updated to a particular value.
I've done some research and it looks like there are questions that are similar to mine but different enough that their solutions don't seem applicable.
I realize this question might be vague but I don't know how else to phrase it.
Are there any solutions to my problem?
Edit: I am using Drupal 7.
Comment: You should let us know what version of Drupal you are using (6,7,8?). It sounds like you may be looking for a workflow solution using something like [Workbench](https://www.drupal.org/project/workbench), specifically [Moderation](https://www.drupal.org/project/workbench_moderation) can be used to set node permissions based on the publication status of a node, but that might be a different kind of "status" than you're talking about.
Comment: The status I'm talking about comes from a select list field on the form. Also I updated the question to include my version of Drupal. Currently looking into workbench!
Answer: I think you can achieve this by implementing hook_node_access() with a check on the particular field.
https://forumone.com/ideas/programmatically-restricting-access-to-drupal-content has a very similar use case (except the field there is an entityreference field to users, but you get the gist)
Comment: This looks great! I'll give it a shot and update when it's done.
Comment: Can this be applied solely to the edit content instead of blocking node access entirely?
Comment: As per [documentation](https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7.x) the `$op` parameter can be "create", "delete", "update" or "view". So any


Difference between ~lp() or simply ~ in R's locfit

Question: (Please note the cross-post at https://stackoverflow.com/questions/7626347/difference-between-lp-or-simply-in-rs-locfit)
I am not sure I see the difference between different examples for local logistic regression in the documentation of the gold standard locfit package for R: http://cran.r-project.org/web/packages/locfit/locfit.pdf
I get starkingly different results with
fit2<-scb(closed_rule ~ lp(bl),deg=1,xlim=c(0,1),ev=lfgrid(100), family='binomial',alpha=cbind(0,0.3),kern="parm")

from
fit2<-scb(closed_rule ~ bl,deg=1,xlim=c(0,1),ev=lfgrid(100), family='binomial',alpha=cbind(0,0.3),kern="parm")

.
What is the nature of the difference? Maybe that can help me phrase which I wanted. I had in mind an index linear in bl within a logistic link function predicting the probability of closed_rule. The documentation of lp says that it fits a local polynomial -- which is great, but I thought that would happen even if I leave it out. And in any case, the documentation has examples for "local logistic regression" either way...
Comment: Please, don't cross-post. Choose one site once and for all. I will delete this one by the end of the week without action from your part.
Answer: The author of the locfit package, Catherine Loader, kindly answered my email. She says that instead of the alpha argument of scb, separate h and nn arguments need to go inside lp if I specify it within the formula for scb.
I could not get the code work that way though. And I am still unsure about why there should a difference from the case without specifying lp() and simply giving the alpha and deg arguments to the scb function.
And she also noted an important error my code as posted: with the 'parm' kernel, there is no local smoothing, but a parametric (in my case, logic) estimate.
Finally, note that the literature seems to suggest specifying type=4 as an argument for scb for logistic regressions.


How do I create an ideogram-based 'features' list on nodes?

Question: I'd like to create a simple checklist-style list on a node. How can I do this?
I presume CCK is involved. I'm thinking that it would follow some logic like this: the node editor checks applicable boxes for the relevant feaures. If a box is ticked, then an image is displayed in the list (and so on) on the node.
Answer: If you get a Drupal 6 specific answer, that's great, but in the meantime, I would suggest you look at this question. It involves Drupal 7, but the basic principal is the same. If I have had the experience of doing this in D6 I would have added the information to that question, but I have not.
Comment: Some time has passed since my question was posted and I've since upgraded to D7, so that link might be more relevant, thanks!
Answer: If you know a little PHP you can do this with Custom Formatters and/or Display Suite and/or Views PHP. Create the checklist with CCK, then when you render your image, load the node and see if the relevant checkbox is ticked. If it isn't just render an empty string.
http://drupal.org/project/custom_formatters
http://drupal.org/project/ds
http://drupal.org/project/views_php
Comment: Kk, well what you're asking is actually pretty easy if you get your PHP chops up a bit :) hang in there..
Comment: I don't know much about PHP, but I'll take a look and see what I can learn from those links, thanks.


Qual a função do set em associação de objetos?

Question: Não entendi exatamente para q serve o set na associação de objetos.
public class App {
    public static void main(String[] args) throws Exception {
        Local local = new Local("Rua das rosas");
        Aluno aluno = new Aluno(22, "Amarildo");
        Aluno[] alunos = {aluno};

        Professor professor = new Professor("Matusalem", "Retorica");

        Seminario seminario = new Seminario("Velhos e novos deuses", alunos, local);
        Seminario[] seminarios ={seminario};

        professor.setSeminario(seminarios); // Meu problema é especificamente a necessidade desse set

    }

}

Vi o uso dele em muitos códigos com relacionamento de objetos, a aplicação ficou meio vazia p mim.
Answer: Em específico parece que nada. Os tais métodos set e associar um objeto com outro não tem uma relação direta, mas em algumas situações a associação é feita, e é comum ser com um método deste tipo.
Não vou falar sobre esse método que costuma fazer par com método get porque tem uma quantidade imensa de respostas sobre o assunto para estudar com detalhes. Inclusive há quem fale que é comum as pessoas abusarem deles. Tem uma resposta com links.
Tome cuidado com exemplos, especialmente na internet, porque muitas vezes eles demonstram o mecanismo e não como deve fazer códigos reais. Ou até são feitos por alguém que aprendeu programar de forma errada, então se copiar também fará errado, até porque quando está começando você não sabe se a pessoa acertou ou não.
É muito comum que essa associação mostrada na pergunta esteja errada e é uso equivocado desse tipo de método.
Primeiro porque há um vazamento de abstração nesse código. E também porque o mais correto seria ter um método que faz a adição de um seminário no objeto de forma mais semântica e não tratar fora. Ou seja, esse set sequer deveria existir. Então deveria existir uma lista interna ao objeto que só ele sabe como lidar e expor apenas formas de por ou tirar seminários. O mesmo acontece com os alunos.
Note que, mesmo errado, há uma certa inconsistência. Por que em Seminarios há um construtor que já aceita os objetos que devem ser associados (e não sei se tem um método set para mudar essa associação) e em Professor não (parece) tem(r) isso e a forma de associar é um método set?
Segundo porque usando um array impede mudar sua composição sem criar um objeto novo.
De qualquer forma, usando errado mesmo, você associaria um objeto em outro sem usar um construtor? Tem formas, na verdade que não é bem como associar, e já passei links onde pode ver isso.
Outras linguagens podem possuir mecanismo que dispense o método set em específico, embora use o mesmo padrão de projeto.
Então entenda todos os mecanismos e como é a real aplicação deles, fugindo dos exemplos ingênuos, simplificados, ou até errados.


What's the difference between .env file and actual environment variable?

Question: Say I have some API-key in my project that I don't wanna share into git repository, then I have to use environment variables. Now, why shouldn't I blatantly set the environmental variable on my local machine (like PATH) instead of making .env file and downloading python-dotenv library to my project for the sake of doing actually the same thing?
Comment: Because `os.environ['API-KEY'] = 'stuff'` will be committed to VCS (exposing `stuff` to the world), unlike your `.env` file.
Comment: Because you would presumably check in that code to the repo, and "stuff" would be visible? Unless I'm misunderstanding the question.
Comment: You shouldn't do that because you explicitly said you don't want the secret to be in git...
Comment: I have to apologise, everyone. I thought that `os.environ['API-KEY'] = 'stuff'` would actually set the environment variable, so that it can be accessed anywhere, just like python PATH environment variable
Comment: You should set the variable in your shell login file.
Comment: I don't use linux, hence I can't set the variable in "shell login file" and it wasn't even mentioned
Answer: .env file is just manner to store this variables in file that can use packages for example dotenv to read as an os.environ varaible. so in short it is manner of storage of configuration.
many times your gitignore will have .env thus users can store the API key with .env file on local machine to help ease of use and ensuring dont accidently leave api keys within committed git files
if you just do a bear os.environ['API-KEY'] = 'stuff' within code it will store in commited git file (and env variables are there within a run of python process, not their permanently between sessions, thus why storing in file is preferred)
with this there are types of way to store configuration dynaconf is a great package and package shows many of the other types of configuration files
Comment: thanks, kamster, it provides some light. I asked the question in a wrong way, because I thought that `os.environ['API-KEY'] = 'stuff'` would store the `API-KEY` environment variable, just like, say, vscode path, so it can be accessed anywhere. And of course I didn't mean to write this line explicitly in the code.
You said that it is convenient for users to have their `.env` file - that's one advantage. Could You provide any more advantages?
Comment: so i guess my question for you would be what other options/ideas looking at? will help answer better and comparing what advantages something like `.env` can have


Equivalente ao operador condicional ou ternário no Kotlin

Question: Abaixo estou logando no monitor do Android Studio em JAVA uma curta frase usando operador condicional ou ternário (?)en. Vejam:
Log.wtf(GOT, (valirianSteel == 0 && glassOfDragon==0)  ? "Run!" : "Run too!");

O que seria equivalente ao operador condicional ou ternário no Kotlin?
Answer: Kotlin não possui operador ternário mas um if pode retornar um valor (ou seja é tratado como uma expressão) e funcionar da mesma maneira, com o detalhe é você é obrigado a ter um bloco else. Como consta na documentação:

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

Caso o algum dos blocos tenha mais de uma instrução a última será considerada o retorno.
Answer: Não existe expressões ternárias propriamente ditas em Kotlin (até a versão tual).
Creio que o mais próximo do ternário em Kotlin seria isso:
val max = if (a > b) a else b

Existem também outras  implementações descritas nessa pergunta do SOEN.
Answer: Em Kotlin se usa essas estruturas como expressões tb:
Log.wtf(GOT, if(valirianSteel == 0 && glassOfDragon==0) "Run!" else "Run too!");

Answer: Apenas para complementar, na versão 1.1 surgiu a extensão takeIf, que junto com o elvis operator (?:) pode contribuir nesse caso.
Sua expressão ficaria:
Log.wtf(GOT, "Run!".takeIf { valirianSteel == 0 && glassOfDragon==0 } ?: "Run too!")

É um pouco diferente do habitual caso esteja cansado do if/else padrão.


Why Azure SQL Managed Instance requires UDR 0.0.0.0/0 next hop type Internet

Question: One of the networking requirements for the Azure SQL Managed Instance is to have UDR 0.0.0.0/Next hop internet that enables access from the private subnet that belongs to Azure VNet and public internet.
Why is this required and what are the risks?
Answer: This rule was meant to simply override common BGP advertisements that could cause asymmetric routing and interfere with the management traffic.
In the case of BGP advertisement of more specific prefixes, this would not be enough to assure management traffic flow and you will need to define UDRs to override the advertised prefixes.
Note that 0.0.0.0/0 next hop type Internet rule don't routes all traffic to the Internet. The next hop is always another device – in this case Internet Gateway that is located inside Azure. It is called Internet Gateway as it handles routing to public Azure IP addresses. As these IP addresses mostly belong to Azure services collocated with Managed Instance the network traffic that always finds the shortest path stays inside the Azure.
Managed Instance needs public Internet access for certificate revocation verification and this is done over the public Internet. Certificate revocation information is made public so no secrets are sent or received that way. Certificate verification information is also signed, to prevent tempering.
You could set limited set of other UDRs besides 0.0.0.0 Next hop internet:

UDRs with private IP ranges* as destination without next hop
restrictions
UDRs with public IP range as destination if the next hop type is Internet

*exception is Managed Instance subnet destination that must have next hop type
Virtual network – otherwise the connections between the Managed Instances could be broken.

This constraint will be relaxed or removed in the future so always
  check the Azure SQL Managed Instance documentation for the update.


Calculate $\sum_{r=0}^n \cosh(\alpha+2r\beta)$

Question: I try to calculate $\sum_{r=0}^n\cos(\alpha+2r\beta)$ first to get some insights.
First we prove that $\sum_{r=0}^\infty\cos(\alpha+2r\beta)=0$. (The statement and the proof is flawed, I will edit it later.)
$Proof$: For $\sum_{r=0}^\infty\cos(\alpha+2r\beta)$ is the real part of $\sum_{r=0}^\infty\exp i(\alpha+2r\beta)$, and the latter (denoted by $X$), as addition of complex numbers, can be viewed as addition of vectors (of module 1), we have:
when $2\beta=2\pi/n$, $X$ equals to sum of vectors that corresponds to edges of a n-polygon, and so $X=0$;
when $2\beta\neq2\pi/n$, $2\pi/n = k\cdot2\beta+\rho$ where $0<\rho<2\beta$, and so by summing $k$ vectors we get a vector $z_{1,j_1}$, i.e. $\sum_{r=j_1}^{j_1+k-1}\exp i(\alpha+2r\beta)$, that is of smaller module and smaller 'phase shift', say $\beta_1$.
Then we have $2\pi/n = k_1\cdot2\beta_1+\rho_1$, and so by summing $k_1$ vectors we get a new vector $z_{2, j_2} = \sum_{r=j_2}^{j_2+k-1}z_{1,j_1}$, that is of smaller module and smaller 'phase shift', say $\beta_2$.
Repeating the process we will finally get smaller and smaller module and 'phase shift', the sequence of modules will tend to $0$ (the proof is left out), which completes the proof. $\blacksquare$
But I have no idea yet how to do similar things to $\sum_{r=0}^n\cosh(\alpha+2r\beta)$. The latter can be viewed as a component of $\sum_{r=0}^n e^{\alpha+2r\beta}$. But one cannot easily separate the former from the latter as we do above (for here is no clear distinction between components like one between real and imaginary parts). And the sum itself can't be calculated conveniently as sum of vectors.
So is this method workable for $\sum_{r=0}^n \cosh(\alpha+2r\beta)$? If not, can anyone just give me a hint about how to calculate it?
(Thanks for pointing out that the sum doesn't converge as $n\rightarrow\infty$.)
A graph representation:
https://www.desmos.com/calculator/nih1sg4fwm
Comment: Do you know that if $a_n$ doesn't converge to zero, then $\sum_0^{\infty}a_n$ doesn't converge?
Comment: Given that $\cosh x\geq 1$ for all $x,$ this doesn't seem to converge.
Answer: $$S_1=\sum_{r=0}^n e^{a+2 b r}=\frac{e^a \left(e^{2 b (n+1)}-1\right)}{e^{2 b}-1}$$
$$S_2=\sum_{r=0}^n e^{-(a+2 b r)}=\frac{e^{-(a+2 b n)}(e^{2 b (n+1)}-1)}{e^{2 b}-1}$$
$$\frac{S_1+S_2}2=\sum_{r=0}^n \cosh(a+2br)=\text{csch}(b) \sinh (b (n+1)) \cosh (a+b n)$$


What is the downside of ultra-low action?

Question: I understand that low action on a guitar makes it easier to play. (See answers to this question for more on action and truss rods).
I've never understood why all guitars aren't set-up with action as low as possible. What is the downside?
Answer: There are those of us out there who have a "heavy hand" when it comes to pick attack. The reasons for this are many. For example, I developed a heavy hand because I learned how to play on an acoustic guitar first--and I play expressively. Expressive players, the ubiquitous example of which is a blues player, need a little extra space to accomodate variations in pick attacks, clean bends, and vibratos. As I'm sure you can imagine, if every note was picked by the player at exactly the same strength--which translates to a human powered compressor--then your playing would sound very uniform and the tolerances in clearance for string vibration in relation to the frets would be predictable. Therefore, you could have uniform action that is as low as the particular guitar setup would allow. That's great if you're Eric Johnson, but what if you're after something more dynamic? Ask any blues player if dynamics lends itself to his art. That would be like asking a metal player if overdrive is of any use. I would argue that many, if not all, of the great musicians of our time see the worth in dynamics as well; which I argue is also illustrated by their use of tube amplifiers, but that is another discussion all together.
So, my take on this is that lighter action is a trade of which the other side not just buzz, but of playing dynamics. Speed demons (the best of which are metal, prog rock, or jazz players) tend to utilize very light action and consequently are forced to have a very light touch in order to sound clean and tidy. On the other hand more dynamic players (such as the aforementioned blues category) have more low to mid range action. No one in their right mind plays with high action unless they don't know any better or somehow derive pleasure from pieces of bare metal wire digging into their fingertips XD.
Comment: Mattias IA Eklundh plays with very high action - http://www.guitarplayer.com/article/86723 - but it is easy to argue that a man who transcribed his inkjet printer is not in his right mind.
Answer: The harder you play, the wider the string vibrates, the more likely that they will hit the strings, sounding clangy and robbing you of sustain and tone. Also, you can get your fingers under the other strings when you bend.
Answer: Right.  "Action" is always a compromise.  Playing ease and string buzz.  If you are a delicate and precise player, you can get away with a very low action.  If you like to "dig in" (as bluegrass players say), you'll need a bit more relief to avoid buzz.
Answer: I've noticed its much more problematic trying to play slide on a guitar with a low action. In fact I have an extra tele with a high action for my slide stuff.


Dynamic programming approach for multidimensional problem

Question: I use a dynamic programming approach to optimize the behaviour of individuals playing a game.I have one strategy matrix that describes the behaviour of individuals in situation 1, which depends on some state variables. Now suppose I would like to add a situation 2. Then I would basically two strategy matrices at the same time which I am trying to optimize. What algorithms I should use for this multidimensional optimization case and can you give me any references for examples?
Comment: This is a bit vague. Why can't you optimize the two situations individually?
Comment: For example (a very simplified version of my problem), individuals are building houses. You can either build house yourself or join another who is building a house. Every time step if you are a free individual (not building yourself or joined another) you can find another and decide if to join or not (depending on a quality of a house). Now I want to add another option that while you are in the group, you can either rest and survive with a high probability or work hard and risk dying. This is a frequency dependent game and it doesn't make any sense to optimize them individually?
Answer: Dynamic Programming can be set up in principle to deal with as large (high a dimension) state space as needed.  But there is something called the curse of dimensionality which strikes Dynamic Programming particularly hard as the dimension increases.
The key to Dynamic Programming is judicious definition of the state space. There is a large amount of intuition and art in that. So think through carefully what you need your state space to be.  If you have enough (correct) states, then it's straightforward to write out the optimization problems which have to be solved at each stage in the Dynamic Program. If you can't write out the optimization problem at each stage, it may indicate your state space is inadequate.  It may not be so straightforward to actually solve them quickly, however.
Generally state spaces which are just big enough are the best, although not necessarily. However, if you are having trouble, it may help if you start with a bigger than needed state space, and once you have that set up, see if you can be more clever and pare back the dimension of the state space.
I leave the definition of the state space as an exercise to you.


How to locate the source of a binding error?

Question: How can I figure out what line of xaml contains the troublesome binding When my debug output is full of lines like the following:
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='UW.Entities.ProgramModel.UWProgram' BindingExpression:Path=; DataItem='RuntimeType' (HashCode=24995901); target element is 'DataGridCollectionViewSource' (HashCode=60976864); target property is 'Source' (type 'Object')
I don't know how to interpret this in a way that can let me find the responsible line of xaml. I can't even figure out what xaml file the error is coming from. Is there some way to get more information when these errors occur?
'UW.Entities.ProgramModel.UWProgram' is just a type - I don't know what the object being bound to is. I also have lots of DataGridCollectionViewSources in various bits of xaml, all who's property 'Source' is bound to something which may or may not have that type (again - no easy way to tell).
Answer: If you do not know which binding fails
I would use the Snoop utility for this purposes. In short - at the top-left corner above the visual tree, you'll find a drop-down list which allows filtering visuals, just select Visuals with binding Error. See online documentation for more details.
If you know which binding fails
Sometime you know which binding fails but was not able to find a source fo the problem since binding is pretty tricky, for instance TemplateBindings, bindings which refer to a DataContext of another control, etc.. I found helpful putting a TextBlock which Text property is bound to the same binding source in this way you can see what exactly bound since TextBlock will display a type name of a bound object.
For instance you have following failed binding:
<ItemsControl ItemsSource="{Binding Parent.DataContext.ActiveItem.DataContext}" />

<TextBlock Text="{Binding Parent.DataContext}" />
<TextBlock Text="{Binding Parent.Inner.Items}" />
<TextBlock Text="{Binding Parent.Inner}" />

Useful links:

Debugging Data Bindings in a WPF or Silverlight Application
Nice trick using special DebugConverter which allows break a debugger whilst doing a binding, see Debugging WPF DataBinding article
Comment: For future readers, "Visuals with binding errors" option is in the top-*left* dropdown, not top-right, as of Snoop 2.8.
Comment: My personal experience is that Snoop promises much but can be a pile of crap at times. I certainly wouldn't depend on it. (nothing personal about your answer, just Snoop isn't reliable).
Comment: I'm going to have to mount a bit of a learning curve - but I can tell this took will be invaluable. Thanks.
Answer: I have been happily using the wonderful snippet from 'Switch on the Code' to detect and report binding errors since it was first published in 2009...
http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors
edit:  still works excellently on VS2012 (Sept 2013)
Update 25 Jan 2016
The link appears broken, so I'll paste in the relevant snippets...
using System.Diagnostics;
using System.Text;
using System.Windows;

namespace SOTC_BindingErrorTracer
{
    public class BindingErrorTraceListener : DefaultTraceListener
    {   //http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors
        private static BindingErrorTraceListener _Listener;
        public static void SetTrace()
        { SetTrace(SourceLevels.Error, TraceOptions.None); }
        public static void SetTrace(SourceLevels level, TraceOptions options)
        {
            if (_Listener == null)
            {
                _Listener = new BindingErrorTraceListener();
                PresentationTraceSources.DataBindingSource.Listeners.Add(_Listener);
            }
            _Listener.TraceOutputOptions = options;
            PresentationTraceSources.DataBindingSource.Switch.Level = level;
        }
        public static void CloseTrace()
        {
            if (_Listener == null)
            { return; }
            _Listener.Flush();
            _Listener.Close();
            PresentationTraceSources.DataBindingSource.Listeners.Remove(_Listener);
            _Listener = null;
        }
        private StringBuilder _Message = new StringBuilder();
        private BindingErrorTraceListener()
        { }
        public override void Write(string message)
        { _Message.Append(message); }
        public override void WriteLine(string message)
        {
            _Message.Append(message);

            var final = _Message.ToString();
            _Message.Length = 0;

            MessageBox.Show(final, "Binding Error", MessageBoxButton.OK,
              MessageBoxImage.Error);
        }
    }
}

And to set it up/initialize it...
namespace WpfListeningForTraceErrors
{
    ///
    /// Interaction logic for Window1.xaml
    ///
    public partial class Window1 : Window
    {
        public Window1()
        {
            BindingErrorTraceListener.SetTrace();
            InitializeComponent();
        }
    }
}

Comment: still doesn't tell me the filename or line number
Comment: This works utterly brilliantly. Still works excellently on VS2013 (Jan 2014).
Comment: It's nice to actually include the snippet, because now that link is broken and your answer just wastes peoples time.
Comment: If you have an app with many binding errors (which I suspect is how people came to this page) won't this just spam you with annoying message boxes?
Comment: This shows the exact same thing that's being written to the Output window in VS. Setting a breakpoint shows no useful stack trace. Rather useless...
Answer: You can add this to every control that binds
  PresentationTraceSources.TraceLevel="High"

And run the program in debug, the detailed  binding information will appear in your Output window.  It may help a bit.  You can also create a pass though converter to catch an error (catches the problem some times but not always).  There are no good tools for debugging XAML in general that I am aware of.
Answer: You can download a tool called Snoop that will allow you to debug bindings. It provides a view of your WPF applications visual tree higlighting any binding errors that it finds.
You can get some basic information about binding errors in the Output Window in Visual Studio. It will show the binding expression path error and the line on which the error occured.
Answer: In VisualStudio goto Tools->Extentions and Updates->(download Output Enhancer). When you build your solution you will get the exact kind of error message you posted in Red color if there is a binding error.


what are the azimuths of the different views of this object?

Question: I think azimuths are probably not a big deal but I've been trying to figure out how to calculate them and somehow I keep getting confused.
I have a few images of a vehicle from different angles. (Shown at the bottom of this post).
In layman's terms I can just say that:

image 1: view from the back of the car ($0^\circ$). we'll refer to this image in the other images below...
image 2: now the car has moved $45^\circ$ to the right from previous position, so it's a total of $45^\circ$ from image 1
image 3: now the car has moved $45^\circ$ to the right from previous position, and a total of $90^\circ$ from image 1
image 4: now the car has moved $45^\circ$ to the right from previous position, and a total of $135^\circ$ from image 1
image 5: now the car has moved $45^\circ$ to the right from previous position, and a total of $180^\circ$ from image 1

and so on...
Now, in the first image, the vehicle is pointing straight ahead (let's assume this is north). So if I assume it's pointing to north, then my question is, what are the "azimuths" for these angles? Will they simply be $0^\circ$, $45^\circ$, $90^\circ$, $135^\circ$, $180^\circ$, and so on?
Answer: First thing to notice: your text speaks of $30^\circ$ increments, but the pictures seem to be taken from angles differing by $45^\circ$, since the third picture is already a straight side view of the car.
Your question "what are the "azimuths" for these angles" is confusing (or confused?). An azimuth is an angle, usually the angle between due north and the direction of some imagined ray, e.g. the ray along which a person is looking. I assume you want the azimuth of the direction where the camera is pointing.
That would indeed change in $45^\circ$ increments (or $30^\circ$ if you go by the text not the pictures), starting at $0^\circ$ since it started out pointing north. The only thing that remains is getting the sign straight. Usually you have azimuth increasing from north to east, with $90^\circ$ corresponding to due east, so if you move around your car in a clockwise fashion, your viewing azimuth would increase. Your sequence however is counter-clockwise, therefore you'd have azimuths $0^\circ, -45^\circ, -90^\circ$ and so on, or equivalently $0^\circ, 315^\circ, 270^\circ, \dots$.
Comment: thanks! yes that was a mistake, it should have said it's incrementing by 45 degrees, not 30.


Number of equivalence classes of matrices under switching rows and columns

Question: I have been thinking about this problem:
Suppose we have all $R$ by $C$ matrices, where the values are integers in $[1,n]$. Two matrices are equivalent under interchanging rows and columns. For example,
1 5
0 0

would be equal to itself and to
0 0
1 5

and would be equal to
0 0
5 1

and would be equal to
5 1
0 0

How many unique such matrices are there?
Any ideas how to go about it?
Any help much appreciated!
Comment: Burnside's theorem gives us a summation formula. It gets quite messy though when we start trying to compute $X^g$, the number of matrices fixed by some permutation $g$ of the rows and columns.
Answer: NOTE: In this answer, I give an explanation of how Burnside's Lemma can solve the question, but I do not arrive at any simplification. Hence, it may not be an ideal answer right now, but I expect some simplification is possible and maybe someone else can see where to go next. Anyway, I do the example of $2 \times 2$ matrices at the end.

We may apply Burnside's Lemma.
Let $G = S_R \times S_C$, where $S_k$ is the symmetric group.
$G$ acts on the set $X$ of $R \times C$ integer matrices where the entries are between $1$ and $n$, where $S_R$ permutes the rows and $S_C$ permutes the columns.
The number of non-equivalent matrices (equivalence classes of matrices, rather) is equal to the number of distinct orbits of this group action.
Burnside's Lemma gives us that this equals
\begin{align*}
\frac{1}{|G|}
\sum_{g \in G} |X^g|
&= \frac{1}{R! C!} \sum_{\sigma \in S_R}\sum_{\tau \in S_C} |X^{(\sigma, \tau)}|.
\end{align*}
What is $|X^{(\sigma, \tau)}|$? It is the number of matrices which are unchanged under applying permutation $\sigma$ to the rows and permutation $\tau$ to the columns.
Let's say $\sigma$ groups $1, 2, 3, \ldots, R$ into cycles of size $c_1, c_2, \ldots c_l$, with $c_1 + c_2 + \cdots + c_l = R$, and similarly $\tau$ groups $1, 2, 3, \ldots, C$ into cycles of size $d_1, d_2, \ldots, d_m$ with $d_1 + d_2 + \cdots + d_m = C$.
Now the set of entries $R \times C$ splits into $lm$ blocks, where each block $(i,j)$ is the entries of cycle $c_i$ cross the entries of cycle $d_j$. This block $(i,j)$ has $c_i d_j$ elements, and in the combined group action of $(\sigma, \tau)$ that block splits into $\gcd(c_i, d_j)$ distinct cycles. All the elements of one of these cycles must be the same in the matrix. In total we have that
$$
|X^{(\sigma, \tau)}| = \prod_{i, j} n^{\gcd(c_i, d_j)}.
$$
I suspect it can be further simplified, but I don't know how right now.

Example: $\boldsymbol{2 \times 2}$ matrices
To check, let's do the example of $2 \times 2$ matrices. $S_2$ has only two elements, which we call $e$ and $\rho$ ($\rho$ switches the two rows or columns, $e$ leaves them the same.)
We have
\begin{align*}
X^{(e,e)} &= \prod_{i=1}^2 \prod_{j=1}^2 n^{\gcd(1,1)} = n^4 \\
X^{(e,\rho)} &= \prod_{i=1}^2 n^{\gcd(1,2)} = n^2 \\
X^{(\rho,e)} &= \prod_{j=1}^2 n^{\gcd(2,1)} = n^2 \\
X^{(\rho,\rho)} &= n^{\gcd(2,2)} = n^2
\end{align*}
So our answer is
$$
\frac{1}{4} (n^4 + n^2 + n^2 + n^2)
= \frac{n^4 + 3n^2}{4}.
$$
For example, if $n = 1$ there is only one matrix, $\begin{bmatrix}1&1\\1&1\end{bmatrix}$.
For $n = 2$, the above formula gives
$\frac{16 + 12}{4} = 7$, so there are $7$ matrices. Indeed, these are
$$
\begin{bmatrix}1&1\\1&1\end{bmatrix},
\begin{bmatrix}2&1\\1&1\end{bmatrix},
\begin{bmatrix}2&2\\1&1\end{bmatrix},
\begin{bmatrix}2&1\\2&1\end{bmatrix},
\begin{bmatrix}2&1\\1&2\end{bmatrix},
\begin{bmatrix}2&2\\2&1\end{bmatrix},
\begin{bmatrix}2&2\\2&2\end{bmatrix}.
$$
Comment: I think it is $d_m$ and not $d_l$
Comment: @RattusRattus Yes, thanks for the correction.
Answer: Here goes an idea (it is not a complete answer but it is too long to go in the comments box): Note that if $K=\begin{pmatrix}0&1\\1&0\end{pmatrix}$ and $M$ is any $2\times2$ matrix then $KM$ correspond to interchange two rows and $MK$ correspond to interchange two columns. Also note that $K^2=I_2$, so the only possible matrices equivalent to $M$ are $M, KM, MK$ and $KMK$. Let $E(M)=\{M,KM,MK,KMK\}$ be the set of matrices equivalent to $M$.
For any $M$ we have two possible options, $KM=MK$ or $KM\neq MK$. In the first case we have $E(M)=\{M,KM\}$ (check that $KMK=M$) and if $M=\begin{pmatrix}a&b\\c&d\end{pmatrix}$, neccesarily $a=d$ and $b=c$, i.e., if $KM=MK$ then $M=\begin{pmatrix}a&b\\b&a\end{pmatrix}$. We have then $n^2$ matrices distributed in sets of 2 elements, so we have $n^2/2$ unique matrices (up to equivalence).
If $KM\neq MK$ we have 3 options (1 and 2 are easy to check but 3 is a little bit problematic)

$E(M)=\{M,KM\}\iff M=\begin{pmatrix}a&a\\b&b\end{pmatrix}$ with $a\neq b$ (so we have $n(n-1)/2$ unique matrices)
$E(M)=\{M,MK\}\iff M=\begin{pmatrix}a&b\\a&b\end{pmatrix}$ with $a\neq b$ (so we have again $n(n-1)/2$ unique matrices)
$E(M)=\{M,KM,KM,KMK\}\iff M=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ with $\cdots$ (if you find a characterization of such matrices, and you find out that there are $N$ of them, then the total number of unique matrices would be $n^2+n(n-1)+N/4$).

This approaching comes from someone with zero experience in combinatorics, so probably there are some mistakes, or better methods to compute such things.
Answer: Burnside's Lemma is probably the right way to approach this problem in general. The idea is to define a group $G$ which corresponds to your combined actions on the set of matrices $M$ of swapping columns or rows; then to think of the equivalence classes of matrices as being orbits, which Burnsides Lemma allows us to count by counting, for each $g \in G$, the number of elements of $M$ which are left unchanged by $g$.
The $2\times 2$ case is simple enough to look at by cases. First, let's think about what the group $G$ looks like in this situation. Let $c \in G$ be the action of swapping columns, and $r \in G$ be the action of swapping rows. Taking $e$ to be 'the action of doing nothing', it's clear that $c^2 = r^2 = e$. Let's call $d = rc$ (i.e., swap rows then columns, which swaps both the diagonal elements). It should be clear that $d = cr$ and $d^2 = e$ as well.
So $G$ has $4$ elements: $\{e, c, r, d\}$ (this is also known as the Klein Group).
You want to count the distinct equivalence classes (a.k.a 'orbits') where $m_1 \sim m_2$ iff $\exists g \in G$ s.t. $g(m_1) = m_2$.
To use Burnside's Lemma, we want to first define, for $g \in G$, $M^g = \{m \in M : g(m) = m\}$; which is to say that $M^g$ is the set of elements of $M$ which are not changed by the element $g$.
It's pretty easy to see that:
$$M^e = M$$
$$M^r = \{m \in M : m_{1,1} = m_{2,1};  m_{1,2} = m_{2,2}\}$$
$$M^c = \{m \in M : m_{1,1} = m_{1,2};  m_{2,1} = m_{2,2}\}$$
$$M^d = \{m \in M : m_{1,1} = m_{2,2};  m_{1,2} = m_{2,1}\}$$
Burnside's Lemma says, where $|M/G|$ is the number of orbits:
$$|M/G| = \frac{1}{|G|}\sum_{g \in G}|M^g|$$
We can see that in your $2\times 2$ example:
$$|M^e| = n^4$$
$$|M^r| = |M^c| = |M^d| = n^2$$
so we get
$$|M/G| = \frac{n^2(n^2+3)}{4}$$