Gregorian Chant vocal technique

Question: What are the following vocal techniques?

on the word Quantus at 0:17
on the word mi-rum at 0:36
on the word mundus at 1:30
on the word ju-dex at 3:14
on the word Et at 3:59
on the word O-ro at 3:12
on the word dona at 6:10.

I asked this question on this on the Gregorian Chant Facebook group, and one of the members thinks that what I'm hearing is reverb added to the recording! I don't think that is the case because Gregorian Chant has overtones and the men that sing Gregorian Chant are perfectly capable of producing them!
For an example of Gregorian Chant overtones, listen to Pater Noster from Gregorian Vespers in honor of Saint Vincent Pallotti (Vesperae de Confessore non Pontifice) recorded by Schola Gregoriana from Pallottine Seminary in Ołtarzew, Poland, conducted by father Dario Smolarek!
Comment: 1) It's not a very good quality recording. 2) I don't hear those words being sung with a noticeably different technique. Can you describe what the technique sounds like to you? How do those notes sound different? What do you mean by "overtones"?
Comment: I would say that I hear no overtones in their voices that aren't present in every trained singer's voice, along with many untrained but experienced singers. Also, I hear the same quantity and quality of overtones during the entire recording, not just on the words highlighted in the question. So I still don't understand what is different about the moments in the recording that are in question from the rest of the recording. I'm assuming it's something I can't hear or that I don't know to listen for because I don't know what change in *sound* you are hearing.
Comment: @AnaMaria I hear no overtones in either the wikipedia recording nor the youtube recording.
Comment: Have you tried listening to this recording on a variety of headphones and/or speakers?  I have found that the overtone content of some recordings, particularly of baritone voices, is highly dependent on the speaker acoustics.
Comment: The overtones produced in Gregorian Chant are the result of many forces working together. First, the monks usually sing in the middle range of their voices, the baritone register. In this register it is easier to produce and to hear the nominally perceptible range of the overtone series. They also make use of what is known as "singer's formant," or the resonant frequencies in the range of 2,000-4,000 hz; this is what gives trained singers the pleasant "buzz" when they sing. By utilizing this singer's formant, and by singing in unison, the chanters are able to reinforce the natural harmonics,
Comment: producing the overtones. In addition, the long melismatic lines on pure vowels help to bring out an awareness of the sounding of the overtones, as does the architecture of the church or cathedral in which the Chant is sung. The overtones of Gregorian Chant are produced by perfectly in-tune unison singing (this is also true with organum, a relative of Chant in which the music is sung in parallel octaves - this effectively reinforces the overtone closest to the fundamental). Singers of Gregorian Chant often practice for up to four years before they sing with a group; by this time, they are able
Comment: to sing the melismatic lines perfectly in-tune with the other chanters. The chanters must breath in the same places, attend to vowel unity, and articulate consonants in a uniform fashion. It is minute attention to these details which allows Gregorian Chant to resonate so well, and thus produce and reinforce overtones.
Answer: There are no special techniques involved in this recording. There are three noticeable traits that occur at or near the time-points mentioned:

The natural reverberation of the space in which the recording was made (throughout the entire recording).
The interchange between the entire ensemble and a smaller subset.
Occasional vibrato.

Gregorian Chant vocal technique


Knockoutjs not saving data if submitted from browser console

Question: there is a website developed using knockoutjs,  when I try to fill and submit form using javascript in browser console it submits form but not saves data.
**how to access form: **
Open this link:
link to open form page
Run this in browser console to show Add loan button
<code>$('.manage_area_login').show();
</code>
Now click on Add loan button it will show up the form.
And run these three commanda in browser console to fill and submit form.
<code>$('#newLoanAmount').val('12');
$('#newLoanInterest').val('2');
$('input[value=Add]').click();
</code>
After that you will see a Loan will be added with 0 amount
Thats the problem its not saving the field values.
Comment: Do you *develop* that website or do you just want to fill in the form automatically and have otherwise nothing to do with them?
Comment: No I just want to fill form and get calculated value
Answer: I think you need to manually trigger a change event if manipulate the value like that.
<code>$('#newLoanAmount').val('12').trigger('change');
</code>
Comment: How to trigger a change event?
Comment: http://stackoverflow.com/questions/34100012/knockout-js-force-change-after-javascript-changes-a-textbox


How to create a custom page in Wordpress?

Question: How can I to create a custom page in Wordpress 3.0. Give me any link of tutorial.
Comment: definitely should be migrated to Wordpress.stackexchange
Answer: WordPress provides a clever way to do this called Custom Page Templates. To create a WordPress Page Template, you'll need to use your text editor. Go to the directory on your server where you installed WordPress, and then navigate to the directory of your theme. Usually that looks something like this: "/wp-content/themes/default" where "default" is your theme name.
That's where you will create your custom page template file. Create a file called "cover_page.php" and add the following code to it:
<code> <?php
 /*
 Template Name: Cover Page
 */
 ?>

 <?php get_header(); ?>

 Here's my cover page!

<?php get_footer(); ?>
</code>
more details read this
http://www.expand2web.com/blog/custom-page-template-wordpress/
Answer: To add to the answers above, one good way is to open a text editor (I like notepad++) and copy and paste the content of the page.php file into a new file, including the php template name code in one of the previous examples.
Call it something unique (like custom_page1.php ) and upload this file via ftp to your active theme folder inside your wordpress install on your server. You can use filezilla for this or another FTP program.
Refresh your editor page in wordpress and you should see your template listed with the others on the right.
Now when you publish a page you can choose this template from the dropdown menu on the side panel.
Answer: You can use the Page Template feature of wordpress to create a custom page.
Answer:
First create page using pages->add new.Then,give title (for e.g. aboutus). Then click
  Publish on right side of the window(no content is needed for the custom page).
Then,on left side of window click Appearance->Menus.
In menus window,on left side you will see Pages heading,in that click Most Recent and
  check aboutus page. Then it will be shown on right side window.
Then,on left above Pages heading, you will see Custom Links, in that enter # in URL textbox
  and aboutus in Label textbox. Then click Add to Menu button.
Done. You will see the menu as custom on right side of the window and then click save menu
  button at the bottom right.
Then to check, on left top of the window click the website or your blog name. You will see
  the menu. Click on it. No changes will occur.

That's it, done!
Answer: Here are some plugins you can use while creating what you need then you can turn them off or remove them.
http://wordpress.org/extend/plugins/theme-file-duplicator/
http://wordpress.org/extend/plugins/theme-file-maker/
Very easy way to do what you need.
Comment: This does not seem to be an appropriate answer. No explanation, no reason for plugins at all here.
Answer: This is a very simple part of WordPress theme development, I suggest giving the documentation (the WordPress Codex) a good read before going any further. There are also a tonne of great WordPress tutorial sites out there that will get you heading in the right direction.
Comment: "This is a very simple part of WordPress theme development", why not write that simple piece of code here? so it helps who have already viewed codex
Comment: I answered the question as asked. That's why.


Como atribuir valores em um JSON em relação ao objeto anterior?

Question: eu recebo um JSON e preciso alterar o valores que recebo dele.
[
    {
        "dataMarcacao": "10/09/2021",
        "dataenvioPS": "2021-09-10",
        "marcacao": "06:00",
        "tipo": "E",
        "registro": "I",
        "dthr_marcacao": "10/09/2021 06:00",
        "cod_acerto": "A"
    },
    {
        "dataMarcacao": "10/09/2021",
        "dataenvioPS": "2021-09-10",
        "marcacao": "09:00",
        "tipo": "E",
        "registro": "I",
        "dthr_marcacao": "10/09/2021 09:00",
        "cod_acerto": "A"
    },
    {
        "dataMarcacao": "10/09/2021",
        "dataenvioPS": "2021-09-10",
        "marcacao": "12:00",
        "tipo": "S",
        "registro": "I",
        "dthr_marcacao": "10/09/2021 12:00",
        "cod_acerto": "A"
    },
    {
        "dataMarcacao": "10/09/2021",
        "dataenvioPS": "2021-09-10",
        "marcacao": "12:50",
        "tipo": "E",
        "registro": "I",
        "dthr_marcacao": "10/09/2021 12:50",
        "cod_acerto": "A"
    }
]

Criei um metódo de Ordenação em relação a data, mas preciso alterar o valores do tipo. O primeiro tipo sempre tem q ser "E" (entrada) , e a partir daí uma sequencia 2° tipo "S" (saída) , 3° "E" e assim sucessivamente, e posso ter somente 4 batidas ou posso ter n batidas. Como posso resolver isso ?

corrigirMarcacoes(file){

    let ordenar = file;

    ordenar.sort( function(a,b) {
      return new Date(a.dthr_marcacao).getTime() - new Date(b.dthr_marcacao).getTime();
    });

    let tempPickList = JSON.parse(JSON.stringify(ordenar));

    if (tempPickList[0].tipo === 'E') {
      tempPickList[1].tipo = 'S';
      tempPickList[2].tipo = 'E';
      tempPickList[3].tipo = 'S';
      tempPickList[4].tipo = 'E';
      tempPickList[5].tipo = 'S';
      tempPickList[6].tipo = 'E';

    }

    console.log ('tempPickList = ', tempPickList);
    console.log('ordenar = ' , JSON.stringify(ordenar))
    return tempPickList;
  }

Eu tenho esse codigo, mas ele não funciona por eu não saber o tamanho do meu JSON, por isso nao posso setar o tamanho.
Answer:
Veja na resposta do hkotsubo a explicação, muito boa, sobre os possíveis formatos de datas e a influência desses formatos na ordenação das datas.

Use um Generator:

const data = [{ "dataMarcacao": "10/09/2021",  "dataenvioPS": "2021-09-10", "marcacao": "06:00",  "tipo": "E", "registro": "I",  "dthr_marcacao": "10/09/2021 06:00", "cod_acerto": "A"}, {"dataMarcacao": "10/09/2021", "dataenvioPS": "2021-09-10", "marcacao": "09:00",  "tipo": "E",      "registro": "I",  "dthr_marcacao": "10/09/2021 09:00", "cod_acerto": "A"}, {      "dataMarcacao": "10/09/2021",  "dataenvioPS": "2021-09-10","marcacao": "12:00",  "tipo": "S", "registro": "I",  "dthr_marcacao": "10/09/2021 12:00", "cod_acerto": "A" }, {"dataMarcacao": "10/09/2021",  "dataenvioPS": "2021-09-10", "marcacao": "12:50",  "tipo": "E", "registro": "I",  "dthr_marcacao": "10/09/2021 12:50", "cod_acerto": "A"}];

