Reordenar barras no ggplot2 de acordo com uma das variáveis de preenchimento (fill)

Question: Olá,
Tenho um gráfico que mostra a proporção de equipamentos disponíveis nas escolas de Pernambuco, e gostaria de ordena-lo dos equipamentos com maior presença (maior possui) para os com menor presença:

Atualmente o meu código está assim:
df %>%
  ggplot(aes(x=equipamento ,y=perc, fill=situacao), arrange(situacao)) +
  geom_col() +
  ggtitle("Percentual de creches que atendem aos parâmetros do CAQi") +
  theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1))

Dada a disposição dos meus dados, não sei se é possível reordenar usando factor:

Agradeço a ajuda!
Comment: `dput(df)`, por favor.
Answer: Use a função fct_reorder do pacote forcats para isso.
df %>%
  mutate(equipamento, = fct_reorder(equipamento, perc)) %>%
  ggplot(aes(x=equipamento ,y=perc, fill=situacao), arrange(situacao)) +
  geom_col() +
  ggtitle("Percentual de creches que atendem aos parâmetros do CAQi") +
  theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1))

Comment: Guilherme, é quase isso. o `fct_reorder` reordenou pelo maior percentual, dessa forma a cozinha ficou em primeiro mas o restante ficou em ordem crescente de não possui (porque são os maiores percentuais), e o que eu gostaria é que ficasse em ordem decrescente de "possui" .
Answer: Porque não utilizar o fct_reorder2? Com isso, você pode ordenar as duas variáveis de preferência.
df %>%
 mutate(equipamento = fct_reorder2(equipamento,situacao, perc)) %>%
  ggplot(aes(x=equipamento ,y=perc, fill=situacao), arrange(situacao)) +
  geom_col() +
  ggtitle("Percentual de creches que atendem aos parâmetros do CAQi") +
  theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1))


Método Uppercase para Metroframework

Question:
Preciso de ajuda em TextBox, onde trabalho em c# usando Metroframework.
Preciso transformar todo o texto digitado nos TextBox em letras maiúsculas. Como posso fazer?
Comment: Já tentou usar o método `.ToUpper()` ?
Comment: Entao para todos os textbox eu uso esse metodo ?!
Comment: Mais uma coisa...onde eu incluo esse metodo no meu form ? Desculpe , sou novo em c#
Comment: quero que todos os dados inclusos no formulario de cadastro , por exemplo " cadastro de clientes" ja aparecem maiusculos , quando forem digitados nos textbox
Comment: ou seja, que apareçam no textbox ja maiúsculas
Comment: Sim, estou usando WinForms
Comment: @RennanHanna, Atualizei minha resposta.
Answer: Se o Framework fosse para Xaml/WPF:
No Xaml de onde está o botão, existe a propriedade CharacterCasing que aceita os seguintes valores: Upper, Lower e Normal.
Setando esta propriedade ao botão diretamente no xaml
<TextBox  CharacterCasing="Upper" />

No momento que o usuário for digitar, as letras já apareceram em maiúsculo.
E quando você for recuperar o valor do TextBox no codebehind ele já vira em maiúsculo.
Outra maneira de setar seria no codebehind:
public MainWindow()
{
    InitializeComponent();
    NomeTextBox.CharacterCasing = CharacterCasing.Upper;
}

O MetroFrameWorkrealmente não suporta essa propriedade. Então vão algumas sugestões:
1 - Você pode usar o ToUpper(), para colocar as letras em maiúsculas antes de jogar os dados para o BD.
2 - Comece usar WPF, é mais avançado em relação ao WinForms, e te da mais liberdade para criar. Site recomendado para começar.
3 - No visual studio 2015, você pode criar apps/programas com estilo metro já por padrão, dispensando uso de frameworks.  - Noticia falando sobre isso.
4 - FrameWork para ´WPF´ Mahapps.
5 - Não sei o seu nível de conhecimento, mas se estiver começando, aprenda como funciona para depois usar frameworks, e comece por WPF, pois a própria microsoft recomenda o uso, pois WinForms está ficando para trás.
Comment: Pois é , justamente! Não existe CharacterCasing nas propriedades, por eu estar desenvolvendo em Metaframework.
Comment: Qual a diferença entre winforms e wfp MeuChapeu?
Comment: @RennanHanna, de uma lida neste [Artigo](http://blog.lambda3.com.br/2010/01/wpf-ou-windows-forms/) do site Lambda3. Ele explica bem certinho, é de 2010, mas tah valendo.
Comment: vou verificar , muito obrigado MeuChapeu
Answer: Para facilitar a vida e não ter necessidade de criar o método em todas os Forms, você pode criar um novo controle que herda desse TextBox que está utilizando e nele você inclui o método indicado na resposta do nosso amigo jbueno.
Exemplo:
class TextBoxEx : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);

        if (char.IsLetter(e.KeyChar))
            e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper());
    }
}

Answer: Uma alternativa é alterar o evento KeyPress do teu TextBox para transformar todas as letras em maiúsculas.
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsLetter(e.KeyChar))
        e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper());
}

Talvez o mais viável no teu caso, seria criar um novo componente que herde o MetroTextBox, ai tu podes sobrescrever (override) essa função e, inclusive, criar uma propriedade com o mesmo intuito de CharacterCasing para que seja possível escolher na property window se tu queres que ele seja case sensitive ou não.
Comment: Que complicação, mas, por mais que seja demorado , vou ter que fazer um por  um em todos os textbox de todos os forms, pois nao sei fazer isso que sugeriu ! rs
Comment: Se tu der uma pesquisada por `UserControl` ou componentes personalizados tu vais achar **muito** material.
Comment: Vou procurar , valeu Jeferson

Método Uppercase para Metroframework


Configuration syncronization not importing everything

Question: I have a remote server which I initially setup with a default Drupal 8.7.7 install.  I have since been building the site on my local development server and would now like to transfer the developments to the remote server.
I exported the configuration using drush config:export
I committed the the exported items to git and pushed them to the remote server.  I then ran composer install --no-dev followed by drush updb on the remote server and logged in.
I then went to the configuration synchronization setting and clicked on the import all button.
Everything seems to be working fine however 12 items will not sync.  I have tried importing them via the import -> single item option and tried importing everything via drush cim, however the following items still will not sync and show no errors:

I have repeated the process a number of times to check it wasn't a one off error.
The only similarity I can see is that they are all core.entity_view_display settings apart from the one core.entity_form_display item.  Each one has different differences.
How can I debug why these items won't syncronize?
Answer: It appears as though the issue I had relates to this issue: Display mode configurations don't get updated with new fields https://www.drupal.org/project/drupal/issues/2915036
I haven't tried the patch yet, but after saving the individual display modes the fields then get put into the export and sync properly.


print many values by a loop in java

Question: public class teste {

public static void main(String[] args) {
    int t1=5;
    int t2=10;
    int t3=30;

    for(int i=1;i<4;i++)
    {
        System.out.println("t"+i);
    }

}}

Hi guys I don't know if it exists in java but I wanna print t1 t2 t3 by a loop, for example for i=1 t(i=1) => t1 so it will give us 5, how can I do that, and thank you all.
Comment: You want to use an array. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Comment: You need to create an array like: `int[] t = {5. 10, 30, etc..}`
Comment: Relevant: https://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java
Comment: thanks I'm convinced
Answer: 3 variables mean three atomic statements are required but to access them in continuous way , collect them in some container like array so use
int t1=5;
int t2=10;
int t3=30;
int[] arr = {t1,t2,t3}; // array index start from 0
//           0  1  2
// arr[0] is 5
// arr[1] is 10 and so on

for(int i=0;i<3;i++)
{
    System.out.println(arr[i]);
}

Other option: use var args which is still sort of an array but flexible like
static void printNums(int... arr){
    for(int i=0;i<arr.length;i++)
    {
        System.out.println(arr[i]);
    }
}

and call it like
printNums(t1,t2);
printNums(t1,t2,t3);
printNums(1,2,3,4,5,6);

Comment: I know this method but I'm looking for others thank you
Comment: @AyoubEloumari what makes you think there are others?
Answer: There is no way to call a variable using String or int or whatever
But that's the purpose of arrays, first index is 0 and last one is length-1 (here 2)
int[] t = new int[]{5, 10, 30};

for(int i=0 ; i<t.length ; i++){
    System.out.println(t[i]);
}
// gives
5
10
30

Comment: @AyoubEloumari others ? With which specificities ?
Comment: I know this method but I'm looking for others thank you
Comment: like I told in the question above and also it exists in php
Comment: @AyoubEloumari Java is not PHP (thank the maker). There is no reason to assume that features in one language would exist in another.
Comment: @AyoubEloumari curious to know how PHP does that
Answer: The for loop will only print the values t1, t2,t3 only because you initialized the t1 as a variable and in your output you using it as a text by including quotation marks.
Try this code.
public class test
{
    public static void main(String[] args) {
        int [] arrValue = {5 , 10 , 30};

        for(int i= 0; i <4; i++)
        {
            System.out.println("t"+i + "=" + arrValue[i]);
        }
    }
}

Comment: Same answer as mine + will throw ArrayOutOfBoundsException ^^
Answer: Can "t" + i be considered a key (instead of a dynamic variable name which is not supported)?  If that fits the context then a Map could be used.  For example:
public static void main(String[] args) {
    Map<String, Integer> tVals = new HashMap<>();
    tVals.put("t1", 5);
    tVals.put("t2", 10);
    tVals.put("t3", 30);

    for (int i = 1; i < 4; i++) {
        System.out.println(tVals.get("t" + i));
    }
}

Answer: Please tell me if I don't understand your question.
What you seem to be trying is to print t1 t2 and t3, but based on the i of the for loop right? So you think that t + i should first be t1, then t2 then t3 and finally output those values. That doesn't work for any language this way. First of all, t is a char, while 1 2 or 3 is an integer. Secondly, if you put it like that in System.out.println it basically means "print out t and then i", instead of "print out what t+i would be (as initialized)". I might not be very clear with explaining. Anyway, you should use an array.
Try the following:
class test{

    public static void main(String[] args) {

        int[] anArray = {
        5, 10, 30,
    };

        for(int i = 0; i < anArray.length; i++)
        {
            System.out.println(anArray[i]);

        }
    }

}

Comment: I wrote this when nobody answered, i cant really do smth about the fact that everyone reacted at the same time. Secondly, this code is correct idk what ur talking about? Maybe learn java be4 talking
Also, some people's codes would give out of bound exception, mine doesnt

print many values by a loop in java


Profiling Webworkers in Firefox

Question: I am trying to profile a Javascript app with Firefox Quantum. The part that I am most interested in runs inside webworkers. I am not sure if I am doing everything correctly, but I cannot find a way to get any useful data with the built in profiler. All I can see is this:

Is there a hidden feature that can help me look inside the webworker?
Answer: For anyone else finding this in the future: https://profiler.firefox.com/ is able to profile Web Workers.
You need to open the Resources drop-down and choose Thread: DOM Worker.
Answer: After further looking into this I came to the conclusion that Firefox does not support runtime analysis for web workers at the moment. I will have stick with Chrome for profiling our app.

Profiling Webworkers in Firefox


Javascript object property inaccessible from another property (function)

Question: Quick question, why does my reference to weekdays inside change_date() give weekdays is undefined error in Firebug?
I also tried this.weekdays, same.
How do I correct this?
var timesheet_common = {

    weekdays : ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],

    change_date: function() {
        $('#text_input').val( weekdays[(new Date()).getDay()] );
    }

};

Comment: Maybe you changed the wrong `weekdays`. Only the `weekdays` inside the function should be `this.weekdays`.
Comment: How are you calling change_date? If you are attaching it to an event handler, the this keyword may refer to the object that is firing the event.
Comment: Alex M., you're right. I'm using `$('#selected_date').datepicker({'onSelect':this.change_date});`
Comment: I'm wondering why the `this.change_date` works, but `this.weekdays` doesn't.
Comment: casablanca, yes I did `$('#text_input').val( this.weekdays[(new Date()).getDay()] );`
Comment: so Alex M., the best way around this is just to use `timesheet_common.weekdays`, right?
Comment: @Obay -`$('#selected_date').datepicker({'onSelect':this.change_date});` will not work as `this` refers to the associated input field inside of the `onSelect` function - http://jqueryui.com/demos/datepicker/ click on the events tab and check out the `onSelect` documentation
Comment: @Obay: I didn't realize you were using `change_date` as an event handler. Event handlers and object methods don't play very well, for the reasons that Alex/Russ mentioned. You really don't need an object in this case then. Can't you just make `change_date` an ordinary function and define `weekdays` inside the function?
Comment: Did you try Marek Kowalski solution? I had some problems like this, too, and they were just matter of scope.
Answer: Use this.weekdays because it's an object.
Edit: I tried with this and it worked for me.
Comment: i get 'this.weekdays is undefined'
Comment: run in Firebug -
`var timesheet_common = { weekdays : ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],change_date: function() {console.log(this.weekdays);}};timesheet_common.change_date();`
Comment: The exact code above, when run in Firebug says `undefined`? Hmm, that sounds like there's something wrong with your Firebug then :) The function context of the anonymous function assigned to the `change_date` property in the given code is the object literal to which the property belongs. What does it say if you replace `this.weekdays` with `this`?
Comment: @Obay Don't confuse the return value with the log message (ie in Chrome Dev Tools). It definitely works.
Answer: In JavaScript the function is not associated with its model. You might do sth like this:
var timesheet_common = (function(){

    var weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

    var change_date = function() {
        $('#text_input').val( weekdays[(new Date()).getDay()] );
    };

    return { weekdays: weekdays, change_date: change_date }

})();

Answer: function TimesheetCommon(){
    this.weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
}
TimesheetCommon.prototype.change_date = function(){
     $('#text_input').val( this.weekdays[(new Date()).getDay()] );
}

var timesheet_common = new TimesheetCommon();

Comment: wow i didn't know you could make objects like that in javascript. what's happening here? how come you can already call a `new` on TimesheetCommon? which part of that code turned TimesheetCommon into an object that is `new`-able?
Comment: Every function creates an object when called with new. Add methods to the prototype property as shown above.
Answer: There are two problems with your code:

Inside change_date() you should refer to weekdays as this.weekdays, because they're both defined in the same object.
When you use change_date() as a click handler, you must use $.proxy(timesheet_common, 'change_date') instead; doing this makes sure change_date() is called within the context of timesheet_common rather than the clicked element.


Exception when access inner class reflectively

Question: Here is a sample program tested in Java 1.5.
I wonder why the two approaches below have different result. Is it a bug or a kind of Java feature?
package test;

public class TestOut {
    public static void main(String[] args) {
        // works
        new TestIn();

        // throws IllegalAccessException
        Class.forName("test.TestOut$TestIn").newInstance();
    }

    private static class TestIn {
    }
}

Answer: The class is private, hence the IllegalAccessException - you can use:
Class cls = Class.forName(...);
Constructor c = cls.getDeclaredConstructors()[0];
c.setAccessible(true);
c.newInstance();

For the record, the exception has a message, which is quite descriptive. Next time don't omit such information from the question. (actually, I'm not sure this message exists on Java 1.5, does it?)

Class test.Test can not access a member of class test.TestOut$TestIn with modifiers "private"

The problem lies in the verifyMemberAccess(..) method of sun.reflect.Reflection, and that it doesn't take into account enclosing classes. If a member (constructor) is private, access is denied.
Comment: How come explicit `new` works even if it's `private`, though?
Comment: @MikeJiang, @polygenelubricants - see my update. The problem is actually elsewhere ;)
Comment: I was about to file a bug, but there is a bug in the password reset option of sun.com. I reported it, so first they'd have to resolve it, and then I'll be able to file the real bug ;)
Comment: I think because reflection eliminates the context, and the context is that the inner class belongs to the outer. The Class object itself retains the reference to the enclosing class, but the Constructor doesn't.
Comment: 3x,Bozho. the "context" is what I am really wondering. IMHO, the Constructor should have enough information to know the enclsong class, and there seems no good reason to implement it in this way.
Answer: This is Bug ID 4221909:

Synopsys: (reflect) Class.newInstance() throws IllegalAccessErrorException when the class has an inner non-public class
State: 6-Fix Understood,   bug
Priority: 4-Low
Submit Date: 19-MAR-1999


Finding $P\{N(s) = k\,|\,N(t) = n\}$

Question:
For a Poisson process with rate $λ$, find $P\{N(s) = k\,|\,N(t) = n\}$ when $s < t$.

My work:
$N(s)\cap N(t)=k$ since $s<t$, thus
 $$P\{N(s) = k\,|\,N(t) = n\}=\frac{P\{N(s) = k, N(t) = n\}}{P\{N(t) = n\}}=\frac{P\{N(s) = k\}}{P\{N(t) = n\}}=\frac{e^{-\lambda}\lambda^k/k!}{e^{-\lambda}\lambda^n/n!}=\frac{n!}{k!}\lambda^{k-n}$$
Is this correct?
Comment: $N_s$ and $N_t$ are numbers, so their intersection is meaningless. On the other hand, use $N$ has independent increments and write $N_t = (N_t - N_s) + N_s.$ The rest should be easy.
Answer: Note that $$P(N(s)=k, N(t)=n) \ne P(N(s)=k)$$
For the numerator, we have
\begin{align}P(N(s)=k, N(t)=n)& =P(N(s)=k, N(t)-N(s)=n-k) \\& = P(N(s)=k)P( N(t)-N(s)=n-k)\\
&= P(N(s)=k)P( N(t-s)=n-k)\\\end{align}

Finding $P\{N(s) = k\,|\,N(t) = n\}$


Electric guitar tuning changes in different holding positions

Question: While trying to correctly intonate guitar(which was problematic, you can see my last question why), I noticed a strange thing and I don't really know if it is normal or not. I've searched about it everywhere and found nothing, so I hope you can help me.
I was fretting 12th fret to check my intonation(But it does this not only on 12th fret, even on open string) and was looking at the tuner same time. I felt that I held my guitar in a bad position(it was slipping) and I corrected it and suddenly there was a different reading on my tuner. Then I did this test: I held my guitar in normal position(not classical) and started to angle it towards the floor while plucking the string and the note was getting flatter. Then I did the same but tilted it towards the ceiling and note got sharper. So my tuning depends on the position the guitar is held and even a little tilt changes it.
What can be cause of this and is it just my problem or guitars do that in general? (I don't have any other electrics to test this)
Edit: I made a video demonstration here (youtube)
Comment: Looking back at you last question, where you swapped a shim - could be that the neck isn't tight.
Comment: It does this on the open string as well. So I don't think that's a problem.
Comment: And you are playing with an amplifier?
Comment: I don't think that it's the position of the guitar in the room. It must be the angle of your finger that changes the tension of the strings when you turn your guitar upside down.
Comment: I'm directly plugged into an audio interface, going into logic pro's tuner. as far as i can hear, it does this while unplugged as well. As for the shim, it did this even before the shim.
Comment: Is your guitar equipped with a tremolo (i.e., vibrato) bar? Because intonation definitely can shift some depending on how the guitar is angled, especially if it is a floating tremolo (pitch goes both up and down). The weight of the bar and bridge is not insignificant compared to the spring tension and will move a bit, depending on how it is adjusted (how many springs, spring tension etc).
Comment: @Johan Yes, it has a fender style tremolo, but I have locked it long ago
Answer: The neck of your guitar is not perfectly rigid, but it bends.
Another possible factor is how well is the neck screwed into the body. If it's even a little loose, it could affect the tuning.
When you put it face down, gravity pulls it down, increasing the curvature of the neck, shortening the distance from bridge to nut and decreasing the tension of the strings. With looser strings the pitch goes down.
And when you put it face up, gravity pulls the neck straighter, increasing the distance between nut and bridge and increasing the tension of the strings. With the strings being pulled harder the pitch goes up.
In intermediate positions, depending on where the force of gravity pulls the neck, you get intermediate levels of string tension and therefore of pitch.
People sometimes grab the headstock with one hand while playing, and push it back and forth to do a tremolo effect. Jimi Hendrix was famous for that, among many others. That's based on the same principle.
Now, this happens to every instrument, but if the neck is rigid enough, the effect is negligible.
Perhaps you can make things better by slightly tightening the truss rod. If the truss rod is too loose, tightening it a bit will not change much the curvature of the neck, but will make it more rigid, and therefore more resistant to these changes in pitch.
And you should also check to make sure that the screws that fasten the neck to the body are holding strong.
(Here's an example of neck bending if the above description wasn't clear enough)
Comment: Well... This guitar had a lot of problems and somehow managed to fixed most of them. I don't think this is fixable. I'll just have to play in the same exact position every time. I'm using 11 gauge strings btw. In E Standard tuning. I've been trying to get a new guitar, but I can't at this time. Either that or I'll go to moon and play there without gravity haha.
Comment: Yes, i have seen many times how Hendrix does this. I've done it myself also, but i don't think this level of pitch shifting is normal. What you said makes a lot of sense, but Truss rod is as tight as it gets, it's just won't turn anymore without a very significant force and I'm afraid that will break it. (Why is it so tight you might ask? Because neck was curved and that was the only way to make it straighter)
Comment: It looks like that guitar's neck is a bit too flexible than it should . It could be just that it came from a piece of wood that it happened to be more flexible than average. And the fact that the neck was so curved that you had to tighten the truss rod all the way just to make it straight, that's consistent with the idea of the wood itself being not rigid enough to start with. The only other thing that I can think of is that the neck might be bolted to the body in a loose way -- i.e. besides the neck itself bending, the connection to the body should be tightened too.
Comment: It's a maple neck with a rosewood fretboard. But the guitar is like 18 years old, so that might be the cause of the flexible wood. I have bolted the neck to the body as hard as I could, but I will still check if it can be tightened more.
Comment: I don't think that age alone causes this. Wood from one tree can be different from another, age differently, react differently to humidity and temperature over the years. Maybe you just got a guitar where the fretboard woods are more flexible than average. And maybe the installation of the truss rod was also slightly defective, and it didn't strengthen and stiffen the neck as much as it should have. It's probably a combination of all these factors, who knows which more and which less. When I've had guitars like that, I tuned them in the same position in which I played them, and it was OK...
Comment: From the video, it seems like gravity might be more of the culprit than you think :-)  That, and maybe even the gauge of string you're using - if there's a lot of heft in the string, gravity is going to affect it more as it dips (and gets *captured*) into and out of the pickup's magnetic field


Making note longer at end of measure

Question: I have the following notes.

They are four notes lasting 1 time unit on a 4 time units measure on a staff.
Now, I want the last note to last two units, but I cannot convert it to a note with an empty circle because it's at the end of a measure on the staff (and it's not possible to have a note that crosses the line).
So, if, it is possible to do this, then how do I do this (how can I write the notes so that beats lasting 1,1,1,2 time units are played consecutively)?
Thanks.
Comment: The usual name for "time unit" is "beat."  The note that has an open notehead and a stem is called a "half note" or a "minim."  Most notation software will, if you put a half note on the last beat here, automatically convert it to two quarter notes with a tie.
Answer: Two, possibly three ways.
Use a tie which ties the last note to one exactly the same at the beginning of the next bar. That will mean the note lasts for two beats.
Change the time signature to 5/4, which gives room for a two beat note as the last in that bar.
Use a pause mark, or fermata - the dot with an eyebrow -  which elongates the last note - although for exactly how long is up to the discretion of the player.
Comment: For the third idea, you might mention "fermata", which is where my mind went first
Answer: Use a "tie". The purpose of a tie is to extend the length of a note, producing the duration of the two notes together. A tie is a curved line from one note, across the bar line in this case, to the adjacent note of the same pitch.

Although it's a convention not strictly followed, a tie should be placed between the notes, as opposed to connecting the tops of the notes. The above image (rendered via ABCjs) is typical, but the below image (from Wikipedia) is more correct.

Slurs are also curved lines that closely resemble ties. Slurs however, have a different meaning — either to play the underlying notes smoothly, or as an indication of a phrase (like a musical punctuation mark).
The below is not a tie, because the connected notes are not adjacent. (It's a slur: for example, see In Chopin Marche funèbre, measure 19, on right hand, is the A flat played once or three times?)

The below is also not a tie, because the connect notes are not identical. (This is also a slur.)
Comment: @Tim try a hard refresh of the page
Comment: @Tim a hard refresh of the page only helps, at least on my mobile browser, if I first request the desktop version of the page.  Without doing so, I see only musical nonsense.
Comment: The "intelligent" notation features on this site are broken and should not be used, they cause more harm than good. Even if they work now, on some computer, they may not work on other computers tomorrow, and when they break there's probably nobody to fix it. Here's what it looks like on a phone, and nothing helps https://i.imgur.com/FnT1Hrp.jpg   Use regular pictures, they work without troubleshooting and without blaming the viewers.
Comment: Although printed music isn't doesn't always handle such things consistently, a tie should be placed between a pair of notes, rather than extending above or below them; if N notes are connected, N-1 separate ties should be used for the purpose.
Comment: @tim https://music.meta.stackexchange.com/questions/3748/abcjs-renderer-is-doing-something-very-strange-with-short-snippets etc
Comment: If I refresh the page I briefly see 3 images pass by, one being a guitar chord box notation. But what stays makes absolutely no sense. Can you flatten your image to only the one you want?
Comment: @VictorEijkhout It's not an image-flattening issue. See the meta link provided above.
Comment: @supercat Great point! I've updated the post.

Making note longer at end of measure


htaccess - extensionless URLs + redirect index to root

Question: There are plently of answers on how to create extensionless URLs and how to redirect index to root. I'm having a hard time combining both in my htaccess file. One always creates a problem with the other. Here is what I'm trying to accomplish:
301 redirects
domain.com to www.domain.com
domain.com/index.php to www.domain.com
domain.com/index to www.domain.com
www.domain.com/index.php to www.domain.com
www.domain.com/index to www.domain.com

/all-other-pages.php to /all-other-pages
/all-other-pages/ to /all-other-pages (if not a directory)

Currently I'm using this:
#-------------------------------------------------------------------------------
# REWRITE TO NON-EXTENSION URL

# unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

# resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

# redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php $1 [R=301,L]

#-------------------------------------------------------------------------------
# REDIRECT TO WWW LOCATION

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index$
RewriteRule ^(.*)index$ /$1 [R=301,L]

#RewriteCond %{HTTP_HOST} !^$
#RewriteCond %{HTTP_HOST} !^www\. [NC]
#RewriteCond %{HTTPS}s ^on(s)|
#RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

All seemed well until I tried:
    www.example.com/index.php
This redirects to:
 www.example.com/index

I didn't keep track of all the variations I've tried, sorry.
This code is copy and pasted which I usually don't like doing especialy when I don't understand the code but I'm afraid I really can't get into learning the instricacies of htaccess and regex at the moment.
There is only one htaccess file that is in document_root, BUT, I will be having a sub-directory where I want the same kind of page redirects to happen.
Thanks for any help,
Barry.
Answer: Have your rules in this order:
RewriteEngine On

# REDIRECT TO WWW LOCATION
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# remove index.php
RewriteCond %{THE_REQUEST} /index(\.php)?[/?\s] [NC]
RewriteRule ^(.*?)index(?:\.php)?$ /$1 [L,R=301,NC,NE]

# redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} \.php[/?\s] [NC]
RewriteRule ^(.+)\.php $1 [R=301,L]

# unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

# resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

Make sure to test it after clearing your browser cache.
Comment: I've now tested all variations I can think of and this now seems to be working perfectly, thank you very much.
Comment: I have an extra problem as I'm testing locally using easyPHP. Not having my site name encoded in the www redirect code causes problems as locally there is no www. I need to sort that out first before I can test this, how should I change your first two lines of code to accomplish that please? Thank you very much.
Comment: I appreciate your help but this still doesn't do all required. example.com/index doesn't resolve to example.com
example.com/page.php doesn't resolve to example.com/page. I cleared the cache plus I'm changing 301 to 302 while testing. Thanks.
Comment: Thank you, the file extension part seems to work perfectly now, even within a sub-directory. Now I just need to sort out the www part in a way that works locally and at my web host. As I say, locally there is no www in the URL, can that be added? If so then I could try your inital code. Thanks again.
Comment: I've added www. to my local virtualhost name now so I can view my local site with the URL www.mysitename_local. When I test without the www. it opens my default search site to search for the URL. Any ideas? I think it's almost there.
Comment: I've slightly modified `www` rule. On my localhost I have an alias as `www.localhost` that just points to `127.0.0.1` like `localhost`. That is how I have tested that `www` rule and it works pretty well.


Is mismatched firmware on drives in a raid-6 a bad thing?

Question: I recently expanded a raid-1 to a raid-6 with six drives. I ordered all four of the new drives from the same place, and all of them were advertised to be the same drives as the original two--Seagate 15krpm 146gb.
However, when I was looking at the drives in the perc6/i utility, one of them appeared to be an earlier firmware version; it had S515, compared to the other five drives with S527. Sure enough, after inspecting the drive itself, the label advertised the earlier firmware version. Running Dell's SAS firmware upgrade utility should have in theory moved them all up to S52A, but when I ran it it moved the S527 drives up to S52A, and left the S515 drive untouched.
Is this something to be worried about? If it's something that should be corrected, is there a way to target a particular drive for upgrade since the firmware utility didn't seem to do it by itself?
Answer: From my experience in dealing with Dell's support robots, they will not talk to you unless you have the latest firmware. they send you a link and tell you call them back when you are done updating.
While Dell may tell you you can't run it mismatched, and it may not be the "best practice", at my old job we ran mismatched firmware pretty much on every single drive, and the failure rate was exactly the same, despite the new firmware versions.
Comment: I've never had that experience with Dell and I doubt that's in the details of the support agreement. You pay for support, they can't refuse to provide said support based on a firmware\driver version. IMHO, one drive having an earlier version firmware than the other drives isn't inherently a problem unless there are known functional or performance problems with that earlier version firmware.
Comment: Been running with 5x S52A and 1x S515 for over a month now, and everything seems to be good. Marking as answered.
Comment: Well, that's reassuring. Any idea how I would go about correcting it if I wanted to get help from Dell? Like maybe swapping the odd drive into the 0 slot so it's first in the array or something?
Comment: Also, don't misconstrue their instruction to update a firmware\driver and get back to them, with a refusal to talk to you. They may instruct you that they can't support a particular version of firmware\driver and that the first step is to update it. That's not the same as saying "I won't speak to you or offer any type of support until and unless you update your firmware\driver". Telling you that you need to update a firmware\driver before they can proceed with troubleshooting\diagnosing the problem is part of the support process.


How to solve a double quadratic inequality

Question: I have a double quadratic inequality of the form $2x^4 + 2x^2 - 3 < 0 $. Had it been equation rather than inequality I would have probably set $x^2 = z$ and looked for the solution in terms of z and finally in terms of x. But how to deal with this inequality?
Answer: You can complete the square:
$$2\left(x^2+\frac{1}{2}\right)^2-\frac{7}{2}<0,$$
or
$$\left(x^2+\frac{1}{2}\right)^2<\frac{7}{4}$$
Can you see how to solve this?
Comment: That is where I am stuck. How can I deal with this inequality?
Comment: Solving $(x^2+\frac{1}{2})^2=\frac{7}{4}$ gives $x^2=-\frac{1}{2}\pm\frac{\sqrt{7}}{2}$, so $-\frac{1}{2}-\frac{\sqrt{7}}{2}<x^2<-\frac{1}{2}+\frac{\sqrt{7}}{2}$.
Comment: You can ignore the lower bound, since $x^2\geq 0$ for all real numbers $x$. So you just need to solve $0\leq  x^2<-\frac{1}{2}+\frac{\sqrt{7}}{2}$.
Answer: It's $$x^2<\frac{-1+\sqrt{7}}{2}$$ or
$$-\sqrt{\frac{-1+\sqrt{7}}{2}}<x<\sqrt{\frac{-1+\sqrt{7}}{2}}.$$


Q: Help to understand the thought process of solving the probability trough conditional probability

Question: While studying for my statistics exam i stumbled over the following question:
"There was a warehouse that created bags with marbles in them, they filled all the bags until "enough" marbles was in them. Unfortunately "enough" was not always the same, instead the probability for a bag containing 14, 15 or 16 marbles was the same. Calculate the probability that a bag contains exactly 3 white marbles if the warehouse contains 10% white marbles."
I have no clue how to solve this and tried for a while but just ended up being more confused than i originally was. Is there anyone that can "slowly" explain the thought process of solving a problem like this?
I would assume that I need to use some conditional probability but can't really get anywhere with it.
Comment: What is the probability of exactly $3$ white marbles in a bag of $14$? in a bag of $15$? in a bag of $16$?  Then combine these results using  "the probability for a bag containing $14$, $15$ or $16$ marbles was the same"
Answer: $\Pr(\text{3 White}) = \Pr(\text{3 White}\mid \text{14 in bag})\Pr(\text{14 in bag}) + \Pr(\text{3 White}\mid \text{15 in bag})\Pr(\text{15 in bag})+\Pr(\text{3 White}\mid \text{16 in bag})\Pr(\text{16 in bag})$
Per the law of total probability.  If you insist on phrasing it that way, you can also imagine an invisible $\text{"}\mid \text{10% white in warehouse"}$ on every term as well, but it is unnecessary.
Each of these terms in the expansion on the right should be readily able to be calculated.

 $\Pr(\text{3 White}\mid\text{14 in bag})$ for instance you can use binomial distribution.  $\Pr(\text{14 in bag})$ is given to you in the problem statement.
Comment: Thanks for your answer, I understand the solution and it makes sense to me. But I dont understand how you so quickly understood to use the binomial distribution? Is it just a lot of practice and eventually you are able to see solutions like this?
Comment: @forsb Practice certainly has a lot to do with it, practice in writing problems, in reading problems, ... Part of the nuance here is that the warehouse is presumed to have "*many*" marbles... that it has enough marbles to produce thousands or tens of thousands of these bags.  In reality, the factory ought to have only finitely many marbles and so technically the color of the marbles as they are being placed into the bag should be dependent on one another... but with a sufficiently "*large*" population we are selecting from, assuming their color is independent is a "good enough" approximation.
Comment: If in reality the factory only had 50 marbles available, and so enough marbles to only make a few bags, then the approximation would not have been a good one and we should have used hypergeometric distribution instead.
Comment: Alright thanks again. I will try to look for some similar exercises and practice some. I find it quite difficult to think of the problem like you explained, but as you say it that has to do with some lack of experience and knowledge!


Bootstrap 5 How to apply different justifications to elements inside div?

Question: I am using Bootstrap 5 to get a layout like the following:

I am using the following html:
<!DOCTYPE html>

        <link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet">

Test1

Test2

                        <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>

                        <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>

I am having problems in the buttons section, to justify the 3 of them to the bottom, and button3 to the right of the layout.
Any idea how to apply different justifications to the elements inside a div?
Answer: Try this:

                    <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>

                    <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>

Update
    <!DOCTYPE html>

        <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet">

Test1

Test2

                          <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>

                          <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>

jsfiddle:  https://jsfiddle.net/n0bod2m6/
Comment: It works for button3. But it does not move all the buttons to the bottom of the div like in my picture


Printing a WPF visual in landscape orientation, printer still clips at portrait dimensions

Question: I've written a small app which creates a visual programmatically, and I'm trying to print it out on a page in landscape orientation (it clips in portrait).  When I print, it does come out in landscape, but my visual is still clipped as through it were limited to portrait orientation.
Here's my code:
StackPanel page = new StackPanel();
// ... generate stuff to the page to create the visual

PrintDialog dialog = new PrintDialog(); // System.Windows.Controls.PrintDialog
bool? result = dialog.ShowDialog();
if(result.HasValue && result.Value)
{
    dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
    Size pageSize = new Size { Width = dialog.PrintableAreaWidth,
        Height = dialog.PrintableAreaHeight };
    // pageSize comes out to {1056, 816}, which is the orientation I expect
    page.Measure(pageSize);
    // after this, page.DesiredSize is e.g. {944, 657}, wider than portrait (816).
    page.UpdateLayout();
    dialog.PrintVisual(page, "Job description");
}

After executing this, the printed content is arranged correctly but still seems to be clipped to a width of 816, cutting off a significant chunk of content.  I've checked this by holding another piece of paper over the printed one and it fits perfectly inside.
Is there something I'm doing wrong to measure and arrange the controls?  How can I get my printer to use the full space of landscape orientation?
Answer: Steve Py's answer was correct for describing the core issue (PrintVisual doesn't respect the PrintTicket settings used).  However after I tried using XpsDocumentWriter and a new PrintTicket, I ran into the same issue (if I set the new PrintTicket's orientation to Landscape, it was still clipped).
Instead I worked around the issue by just setting a LayoutTransform to rotate the content 90 degrees, and print in Portrait mode.  My final code:
StackPanel page = new StackPanel();
// ... generate stuff to the page to create the visual
// rotate page content 90 degrees to fit onto a landscape page
RotateTransform deg90 = new RotateTransform(90);
page.LayoutTransform = deg90;

PrintDialog dialog = new PrintDialog();
bool? result = dialog.ShowDialog();
if (result.HasValue && result.Value)
{
    Size pageSize = new Size { Height = dialog.PrintableAreaHeight, Width = dialog.PrintableAreaWidth };
    page.Measure(pageSize);
    page.UpdateLayout();
    dialog.PrintVisual(page, "Bingo Board");
}

Comment: I was trying very hard. Your suggestion solved my problem. Thanks.
Answer: There is a known issue around landscape visual printing. This should provide details on how to address it.
http://social.msdn.microsoft.com/Forums/en/wpf/thread/56fb78b1-efc2-4ff7-aa2c-73c198a790b4
Comment: I tried using the method described there (using XpsDocumentWriter with a newly created PrintTicket), but ran into mostly the same issue.
Answer: try
PrintDialog printDlg = new PrintDialog();
PrintTicket pt = printDlg.PrintTicket;
pt.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA5Rotated);