//Função geradora cíclica que retorna indefinida E,S,E,S,.....
function* genEI() {
  while (true) {
    yield "E";    //Retorna E e abandona a função.
    yield "S";    //Retorna S e abandona a função.
  }
}

//Obtém o Generator partir da função geradora.
const getEI = genEI();

//Ordenação por data apresentada na pergunta.
let newData = data.sort((a, b) => {
  return new Date(a.dthr_marcacao).getTime() -
    new Date(b.dthr_marcacao).getTime();
});

//Para cada objeto e no array newData...
for (let e of newData) {
  e.tipo = getEI.next().value;       //...substitui o valor da propriedade e.tipo por um valor obtido do gerador getEI.
}

console.log(newData);

Um Generator é um objeto retornado por uma função geradora, esse objeto está em conformidade com o protocolo iterável e o protocolo de iteração.
Geradores são funções cuja execução pode ser interrompida e posteriormente reconduzida. Seus contextos ficarão salvos entre cada recondução. Veja a explicação feita na documentação:

Chamar uma função geradora não executa seu conteúdo imediatamente; ao
invés disso um objeto iterator é retornado. Quando o método next() do
objeto iterator é chamado, o conteúdo da função do gerador é executado
até a primeira expressão yield, que especifica o valor a ser devolvido
do iterator ou com yield* que delega para outra função geradora. O
método next() retorna um objeto com uma propriedade value contendo o
valor retornado e a propriedade boolean: done indicando se o gerador
produziu seu último valor. Chamar o método next() com um argumento
resumirá a execução da função geradora, substituindo a expressão yield
onde a execução foi pausada com o argumento de next().
Uma expressão return em um gerador, quando executada, fará com que o
gerador termine (isto é, a propriedade done do objeto retornado será
atribuído com o valor true). Se um valor foi retornado, este será
usado como propriedade value do objeto retornado pelo gerador.
Semelhantemente a uma expressão return, um erro lançado dentro do
gerador o terminará -- a não ser que tratado no corpo do gerador.
Quando um gerador estiver terminado, chamadas next subsequentes não
executarão nenhum código do gerador, retornarão simplesmente um objeto
da seguinte forma: {value: undefined, done: true}.
Comment: Funcionou pra mim, obrigado !! Consegui tbm outra forma puxando pelo índice tempPickList.forEach( function (value, index) {

      if (index % 2 === 0) {
        value.tipo = 'E';

      } else {
        value.tipo = 'S';
      }
    });