How to compare diet composition

Question: Problem description:
I have 14 faecal pellets from 6 bat individuals (3 females, 3 males). All pellets are approximately of equal size. Prey composition (3 types: A, B, C) has been determined by calculating percentage volume of prey item within pellet. My aim is to compare whereas females eat more/less of particular prey than males.
my.data <- data.frame(pellet = seq(1,14,1),
                      individual = rep(c(LETTERS[1:6]), times=c(3,2,4,2,1,2)),
                      group = rep(c("female","male"), times = c(9, 5)),
                      prey.A = c(10,20,40,0,0,20,0,10,80,20,40,40,20,10),
                      prey.B = c(0,0,10,0,0,20,0,0,0,30,30,0,10,0),
                      prey.C = c(90,80,50,100,100,60,100,90,20,50,30,60,70,90))

# --- custom function start--- #
    error.bar <- function(x, y, upper, lower=upper, length=0.1,...){
    if(length(x) != length(y) | length(y) !=length(lower) | length(lower) != length(upper))
    stop("vectors must be same length")
    arrows(x,y+upper, x, y-lower, angle=90, code=3, length=length, ...)
    }
# --- custom function end--- #

# data handling
library(psych)
prey_female <- subset(my.data, group == "female")
prey_male <- subset(my.data, group == "male")
female_data <- c(prey_female$prey.A, prey_female$prey.B, prey_female$prey.C)
mtrx.female <- matrix(female_data,9,3)
female.means <- apply(mtrx.female,2,mean)
female.sd <- apply(mtrx.female,2,sd)
male_data <- c(prey_male$prey.A, prey_male$prey.B, prey_male$prey.C)
mtrx.male <- matrix(male_data,5,3)
male.means <- apply(mtrx.male,2,mean)
male.sd <- apply(mtrx.male,2,sd)
yy <- matrix(c(female.means,male.means),2,3,byrow=TRUE)
ee <- matrix(c(female.sd,male.sd),2,3,byrow=TRUE)*1.96/10

# plot creation
barx <- barplot(yy, beside=TRUE,col=c("palevioletred","lightskyblue2"), ylim=c(0,100),
    names.arg=LETTERS[1:3], axis.lty=1, xlab="prey", ylab="percetage volume (%)")
error.bar(barx,yy,ee)

I have two solutions - but I can not decide which is more appropriate.
First solution is to use Wilcoxon-Mann-Whitney Test to compare medians of both groups. Here is test which compares females and males with respect to prey item A.
library(coin)
wilcox_test(c(prey_female$prey.A,prey_male$prey.A) ~ as.factor(c(prey_female$group, prey_male$group)))
# Asymptotic Wilcoxon-Mann-Whitney Test
# data:  c(prey_female$prey.A, prey_male$prey.A) by
#    as.factor(c(prey_female$group, prey_male$group)) (1, 2)
# Z = -1.1618, p-value = 0.2453
# alternative hypothesis: true mu is not equal to 0

Second solution is to do Chi-squared test.
chisq.test(c(mean(prey_female$prey.A),mean(prey_male$prey.A)), p = c(1/2,1/2), correct = TRUE)
#   Chi-squared test for given probabilities
# data:  c(mean(prey_female$prey.A), mean(prey_male$prey.A))
# X-squared = 0.78261, df = 1, p-value = 0.3763

Data are fabricated, original dataset is much larger. How to make the comparison rigorously? It seems to me that both tests answer the same question.
Comment: I don't have a straightforward solution to your issue but some thoughts that might simplify the problem. Both tests lead to incorrect results as they assume independence of your observations. Observations are repeated for individuals and thus likely dependent within an individual. You might be able to work around this by first aggregating the data to the individual level. Moreover you may consider leaving one dependent variable out of the analyses. Knowing proportion A and B means that you know the proportion for C. Having all three variables in the analyses doesn't seem to add any information
Comment: This clearly requires a repeated measures analysis / mixed effects model. The difficult part is that your three DVs are percentages and that they depend on each other. Consider this scenario: Males and females eat equal amounts of prey A and prey B, but males also eat an additional amount of prey C. In such a case, you'd get different percentages for males and females although they eat the same amounts of a given prey A or B. Do you have access to data giving the actual amounts (this would require you to estimate the number of pellets excreted)?
Comment: Hi @Roland! Unfortunately, I do not have the number of pellets excreted. Only I can assume that - in reality - the number of pellets should not differ significantly between sexes. Usually the bats are caught, and inserted into cloth bags for 10-15 minuted till they defecate. We can not hold some animals longer/shorter till we get an equal number of pellets for each individual (large stress). Also, such analysis/research has many inherent complications - f.e. some prey although very abundant may be digested fully and there is nothing found in pellets.
Comment: I understand. But that means that you have three percentages that sum to 100 as the dependent in addition to a repeated measures dependency structure. I don't know how to best analyze such data, but it's an interesting question.
Answer: Since you have multiple pellets for each individual, as Roland mentioned, you have a repeated measure or similar situation.  Also as Roland mentioned your diet is not three things but a composite of three percentages (A, B, C) which sum to 100.  If I understand what you are trying to do, you'd want to say that if in aggregate:
Bat A,B,C are males had diets averaging say 10%, 0% and 90% (A,B,C) and
Bat D,E,F are females and had diets of say 0%, 90%, and 10% (A,B,C) are they statistically different?
If that is so, then I would look at Cochran's Q test.  I recently used it in a PLoS pub to do something similar Performance of three diagnostics.  You'd likely set it up blocking differently than I did but I think it would work.
You can read about it here Cochran's Q Wikipedia or Cochran's Q

How to compare diet composition


How to set value of (initialize) unichar/UInt16 in hexadecimal in Swift

Question: I want to set the value of a constant UInt16 to a hexadecimal value.
I know that the way to set a Swift Character is
let myValue: Character = "\u{1820}"

so I tried
let myValue: UInt16 = "\u{1820}"
let myValue: unichar = "\u{1820}"
let myValue: UInt16 = "\u{1820}".utf16
let myValue: unichar = "\u{1820}".utf16
let myValue = "\u{1820}"

but none of these worked.
When searching for the answer, I mostly got SO questions about converting from NSString or other type.
This is surely a silly question for all you experienced Objective C programmers, but I was having a hard time finding the answer. I finally did find it, though, so I will share my question and answer to hopefully add a few keywords for others who may search for the same question in the future.
Note:

How to initialize a unichar variable in swift? This Q&A doesn't tell how to initialize with hexadecimal.
Answer: If you had read the The Basics of the Swift documentation a little more carefully you would have found it.

Integer literals can be written as:

A decimal number, with no prefix
A binary number, with a 0b prefix
An octal number, with a 0o prefix
A hexadecimal number, with a 0x prefix

All of these integer literals have a decimal value of 17:
let decimalInteger = 17
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

So you would do
let myValue: UInt16 = 0x1820

or
let myValue: unichar = 0x1820 // unichar is a type alias of UInt16


JavaScript: Assign an unique identifier to an array and iterate over objects in the array

Question: I have 4 arrays full of objects:
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(27) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(21) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]

Each object contains a bit of information, that I want to display to the viewer:
0: Object { exchange: "NYSE", quote: "JPY", price: "3923.76016", … }

1: Object { exchange: "DEF", quote: "GBP", price: "3924.60972", … }

2: Object { exchange: "FEG", quote: "EUR", price: "3917.31980", … }

3: {…}

exchange: "NEX"

price: "3914.70000"

quote: "USD"

timestamp: "2018-12-31T07:47:11.253Z"

<prototype>: Object { … }
How can I
1) Assign a unique value to the array, ie. Array #1 is VTX, Array #2 is DEF, so that when I display it on the page, I don't need to change the ticker symbol (ie. VTX on exchange NEX is $100, and I only need to change the exchange name and currency/amount)
2) iterate over the arrays to where the iterator moves on to the next object in the array, let's say, every 2-3 seconds?
I'm doing this in React and have passed the data on to props, but now I'm stuck trying to figure this out.
Comment: 1) Assign the arrays to properties of an object: `{VTX: array1, DEF: array2, ...}`. 2) Keep a counter variable, `i`, increase it every 2-3 seconds and access `array[i]`.
Answer: 1) You can store all your arrays in on object like this :
const myArrays = [
    {
        uniqueName: 'VTX',
        infos: []
    },{
        uniqueName: 'DEF',
        infos: []
    }
]

2) You should store the index in the state, and make it change with setInterval in componentDidMount
componentDidMount() {
    this.timerID = setInterval(
        () => this.nextInfo(),
        1000
    );
}

Comment: Thanks! I was able to assign the ID to my arrays to differentiate between quotes.

For the second part, I'm still working it out...
Comment: Don't hesitate to upvote and accept the answer if it helped.


Google Table Chart Number Formatting displays NaN when using formatted numeric value with comma's

Question: As often happens whenever Google has a major release of their charts library       things break.  The following code was implemented about 3 years ago and worked fine for a couple of years and within the last year it broke this way
I populate a Data Table and format the numbers with this code
            var formatter = new google.visualization.NumberFormat({pattern:'#,###.##'});

        var cl = jsonChartData.rows[0].c.length;
        for (var c=0;c<cl;c++) {
            if (jsonChartData.cols[c].type == 'number'){
                formatter.format(popDataTable, c);
            }
        }

and this works well and produces a result like this: v: 6155177.2549019605,  f: '6,155,177.25'
And is supported by documentation here Google Table Chart, here Generic formatters, and here ICU 58.1
I populate the view that is passed to the chart object using the following code
            var tabOpt = {
                width: '100%'
                ,allowHtml: true
                ,cssClassNames: {
                    tableRow: 'chartTabRow'
                    ,oddTableRow: 'chartTabRow'
                    ,headerRow: 'chartHeadRow'
                    ,tableCell: 'chartTabRow'
                    ,headerCell: 'chartHeadRow'
                    }
                };
        var wdt = popDataTable;
        wdt.sort([
            {column: colID(wdt, 'sumlev')}
            ,{column: colID(wdt, 'estyear')}
            ,{column: colID(wdt, 'estdata')}
            ,{column: popFactCol, desc:  true}]);
        dView = new google.visualization.DataView(wdt);
        dView.setRows(dView.getFilteredRows([
            {column: colID(dView, 'sumlev'), value: '010'}
            ,{column: colID(dView, 'estdata'), value: popFact}
            ,{column: colID(dView, 'estyear'), value: popFactYear}]));

        var jsonPopParams = {
          "cols":
              [
              {"id":"","label":"Parameter(N)","pattern":"","type":"string"},
              {"id":"","label":"Value","pattern":"","type":"number"}
              ]
              ,
              "rows":
              [
                {"c":
                [
                {"v":"N","f":null},
                {"v":0,"f":null}
                ]
                },
                {"c":
                [
                {"v":"Sum","f":null},
                {"v":0,"f":null}
                ]
                },
                {"c":
                [
                {"v":"Min","f":null},
                {"v":0,"f":null}
                ]
                },
                {"c":
                [
                {"v":"Max","f":null},
                {"v":0,"f":null}
                ]
                },
                {"c":
                [
                {"v":"Range","f":null},
                {"v":0,"f":null}
                ]
                },
               {"c":
                [
                {"v":"Mean","f":null},
                {"v":0,"f":null}
                ]
                },
               {"c":
                [
                {"v":"Median","f":null},
                {"v":0,"f":null}
                ]
                },
               {"c":
                [
                {"v":"Variance","f":null},
                {"v":0,"f":null}
                ]
                },
               {"c":
                [
                {"v":"Standard Dev","f":null},
                {"v":0,"f":null}
                ]
                },
               {"c":
                [
                {"v":"Skewness","f":null},
                {"v":0,"f":null}
                ]
                },
               {"c":
                [
                {"v":"Kurtosis","f":null},
                {"v":0,"f":null}
                ]
                }]
              ,
              "p":null
              };

        jsonPopParams.rows[0].c[1].f = dView.getFormattedValue(0, colID(dView, 'pn'));
        jsonPopParams.rows[1].c[1].f = dView.getFormattedValue(0, colID(dView, 'psum'));
        jsonPopParams.rows[2].c[1].f = dView.getFormattedValue(0, colID(dView, 'pmin'));
        jsonPopParams.rows[3].c[1].f = dView.getFormattedValue(0, colID(dView, 'pmax'));
        jsonPopParams.rows[4].c[1].f = dView.getFormattedValue(0, colID(dView, 'prange'));
        jsonPopParams.rows[5].c[1].f = dView.getFormattedValue(0, colID(dView, 'pmean'));
        jsonPopParams.rows[6].c[1].f = dView.getFormattedValue(0, colID(dView, 'pmedian'));
        jsonPopParams.rows[7].c[1].f = dView.getFormattedValue(0, colID(dView, 'pvariance'));
        jsonPopParams.rows[8].c[1].f = dView.getFormattedValue(0, colID(dView, 'pstndev'));
        jsonPopParams.rows[9].c[1].f = dView.getFormattedValue(0, colID(dView, 'pskew'));
        jsonPopParams.rows[10].c[1].f = dView.getFormattedValue(0, colID(dView, 'pkurt'));

        var tblChart = new google.visualization.Table(document.getElementById(paramDiv));
        wdt = new google.visualization.DataTable(jsonPopParams);
        var tblView = new google.visualization.DataView(wdt);
        tblChart.draw(tblView, tabOpt);

Setting a break point and stepping though each instruction, I can see that for formatted value is getting populated in the JSON object jsonPopParams.
So for example pmean has a formatted value of '6,155,177.25'
When the chart is rendered, any value that has a comma in the formatting displays an NaN.
I created a working pared down example in JS Fiddle here:
In there I tested three scenarios

formatted value has no commas and 2 decimals ###.## using view.getFormattedValue and produces 6,155,177.25  this of course is the work around
formatted value has commas and 2 decimals #,###.## using view.getFormattedValue and produces NaN  what its doing right now
formatted value has commas and 2 decimals but uses view.getValue and produces 6,155,177.255 the default low order positions must be 3... it works but not according to spec.

So I'm not sure if
1) I was doing it wrong before and getting away with it and now Google fixed a root cause and now my wrong code is not working any more
OR
2) Google broke something and now my correct code is not working any more.
Hopefully a second set of eyes with a fresh perspective can see though.
Any help will be appreciated.  Thanks
Comment: Updated code example and JSFiddle to assign to correct element `.f` with formatted value.  `jsonPopParams.rows[5].c[1].f = dView.getFormattedValue(0, colID(dView, 'pmean'));`
Answer: problem appears to be these lines...
jsonPopParams.rows[0].c[1].v = dView.getFormattedValue(0, colID(dView, 'pn'));
jsonPopParams.rows[1].c[1].v = dView.getFormattedValue(0, colID(dView, 'psum'));
....

the value property (v) is being set with the formatted value (f)
so it should either be...
jsonPopParams.rows[0].c[1].f = dView.getFormattedValue(0, colID(dView, 'pn'));

or...
jsonPopParams.rows[0].c[1].v = dView.getValue(0, colID(dView, 'pn'));

or both...
jsonPopParams.rows[0].c[1].v = dView.getValue(0, colID(dView, 'pn'));
jsonPopParams.rows[0].c[1].f = dView.getFormattedValue(0, colID(dView, 'pn'));