Comment: @Rabelo Inclusive eu acho mais simples assim usando o próprio índice. Mas tem um detalhe na ordenação das datas que menciono na [minha resposta](https://pt.stackoverflow.com/a/535121/112052), vale a pena dar uma olhada
Comment: @hkotsubo, citei sua resposta na minha pois eu gosto de como você escreve e explica as coisas e eu não conseguiria fazer tão bem quanto você fez.
Answer:
por eu não saber o tamanho do meu JSON

É claro que você sabe. Repare que ele é delimitado por [ ], o que significa que é um array. E todo array tem a propriedade length que indica o seu tamanho.
Na verdade, pelo seu código, você provavelmente tem um array do JavaScript, e não um JSON (apesar de "parecidos", eles não são a mesma coisa).
Porque se fosse um JSON mesmo (ou seja, uma string contendo os dados neste formato), você não conseguiria chamar sort nele.

Mas enfim, vamos por partes.
Primeiro, você está criando as datas passando os valores "dd/mm/aaaa" direto para o construtor de Date. Só que nem sempre isso funciona, pois alguns browsers interpretam isso como "mm/dd/aaaa" (ou seja, new Date("10/09/2021 10:00") pode ser interpretado como 9 de outubro, e não 10 de setembro). Conforme já explicado aqui, o único formato que funciona em todos os ambientes é o ISO 8601 ('aaaa-mm-ddThh:mm'). Enfim, tem que ajustar isso se quiser ordenar corretamente pela data.
Depois, JSON.parse(JSON.stringify(algo)) me parece completamente desnecessário. Se a ideia era criar uma cópia do array, use apenas slice. Mas se a ideia é usar o mesmo array, não faça nada (lembre-se que sort altera o array, então tem que ver se você quer ou não alterar o array original).
Depois, basta iterar pelo array, e nas posições pares você coloca o "E", e nas ímpares coloca o "S":

// converte dd/mm/aaaa hh:mm para aaaa-mm-ddThh:mm
function getTimestamp(str) {
    const [data, hora] = str.split(' ');
    const [dia, mes, ano] = data.split('/');
    return new Date(`${ano}-${mes}-${dia}T${hora}`).getTime();
}

let dados = [
    { "dataMarcacao": "10/09/2021", "dataenvioPS": "2021-09-10", "marcacao": "12:50", "registro": "I", "dthr_marcacao": "10/09/2021 12:50", "cod_acerto": "A" },
    { "dataMarcacao": "10/09/2021", "dataenvioPS": "2021-09-10", "marcacao": "09:00", "registro": "I", "dthr_marcacao": "10/09/2021 09:00", "cod_acerto": "A" },
    { "dataMarcacao": "10/09/2021", "dataenvioPS": "2021-09-10", "marcacao": "06:00", "registro": "I", "dthr_marcacao": "10/09/2021 06:00", "cod_acerto": "A" },
    { "dataMarcacao": "10/09/2021", "dataenvioPS": "2021-09-10", "marcacao": "12:00", "registro": "I", "dthr_marcacao": "10/09/2021 12:00", "cod_acerto": "A" }
];

// se quiser copiar o array, use slice (senão use o próprio "dados" mesmo)
let copia = dados.slice();

copia.sort((a, b) => getTimestamp(a.dthr_marcacao) - getTimestamp(b.dthr_marcacao));
for (let i = 0; i < copia.length; i++) {
    copia[i].tipo = i % 2 == 0 ? 'E' : 'S';
}

console.log(copia);
Comment: Obrigado pela resposta @hkotsubo - eu tenho que usar o JSON.parse(JSON.stringify(algo) , pq recebo um erro "Cannot assign to read only property 'tipo' of object '#'" caso não use esse método, sobre o .sort alterar o array é por isso que uso uma cópia e nao o array original.


Calculation of the Fourier transform of $x/(x^2+1)^2$ using the properties of the transform

Question: I am trying to calculate the Fourier transform of $$f(x)=\frac{x}{(x^2+1)^2}$$
using the property of Fourier transform. So I am trying to use$$\widehat{g_1(x)g_2(x)}=\frac{1}{2\pi}\widehat g_1 *\widehat g_2(\epsilon)$$ Since we already know $$\widehat {\frac{1}{x^2+1}}=\pi e^{-|\epsilon|}$$ .So first I tried to set $$g_1(x)=g_2(x)=\frac{1}{x^2+1}$$ then after finding the $\widehat{g_1(x)g_2(x)}$ by calculating the convolution. Using the property again to calculate  $$\widehat f=\widehat{[g_1(x)g_2(x)]x}$$ But I found this doesn't work since the Fourier integral of $x$ doesn't converge.
So I tried to set $$g_1(x)=\frac{x}{x^2+1}$$ $$g_2(x)=\frac{1}{x^2+1}$$ But I don't know how to calculate the Fourier transform of $$g_1(x)=\frac{x}{x^2+1}$$ and I also don't know if it converges. Since I tried to calculate it by using residue theorem. The integral on the complex part $$\int_{complex}\frac{e^{-iz\epsilon}z}{z^2+1}$$I don't know how to deal with it.
Does anyone know about this. Please help. Thanks so much!:)
Answer: You are on the wrong track when trying to work with $\frac{x}{(x^2+1)^2}$ as the product of $\frac{1}{x^2+1}$ and $\frac{x}{x^2+1}$. Instead, use the fact that
$$
\frac{d}{dx}\left(\frac{1}{x^2+1}\right) = -\frac{2x}{(x^2+1)^2}
$$
and invoke the formula for $\widehat {f'}$ in terms of $\widehat{f}$.


Pegar id de um select dinamico com o jquery

Question: Preciso pegar o id Bairro3, estou fazendo assim
$(document).on('change', '#bairro', function(){
        var bairroID = $(this).val();

mas mesmo assim nao funciona.
Tem que acrescentar uma variavel no #bairro, para cada formulario que abrir tenha um id diferente #bairro1 #bairro2 #bairro3..., como posso fazer isso, imagino que teria que fazer isso para o id #rua também #rua1 #rua2 #rua3...
$(document).ready(function(){

    $(document).on('change', '#sectionChooser', function(){
        var myID = $(this).val();
        $('.panel').each(function(){
            myID === $(this).attr('id') ? $(this).show() : $(this).hide();
            console.log("ok");
        });
    })

    $(document).on('change', '#bairro', function(){
        var bairroID = $(this).val();

        if(bairroID){
            $.ajax({
                type:'POST',
                url:'ajax_data2.php',
                data:'bairro_id='+bairroID,
                success:function(html){
                    $('#rua').html(html);
                    console.log("ok");
                }
            });
        }else{
            $('#rua').html('<option value="">Select categoria first</option>');

        }
    });

});

Html

Planos
<select name="Planos" id="sectionChooser" class="form-control valid" aria-invalid="false">
   <option value="">Selecione</option>
   <option value="1">Diamante</option>
   <option value="2">Ouro</option>
   <option value="3">Prata</option>
   <option value="4">Light</option>
   <option value="5">Free</option>
   <option value="19">Link</option>
</select>

      Diamante

   Bairro
   <select class="form-control valid" name="bairro" id="bairro3" required="" aria-invalid="false">
      <option value="">Selecione</option>
      <option value="1">teste bairro</option>
      <option value="2">teste bairro 2 3</option>
      <option value="3">ação bairros</option>
      <option value="4">Centro</option>
   </select>

   Rua
   <select class="form-control" name="rua" id="rua" required="">
   </select>

Comment: Conforme falei no chat, Vc não precisa criar vários ids... basta criar names com arrays, tipo name="bairro[]"... e vc consegue pegar o valor de cada uma com `$(document).on('change', '[name^="bairro"]', function(){ var bairroID = $(this).val();`
Comment: Não olhando muito a fundo na sua questão, id's crescentes quase nunca(senão mesmo nunca) é o que você pretende, mas sim classes(todos com a mesma), ou uma solução como o @dvd indicou.
Comment: Acho que você poderia ter se concentrado na outra questão que é quase a mesma coisa desta, aí vc já resolveria tudo
Comment: É óbvio que se você usar o seletor por ID como aqui `$(document).on('change', '#bairro'` o resultado sempre será **"bairro"**. Por que não faz um seletor por nome, ou tipo de tag ( `select`, `input`, etc) ou ainda por classe?
Answer: Ficou assim o código, funcionou
$(document).ready(function(){

    $(document).on('change', '#sectionChooser', function(){
        var myID = $(this).val();
        $('.panel').each(function(){
            myID === $(this).attr('id') ? $(this).show() : $(this).hide();
            console.log("ok");
        });
    })

   $(document).on('change', '[name^="bairro"]', function(){ var bairroID = $(this).val();
        console.log("ok");

        if(bairroID){
            $.ajax({
                type:'POST',
                url:'ajax_data2.php',
                data:'bairro_id='+bairroID,
                success:function(html){
                    $('#rua[name^="rua"]').html(html);

                }
            });
        }else{
            $('#rua').html('<option value="">Select categoria first</option>');

        }
    });

});


jQuery Ajax - return value to specific DIV

Question: Can one of you jQuery kings please tell me why my script.asp will not load for each separate button? I modified the code form http://www.sitepoint.com/ajax-jquery/.
Thanks

<title>AJAX with jQuery Example</title>

<input type="submit" id="generate1" class="generate" value="Generate!">

<input type="submit" id="generate2" class="generate" value="Generate!">

<input type="submit" id="generate3" class="generate" value="Generate!">

Comment: You should stay consistent with your quotes as well.
Answer: .find() assumes there are elements nested inside of the element you're querying. Your element, however, is next to the element you're working with.
Try this:
$(this).next('.quote').load('script.asp');

Comment: Valiant effort gentlemen but neither worked. However, thanks for the direction. I will research the next/nextAll methods.
Answer: You need to use nextAll and first to select the closest div.quote sibling:
$(".generate").click(function(){
    $(this).nextAll('div.quote').first().load("script.asp");
});

.find finds all descendants of the selector matching the given selector, not siblings like you want.
Answer: your .find( finds WITHIN the .generate class (enclosed in)
.nextAll( finds all SIBLINGS with the selector applied :first being of course the first one of those selected siblings
$(".generate").click(function(){
   $(this).nextAll('div.quote:first').load("script.asp");
});

an alterative would be to wrap the input and the quote div in another div and then do:

    <input type="button" id="generate1" class="generate" value="Generate!">

$(".generate").click(function(){
       $(this).parent().find('div.quote').load("script.asp");
});

NOTE: in my example, I changed the input type to 'button' because, it is not really a submit now is it, an that will cause other interesting challenges.
Comment: The King has spoken! Thank you all with a special thanks to King Mark. The first example you gave did not work but the second on did by wrapping the elements in a new DIV. Thanks so very much!
Comment: I wondered about your markup just a bit...the real one probably varied some - I did check it here: http://jsbin.com/awuguf/3/edit#javascript,html,live prior to submission however.  Since you are new to StackOverflow, on an answer you LIKE/Accept click the check to the left to show acceptance. (do not do that super quick to get more/better options) unless you really like one.


Not Receiving SMS in Twilio

Question: I need to fetch SMS Response sent from Twilio using web hook using Twilio trial account credentials. In that, generated number is from US. And sms is sending from India number. And when message is sent back to Twilio that is not shows in incoming messages and not call the webhook url also.
I created app in twiml. And set webhook url in that also. But doesn't work.
For web hook I am using ngrok so in my local server so I can get data.
Any one have idea what is wrong I am doing.
EDITED
I have created testing twilio account. Generated number and the generated number is from US. I have set up webhook url in manage numbers.

URL is generated from ngrok so It can be used outside my network.
I have setup Twiml App also. And webhook url is also set there.

I am sending one programmable message from my node api. And that was working fine. User is getting programmable message but when user reply to that message it should call my webhook url. But it not calling my webhook url and also it not showing in my incoming message.

Thanks for any help.
Comment: Without seeing some of your code, and a better description of what `doesn't work` actually means, no, nobody is likely to have any idea what you are doing wrong.  For tips on formulating your question, check out [how to ask](https://stackoverflow.com/questions/how-to-ask), and how to create a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve).
Comment: @Don'tPanic please check my Question. I Edited my question.
Comment: Open a support ticket with all the details, something isn't correct if the logs aren't showing a response - https://www.twilio.com/console/support/tickets/create.
Answer: For those who are struggling with this,
As of now Twilio not supports 2-way messaging in India.
Please refer this for more details.
Twilio Guidelines for India

Not Receiving SMS in Twilio


Spring boot rest serve images and other files

Question: I would like to ask if it is good approach to just serve static content like this
<code>spring.web.resources.static-locations=classpath:/static/
</code>
so user would just go to
<code>  localhost:8080/images/image.png
</code>
or better go with
<code>@GetMapping(value = "/image/{image}")
public void userImage(HttpServletResponse response, @PathVariable String image) {
    Path path = Paths.get("src\\main\\resources\\static\\UsersImages\\" + image);
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);

    try {
        InputStream is = Files.newInputStream(path);
        IOUtils.copy(is, response.getOutputStream());
    }catch (Exception e){
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,"Error while streaming image!");
    }
}
</code>
I want to use this for users images..
In the future I would also like to serve videos etc..
Thanks
Comment: Static content is already served from that location automatically. You are basically working around the already existing feature.
Answer: The service approach could be the best in case you wanna improve it or even extend it in the future. I suggest that the path should be a property value instead of that long string which may break the implementation in the future.
Answer: For me, url should be without file extesions see there.
You can prepare few endpoints, one for images, second for videos, other for pdf files etc.
Files, I would save on other location like sftp server, DMS repository or in cloud.
If you're new, you can try put on some folder outside of project.


Pointwise convergence of $1_{(a,b]}$ by a sequence of functions

Question: I am trying to work through an exercise (on my own) out of Resnick's A Probability Path.
One question states the following:
Suppose $-\infty<a\le b<\infty$ and assume we have an indicator function of the form $1_{(a,b]}(x)$. Can this function be approximated by bounded and continuous functions.
Said another way, does there exist a sequence $f_n: 0\le f_n\le 1$ such that $f_n\rightarrow1_{(a,b]}$ pointwise.
Using the hint in the text, my attempted solution was:
Attempt at a solution:
$f_n$ such that:
$f_n(x) = \begin{cases} 0, & x \leq a, x \geq b + \frac1n \\
1, & a + \frac1n < x \leq b
\end{cases}$
 and linear otherwise
The problem (or one problem?) is that this doesnt appear continuous to me. I could also use some help in learning how to be more explicit about limits. For example, why does $x>b$ imply $f_n\rightarrow 0$. I "know" this intuitively, but obviously need help explaining it with precision.
Thanks as always!
Answer: Try piecing $1_{(a+ \frac{1}{n}, b ]}$ together with a positively-sloped line segment from $a$ to $a+\frac{1}{n}.$ Let me know if you'd like more detail.
EDIT: In other words, your sequence should look something like this
$f_n(x) = \begin{cases}
0 \textrm{ if } x < a \textrm{ or } x >b \\
nx - na \textrm{ if } a\le x \le a + \frac{1}{n}\\
1 \textrm{ if } a + \frac{1}{n} < x \le b
\end{cases}$
Try drawing a picture to get a sense for how the line segment was constructed. To show that this converges to pointwise to $1_{(a,b]}$, you should consider the cases of $x\notin (a,b]$ and $x\in (a,b]$ separately. The first case is pretty easy - the second case doesn't require too much work if you are familiar with Archimedes' Property.
Comment: thank you for the response. Detail would be helpful as I am learning this from scratch. What do you mean exactly by "piece together"? Are you saying to construct a rectangle for the approximation?
Comment: @Justin, let me know if the edit above can be clarified any more.
Comment: Thank you Tim. I think it makes sense now.
Answer: You are looking at functions which are constant ($0$ or $1$) everywhere with the exception of the intervals $(a, a+1/n)$ and $(b, b+1/n)$. In these intervals you have linear functions with increasing slope which grow from $0$ to $1$ or the other way round.
To prove pointwise (!) convergence just look at:
i) $x\le a$. There your sequence is constantly zero, so it converges to $0$
ii) any $x \in (a, b]$. Choose $N$ such that $a+1/n < x$ for $n\ge N$ . Then $f_n(x) = 1$ for each such $n$, hence $f_n(x)\rightarrow 1$
iii) $x>b$. Choose $N$ such that $x\le b+1/n$ for $n\ge N$. Then $f_n(x)=0$ hence $f_n(x)\rightarrow 0$.
Then you are done.


Como armazenar respostas dos meus scanf/gets em C

Question: Preciso realizar esse sistema para faculdade, sendo essas  funcionalidades essenciais:
O sistema deverá oferecer, ao usuário, as seguintes funcionalidades:

Listar os veículos cadastrados;

Inserir um novo veículo;

Listar os veículos filtrando-se por ano de fabricação;

Listar os veículos com o ano de fabricação acima de um certo valor especificado pelo usuário.

Listar os veículos filtrando-se pelo modelo.

O sistema deverá armazenar os veículos ordenados pelo ano de fabricação, ou seja, ao inserir um novo veículo, este deve ser inserido em ordem crescente de ano de fabricação.
O que não consigo fazer é salvar as respostas de cadastro do veículo, por exemplo, o usuário vai realizar um cadastro de um carro, não consigo saber onde e como salvar e como resgatar as respostas em forma de lista. Outra coisa que não consigo é limitar as respostas em 10 veículos no máximo.
Segue o código fonte abaixo:
struct cadastro{
        char marca[30];
        char modelo[30];
        char placa [9];
    } veiculos [10];

int main(void) {

    setlocale(LC_ALL, "Portuguese");
    int digitado;
    int valor;

    printf("O que deseja realizar?: ");
    printf("\nDigite 1 para Listar os Veículos já cadastrados\nDigite 2 inserir um novo veículo\nDigite 3 para ver os anos de fabricação dos veículos cadastrados\nDigite 4 para ver um veículo do preço que desejar\nDigite 5 para ver os modelos dos veículos.\n\n");
    scanf("%d", &digitado);

    if(digitado == 2){
    int i;
    for(i=0;i<1;i++){
        printf("\nDigite a marca do carro: \n\n");
        scanf("%s", &veiculos[i].marca);
        setbuf(stdin,NULL);
        printf("\nDigite o modelo e ano do carro: \n\n");
        gets(veiculos[i].modelo);
        setbuf(stdin,NULL);
        printf("\nDigite a placa do carro(Ex: ABC-0123): \n\n");
        scanf("%s", &veiculos[i].placa);
        setbuf(stdin,NULL);
        getchar();

    }
    for(i=0;i<1;i++){
        printf("\nCarro da marca: %s, do modelo/ano: %s, com a placa: %s adicionado à lista!\n",veiculos[i].marca,veiculos[i].modelo,veiculos[i].placa);
    }
}else if(digitado == 1){
        printf("\nCarro da marca: %s, do modelo/ano: %s, com a placa: %s",veiculos[0].marca,veiculos[0].modelo,veiculos[0].placa);
}else if(digitado == 3){
    printf("Anos dos veículos listados: %i", veiculos[0].modelo);
}else if(digitado == 5){
    printf("Aqui estão os modelos dos carros: %s", veiculos[0].modelo);
}else if(digitado == 4){
    printf("Digite um valor: ");
    scanf("%d", &valor);
    if(valor < 10000){
        printf("Ano: %d", veiculos[0].modelo<2010);
    }else{
        printf("Ano: %d", veiculos[0].modelo>2010);
        setbuf(stdin,NULL);
    }
}

system('pause');
return 0;
}

Answer: Seu programa tem um certo número de problemas, todos problemas comuns. E assim pode ser útil para mais usuários ter uma resposta aqui

Como armazenar respostas dos meus scanf/gets em C

Acho que não era isso que você queria perguntar. De todo modo: não use gets(), essa função foi abolida há décadas. Use fgets().
Para armazenar os resultados o primeiro argumento é um ponteiro para a área que vai receber os resultados.
scanf() não aloca memória, então para cada especificador, aquelas coisas que começam por % no primeiro argumento, você deve passar um endereço.
Teste sempre o retorno dessas funções. SEMPRE.
Não vou corrigir o programa todo porque nem ajuda muito. Mas vou listar alguns dos problemas e você poderá ir acertando se achar adequado
            gets(veiculos[i].modelo);

Pode ser algo como
            fgets(&veiculos[i].modelo, sizeof veiculos[i].modelo, stdin);

o retorno de fgets()
fgets() tem esse parâmetro que limita o tamanho do campo. A falta disso em gets() foi uma bobagem dos anos 70 e deixa uma abertura para um estouro do campo. Por isso é um desastre em termos de segurança e estabilidade do programa, e a função foi abandonada.
Mas fgets() retorna um ponteiro para o valor lido, assim como gets(). E você tem que testar.
Eis o que acontece: se não ler nada a função retorna NULL e os dados no primeiro argumento não são alterados. Isso quer dizer que o programa vai achar que leu os mesmos dados que já estavam lá, se é que tinha algum.
o retorno de scanf()
                scanf("%d %d %d", &digitado, &outro, &mais_um);

Essa chamada por exemplo lê 3 valores. Então pode retornar 3, 2, 1, 0 ou -1 conforme leia algo. -1 para erro.
Se você não testar nunca vai saber o que leu e se leu. Se o cara teclar w ao invés de 2 que é pertinho no teclado, vai retornar zero...
Mas se ele teclar 2 2 w vai retornar 2. Ou se ele digitar 2 w vai retornar... 1. Acho que entendeu.
Escreva em torno dos dados
struct cadastro
{
    char marca[30];
    char modelo[30];
    char placa[9];
} veiculos[10];

Essa é sua única estrutura. E é global. Está declarada fora de main() ou de qualquer função do programa. Isso é um desastre, proibido em toda parte, escolas e empresas.
E de todo modo entenda que isso não é um cadastro. A struct descreve apenas um carro. O cadastro seria uma coleção de carros. Com um certo número. De carros.
Compare com essa estrutura, comum em C
typedef struct
{
    char marca[30];
    char modelo[30];
    char placa[9];

} Carro;

typedef struct
{
    unsigned n; // quantos carros
    Carro    c[10];

}   Cadastro;

int main(void)
{
    Cadastro cad1;
    Cadastro outro;

E veja que ao usar Cadastro como uma struct que tem um contador e um vetor para até 10 Carro seu programa fica muito mais simples. Cada cadastro tem seu contador dentro. Isso é encapsulamento, uma daquelas palavras chiques de programação orientação a objetos.
Não use system() nunca. Para nada. Está programando em C. system() foi escrita em C, o Windows foi escrito em C, a API do Windows é C. Pode fazer tudo.
Não use setbuf() Não vai funcionar como quer. Esqueça isso de buffer de teclado e lixo. Não existe lixo de teclado, apenas programas que não consomem os dados direito.
Não use getchar() para parar o programa sem uma mensagem avisando do que está fazendo.
        for (i = 0; i < 1; i++)

Exceto nos óbvios casos em que a lógica exija declare as variáveis de controle do loop dentro do comando. Isso é um pesadelo de manutenção e sempre vai cair na sua cabeça. Em algum lugar vai ter uma variável global à função com o ingênuo nominho de i.
        for (int i = 0; i < 1; i++)

E sobre isso... Qual a razão de um loop que roda uma única vez, de 0 até 0?


Why do we have alignment padding if memory is byte-addressable?

Question: Since we can address every byte of memory individually, why do compilers take extra care to make sure that structs and it's members align to 32-bit borders in memory?
I could be wrong here, but on a 32-bit system, is it not just as fast to get 4 bytes starting from say 0x0800, as it is from 0x0801?
Comment: You should try google, http://www.eventhelix.com/realtimemantra/ByteAlignmentAndOrdering.htm
Comment: possible duplicate of [Purpose of memory alignment](http://stackoverflow.com/questions/381244/purpose-of-memory-alignment)
Answer: On most architectures it is faster to perform read/write on naturally aligned data types. On some systems it will generate an exception (i.e. crash in most cases) if you try to access certain types when they are misaligned. So in general you always want to maintain natural alignment unless you have a very good reason not to.
See also related SO questions and answers:

Purpose of memory alignment
why is data structure alignment important for performance?
Does unaligned memory access always cause bus errors?
Answer: Taken from wikipedia:

For example, when the computer's word size is 4 bytes (a byte meaning 8 bits), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4-byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. Even though the previous data structure ends at the 14th byte, the next data structure should start at the 16th byte. Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte

The memory has to be multiple of 4 bytes for faster access and to reduce computation for better performance.
so if the memory is address byte addressable usually of 4 bytes chunks in most of cases then we know where the next address is going to start e.g. as explained above also if you end up with 14 bytes (that should be 16 bytes 4*4 = 16) then you know how much padding you have to use 16-14 = 2 bytes padding. that is why padding is used in misaligned memory.


Converting & to & etc

Question: I want to convert & to &, " to " etc.
Is there a function in c# that could do that without writing all the options manually?
Answer: System.Web.HttpUtility.HtmlDecode()

Edit: Note from here that "To encode or decode values outside of a web application, use..."
System.Net.WebUtility.HtmlDecode()

Comment: @AbuHamzah it should not work for & but it should work for &
Comment: @BartoszWojcik This method has been around since .NET 1.1.  See MSDN documentation: http://msdn.microsoft.com/en-us/library/aa332854%28v=vs.71%29.aspx
Comment: Rishav, we need to add reference to System.Web in order to use the function.
Comment: I use 4.7.1 but cant find `System.Web.HttpUtility.HtmlDecode()`
Answer: Use the static method
HttpUtility.HtmlEncode

to change & to & and " to ". Use
HttpUtility.HtmlDecode

to do the reverse.
Answer: You can use System.Net.WebUtility.HtmlDecode(uri);
Comment: @AmirNo-Family If you are not in a web application, then yes, you need the System.Net.WebUtility version.  Otherwise, System.Web.HttpUtility.HtmlDecode works just fine.
Answer: using System.Web;
...
var html = "this is a sample & string";
var decodedhtml = HttpUtility.HtmlDecode(html);

Comment: Although this code might (or might not) solve the problem, a good answer should explain what the code does and how it solves the problem.
Answer: Server.HtmlDecode.
Comment: This works in ASP.NET. But otherwise, Matt's answer is better.
Comment: I was assuming ASP.NET. The documentation mentions HttpUtility's HtmlDecode, as this is what Server.HtmlEncode calls anyway. Its easy to work this out by reading the documentation- Server.HtmlEncode's documentation actually explains what it does, unfortunately HttpUtility.HtmlDecode's doesn't.
Answer: For .NET < 4 simple encoder
    public static string HtmlEncode(string value)
    {
        return value.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'");
    }

Converting & to & etc


How to alter the Views UI config form

Question: Part 1: How do I add a form element (ie checkbox) to the field of a specific type (ie all image fields) inside the admin Views UI.  What code do I need include in a custom module.
Part 2: How do I save it to the database.

This is not a default view.
I am not creating a need field.  I am trying to alter an existing field.
Answer: You need to use Views handlers https://api.drupal.org/api/views/views.api.php/group/views_handlers/7.
Basically, you need to extend the handler class that is used by that field which in your case is field_image.
In order to start and make your custom handler work you need two basic functions to tell Views you mean some business with them. These are  hook_views_api() and hook_views_data_alter() function.
MODULE.module
/**
 * Implements hook_views_api().
 */
function uc_addons_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'uc_addons') . '/views',
  );
}

MODULE.views.inc
/**
 * Implements hook_views_data_alter().
 */
function uc_addons_views_data_alter(&$data) {
  dsm($data);
}

The hook_views_data_alter() function needs to be inside your MODULE.views.inc file.
Lastly of course is your handler w/c adds your field by extending the base handler as you can get more idea from the link. Also from my experience, the saving of values from fields are taken care by Views already.
Comment: I am changing all fields of a specific type.  If possible i do not want to create a custom handler.   I want to change alter all image type fields, that way other modules can alter image type fields as well.
Comment: Absolutely, you still need the handler for the custom field's functionality then inside hook_views_data_alter() you would place your code to run through the $data array, find the handler you extended and update the value to use your handler.
Answer: Was able to solve this problem with 2 functions:

hook_field_formatter_info_alter()
hook_form_FORM_ID_alter() where FORM_ID = views_ui_config_item_form

hook_field_formatter_info_alter() lets you set the default value.
The value itself gets save to the view/database.  There is no extra code you need to write for this to happen.
Below is an example that went into MYMODULE.module file (MYMODULE = image_field_caption).
/**
 * Implements hook_field_formatter_info_alter().
 */
function image_field_caption_field_formatter_info_alter(&$info) {
  // Add a caption visible setting to image field.
  $info['image']['settings'] += array(
    'caption_visible' => TRUE,
  );
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Altering formatter settings for field handlers in Views.
 * TODO: Drupal 8 change to hook_field_formatter_settings_form_alter().
 */
function image_field_caption_form_views_ui_config_item_form_alter(&$form, &$form_state) {
  // Get the views handler.
  $handler = $form_state['handler'];

  // Check to see if the field is an image type.
  if (isset($handler->field_info['type']) && $handler->field_info['type'] == 'image') {
    $form['options']['settings']['caption_visible'] = array(
      '#title' => t('Include Caption'),
      '#type' => 'checkbox',
      '#default_value' => $handler->instance['display']['_custom']['settings']['caption_visible'],
      '#description' => t('By default, the caption is attached to the image in the view.'),
    );
  }
}

Another alternative for Drupal 7 is to use the Field Formatter Settings API module.  This module add the hook_field_formatter_settings_form_alter() hook which you can use.
For Drupal 8 hook_field_formatter_settings_form_alter() is now part of core see field_ui.api.php API documentation.
Comment: At the time of this answer, the function has not been added to the api.drupal.org Drupal 8 section.  An alternative link is http://api.hostdog.gr/api/drupal-8/drupal!core!modules!field_ui!field_ui.api.php/function/hook_field_formatter_settings_form_alter/8.x
Comment: How can I get `$handler = $form_state['handler'];` in d8 ?
Comment: Posted d8 solution in the new answer.
Answer: Drupal 8 example: how to add a new custom setting in the Views UI config form.
This example adds new option to the Ajax settings by checking the use_ajax option, but you can change it to anything you like.
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_views_ui_edit_display_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (!empty($form['options']['use_ajax'])) {
    /** @var \Drupal\views\Entity\View $view */
    $view = $form_state->getStorage()['view'];
    $display = $view->getExecutable()->getDisplay();
    $form['options']['mymodule_option'] = [
      '#type' => 'checkbox',
      '#title' => t('Use mymodule_option'),
      '#default_value' => !empty($display->display['display_options']['mymodule_option']),
    ];

    array_unshift($form['actions']['submit']['#submit'], '_MYMODULE_form_views_ui_edit_display_submit');
  }
}

/**
 * Form submit callback for views_ui_edit_display.
 */
function _MYMODULE_form_views_ui_edit_display_submit(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\views\Entity\View $view */
  $view = $form_state->getStorage()['view'];
  $display = $view->getExecutable()->getDisplay();
  $display->display['display_options']['mymodule_option'] = $form_state->getValue('mymodule_option');
}

How to alter the Views UI config form


In mysql how can I sum 2 columns in different tables and group by a common column

Question: I have two tables:
Doctor
Headings wardName, x, y, docYears

Nurse
Headings wardName, a, b, nurseYear

There are several rows with the same wardName in each table. I want to sum all of the docYears+nurseYears for each wardName. At the moment I have this:
SELECT Doctor.wardName, SUM(docYears+nurseYears) AS Total
FROM Doctor
JOIN Nurse WHERE Doctor.wardName=Nurse.wardName
GROUP BY Doctor.wardName, Nurse.wardName;

And this effectively giving the sum(docYears)*number of rows nurses + sum(nurseYears)*number of rows of doctors for each ward. I don't want to have it multiplying by the number of rows in the other table as this gives the incorrect answer. Could anyone help me rectify this please?
Comment: First, I recommend using some formatting on your code in your question. Just highlight the lines containing your SQL statements and click on the code icon in the formatting toolbar of the editor. This will add an indentation of 4 spaces, signaling the Markdown preprocessor that it is a block of code. People who'd like to answer can more easily read your question in this way.
Answer: Try removing your WHERE Line and instead do this:
FROM Doctor JOIN Nurse ON Nurse.wardName = Doctor.wardName

Comment: This still leads to the same problem


What's the difference between Findbugs-IDEA plugin and QAPlug - Findbugs plugin in IntellijJ IDEA

Question: When I browse repos on intellij plugins, I see

FindBugs - IDEA plugin
QAPlug - Findbugs plugin

For now I installed QAPlug, since it integrates with PMD, Checkstyle etc. But I was curious to know what's the differences between those two.
Answer: A website I found helpful is https://code.google.com/p/findbugs/wiki/IntellijFindBugsPlugins. It has a graph showing the difference between the three findbugs plugins that are commonly found in IntelliJ IDEA and walks the reader through some settings of each of them.
Comment: No problem. Happy I could help, even though it was almost a year after you asked.
Comment: That table was EXACTlY what I was looking for. Thanks :)
Answer: Findbugs-IDEA seems to have a lot more features than QAPlugs - Findbugs.  One such feature is background scanning, which I find very helpful.