when the DataTable is created here...
var tblChart = new google.visualization.Table(document.getElementById(paramDiv));
wdt = new google.visualization.DataTable(jsonPopParams);
....

strings are being used instead of numbers,
since the column type is number --> {"id":"","label":"Value","pattern":"","type":"number"}
NaN is returned
Comment: Yes that is it exactly.  Which makes perfect sense:  Numeric value goes to v (number) and formatted value goes to f (string).  The smaller numbers don't have commas and therefore the number as string could be cast to integer.  The newer version of the library must be enforcing better type safety.  I don't recall from 3 years ago but assigning to v was the working answer.  Thanks


Trouble with relation in postgresql database migration

Question: I'm working through the Rails Crash Course book, and the project is to create a social tumblr style clone. I've created a User model with just a name and id (and already migrated), and now I'm trying to implement the following/subscription style that tumblr does. The book has the following to create a new model and migration:
bin/rails g model Subscription leader:references follower:references

The thought is the leader will the the person followed, and the follower is obviously the follower. Both will reference the id from the User table though.
The problem is with the migration. I get the following:
PG::UndefinedTable: ERROR:  relation "leaders" does not exist
: ALTER TABLE "subscriptions" ADD CONSTRAINT "fk_rails_7b4891a3a6"
FOREIGN KEY ("leader_id")
  REFERENCES "leaders" ("id")

Plus a bunch of other stuff that looks almost exactly the same.
While I'm assuming that it's throwing an error because no leader table with it's own id exists, is there a way to fix the migration to reference the user.id for each reference, or will I just manually need to create each column?
Answer: I think it's a Postgres specific problem. You can bypass it by using:
bin/rails g model Subscription leader_id:integer:index follower_id:integer:index

Comment: Eww, new problem. Is there a way to add a foreign_key to both of these columns with that migration?
Comment: Thanks Erik! The only bummer is it doesn't generate the model with the nice belongs_to: references this way, but that isn't a problem.
Comment: Do you mean directly on the command line? I don't think so but you can always edit that migration manually.


what if m = infinity in y = mx+c?

Question: I'm having trouble trying to understand linear functions.
First, we recognize a function from a graph using vertical straight line, if it crosses two points, we say the graph does not represent a function.
if we use the vertical line method on y = mx + c if m equals or approaches to infinity, then y = mx + c does not represents a function, let alone represent a linear function.
Am i right or wrong in this situation ?
Comment: Yes, a vertical line $x=c$ is not a function. It fails vertical line test, intersecting it at infinitely many points. In the definition of linear function $f: \Bbb R \to \Bbb R$, such that $f(x)=mx+c$, $\; m$ and $c$ are real constants. Therefore an undefined value of $m$, as you know infinity does not belong to $\Bbb R$, can make $f$ undefined.
Answer: The general formula to represent a line in 2D space is: $Ax+By+C=0, A\in R, B\in R$($A$ and $B$ should not equal to $0$ simultaneously), and $y=mx+c$ is a restricted form that excludes the case $B=0$.
So, w.r.t your question, a vertical line is exactly the case that $B=0$, and $Ax+C=0, A\neq 0$ is a function of $y$, namely $x(y)=0$, which means that given any $y$, $x$ remains the same number $-\frac{C}{A}$. It can be understood in the same way with $y=c$.
And, when you let $m\to\infty$, you reach the limitation of the representation ability of this restricted form $y=mx+c$.
Answer: Well.. as the 'm' represents the slope of the line which is given by tan (angle of the line with the x-axis), so if the 'm' i.e. slope is equal to infinity therefore the tan of the angle will be infinity and since tan of 90 degree is infinity(actually its undefined but it approaches infinity at pi/2 radians so we can assume), thus your line will be perpendicular to the x axis.. for e.g. x = 5 can be such a line.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).

what if m = infinity in y = mx+c?


Bind form values in session bean

Question: i have a Bean stored in session, and three forms. I need save the submitted values to the bean, this is the sequence: Form1.jsp -> Form2.jsp -> Form3.jsp -> ViewValues.jsp.
This is my bean:
package bean;

public class Cotizacion implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    // Some properties ...

    public Cotizacion(){
        // Nothing ...
    }
    // Accessors & toString ...
}

The first JSP have this action:
<jsp:useBean id="cotizacion" class="bean.Cotizacion" scope="session" />

The second and third JSP have this action:
<jsp:useBean id="cotizacion" class="bean.Cotizacion" scope="session">
    <jsp:setProperty name="cotizacion" property="*" />
</jsp:useBean>

When i try <% System.out.print("Cobertura.jsp: " + cotizacion); %> in the third form, the console output is:

Cobertura.jsp: Ford;T;1990;5000;null;null;null;null;null;null

The bean is only populated after the first submit. The bean properties are same that the request params.
Any ideas?
Answer: <jsp:setProperty name="cotizacion" property="*" /> reinitialized properties from request parameters, but you didn't use parameters or parameters are empty. Ensure the bean has getters and setters. If you remove this tag the bean should keep session values. If you want to populate the bean with parameters from the request then use
<jsp:useBean id="cotizacion" class="bean.Cotizacion" scope="session"></jsp:useBean>
<jsp:setProperty name="cotizacion" property="*" />

The above example results in iteration over the HTTP request parameters, matching bean property names with request parameter names and setting bean property values according to the corresponding request parameter values. If you submit the form using POST method you are missing parameters from the request.
Comment: Roman, the params exists in POST request. The setters are defined in the bean. If i remove the `` the bean never will be populated after each submit.
Comment: If you want to populate the bean with parameters from the request then see above code.
Comment: Glad that worked for you, with this parameters and properties meanings.

Bind form values in session bean


Help on how to show that $\int_{0}^{1}\left(2{x-1\over \ln^2{x}}-{x+1\over \ln{x}}\right)dx=3\ln{2}-2$

Question: $$\int_{0}^{1}\left(2{x-1\over \ln^2{x}}-{x+1\over \ln{x}}\right)dx=3\ln{2}-2\tag1$$
Rewrite, so we can apply Frullani's formula on first part
$$\int_{0}^{1}\left(-{x+1\over \ln{x}}+{2\over \ln{x}}+{2(x-1)\over \ln^2{x}}\right)=3\ln{2}-2\tag2$$
$$-\ln{2}+\int_{0}^{1}\left(-{2\over \ln{x}}+{2(x-1)\over \ln^2{x}}\right)=3\ln{2}-2\tag3$$
$$\int_{0}^{1}\left(-{1\over \ln{x}}+{x-1\over \ln^2{x}}\right)=2\ln{2}-1\tag4$$
How do I continue from $(4)$?
Comment: Chill out, guys. I think enough context is provided by $(2),(3)$ and $(4)$, and the main integral $(1)$ belongs to a class of interesting integrals that we may compute through Feynman's trick or Frullani's theorem, related with the integral representation of the Euler-Mascheroni constant or Catalan's constant, for instance.
Comment: Please improve the question by adding additional context: where did the integral come from? Why is it of interest?
Answer: Through the substitution $x=e^{-t}$ the original integral equals:
$$ I=\int_{0}^{+\infty}\left(2\frac{e^{-t}-1}{t^2}+\frac{e^{-t}+1}{t}\right)e^{-t}\,dt \\=2\color{purple}{\int_{0}^{+\infty}\frac{e^{-t}-1+t}{t^2}\,e^{-t}\,dt}+\color{blue}{\int_{0}^{+\infty}\frac{e^{-t}-1}{t}\,e^{-t}\,dt}$$
where the blue integral is yet manageable through Frullani's theorem (leading to a $\log 2$), and the purple one becomes a similar integral by integration by parts, since:
$$ \frac{d}{dt}\left[(e^{-t}-1+t)e^{-t}\right]= 2(e^{-t}-e^{-2t})-te^{-t}.$$
By collecting pieces, $I=\color{red}{3\log 2-2}$ as wanted.
Answer: We can write the interal in $(4)$ as $$I=-\int_{0}^{1}\frac{1-x+\log\left(x\right)}{\log^{2}\left(x\right)}dx
 $$ now define $$I\left(\alpha\right)=-\int_{0}^{1}\frac{x^{\alpha}\left(1-x+\log\left(x\right)\right)}{\log^{2}\left(x\right)}dx,\,\alpha\geq0
 .
 $$ We have $$I''\left(\alpha\right)=-\int_{0}^{1}x^{\alpha}\left(1-x+\log\left(x\right)\right)dx=-\frac{1}{\alpha+1}+\frac{1}{\alpha+2}+\frac{1}{\left(\alpha+1\right)^{2}}
 $$ so integrating twice we have $$I\left(\alpha\right)=\left(2+\alpha\right)\log\left(\frac{2+\alpha}{1+\alpha}\right)+C\alpha+D
 $$ now since $$\lim_{\alpha\rightarrow\infty}I\left(\alpha\right)=0
 $$ and $$\lim_{\alpha\rightarrow\infty}\left(2+\alpha\right)\log\left(\frac{2+\alpha}{1+\alpha}\right)=1
 $$ we must have $C=0,\, D=-1
 $. So taking $\alpha=0
 $ we have

$$I=I\left(0\right)=\color{red}{2\log\left(2\right)-1}$$

as wanted.
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\color{#f00}{\int_{0}^{1}}\overbrace{\bracks{\color{#f00}{2\,{x - 1 \over \ln^2\pars{x}} - {x + 1 \over \ln\pars{x}}}}}
^{\ds{\int_{0}^{1}\pars{1 - 2t}x^{t}\,\dd t}}\color{#f00}{\,\dd x} =
\int_{0}^{1}\pars{1 - 2t}\int_{0}^{1}x^{t}\,\dd x\,\dd t =
\int_{0}^{1}{3 -2\pars{1 + t} \over t + 1}\,\dd t
\\[5mm] = &\
3\int_{0}^{1}{\dd t\over t + 1} - 2\int_{0}^{1}\dd t =
\color{#f00}{3\ln\pars{2} - 2}
\end{align}


How do I properly setup javamail to use STARTTLS?

Question: When setting up my session I am setting the starttls.enable and .required properties but when the connection happens it should fail according to the documentation:

mail.smtp.starttls.enable  boolean  If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Note that an appropriate trust store must configured so that the client will trust the server's certificate. Defaults to false."
  http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html

props = new Properties();
props.put("mail.smtps.host", MAILSERV);
props.put("mail.smtps.socketFactory.port", 465);
props.put("mail.smtps.auth", "true");
props.put("mail.smtps.port", 465);
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.socketFactory.class","utils.DummySSLSocketFactory");
props.put("mail.smtps.quitwait", "false");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
Session session = Session.getInstance(props, authenticator);

transport = session.getTransport("smtps");
transport.connect(mailServer, port, username, password);
transport.sendMessage(message, message.getAllRecipients());

So what am I doing wrong that is allowing me to use Starttls when its not supported by the server?
Comment: "Note that if you're using the "smtps" protocol to access SMTP over SSL, all the properties would be named "mail.smtps.*".", you seem to be using port 465, which is usually SMTP over SSL. Although, I'm not even sure if you can do STARTTLS on top of smtps
Comment: You can get rid of those socket factory properties too, [you don't need them](http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes).
Comment: I think you are correct. After defaulting everything to "smtp" instead of "smtps", I am getting  the desired results. I really do not like using properties for this reason.
Answer: The issue I was having with STARTTLS was caused by me getting a secure transport:
transport = session.getTransport("smtps");

After changing it to "smtp" i was able to use STARTTLS.


Gaps In Plot Of Piecewise Function in Matlab

Question: I want to plot a piecewise function, but I don't want any gaps to appear
at the junctures, for example:
<code>t=[1:8784];

b=(26.045792 + 13.075558*sin(0.0008531214*t - 2.7773943)).*((heaviside(t-2184))-(heaviside(t-7440)));

plot(b,'r','LineWidth', 1.5);grid on
</code>
there should not be any gaps appearing in
the plot between the three intervals , but they do.
I want the graph to be continueous without gaps.
Any suggestions on how to achieve that.
Thanks in advance.
EDIT
Actually, my aim is to find the carrier function colored by yellow in the figure below. I divide the whole interval into 3 intervals: 1-constant 2-sinusoidal 3- constant, then I want to find the overall function from the these three functions
Comment: can you add a plot to your question demonstrating the 'gaps'.
Answer: Of course there are "gaps". The composite function is identically zero for all t<2184, and for all t>7440. The relationships can only be non-zero inside of that interval. And you have not chosen a function that is zero at the endpoints, so how can you expect there not to be "gaps"?
What values does your function take on at the endpoints of the interval?
<code>>> t = [2184 7440];
>> (26.045792 + 13.075558*sin(0.0008531214*t - 2.7773943))
ans =
       15.689       20.616
</code>
So look at the hat function part of this. I'll be lazy and use ezplot.
<code>>> ezplot(@(t) ((heaviside(t-2184))-(heaviside(t-7440))),[0,8784])
</code>

Now, combine this, multiplying it by a trig piece, and of course the result is identically zero outside of that domain.
<code>>> ezplot(@(t) (26.045792 + 13.075558*sin(0.0008531214*t - 2.7773943)).*((heaviside(t-2184))-(heaviside(t-7440))),[0,8784])
</code>

But if your goal is some sort of continuous function across the two chosen points in the hat function, you need to chose the trig part such that it is zero at those same two points. Mathematics is not spelled mathemagics. Wishing that you get a continuous function will not make it so.
So is your real question how to chose that internal piece (segment) as one such that the final result is continuous? If so, then we need to know why you have chosen the arbitrary constants in there. Surely these numbers, {26.045792, 13.075558, 0.0008531214, 2.7773943} all must have some significance to you. And if they are important, then how can we possibly make the result a continuous function?
Perhaps, and I'm just guessing here, you want some other result out of this, such that the function is not identically zero outside of those bounds. Perhaps you wish to extrapolate as a constant function outside of those points. But to help you, you must help us.
Comment: thanks, actually, my aim is to find the carrier function colored by yellow in this graph: http://www5.0zz0.com/2010/12/31/13/615589208.jpg                    I divide the whole interval to 3 intervals: 1-constant 2-sinusoidal 3- constant, then I want to find the overall function from the these three functions.       regards
Comment: So you are trying to write your own regression spline model, composed of various arbitrary functional forms for the pieces? Why not use a tool that already has the required abilities?


asp mvc roles from httpcontext

Question: i want to pass current area name to authorization attribute, like:
<code>[SexyAuthorize(Roles = Url.RequestContext.RouteData.Values["area"])]
public class FormsController : Controller
{
}
</code>
but Url is member of controller. how can i pass it other way?
i know that i can use User.InRole in each method, but i want do it for class. thx.
Answer: You can't pass dynamic values to an attribute like this. All values passed to an attribute in .NET need to be known at compile time. One possible workaround is to fetch this value in your custom implementation of the attribute as you have access to the HTTP context.
Something like:
<code>[SexyAuthorize(RolesRouteParamName = "area")]
public class FormsController : Controller
{
    ...
}
</code>
and then:
<code>public SexyAuthorizeAttribute: AuthorizeAttribute
{
    public string RolesRouteParamName { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }
        var roles = httpContext.Request.RequestContext.RouteData.Value[RolesRouteParamName];
        // TODO: continue with the implementation...
        ...
    }
}
</code>

asp mvc roles from httpcontext


Gaussian process and Correlation

Question: I am have been wondering why people use Gaussian processes (GP) to model an unknown (sometimes deterministic) function. For instance consider an unknown function $y=f(x)$. We have three independent observations from this function :
$$\big(x_1,y_1); \big(x_2,y_2); \big(x_3,y_3) $$
To learn the underlying function, the GP is a common non-parametric technique that treats all outputs as a common multivariate normal distribution. Assume a specific covariance function $K(x_i,y_i)$  and assume:$$\mathbf{y}=(y_1,y_2,y_3);\mathbf{X}=(x_1,x_2,x_3)$$
The GP takes the following form
$$\\
\bf{y}|X
\sim N\Bigg(\mathbf{0},\begin{bmatrix}
 K(x_1,x_1) & K(x_1,x_2) & K(x_1,x_3) \\
K(x_1,x_2) & K(x_2,x_2) & K(x_2,x_3) \\
K(x_1,x_3) & K(x_2,x_3) & K(x_3,x_3) \
\end{bmatrix}\Bigg)\\$$
The observations $\big(x_i,y_i)$ are independent. Their only commonality is that they come from the same underlying function.
My main question is: Why are we forcing $\big(x_i,y_j)$ and $\big(x_{l},y_{m})$ to be correlated ? Isn't that the wrong model ? Why can we assume that we can get good prediction results for any $y|x$.
I am not sure what aspect I am missing in this problem and why is forcing correlation helping.
Answer: Choosing a kernel is equivalent to choosing a class of functions from which you will choose your model. If choosing a kernel feels like a big thing that encodes a lot of assumptions, that's because it is! People new to the field often don't think much about the choice of kernel and just go with the Gaussian kernel even if it's not appropriate.
How do we decide whether or not a kernel seems appropriate? We need to think about what the functions in the corresponding function space look like. The Gaussian kernel corresponds to very smooth functions, and when that kernel is chosen the assumption is being made that smooth functions will provide a decent model. That's not always the case, and there are tons of other kernels that encode different assumptions about what you want your function class to look like. There are kernels for modeling periodic functions, non-stationary kernels, and a whole host of other things. For example, the smoothness assumption encoded by the Gaussian kernel is not appropriate for text classification, as shown by Charles Martin in his blog here.
Let's look at examples of functions from spaces corresponding to two different kernels. The first will be the Gaussian kernel $k_1(x, x') = \exp(-\gamma |x - x'|^2)$ and the other will be the Brownian motion kernel $k_2(x, x') = \min \{x, x'\}$. A single random draw from each space looks like the following:

Clearly these represent very different assumptions about what a good model is.
Also, note that we aren't necessarily forcing correlation. Take your mean function to be $\mu(x) = x^T \beta$ and your covariance function to be $k(x_i, x_j) = \sigma^2 \mathbf 1(i = j)$. Now our model is
$$
Y | X \sim \mathcal N(X\beta, \sigma^2 I)
$$
i.e. we've just recovered linear regression.
But in general this correlation between nearby points is an extremely useful and powerful model. Imagine that you own a oil drilling company and you want to find new oil reserves. It's extremely expensive to drill so you want to drill as few times as possible. Let's say we've drilled $n=5$ holes and we want to know where our next hole should be. We can imagine that the amount of oil in the earth's crust is smoothly varying, so we will model the amount of oil in the entire area that we're considering drilling in with a Gaussian process using the Gaussian kernel, which is how we're saying that really close places will have really similar amounts of oil, and really far apart places are effectively independent. The Gaussian kernel is also stationary, which is reasonable in this case: stationarity says that the correlation between two points only depends on the distance between them. We can then use our model to predict where we should next drill. We've just done a single step in a Bayesian optimization, and I find this to be a very good way to intuitively appreciate why we like the correlation aspect of GPs.
Another good resource is Jones et al. (1998). They don't call their model a Gaussian process, but it is. This paper gives a very good feel for why we want to use the correlation between nearby points even in a deterministic setting.
One final point: I don't think anyone ever assumes that we can get good prediction results. That's something we'd want to verify, such as by cross validation.
Update
I want to clarify the nature of the correlation that we're modeling. First let's consider linear regression so $Y | X \sim \mathcal N(X\beta, \sigma^2 I)$. Under this model we have $Y_i \perp Y_j | X$ for $i \neq j$. But we also know that if $||x_1 - x_2||^2 < \varepsilon$ then
$$(E(Y_1 | X) - E(Y_2 | X))^2 = (x_1^T \beta - x_2^T \beta)^2 = \langle x_1 - x_2, \beta \rangle^2 \leq || x_1 - x_2||^2 ||\beta ||^2 < \varepsilon ||\beta ||^2.
$$
So this tells us that if inputs $x_1$ and $x_2$ are very close then the means of $Y_1$ and $Y_2$ are very close. This is different from being correlated because they're still independent, as evidenced by how
$$P(Y_1 > E(Y_1 | X) \ \vert \ Y_2 > E(Y_2 | X)) = P(Y_1 > E(Y_1 | X)).$$
If they were correlated then knowing that $Y_2$ is above its mean would tell us something about $Y_1$.
So now let's keep $\mu(x) = x^T \beta$ but we'll add correlation by $Cov(Y_i, Y_j) = k(x_i, x_j)$. We still have the same result that $||x_1 - x_2||^2 < \varepsilon \implies (E(Y_1 | X) - E(Y_2 | X))^2$ is small, but now we've gained the fact that if $Y_1$ is larger than its mean, say, then likely $Y_2$ will be too. This is the correlation that we've added.
Comment: Thank you for your comment. Your explanation is very useful. However, my question is mostly focused on the idea that correlation between the tuples $(x_i,x_j)$ and $(x_l,x_m)$ does not exist in reality. Then the GP forces a correlation in the multivariate normal distribution (other than the case $K=1(i=j)$). Is this correlation the same correlation as that of random variables ? or is defined differently since we are modeling functional relationships ? Is this correlation interpretable ? and how come it helps ?
Comment: Also can we say $y_i$ is not independent of $y_j$ because they come from same underlying function and both depend on $x$ ? this why the should have correlation. I really appreciate you help on these questions
Comment: @kon7 I've added an update on the correlation that hopefully helps.
Comment: Thank you a lot, your answer is amazing. I have accepted the answer. I still have one small inquiry. The type of information we added, can we call it correlation, in the typical statistical meaning of correlation ? Does it have a meaning in the sense of functional correlation because here we are looking at the tuples $\big(x_i,y_i)$ rather than the random variables  $y's$
Comment: @kon7 This is entirely the standard sense of correlation because we are working with a covariance matrix $K$. $X$ is how we compute this but the $x_i$ are deterministic in the standard formulation and the only covariance is between the $Y_i$.
Comment: Really great example so you have used the notion that if $x's$ are close then we @jld can assume their $\mu's$ are close, however it doesnt mean they are correlated, they could be still independent. Also if they are +ve correlated then it "only" tells us if one rv is above its mean then other rv should also be above its mean, thats all. Right?
Comment: @jld also correlation is kinda like a magnet, if one rv is pulled above its mean, the other rv will also be pulled by the force proportional to correlation amount. So if they are correlated by +1 then that is the maximum amount of pull from its mean..right
Answer: If $x_i$ and $x_l$ are similar to each other, i.e. $k(x_i, x_l)$ is large, then $y_i$ and $y_l$ should likely be similar to each other as well.  Therefore, closeness in the input space (of the function to be approximated) results in the closeness in the output space.  This is reasonable assumptions for many applications.  For example, if two students have similar high school GPA, they are expected to perform similarly in the SAT exam as well.

Gaussian process and Correlation


What does the dollar sign ($) do in a printf format string?

Question: I am trying to format in java using the printf statement like in this webpage: Click Here. But I just can't figure out what the purpose of the $ sign is. Can someone please explain this to me?
Input:
java 100
cpp 65
python 50

Expected Output: ( there should be a space instead of _ )
 ================================
 java___________100
 cpp___________065
 python_________050
 ================================

My code:
public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i=0;i<3;i++)
        {
            String s1=sc.next();
            int x=sc.nextInt();
            System.out.printf(s1 + "%03d", x);
            System.out.println();
        }
        System.out.println("================================");

    }
}