Request passphrase at user registration and automatically assign role to user

Question: Is there a module that would allow us to request an optional predefined pass-phrase/password at user registration?
So if the user fills in the pass-phrase he would be registered as a premium user or something, if not he would be set as a simple authenticated user.
By the way, I'm using Drupal 7.
Comment: I'm currently using Auto Assign Role and different registration paths which is similar.
Answer: Use the Rules module to implement such feature, as further detailed  below.
Step 1: Add a field to the registration form, which wil be used to have a user enter your passphrase. Even though you can use any "machine name" for that field, let's assume you call it "field_optionlist"
Step 2: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

Replace the Rules event to something like "After a new user submits a registration request"
Replace the "Value C" in the Rules condition to the value of your passphrase
For debugging reasons, start with a Drupal message to be shown (imilar to the rule mentioned above. After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user".
Answer:
Download  Rules module
Enable Rules and Rules UI
In user fields, add a new text field. Name it ex: Catch Phrase (check mark the show on user registration)
Add a new rule

React on (under user) After saving a new user account
Add Condition: Data comparison >> account:field-catch-phrase >> [enter catch phrase]
Add Action: (under user) Add user Role >> premium role

(optional) Download and enable Field Permission. With this you can hide the catch phrase field so it doesn't show up when they edit their user account.
Comment: Ehm.. sorry Pierre. I can't grant you both the answer. I was looking for a quick solution so the acceptance was almost instant. No Sssweat replied slightly first. :( You can have my up-vote of course if this could make up for it..
Comment: @Pierre.Vriens I don't think deleting an answer would be a proper reaction in ANY case. This question is gonna stay here for others to see, so maybe your approach fit them better or make the solution more clear to them. Please feel free to edit or enhance it, my upvote is permanent for your contribution. Thank you both!
Comment: Looks great! I will try it soon and I'll come back with any comments.
Comment: Oeps ....! Looks like "Rules" is the way to go, right? Now what, should I delete my "simultaeniously written answer"?
Comment: @Pierre.Vriens Sorry, I did say I was taking a pass on this (I deleted comment), but then I couldn't go to bed knowning that Kiamlaluno could close or even delete this Q. If you want to leave your answer, that's fine with me.
Comment: No need for sorry, though "I" wonder what the "rules" (oeps!) are in such scenario like here, where 2 "**pretty similar**" answers where posted more or less at the same time. Would be nice if there would be like a "answer-in-progress"-locking mechanisme (similar to suggested edits), no? Think this is worth asking as a question on meta.SE (and use our both answers as a sample to illustrate it)?
Comment: BTW, not to "argue" about your answer, but as per the current "*I will try it soon*" comment, IMHO the "accepted"-mark seems premature for now, no?
Comment: @Pierre.Vriens yes, the accept was premature. I'm fine if you want to use this as an example for meta.SE. I think the rule is whoever answers first, but eh, I am not offended if you leave your answer.
Comment: @LePhleg : **No need for sorry** either ... but now that you upvoted my answer also, I believe it's OK to leave my answer anyway. If "the community" has other thoughts about that: flag and/or vote it to get it deleted anyway. While waiting for that to ever happen, I *might* further enhance my answer later on. And if it would turn out you don't like the enhanced answer anymore, feel free to then un-upvote it again, ok?


Using two nested CellLists

Question: I'm trying to use two nested Cell-Lists while using the GWT UI-Binder for both of these lists.
Basically, I have a model-list, and every model-element contains an article-list as an UI-field. Unfortunately, a model-element (which is an AbstractCell-class) can't bind another CellList as an UI-field because AbstractCell is not a Widget. The only solution I found is passing the article-list as an HTML-string in the render-method of the AbstractCell-class.
So my question is whether there is any possibility to use a CellList (article-list) as an UI-field in another CellList (model-list) while using the UI-Binder for both of these lists?
Comment: ui-binder is something you use for Composite subclasses. Why do you want the nested cell to be a @UiField? You can store it as a field of your Top-level CellList, right?
Comment: every cell of my model-list (Top-level CellList) should have an own article-list ( represented by an UI-Binder). So I have several article-lists (one for every model-element).
Comment: if those are going be used for editing - perhaps you need just one, as a popup? Otherwise - you can put a widget there like this http://stackoverflow.com/questions/17548420/custom-gxt-cell-which-may-take-widget
Answer: The CellList is a very flat Widget type. Basically you are just rendering cells by returning HTML.
Therefore you will not be able to easily nest another Widget into a CellList.
I would also think that your UI might be complicated for the user if there is another list inside your main list - if I did not get you wrong on that?
Usually I would solve that by providing two lists - either one over the other or side-by-side. The first list is the main or master list and the second one is the child list. If you select an item in the master list, you populate the child list with all according child entries. And if you put a label "model" and "article" on them, it should be pretty clear to the user. Just keep the master list first in your UI first - at least if your UI is targeted to left-to-right (RTL) reading people.

Using two nested CellLists


Webpack does not preserve symlinks in project path

Question: I created a symlink for my "Dropbox (Personal)" folder so I could have an asset path without spaces. If I build my webpack project from a project there, however, it still uses the original path when running and referencing assets. I'm on OSX btw.
Current behavior
$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<ORIGINAL>/<project>

Desired behavior
$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<SYMLINK>/<project>

Does anyone know of a way to achieve the above? Thanks.
UPDATE
Turns out I needed to use a hard link for the Dropbox folder instead of a soft link. The soft link just meant it was basically an alias that always gets resolved to the real path. A hard link means it acts as an actual folder that contains links to the same data as the original. I used the following steps to do it properly:

Quit Dropbox app
$ mv "Dropbox (Personal)" Dropbox
$ ln -s Dropbox "Dropbox (Personal)"

I can now effectively use the Dropbox directory exactly the same as Dropbox Personal.
Also removing the webpack tag since the issue turned out to be unrelated to webpack.
Comment: An alternative? Maybe let's talk about why you are doing this? :)  Assuming you need to share across computers, can you use an alternate method like a free hosted git repo?
Comment: @olore thanks for the suggestion but I discovered the problem was I'm an idiot and didn't create a proper link in the first place
Answer: I think you need to enable symlinks - https://webpack.js.org/configuration/resolve/#resolve-symlinks
resolve: {
  /* other stuff */
  symlinks: true
}

Comment: Thanks for the response -- in this case, I want it to use the symlink as the path, rather than resolve it to the true path. I tried this option just now with symlinks set to false (and true for good measure), but didn't get any different result.
Comment: @Henry You could also try this: https://github.com/webpack/webpack/issues/554#issuecomment-565541421
Answer: Turns out I needed to use a hard link for the Dropbox folder instead of a soft link. The soft link just meant it was basically an alias that always gets resolved to the real path. A hard link means it acts as an actual folder that contains links to the same data as the original. I used the following steps to do it properly:

Quit Dropbox app
$ mv "Dropbox (Personal)" Dropbox
$ ln -s Dropbox "Dropbox (Personal)"

I can now effectively use the Dropbox directory exactly the same as Dropbox Personal.
Also removing the webpack tag since the issue turned out to be unrelated to webpack.
Comment: I think you want to remove the `-s` in your `ln` command. `-s` makes it a symlink


'/var/lib/mysql/mysql.sock' (13 "Permission denied") when accessing the socket as non mysql user

Question: I am trying to connect to local mysql server I use for development
The server starts fine, but I can not connect to it as a non-root user.
[root@somepc ]# mysql -u [someuser] -p[somepass]
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (13 "Permission denied")

As root, this works as expected. So that user does have permissions to access mysql.
mysql -u [user] -p[password]
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.30-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

When I check the permission of as my user
stat /var/lib/mysql/mysql.sock
stat: cannot stat '/var/lib/mysql/mysql.sock': Permission denied

What should these permission be for a non-root user?
Answer: The problem was related to the error on permissions on the socket file
namei -l /var/lib/mysql/mysql.sock                                                                                Wed 07 Feb 2018 12:53:54 SAST
f: /var/lib/mysql/mysql.sock
drwxr-xr-x root  root  /
drwxr-xr-x root  root  var
drwxr-xr-x root  root  lib
drwx------ mysql mysql mysql
                       mysql.sock - No such file or directory

As root I can see that the permissions on the socket file are
 ll /var/lib/mysql/mysql.sock
 srwxrwxrwx 1 mysql mysql 0 07.02.2018 12:42 /var/lib/mysql/mysql.sock=

So the problem is the directory for mysql as can be seen above.
drwx------ mysql mysql mysql

I fixed this by giving everybody access. As this is my local machine used for development.
sudo chmod go+rx /var/lib/mysql/

On a production machine, I would consider the correct users to the mysql group.
sudo chmod g+rx /var/lib/mysql/

grep mysql /etc/group
mysql:x:89:[someusers]

Please use common sense and replace whatever you need between the [] above
This now works as expected
mysql -u [user] -p[password]
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.30-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

Answer: Another solution to this problem was to not use the socket when connecting.
mysql -u [aaron] -p[aarw] -h 127.0.0.1
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.30-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

Your user would need to have the correct grants to connect to the server.
Either of these could work.
-- Grants for '[username]'@'localhost'
GRANT ALL PRIVILEGES ON *.* TO '[username]'@'localhost' IDENTIFIED BY PASSWORD '*somehash' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON `%`.* TO '[username]'@'localhost' WITH GRANT OPTION;

You need to understand the security implications of what that does before you run it.  Allow all hosts to connect, include anywhere on the internet.
-- Grants for '[username]'@'%'
GRANT ALL PRIVILEGES ON *.* TO '[username]'@'%' IDENTIFIED BY PASSWORD '*somehash' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON `%`.* TO '[username]'@'%' WITH GRANT OPTION;


Creating directories in OpenShift

Question: I think this has something to do with my SSH keys, but I'm not quite sure.
I can log into my app through terminal using:
rhc ssh getYahooPrices

However, when I try to make a new directory with:
mkdir data

I get this error:
mkdir: cannot create directory `data': Permission denied

How can my permission be denied if I'm already in the app?
I've also tried:
sudo mkdir data

Suggestions?
Answer: You don't have root permissions on your gear. In particular on specific directories are writable by you. Do an ls -la and you see the different permissions for all the folders. You can create directories in the folders which are owned by the app, however, some of of them might get deleted and re-created on deploys. See also https://help.openshift.com/hc/en-us/articles/202398490-Persistant-storage-for-OpenShift-applications. There is already a data dir under app-root. You probably should use that one.

Creating directories in OpenShift


Decode multiple base64 strings from standard input

Question: I have a file that contains multiple base64 encoded strings split by a new line character:
Y2F0Cg==
ZG9nCg==
ZmlzaAo=

When I execute: cat b64s.txt | base64 -D I expect to see:
cat
dog
fish

but I only see:
cat

What's an easy way to execute base64 -D for each line read from standard in?
Answer: while read line; do base64 -D <<< "$line"; done < b64s.txt

For what it's worth, on my Linux system with GNU coreutils 8.28 the decode flag is -d and it automatically decodes a file with multiple strings:
$ base64 -d b64s.txt
cat
dog
fish

Comment: What does this look like if `b64s.txt` is piped via cat in the example above?
Comment: `cat b64s.txt | while ...`. The redirection with `<` avoids the [useless use of cat](http://porkmail.org/era/unix/award.html).
Answer: The stock /usr/bin/base64 in macOS will only decode the first string from your input file. But base64 decoders vary wildly, there's been a fair amount of discussion on the topic even her in SO.
Python is installed by default in macOS, and the Python 2.7 interpreter that probably lives at /usr/bin/python will likely behave the way you want.
$ uname -a
Darwin ghoti.local 15.6.0 Darwin Kernel Version 15.6.0: Tue Jan 30 11:45:51 PST 2018; root:xnu-3248.73.8~1/RELEASE_X86_64 x86_64
$ cat i
Y2F0Cg==
ZG9nCg==
ZmlzaAo=
$ python -m base64 -d < i
cat
dog
fish


How to use FactoryBot with a read-only database

Question: I have 2 Rails applications. The first one manages user data. The second one has read only access to the first's database to retrieve that user data.
user = FactoryBot.create(:user)
# Test user associations that only exist in the 2nd application

Obviously that line will fail as the user cannot be created due to database-level permissions. My first thought would be to open up the first database's _test database to have full write permissions, but this feels wrong as it would have different permissions than the production environment, potentially hiding/causing other issues.
What is the best approach for using FactoryBot to test aspects of the second application using mock user data from the first?
Update
One thought I had was to pre-load a dummy test database with data and ensure the 2nd application has read only access to it. Then my tests would simply query for an existing user (would need to have prior knowledge about the data inside though) instead of using FactoryBot to create ones. Is this a viable approach?
Comment: "Is this a viable approach" - yes. It's called fixtures and it is what people do in "vanilla" rails, without factory_bot.
Comment: Can you explain how fixtures would help? I may have a misunderstanding of them. The database is read-only for the 2nd application. Wouldn't the fixture fail to be applied?
Comment: I meant the general idea: some seed data exists before tests are run. And tests are assuming structure/content of that pre-existing data ("user with id=123 and name=Joe is expected to exist", etc.)
Comment: Okay, thanks for the clarification. The only downside at this point is that the fixture data would be loaded externally. When using fixtures normally, you can easily see what data lives in the database and it can be controlled/modified/etc. This read-only thing is throwing a wrench into plans, haha
Comment: Yeah, it is, it is :)
Answer: Loading a fixture would be a good choice here as you can simulate the read only database with your user data interactions.
You will need to read in a yml or xml file similar setup to your db .. parse out the mappings of the file and then you can use it.
Quick example:
def fixture_file_path(filename)
  Rails.root.join("spec/fixtures/#{filename}").to_s
end

def read_fixture_file(filename)
  File.read fixture_file_path(filename)
end

let(:fixture)      { read_fixture_file("file.xml") }

Then create a subject here which will be useful as you will be calling this in many tests .. call the fixture
subject(:service) { described_class.call fixture }

Then you can go from there and build the interactivity to test how you need.


Test whether variables follow the same distribution

Question: If you want to test whether two variables follow the same distribution, would it be a good test to simply sort both variables, and then check their correlation? If it is high (at least 0.9?), then the variables most likely come from the same distribution.
With distribution here I mean "normal", "chi-square", "gamma" etc.
Answer: Let's find out whether this is a good test or not.  There's a lot more to it than just claiming it's bad or showing in one instance that it doesn't work well.  Most tests work poorly in some circumstances, so often we are faced with identifying the circumstances in which any proposed test might possibly be a good choice.
Description of the test
Like any hypothesis test, this one consists of (a) a null and alternate hypothesis and (b) a test statistic (the correlation coefficient) intended to discriminate between the hypotheses.
The null hypothesis is that the two variables come from the same distribution.  To be precise, let us name the variables $X$ and $Y$ and assume we have observed $n_x$ instances of $X$, called $x_i = (x_1, x_2, \ldots, x_{n_x})$, and $n_y$ instances of $Y$, called $y_i$.  The null hypothesis is that all instances of $X$ and $Y$ are independent and identically distributed (iid).
Let us take as the alternate hypothesis that (a) all instances of $X$ are iid according to some underlying distribution $F_X$ and (b) all instances of $Y$ are iid according to some underlying distribution $F_Y$ but (c) $F_X$ differs from $F_Y$.  (Thus, we will not be looking for correlations among the $x_i$, correlations among the $y_i$, correlations between the $x_i$ and $y_j$, or differences of distribution among the $x$'s or $y$'s separately: that's assumed not to be plausible.)
The proposed test statistic assumes that $n_x = n_y$ (call this common value $n$) and computes the correlation coefficient of the $(x_{[i]}, y_{[i]})$ (where, as usual, $[i]$ designates the $i^\text{th}$ smallest of the data).  Call this $t(x,y)$.
Permutation tests
In this situation--no matter what statistic $t$ is proposed--we can always conduct a permutation test.  Under the null hypothesis, the likelihood of the data $\left((x_1, x_2, \ldots, x_n), (y_1, y_2, \ldots, y_n)\right)$ is the same as the likelihood of any permutation of the $2n$ data values.  In other words, the assignment of half the data to $X$ and the other half to $Y$ is a pure random coincidence.  This is a simple, direct consequence of the iid assumptions and the null hypothesis that $F_X=F_Y$.
Therefore, the sampling distribution of $t(x,y)$, conditional on the observations $x_i$ and $y_i$, is the distribution of all the values of $t$ attained for all $(2n)!$ permutations of the data.  We are interested in this because for any given intended test size $\alpha$, such as $\alpha = .05$ (corresponding to $95$% confidence), we will construct a two-sided critical region from the sampling distribution of $t$: it consists of the most extreme $100\alpha$% of the possible values of $t$ (on the high side, because high correlation is consistent with similar distributions and low correlation is not).  This is how we go about determining how large the correlation coefficient must be in order to decide the data come from different distributions.
Simulating the null sampling distribution
Because $(2n)!$ (or, if you like, $\binom{2n}{n}/2$, which counts the number of ways of splitting the $2n$ data into two pieces of size $n$) gets big even for small $n$, it is not practicable to compute the sampling distribution exactly, so we sample it using a simulation.  (For instance, when $n=16$, $\binom{2n}{n}/2 = 300\ 540\ 195$ and $(2n)! \approx 2.63\times 10^{35}$.)  About a thousand samples often suffices (and certainly will for the explorations we are about to undertake).
There are two things we need to find out: first, what does the sampling distribution look like under the null hypothesis.  Second, how well does this test discriminate between different distributions?
There is a complication: the sampling distribution depends on the nature of the data.  All we can do is to look at realistic data, created to emulate whatever it is we are interested in studying, and hope that what we learn from the simulations will apply to our own situation.
Implementation
To illustrate, I have carried out this work in R.  It falls naturally into three pieces.

A function to compute the test statistic $t(x,y)$.  Because I want to be a little more general, my version handles different size datasets ($n_x \ne n_y$) by linearly interpolating among the values in the (sorted) larger dataset to create matches with the (sorted) smaller dataset.  Because this is already done by the R function qqplot, I just take its results:
test.statistic <- function(x, y) {
  transform <- function(z) -log(1-z^2)/2
  fit <- qqplot(x,y, plot.it=FALSE)
  transform(cor(fit$x, fit$y))
}

A little twist--unnecessary but helpful for visualization--re-expresses the correlation coefficient in a way that will make the distribution of the null statistic approximately symmetric.  That's what transform is doing.
The simulation of the sampling distribution.  For input this function accepts the number of iterations n.iter along with the two sets of data in arrays x and y.  It outputs an array of n.iter values of the test statistic.  Its inner workings should be transparent, even to a non R user:
permutation.test <- function(n.iter, x, y) {
  z <- c(x,y)
  n.x <- length(x)
  n.y <- length(y)
  n <- length(z)
  k <- min(n.x, n.y)
  divide <- function() {
    i <- sample.int(n, size=k)
    test.statistic(z[i], z[-i])
  }
  replicate(n.iter, divide())
}

Although that's all we need to conduct the test, in order to study it we will want to repeat the test many times.  So, we conduct the test once and wrap that code within a third functional layer, just generally named f here, which we can call repeatedly.  To make it sufficiently general for a broad study, for input it accepts the sizes of the datasets to simulate (n.x and n.y), the number of iterations for each permutation test (n.iter), a reference to the function test to compute the test statistic (you will see momentarily why we might not want to hard-code this), and two functions to generate iid random values, one for $X$ (dist.x) and one for $Y$ (dist.y).  An option plot.it is useful to help see what's going on.
f <- function(n.x, n.y, n.iter, test=test.statistic, dist.x=runif, dist.y=runif,
    plot.it=FALSE) {
  x <- dist.x(n.x)
  y <- dist.y(n.y)
  if(plot.it) qqplot(x,y)

  t0 <- test(x,y)
  sim <- permutation.test(n.iter, x, y)
  p <- mean(sim > t0) + mean(sim==t0)/2
  if(plot.it) {
    hist(sim, xlim=c(min(t0, min(sim)), max(t0, max(sim))),
         main="Permutation distribution")
    abline(v=t0, col="Red", lwd=2)
  }
  return(p)
}

The output is a simulated "p-value": the proportion of simulations yielding a statistic that looks more extreme than the one actually computed for the data.

Parts (2) and (3) are extremely general: you can conduct a study like this one for a different test simply by replacing test.statistic with some other calculation.  We do that below.
First results
By default, our code compares data drawn from two uniform distributions.  I let it do that (for $n.x = n.y = 16$, which are fairly small datasets and therefore present a moderately difficult test case) and then repeat it for a uniform-normal comparison and a uniform-exponential comparison.  (Uniform distributions are not easy to distinguish from normal distributions unless you have a bit more than $16$ values, but exponential distributions--having high skewness and a long right tail--are usually easily distinguished from uniform distributions.)
set.seed(17)             # Makes the results reproducible
n.per.rep <- 1000        # Number of iterations to compute each p-value
n.reps <- 1000           # Number of times to call `f`
n.x <- 16; n.y <- 16     # Dataset sizes

par(mfcol=c(2,3))        # Lay results out in three columns
null <- replicate(n.reps, f(n.x, n.y, n.per.rep))
hist(null, breaks=20)
plot(null)

normal <- replicate(n.reps, f(n.x, n.y, n.per.rep, dist.y=rnorm))
hist(normal, breaks=20)
plot(normal)

exponential <- replicate(n.reps, f(n.x, n.y, n.per.rep, dist.y=function(n) rgamma(n, 1)))
hist(exponential, breaks=20)
plot(exponential)

On the left is the null distribution of the p-values when both $X$ and $Y$ are uniform.  We would hope that the histogram is close to uniform (paying especial attention to the extreme left end, which is in the range of "significant" results)--and it actually is--and that the sequence of values obtained during the simulation, shown below it, looks random--and it does.  That's good.  It means we can move on to the next step to study how this changes when $X$ and $Y$ come from different distributions.
The middle plots test $16$ uniform variates $x_i$ against $16$ normal variates $y_i$.  More often than not, the p-values were lower than expected.  That indicates a tendency for this test actually to detect a difference.  But it's not a large one.  For instance, the leftmost bar in the histogram shows that out of the 1000 runs of f (comprising 1000 separately simulated datasets), the p-value was less than $0.05$ only about 110 times. If we consider that "significant," then this test has only about an $11$% chance of detecting the difference between a uniform and normal distribution based on $16$ independent values from each.  That's pretty low power.  But maybe it's unavoidable, so let's proceed.
The right-hand plots similarly test a uniform distribution against an exponential one.  This result is bizarre.  This test tends, more often than not, to conclude that uniform data and exponential data look the same. It seems to "think" that uniform and exponential variates are more similar than two uniform variables! What's going on here?
The problem is that data from an exponential distribution will tend to have a few extremely high values.  When you make a scatterplot of those against uniformly-distributed values, there will then be a few points far to the upper right of all the rest.  That corresponds to a very high correlation coefficient.  Thus, whenever either of the distributions generates a few extreme values, the correlation coefficient is a terrible choice for measuring how different the distributions are.  This leads to another even worse problem: as the dataset sizes grow, the chances of obtaining a few extreme observations increase.  Thus, we can expect this test to perform worse and worse as the amount of data increase.  How very awful... .
A better test
The original question has been answered in the negative.  However, there is a well-known, powerful test for discriminating among distributions: the Kolmogorov-Smirnov test.  Instead of the correlation coefficient, it computes the largest vertical deviation from the line $y=x$ in their QQ plot.  (When data come from the same distribution, the QQ plot tends to follow this line.  Otherwise, it will deviate somewhere; the K-S statistic picks up the largest such deviation.)
Here is an R implementation:
test.statistic <- function(x, y) {
  ks.test(x,y)$statistic
}

That's right: it's built in to the software, so we only have to call it.  But wait!  If you read the manual carefully, you will learn that (a) the test supplies a p-value but (b) that p-value is (grossly) incorrect when both x and y are datasets.  It is intended for use when you believe you know exactly what distribution the data x came from and you want to see whether that's true.  Thus the test does not properly accommodate the uncertainty about the distribution the data in y came from.
No problem!  The permutation test framework is still just as valid.  By making the preceding change to test.statistic, all we have to do is re-run the previous study, unchanged.  Here are the results.

Although the null distribution is not uniform (upper left), it's pretty uniform below $p=0.20$ or so, which is where we really care about its values.  A glance at the plot below it (bottom left) shows the problem: the K-S statistic tends to cluster around a few discrete values.  (This problem practically goes away for larger datasets.)
The middle (uniform vs normal) and right( uniform vs exponential) histograms are doing exactly the right thing: in the vast majority of cases where the two distributions differ, this test is producing small p-values.  For instance, it has a $70$% chance of yielding a p-value less than $0.05$ when comparing a uniform to a normal based on 16 values from each.  Compare this to the piddling $11$% achieved by the correlation coefficient test.
The right histogram is not quite as good, but at least it's in the correct direction now!  We estimate that it has a $30$% chance of detecting the difference between a uniform and exponential distribution at the $\alpha=5$% level and a $50$% chance of making that detection at the $\alpha=10$% level (because the two bars for the p-value less than $0.10$ total over 500 of the 1000 iterations).
Conclusions
Thus, the problems with the correlation test are not due to some inherent difficulty in this setting.  Not only does the correlation test perform very badly, it is bad compared to a widely known and available test.  (I would guess that it is inadmissible, meaning that it will always perform worse, on the average, than the permutation version of the K-S test, implying there is no reason ever to use it.)
Comment: It's all easy to find on Wikipedia through the obvious searches :-).  As far as correlation goes, the problem is that variables can be strongly correlated but have totally different distributions; in fact, there exist sequences of distributions that get arbitrarily "far apart" (in an intuitive sense) while the distribution of their correlation coefficient gets arbitrarily close to $1$ in large datasets.  This makes the correlation coefficient a poor discriminator of distribution.
Comment: Very nice explanation, and I like to see others do some simulations. I still have a trouble getting why a correlation does seem to predict a little (or we can't even say that much?). Also, the only vague (yet critical part to understand why KS works) is about "the x = y" line ("it computes the largest vertical deviation from the line y=x in their QQ plot. (When data come from the same distribution, the QQ plot tends to follow this line."). Thanks for the effort though, I learned a lot
Comment: KS tests whether two datasets came from the same distribution function, ie their CDFs are the same. It seems to me, though, that OP may be looking for a test that will say that Exp(0.1) is the same thing as Exp(100), and Normal(0, 5) is the same as Normal(10, .2). KS doesn't do this at all, and indeed it's probably impossible in general (and I don't really know when you'd want it). But some test of how deformable one is into the other might work in simple cases (e.g. centering and standardizing will handle normals decently, though not exponentials).
Comment: @Dougal I reread your comment. Is it correct to say that when we mention that "distributions are the same", we mean that the CDF are the same?
Comment: @PascalvKooten "Distribution" is a word that gets used to mean different things in different contexts. In general, though, I think that "distribution" is typically taken to mean something defined by a particular CDF (or equivalent); "normal" or "gamma" refer to _families_ of distributions, which define a particular distribution by their parameter values (e.g. $\mu$ and $\sigma^2$ for a normal).
Comment: @Dougal And you're saying that these family of distributions can be identified on the basis of their CDF?
Comment: @PascalvKooten I don't quite know what you mean by that. You can view the normal distribution family as a family of CDFs, each of them obtained by a particular combination of $\mu$ and $\sigma$; if you're given a CDF and want to see whether it's normal, you can try to find $\mu$ and $\sigma$ that produce that function, or say that it's not a member of the family.
Comment: @whuber Hi. Apologies for contacting you via this old post, but I am looking for a way to test if two sets of observations, $\mathbf{X} and \mathbf{Y}$, which are generated by a correlated bi-vitiate ARMA-GARCH type process, have the same unconditional marginal distribution. So, the two samples are cross-correlated and observations within each sample are not independent. As far as I can tell KS, AD and other similar tests cannot be applied in this case. Would you be able to suggest an approach / reference? Thanks
Comment: @whuber The KS test doesn't seem to work even if the two samples are simple cross-correlated. For example, when I run a 2-sample KS test with one sample contacting observation from standard normal and the other from correlated (90%) t-distributed with 5 degrees of freedom, the test is passed at even 90% confidence level.
Answer: No, correlation is not a good test of this.
x <- 1:100 #Uniform
y <- sort(rnorm(100)) #Normal
cor(x,y) #.98

I don't know of a good test that compares whether, e.g. two distributions are both normal, but possibly with different mean and s.d. Indirectly, you could test the normality of each, separately, and if both seemed normal, guess they both were.
Answer: If there are a sufficiently large number of variables, then this may show more correlation with size-ordered values. However, it doesn't seem to be a particularly useful method, not least because it provides little means to estimate confidence that they might use the same model.
A problem that you are liable to experience is when you have models with similar mean and skewness, but a difference in kurtosis, as a moderate number of measurements may fit sufficiently well to look fairly well correlated.
It seems more reasonable to model both variables against different distributions to see which is most likely for each, and compare the results.
There may be some merit to normalising both values, sorting and plotting each - this will allow you to see how the fits compare - and you can plot a possible model for both as well, which would be related to what you suggested, but rather than expecting a concrete answer, just a visual idea on the closeness of the distributions.
Comment: (1) My analysis finds that the expectation expressed in the first sentence is not borne out: with a sufficiently large number of variables, if one of the distributions has short tails and the other has just a slight chance of exhibiting more extreme values, then the correlation tends to be unduly high. (2) When you "model ... against different distributions" how do you control for the multiple dependent tests that are implied by that prescription?


Centered DIV w/ width dependant on text, buffered by two divs that should fill the containing DIV

Question: Thank you all for your help so far.  I updated the description, concept image, and JSFiddle link to make things a little clearer.

I have been wracking my brains on this seemingly small issue the whole day.  My web dev friends are baffled and I could not find a suitable answer in my search of this site and others (though, I could have missed it somewhere along the way).
Here's what I am trying to achieve:

3 non-fixed-width DIVs within one fixed-width container DIV
The center DIV needs to be centered, and no larger than the text it contains.
The left and right DIVs need to fill the remaining space in the container DIV.

Here are some links to help communicate this concept:
This is what I'd like to end up with
Check out this JSFiddle Link

The basic HTML:

Text inside center should resize this block

Below, I removed most of the styles I have tried.  This CSS currently centers the DIV (if I set it as an inline block), but I need the other divs to fill the left and right space remaining:
#container {
  width:750px;
  text-align:center;
  border:3px solid #E85355;
}
#left {
  background-color:#A3CB46;
}
#center {
      background-color:#6D6E71;
  display:inline-block;
  color:#FFFFFF;
}
#right {
  background-color:#1DB0CE;
}

I've tried floating, no-wrap, overflow, etc.  Thanks a million to whomever can offer some help!
Comment: Do none of the answers given solve your problem?
Answer: Try the following CSS. It fills the width of the container...
#container {
    width:764px;
    text-align:center;
}
#container > div {
    display: table-cell;
}
#center {
    background-color:#CDD7D7;
}
#right, #left {
    background-color:#E85355;
    width:200px;
}

EDIT: display:table on container, not needed...
Answer: Do you need this ?
CSS
#container {
    width:764px;
    text-align:center;}
#left {
    background-color:#E85355;
    width:20px;
    height:20px;
    float:left;
}
#center {
    background-color:#CDD7D7;
    display:inline-block;}
#right {
    background-color:#65A8A6;
    width:20px;
    height:20px;
    float:right;
}

DEMO
Comment: Hmmm.  Not sure what you were trying to show here.  I should specify that only the #container DIV is fixed-width.  The #center DIV width is determined by the text inside it, and the #left/#right DIVS should then fill the remaining space of the #container DIV.
Answer: Try this:
jsfiddle.net/SHnc9/36/
Comment: That is interesting, but I am looking to get the center DIV (with "I'm Fluid" text) to shrink to the size of the text.  Then, the two outer DIVS fill the space.  Does that make sense?
Answer: You can do it with flexbox! Demo: http://dabblet.com/gist/7187048
Markup

enter text here to see this box grow!

CSS
.container {
  display: flex;
  }

.box {
  flex-grow: 1;
  }
.center {
    flex-grow: 0; /* to get the box to wrap closely around the text */
    }

According to caniuse.com http://caniuse.com/#search=flexbox, it's supported in all the major desktop browsers with firefox having partial support which probably means it uses the old syntax / doesn't support some new properties but the demo worked fine when I checked.
Just be sure to use prefixes(or use a prefixfree / unprefix plugin), add the old syntax for old browser versions (add old syntax below the new ones).
Also, use display: inline-block as a fallback.
You may also want to check out flexie.js http://flexiejs.com/.
Essential reading:
http://css-tricks.com/snippets/css/a-guide-to-flexbox/


Working with android and redmine restapi to log time

Question: i m working on a app that can log time using redmine.
for now i can receive the projects, but i have no idea about log the time.
there is a restapi of redmine, but i dont find any answers...:
http://www.redmine.org/projects/redmine/wiki/Rest_api
regards,
kai
Comment: How about clicking the Time Entries link
Comment: http://www.redmine.org/projects/redmine/wiki/Rest_TimeEntries  it says how to log time to either project or issue right there..
Comment: of courde i saw this, but i dont know how to implement it
Answer: You could follow what the redmine-java-api does. Unfortunately the redmine-java-api doesn't work out of the box on android but it can be modified to do so. See my answer here.
Alternatively follow this answer on how to make a HTTP request and make a request by:
<code>new RequestTask().execute("http://demo.redmine.org/time_entries.json");
</code>
Then, to make a POST request follow this guide


MFC OnMouseActivate: Where is focus if you eat the mouse event?

Question: Where does focus remain?
Is focus left on the window that previously held focus, or is focus in limbo, on no window?
I've noticed that when I eat a message, it appears as if nothing has focus.
I return MA_NOACTIVATEANDEAT
Comment: Are you returning `MA_ACTIVATEANDEAT` or `MA_NOACTIVATEANDEAT` from the function?
Answer: The focus can't be in limbo. Something always has to have the focus, so it will either be the window that previously held the focus, or the new window that is activated by the mouse event.
The documentation for CWnd::OnMouseActivate tells us what will happen, depending on the value that you return from the function:

MA_ACTIVATE           Activate CWnd object
MA_NOACTIVATE         Do not activate CWnd object
MA_ACTIVATEANDEAT    Activate CWnd object and discard the mouse event
MA_NOACTIVATEANDEAT  Do not activate CWnd object and discard the mouse event

Since you're returning MA_NOACTIVATEANDEAT, the previously focused object will retain the focus and the mouse event will be discarded.
Comment: sorry about that delay.
It twas something I thought I did, but alas didn't.


solutions fort-order homog. system

Question: Question: Can one of the following functions be a solution of a first-order autonomous homogeneuous system?
(1) $x(t)=(3e^{t}+e^{-t},e^{2t})$
(2) $x(t)=(3e^{t}+e^{-t},e^{t})$
(3) $x(t)=(3e^{t}+e^{-t},t e^{t})$
(4) $x(t)=(3e^{t},t^2 e^{t})$
I know that every solution can be written as a linear combination of $t^j exp(\alpha t)$, therefore I would say that only (4) can be a solution, true?
Answer: Its a first order system with a 2nd order characteristic equation for each of the variables. These two solutions show up as linear combinations of exp in the answer.
It is also possible that the two roots are in fact, repeated roots, in which case you do not have two distinct combinations of exp, but what you will have is exp of the repeated root with an extra factor of t. Possible answers would therefore look like:
$Ae^a + Be^b, Ce^a + De^b$
OR
$Ae^a , t Be^{a}$
None, but 2) of the options matches the form above.
4) cannot be an answer because, only a triple repeated root would have a t^2, which is not possible for a 1st order system.
Comment: So the two possible solutons are (2) and (3), right?
Comment: No. By 2) I meant only number (2), 3) cannot be an answer because the system does not have 3 roots.
Answer: I assume by "homogeneous system" you mean "homogeneous linear system".
A $2 \times 2$ matrix can either have two eigenvalues or one eigenvalue of multiplicity $2$.  In the first case the solutions are linear combinations of vectors times two exponentials $e^{\lambda_1 t}$ and $e^{\lambda_2 t}$.  That's what you have in one of your four examples.
In the second case you have one exponential and $t$ times that exponential.
But you can't have three different $\lambda$'s, or $e^{\lambda_1 t}$ and $t e^{\lambda_2 t}$ with $\lambda_2 \ne \lambda_1$, or $t^2 e^{\lambda t}$.

solutions fort-order homog. system


Why str can't get a second parameter,when __str__ can?

Question: I decided to use str for printing the contents of a tree in tree-like structure,using something like
print tree

The nodes of the tree are all objects of user-created classes and I overload their __str__ magic method in order to use the child nodes' str after indent t tabs like that
def __str__ (self,t=0) :`
    return t*'\t' + str(self.label) +':' +'\n'+ str(self.l,t+1)+'\n'+str(self.right,t+1)+'\n'

However I can't call str with that t parameter,but I can call node.__ str__(t=4).Isn't str,only shortcut to the magic method?Or is that because the parser rejects additional params to str without checking the magic method?
P.S. I am interested in the behaviour.I know that's not the best way to print a tree,it was a hack ;)
Answer: Imagine it this way.
def str(obj):
    try:
        return obj.__str__()
    except ...:
        ...

Just because __str__ can take more parameters, doesn't mean that str is configured to pass those parameters through.
Comment: but if str behaves as in your example,it'll work if obj.__str__() doesn't lead to exception.And it doesn't in my case.
Comment: @Alexander Ivanov: The `...` in the code is *omitted code*, just for illustration purposes only.  I did not intend to give a complete implementation of `str`.
Comment: i know,I got confused by something else
Answer: If you have a Class C with a method __str__(self, t=0), str(c) will call C.__str__(c) which sets t to zero as declared. str() itself only accepts one argument.