Comment: Please post your code here, not a link. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve)
Comment: See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
Comment: In short, the dollar character is not going to solve your problem.  Try "%10.0d" instead.  Read the javadocs fof a specification of what the format string means.
Answer: It is the Argument Index. You can read the docs. I will try to explain the string from the tutorial for you:
String fmt = "%1$4s %2$10s %3$10s%n";

// format
cnsl.printft(fmt, "Items", "Quantity", "Price");
cnsl.printft(fmt, "-----", "-----", "-----");
cnsl.printft(fmt, "Tomato", "1 kg", "15");
cnsl.printft(fmt, "Potato", "5 kg", "50");
cnsl.printft(fmt, "Onion", "2 kg", "30");
cnsl.printft(fmt, "Apple", "4 kg", "80");

In general the format is %[argument_index$][flags][width][.precision]conversion.
In our example, #$ points to the position within our printft() statement. We have 3 strings to be formatted and hence why our format string has 1$, 2$,3$. The number that follows its the width between each argument. This width begins at 0 which means the actual width would be +1. The s is our conversion to string and the %n new line at the end.
Items      Quantity      Price
-----      --------      -----
Tomato     1 kg          15
Potato     5 kg          50
Onion      2 kg          30
Apple      4 kg          80


Javascript works well for DropDownListField but not for RadioButtonList. Where is problem?

Question: i have a problem with javascript in cshtml. Works like a charm when i am using DropDownListField.
        @Html.Editor("Bod2List", "DropDownListField", new
            {
                items = new List<SelectListItem>() {
                    new SelectListItem() { Text = "uvádím v komentářích k jednotlivým ustanovením v návrhu smlouvy", Value = "ne"},
                    new SelectListItem() { Text = "chci změnit následující", Value = "ano"} },
                    label = "Vyberte z možností",
                required = true
                })

        @Html.EditorFor(m => m["Bod2TextBox"], "StringField", new { placeholder = "Ustanovení (odkaz na čl. a odst. Smlouvy): + požadovaná změna", multiline = true })

SCRIPT PART:

I want to change DropDownListField to RadioButtonList, but when i do my script does not work at all. Could somebody help me?
Many Thanks
Comment: Please share your code snippet for the `RadioButtonList`
Comment: It is the same, i just want to change DropDownFieldList to RadioButtonList in this example.
Answer:

Comment: Thanks for super quick response but unfortunately that does not work. :-(
Comment: in the end you helped me a lot
Answer: Accessing selected value from radio button list is somewhat different compare to that of dropdown list. I hope the below snippet gives an idea...
HTML
<select id="idSelectList">
    <option value="1">1</option>
    <option value="2" selected>2</option>
    <option value="3">3</option>
</select>

    <input type="radio" value="1">
    <input type="radio" value="2" checked>
    <input type="radio" value="3">

jQuery snippet to access value
var selectedDropDownOption = $("#idSelectList").val();

// :checked css selector to be used for getting checked radio button
// Without this, the snippet always gives first radio button's value
var checkedRadioButton = $("#idRadioList input[type=radio]:checked").val();

Comment: Thanks, but this is to much for me. :-) I'm not expert at this at all. I am just changing custom form in our company Service Desk. Coding skills are very limited.
Comment: @cyppisek try to have a look at generated html in client side when rendering `DropDownList` and `RadioButtonList`. Right click on rendered control in page, and click on inspect element. Based on rendered content, the code to access `SelectedValue` changes.
Comment: I tried. What is weird that when i changed the script function and deleted if/else - it will only affect first SelectListItem (Value = "ne") - when i am clicking ond second SelectListItem it does nothing - i am guessing i will stick with DropDownListField...
Answer: Finally i got it - thanks everyone. :-)
$("input[value=ano][type=radio][name=Bod3List]").on("change", function () {
            $("#Bod3Section").slideDown(300);
    })

$("input[value=ne][type=radio][name=Bod3List]").on("change", function () {
            $("#Bod3Section").slideUp(300);
    })


Serialização de exceções

Question: Segundo as documentações msdn, uma exceção deve ser serializada caso ela deva ser propagada para fora do assembler.
No visual studio, tenho uma solução com alguns projetos, dentre eles um projeto de biblioteca de classes (dll), no qual eu crio várias exceções próprias.
Até onde eu entendo esse projeto (dll), será um assembler independente onde os outros projetos(outras dlls), main, etc, irão precisar acessar as classes contidas nele para tratar e lançar as exceções que foram criadas lá.
Esse é um caso em que as exceções devem ser serializadas?
Answer: Se a exceção que você define na DLL (a) não vai sair da "caixa preta do processo onde ela está rodando", então você não precisa se preocupar com serialização. Se você tem uma DLL (b) ou um EXE (c) que referenciam a DLL (a), e o código deles catch a exception, você ainda está na mesma caixa do processo, e a exceção é apenas mais um objeto em memória, que é compartilhada por todos os componentes (exe e dll) do processo. Isso é o caso da maioria das aplicações.
Se a sua exceção pode escapar do processo - por exemplo, você tem um service com um método externo que pode throw a exceção, então a serialização precisa ser implementada, para que ela seja enviada para o cliente via "rede" (pode ser a rede de verdade, um named pipe entre processos, ou qualquer outra forma onde o objeto tenha que ser transformado em uma stream de bytes). Outros exemplos são se você quer persistir a informação da exceção no disco, ou por qualquer motivo realizar a serialização "na mão" da exceção (ou de um objeto que a contenha).
Note que mesmo em situações onde você quer transmitir um erro para um cliente (por exemplo, num web service), raramente você quer transmitir o objeto da exceção diretamente, pois ele contem muito mais informações que o cliente precisa (por exemplo, stack trace). Nesse caso é comum a criação de DTOs (data transfer objects) para conter somente a informação relevante.

Serialização de exceções


in STM32F10, for instance, when i enable the Usart1 why doesnt the CUBEMX call HAL_GPIO_Init to set the alternate function of the corresponding pins?

Question: I just try to understand how the .ioc(cubemx) file respond to the configuration i set into my MCU and when i enable a peripheral lets say usart or whatsoever, it has to generate the code associated with setting the corresponding pins allocated to that specific peripheral(usart) but when i  check the code i cant find the section where it does (i tested for a gpio and set it as output and the cubemx just generated the code (HAL_GPIO_Init) )!!
how does it work?
enter image description here
enter image description here
Where is the code associated with the Pin configuration?
Comment: cut and paste code, not pictures of code.
Answer: Have a look in Core/Src, you should see a file called stm32f1xx_hal_msp.c or similar.
It will have a function in it called HAL_UART_MspInit(). This configures the GPIO pins used by your UART.
Comment: CubeMX is just a configurator for Cube, so if you intend to use it to set up a Cube/HAL program, you are supposed to be familiar with the Cube/HAL driver model, as described in Cube manual - in your case, CubeF1 manual [UM1850](https://www.st.com/resource/en/user_manual/um1850-description-of-stm32f1-hal-and-lowlayer-drivers-stmicroelectronics.pdf), see chapter _3.12 How to use HAL drivers_, and _Figure 7. HAL driver model_ in there. That explains what @pmacfarlane said above.


Closing old accepted questions

Question: Please refrain from marking as closed 3 year old questions with answers.
This question is a decent example: change block call order in checkout
It makes the moderation queue difficult to sift through. Let's focus on answering current questions.  If you feel something is egregious, however, please flag for moderators instead of close voting.
Comment: To clarify why flags are preferable: close votes can pile on without a feedback loop. A moderator or the team of mods can make the decision to close or, more appropriately for old questions, flag them as off topic but retained for historical value.
Comment: Phil thx  for noticed this.. We should more care about close vote
Comment: Personally in future i will more care full about close vote
Comment: So @philwinkle for old questions with no answers at all, that do not seem to be answerable, it is still OK to raise a close flag in your opinion?
Comment: @7ochem that sounds fine
Answer: Well I reckon I'm faulty on this one.
Whenever I see people talking about a module provider (in this case it was ebizmarts) I always search for questions regarding this module provider and I mark them for closing.
I felt like it was a good thing to do for off topic questions that went through the moderators' net. I didn't think it was bad to do it for answered questions. Apologies
Comment: It was good for M2EE questions which had zero answers. For historical questions with answers, best to leave it alone.
Comment: @philwinkle thanks for enlightening me I'll be more careful from now

Closing old accepted questions


Populate a field on node creation

Question: I have a content type "abc". I have a field "listing id". I want this field to be prepopulate starting from  1 and autoincrement" on every "abc" node creation.
How can I do this.
Answer: It looks like you can use the Serial Field module to accomplish this.
From the Serial Field page on Drupal.org:

Usage
You can add a serial field to any type at admin/content/types ->
  manage fields. In the New Field form select Serial as the type of data
  and label and field name as your choice, and Save. No other settings.

Populate a field on node creation