Gerar arquivo .ret Boleto

Question: Pesquisei na internet e vi que o arquivo .ret serve para ver se o boleto foi pago.
Ja consegui abrir esse arquivo .ret com o PHP com alguns exemplos na internet, como faço para que o PHP gere esse arquivo .ret quando é gerado o boleto, afim de checar posteriormente se o mesmo foi pago?
Estou usando o boleto do Santander (se isso for relevante)
Comment: Consegui te ajudar? :)
Comment: Me ajudou sim amigo, queria ver uma forma de o site pegar esses arquivo .ret automático sem tem que estar acessando o site do Santander. Será que existe alguma forma? Porque como o PagSeguro faz por exemplo para saber se o boleto foi pago? Deve ser automático isso
Comment: Infelizmente isto só é possível através de VAN's (serviços terceirizados contratados)
Answer: Se quiser entender um pouco mais sobre os arquivos .RET de uma olhadinha aqui.
Basicamente, os arquivos de retorno do bancos 'Não são gerados', eles são retornos!
O responsável por fornecer estes dados são os bancos, no seu caso, o Santander e devem ser extraídos do site do seu banco(o primeiro link demonstra como extrair o arquivo e o segundo um pouco do uso)
Oque sua aplicação deve fazer é: Ler os arquivos retornos do banco.
Com isto é possível saber se os afins foram pagos ou se são inválidos(Seguidos dos códigos que apontam os motivos para isto, para que possam ser devidamente corrigidos)

Acesse o Site do seu banco
Clique em Transferência de Arquivo" e depois na opção Retorno, clique em "Consultar".

Caso apareça a tela abaixo, selecione "Transferência Simples" e depois "Personalizar"

Coloque data inicial, data final e depois clique no botão "Enviar".

Basta Salvar no seu computador.

O Passo a Passo foi retirado da seguinte pagina e contem 7 passos, porem os últimos 2 podem ser ignorados por serem específicos de um sistema.

Gerar arquivo .ret Boleto


tf.decode_csv lasts too long

Question: I am using TensorFlow v0.8, and it's strange that it takes around 5 minutes to print the second print time.time(). I thought tf.decode_csv() would just simply add an operation into the graph without doing any computation.
Why does it take so long to call tf.decode_csv()?
def main(argv=None):
  # deal with arguments
  with tf.device("/cpu:0"):
    filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(train_set_filename + "*"))

    reader = tf.TextLineReader()
    _, line = reader.read(filename_queue)

    default = [[-1.0] for x in range(image_size * image_size * channels + 1)]
    print time.time()
    line = tf.decode_csv(line, record_defaults=default)
    print time.time()
    label = line[0]
    feature = tf.pack(list(line[1:]))

    ...

Answer: The tf.decode_csv(line, record_defaults=default) takes a lot of time because you use so many columns.
I don't know your image_size, but if it is around 200 you are trying to set 120,001 columns to your csv, which is huge. You are right, TensorFlow is not doing any computation, but it has to build the graph properly and with that much columns it takes a lot of time !
I strongly advise you to not use csv format for images. Instead you should store your images in JPEG format, and use tf.image.decode_jpeg().
Comment: yes, my image_size is 224. thanks for the suggestion, I will have a try tomorrow.

tf.decode_csv lasts too long


Algebra of a cartesian product of two or more copies of a Lie Group

Question: Let $G$ be a Lie Group end let us consider the Cartesian product of $n$ copies of $G$ ($N\geq 2$): $G\times G\times \ldots \times G$.
What is the Lie Algebra of this group?
Is the Lie Algebra the direct sum g+g...+g (where g is the Lie algebra of $G$) ?
Answer: Of course it is.
Generally, when $M_1,\ldots,M_n$ are manifolds and for every $i$, $p_i\in M_i$ we have the identity $$T_{(p_1,\ldots,p_n)}M_1\times\ldots\times M_n=\bigoplus_iT_{p_i}M_i.$$Now given a Lie group $G$, its Lie algebra can be identified with $T_eG$, and we're done.
Comment: You need to know that this identification is natural in order to know that it respects the Lie bracket; a priori this argument only tells you that you get an identification as vector spaces.


Editing client password on a live system - how bad a mistake is this?

Question: I was tasked with adding some users to Active Directory today. I did all of this, however, I had a list of 20 users to add. Of this list, it listed 5 users already added.
The list's instructions were basically to just add the users, so I did. There is no way I can get passwords of existing users from AD so for testing purposes I changed these passwords of the existing accounts. Unfortunately, these accounts are in use (don't know how often).
My senior dev said it's fine learn from your mistakes you weren't to know (I did make a similar mistake just days before but that was due to attention to detail and was 100% my fault but I am still doing ok in my job - I'm on probation - as my senior dev always says).
There has been no client impact (yet?). How big a mistake is this?
Thanks
Answer: If the accounts are physical users, there's very little problem. They'll have to contact support to get their password reset. The trouble depends on how senior the person is and how much trouble is involved in them contacting support; a remote user with a laptop is going to have more trouble than someone who sits next to the person that can change their password.
If the account is used by a process, the trouble depends on whether that password is known and how many places might require changing if it isn't.
Generally, unless you have a pattern of making mistakes, I doubt you need to worry. Obviously I'm not your manager.
Comment: There isn't much involved in contacting support, but the users may be senior.
Answer: If they're physical users, there must be a way to trace those users back to real people. Be proactive and notify them their password has been changed and they will need to contact support. If you silently sit there and "hope nobody notices", it's liable to get you fired when they trace the problem back to you. Acknowledge what happened and take steps to correct it. And if you're not the one to take the phone call, make sure they know what happened too, so they can respond quickly and appropriately to complaints.
Push comes to shove, it's only 5 users. It's not like an entire office of a large corporation will be flooding support with phone calls. Assuming it takes 5 minutes to reset a password, we're looking at a total of 25 minutes lost somewhere. Humans make mistakes, and in the world of such mistakes, 25 minutes with a very clear solution isn't too bad.

As David Pashley says, however, if they're used by a process and aren't physical people, hopefully the password is known and can be set back. If not, this could be a sticking point.
As a side question, if the list showed 5 users were already added, why didn't you just add and test only the other 15? Answer this and you can answer your own question of how bad a mistake it was (or whether it even was an avoidable case).
Comment: It'd take less than 25 minutes. Password management is a very quick thing (on AD). I am a junior dev. I just didn't know of the internal procedures in the company (eg I need authorisation to work with existing accounts). They are physical people. When the passwords are set, the client gets an email with the credentials. Hopefully I can find this. I didn't just add the other 15 because of the post below yours.
Answer: You'll know when a mistake is really bad.  The phones will ring off the hook, whoever answers the phones will give you dirty looks for a week, etc...
Sounds like you already have a decent idea what the actual impact on your users was (minimal to none).  You did what you were told ("adding users") without taking the initiative to first check if any of those users existed. I must say, though: one of the most important "skills" for system administration is "attention to detail"; I'd rather hire a junior admin with almost no experience on my particular platform who has strong attention to detail than a junior admin somewhat experienced on the platform without it.
I suggest that in the future, concentrate on how to mitigate (minimize the impact of) mistakes instead of eliminate mistakes.  Everybody makes mistakes, you can't avoid it happening now and then.  Learn from them.  Expect them.

Worst Case: you make a mistake and try to cover it up.  Sometimes you get away with it, sometimes it backfires.
Best Case: you make a mistake, it's on a test system/environment and nobody has any reason to care except you (maybe means you have to spend 15 minutes recreating the test system/env).  Heck, you can call these mistakes "experiments" or something, even.
Reasonable Case: you make a mistake, you immediately let anybody that can help mitigate (boss, senior sysadmin, helpdesk staff, users affected) know and minimize the actual impact to business
Alternate Reasonable Case: you make a mistake and have a backout plan that allows for immediate repair (copy the config file, edit it, break it, put the original back)

For instance, if the helpdesk knows that users X, Y and Z may have had their password accidentally reset, when user Y calls about not being able to log into the system, they can immediately assist them with the correct solution instead of wasting 5 minutes with unnecessary troubleshooting because the mistake got covered up.
Answer: Sounds like poor instructions to me (at least, the way you have told the story...) Why were you given a list with duplicates? If this is part of a regular process (say, adding new users once a week) then you need to investigate the process that produced the list to prevent the next junior guy making the same mistake.
Comment: I have no idea why the list contained duplicates. That gave me the impression that the existing accounts hadn't been signed off/given to the client, because they could be changed. I am working on this site with someone and he said "the client will want access, let me know when", so I'm not sure if the client has access but then the site has content on it (which we put up).


Laravel 5.7.28 Debug not setting off in live server [ APP_DEBUG = false ] not working

Question: I have uploaded one laravel project to live server. I have set APP_DEBUG=false
But it still loading things into debug mode.
ie. Showign .env file output when we open in browser
Laravel version is 5.7.28

.env ==> [ APP_DEBUG=false ] Done
config/app.php  ==> 'debug' => env('APP_DEBUG', false),   DONE
Both above changes has been made but it still shoing all the output.

I don't have access to live server terminal to install any addition server. Can anyone helps me to find any other setting to prevent debug on in live server.
How to prevent debugging and direct access to file.
Any suggestion or help appreciated.
Comment: What do you mean by "Showign .env file output when we open in browser"? Looks like a bug in your application
Comment: Thanks Haase. I mean direct access of all dot files including .ENV file.
For example, If you type www.website/.env
Comment: Why do you place `.env` in some directory that is accesible? Usually, you should place it outside the document root
Comment: I have no idea how to configure .env outside root in laravel. Laravel setup comes default as .env on root folder.
Answer: Generally to stop debug mode in laravel following should work.

.env ==> [ APP_DEBUG=false ]
config/app.php ==> 'debug' => env('APP_DEBUG', false),

You said you cannot access terminal. Is it require for php artisan command ??
For that you can use route call to execute laravel command.
<code>Route::get('/clear-cache', function() {
    Artisan::call('cache:clear');
    return "Cache is cleared";
});
</code>

You said you want to prevent direct access of file.
Generally into google you can easily search for websites which have .env files. And direct access are generally open.
Do following changes into .htaccess file.
<code># To Disable index view
Options -Indexes

# To Hide a .env file
<Files .env>
    Order allow,deny
    Deny from all
</Files>

# To Hide all .(DOT) files
<FilesMatch "^\.(.+)$">
   order deny,allow
   deny from all
   allow from 127.0.0.1
</FilesMatch>
</code>


Graphical Model Equivalent of Matrix Pseudoinverse

Question: The may sound like a strange question but I was wondering if a Pseudoinverse of a matrix could be found using SVD whether there was a graphical modelling equivalent that could be used to estimate the inverse of a matrix.
Answer: If $A = U \Sigma V^{*}$ then $A^{+} = V \Sigma^{+} U^{*}$ where
$\Sigma^{+}(i,i) = \frac{1}{\sigma(i)} $ when $\sigma(i) \neq 0$ and 0 everywhere else.
Comment: Is there a name for this so I can look it up as a reference?
Comment: is sigma the standard deviation?
Comment: $\sigma$ are the singular values of the original matrix. Look up Moore-Penros Pseudoinverse
Comment: I have been using the Moore-Penros Pseudoinverse. My question was asking whether a Bayesian method existed?


jquery show only next div with same class

Question: I'm trying to do a sequence of steps with jquery but I'm failing to achieve the result I want.
I have 3 steps, with a class of .wiki-step- plus a number.
my javascript is this one:
function stepping() {
    var stepButton = $("a.button");
    var step = $("[class*='wiki-step-']");
    stepButton.closest(step).hide().next(step).show();
}

$("a.button").on("click",function(){
    stepping();
});

It works correctly with only 2 steps but I've noticed that if I add a third one, the jquery (next) shows all the other steps at once but I want to show only the next div in line, not all of them.
Here's a fiddle: https://jsfiddle.net/vsomcag2/1/
you can see how it shows the 2nd and 3rd step at once.
I can't use nextUntil() i guess, I think I should use a counter of some sort but I don't know where to start. I would like to avoid specifying numbers because I would like to have the ability to add or remove steps without editing the js.
Any help is greatly appreciated.

    function stepping() {
        var stepButton = $("a.button");
        var step = $("[class*='wiki-step-']");
        stepButton.closest(step).hide().next(step).show();
    }

    $("a.button").on("click",function(){
        stepping();
    });
div[class*="wiki-step-"] {
        display: none;
       width: 500px;
       height: 500px;
       border:1px solid red;
    }

step 1

next

step 2

next

step 3

Answer: You need to get reference to the clicked object a  and show hide according to that object.
function stepping(obj) {
  var stepButton = $(obj);
  var step = $("[class*='wiki-step-']");
  stepButton.closest(step).hide().next(step).show();
}

$("a.button").on("click", function () {
   stepping(this);
});

Here is jsfiddle
Answer: Could be pretty simple:
$("a.button").on("click",function(){
        $(this).parent().hide();
        $(this).parent().next().show();
    });

Demo: https://jsfiddle.net/vsomcag2/3/
Answer: If you want to show only one at a time you can use this:

function stepping(elem) {
  var step = $("[class*='wiki-step-']");
  elem.closest(step).hide().next(step).show().next(step).hide();
}

$("a.button").on("click", function() {
  stepping($(this));
});
div[class*="wiki-step-"] {
  display: none;
  width: 500px;
  height: 500px;
  border: 1px solid red;
}

step 1

  next

step 2

  next

step 3

Basically what I am doing is passing the clicked element to the function which is a single element rather than an array of elements.
Answer: Try following code:
function stepping(self) {
    var step = $("[class*='wiki-step-']");
    $(self).closest(step).hide().next(step).show();
}

$("a.button").on("click",function(){
    stepping(this);
});

Answer: First, you get the current step, who is visible, then check if there is a step after that one, then show it if it exists, and hide the current one.

    function stepping() {
        //var stepButton = $("a.button");
        var currentStep = $("[class^='wiki-step-']:visible") ;
        var nextStep = $(currentStep).next("[class^='wiki-step-']");
        if(nextStep.length>0){
             currentStep.hide();
             nextStep.show();
        }
        //var step = $("[class*='wiki-step-']");
        //stepButton.closest(step).hide().next(step).show();
    }

    $("a.button").on("click",function(){
        stepping();
    });
div[class*="wiki-step-"] {
        display: none;
       width: 500px;
       height: 500px;
       border:1px solid red;
    }

step 1

next

step 2

next

step 3

Answer: I've slightly modified your HTML & CSS, as I believe a data attribute works well for this type of stuff.
Also I've just used a brute force, hide everything, and then show the page you require. I often find this approach leads to less errors, in a way it's like how React works as the view becomes a state.  As such to make this have a prior stage would require very little modification.

function stepping() {
  var nextStep = ($(this).closest('[data-step]').
     attr('data-step')|0) + 1;
  $('[data-step]').addClass('hidden');
  $('[data-step=' + nextStep+']').removeClass('hidden');
}

$("a.button").on("click",stepping);
[data-step] {
  width: 500px;
  height: 500px;
  border:1px solid red;
}

.hidden {
   display: none;
}

step 1

  next

step 2

  next

step 3


Função não retorna valores

Question: Sou iniciante no JS e to tendo alguns problemas com a função abaixo.
Não estou conseguindo retornar o array com este código. Ele é apenas retornado quando eu removo o "vet = []" onde esvazio o mesmo (algo necessário).
A função deve gerar e retornar um vetor gerado aleatoriamente com tamanho definido a partir de uma seleção feita na página onde o usuário escolhe 10, 100, 1000, 10000 ou 100000 elementos para o vetor.
function Valeatorio(vet){
    let tamanho = document.getElementById("TVetor").value
    vet = [] //Removendo esse trecho o Array retorna
    if (tamanho > 0 && tamanho <= 10){
        console.time("Vetor Aleatório")
        for (let i = 0; i < tamanho; i++) {
                vet.push(parseInt(Math.random() * 100))
            }
        console.timeEnd("Vetor Aleatório")
        console.log(vet)
        document.getElementById('VetorG').innerHTML = `<strong>Vetor gerado:</strong><br>${vet}`
    } else if(tamanho > 10){
        console.time("Vetor Aleatório")
        for (let i = 0; i < tamanho; i++) {
                vet.push(parseInt(Math.random() * 100))
            }
        console.timeEnd("Vetor Aleatório")
        console.log(vet)
        document.getElementById('VetorG').innerHTML = "Vetor gerado:
Tamanho máximo permitido para visualização ultrapassado"
    }
    return [vet]
}

Obrigado!
Comment: Ola @Galbert22, Bem vindo ao SOpt, antes de começar de uma olhada em nosso [Tour]. Sobre sua pergunta se sua intenção é retornar um `Array` com esses valores, me parece que esta faltando  abrir e fechar *conchete*, ficando +/- assim `return [ tamanho, vet1, vet2, vet3 ];`, por esse motivo estou sinalizando como **erro de digitação** =D
Comment: Além disso, o trecho `vet1 = [], vet2 = [], vet3 = []` está sobre-escrevendo os parâmetros `vet1`, `vet2` e `vet3`. Isso é realmente o que você quer fazer? E ainda mais: `Valeatório` não é um nome de função válido no JavaScript, já que inclui um acento (`ó`).
Comment: Suas condições não abrangem todas as possibilidades, se `tamanho` for negativo a função não retorna nada, e aparentemente você espera que sua função sempre retorne algo. Outra coisa, pra que você recebe o argumento `vet` se vai sempre sobrescrevê-lo a cada chamada de função? Você poderia simplesmente criar um vetor vazio quando precisar e pronto.
Comment: Por que você retorna [vet], e não vet?
Comment: Você também deve atentar que `input.value` retorna uma string, então você deveria fazer a conversão para inteiro antes de usá-la para comparações. Você pode usar o método `parseInt(input.value, 10)` (eu sempre uso o 2º parâmetro, _radix_, para garantir que o navegador não interpreta strings numéricas começadas em zero como octal)
Comment: Eu acabei modificando o código nesse meio tempo, vou editar a postagem principal deixando-o como está.
Utilizando os colchetes para retornar o valor não adiantou e, sim, sobreescrever os parâmetros sempre que a função for chamada é o que eu gostaria de fazer.
Comment: Você poderia editar a sua pergunta novamente para adicionar o trecho do código HTML que é necessário para o funcionamento do código? Se possível, adicione um _snippet_ executável.
Comment: Além disso... Qual a necessidade do `parseInt` no `Math.random()`, que já retorna um inteiro? (Em: `parseInt(Math.random() * 100)`)
Comment: Luiz, [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) retorna um float.
Comment: E seria melhor usar a função [`Math.floor()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) com o random, a operação matemática é mais eficiente do que todo o processo de parsing de string. Ex.: `Math.floor(Math.random() * 100);`
Comment: Enfim Galbert22, tem bastante coisa que dá pra melhorar na sua função, só que não dá pra simplesmente mudar seu código para o que eu acho que é melhor. Seria legal se você explicasse o que essa função deveria fazer e para quê o resultado dela será usado. Dessa maneira poderíamos te ajudar com muita mais rapidez e eficácia.
Comment: Editei novamente o post original com as informações sobre a utilidade dessa fução, obrigado @fernandosavio pela dica.
Comment: Como eu disse no post, se eu não limpar o vetor quando a função for chamada, ela retorna sem nenhum problema. Mas a limpeza é necessária para não acumular os números sempre que ele for gerar os aleatórios.
Answer: Vou tentar recriar essa função baseado no que você disse em:

A função deve gerar e retornar um vetor gerado aleatoriamente com tamanho definido a partir de uma seleção feita na página onde o usuário escolhe 10, 100, 1000, 10000 ou 100000 elementos para o vetor.

E também vou supor que arrays com mais de 10 elementos não devem ser mostrados para o usuário por questões de apresentação pelo que vi do seu código.
Então vou quebrar o problema em partes:

Criar uma função que gere um array de N números aleatórios
Receber o tamanho do array de um input do usuário
Apresentar (ou não) o novo vetor para o usuário

Vou tentar deixar bem explicado para que você entenda os motivos das minhas decisões:

1.  uma função que gere um array de N números aleatórios

A função abaixo gera um array do tamanho definido pelo argumento tamanho preenchido com valores aleatórios entre 0 e 99.
function gera_array(tamanho) {
    // Cria o novo array
    let novo_array = [];

    // Popula o array
    for (let i=0 ; i < tamanho ; i++) {
        novo_array.push(Math.floor(Math.random() * 100))
    }

    // Retorna o novo array populado
    return novo_array;
}

2. Receber o tamanho do array de um input do usuário

Para receber o valor de um <input> do usuário vou apenas converter o atributo input.value para um inteiro e usá-lo como parâmetro para a função gera_array.
// Guarda a referência para o elemento HTML
let input_tamanho = document.querySelector("#tamanho")
// Converte `input.value` para inteiro
let tamanho = parseInt(input_tamanho.value, 10)

Repare que criei uma variável input_tamanho guardando a referência ao elemento HTML. Fiz isso porque pesquisar na árvore DOM é computacionalmente caro para o navegador, mas como eu salvei sua referência basta usar input_tamanho sempre que eu precisar sem que o navegador tenha que procurar pelo elemento no DOM novamente.
Obs.: A dica de salvar a referência para o elemento HTML não é obrigatória, mas todo mundo deveria fazer isso e entender o porquê.

3. Apresentar (ou não) o novo vetor para o usuário

Vou criar uma função que lê o array e retorna uma string para ser colocada no HTML como feedback para o usuário.
function array_to_string(array) {
    if (array.length <= 10) {
        return "[" + array.join(", ") + "]"
    else {
        return "Array muito grande para visualizar"
    }

Agora juntando tudo teríamos:

function gera_array(tamanho) {
    let novo_array = [];

    for (let i=0 ; i < tamanho ; i++) {
        novo_array.push(Math.floor(Math.random() * 100))
    }
    return novo_array;
}

function array_to_string(array) {
    if (array.length <= 10) {
        return "[" + array.join(", ") + "]"
    } else {
        return "Array muito grande para visualizar"
    }
}

// referências:
let input_tamanho = document.querySelector("#tamanho")
let btn = document.querySelector("#btn")
let resultado = document.querySelector("#resultado")

btn.addEventListener('click', function() {
    let tamanho = parseInt(input_tamanho.value, 10)
    let vetor = gera_array(tamanho)

    resultado.innerHTML = array_to_string(vetor)
})
<input id="tamanho" type="number" value="10">
<button id="btn">Criar array</button>

Resultado...

Comment: Aprendi algumas coisas com seu post, muito obrigado. ♥
Mas continuo sem compreender o porquê da minha função não retornar o array.
Comment: Outra hora edito e melhoro a resposta. :D
Comment: @Galbert22 Sua função retorna normalmente. [Veja](https://jsfiddle.net/f8xmb05z/1/)

Função não retorna valores


E flat or E natural in score of Beethoven String Quartet Op 131?

Question: I have heard recordings of Beethoven's C sharp minor string quartet Op. 131 where, in bar 53 the third crotchet of the first violin part is played as E flat, and at least one recording where it is played as E natural. The E flat (or D sharp), combined with the other parts would give the chord B major, while the E natural would give a B suspended 4th, if I'm not mistaken.
(The "E natural" recording I have in mind is by the Taneyev Quartet of Leningrad dated 1988, and is on an LP on the мелодиа (Melodia) label.)
Given the tempo and the prominence of this particular note, it seems highly unlikely to be a `bum note' on the part of the player.

Are there different editions of the score that would account for this? Is there any consensus as to which was Beethoven's true intention?

EDIT: Using the links kindly provided by Carl below, I found one possible source of the E natural, namely the 1863 Breikopf and Haertel edition. Here it appears with the accidental immediately preceding the note. In other editions (including at least one older edition) there is no such accidental, so following the key signature the note is E flat.
So the answer to my first question above is yes. But what is the source of the Breikopf and Haertel natural sign? And which is the composer's likely intention?
Comment: FWIW, there are (at least) two scores available online at  http://imslp.org/wiki/String_Quartet_No.14,_Op.131_(Beethoven,_Ludwig_van)   and http://www.free-scores.com/download-sheet-music.php?pdf=2388
Comment: Right enough, looking through the scores on the first link, I think I can now see where the E natural may have come from: the Breitkopf & Härtel edition, 1863. This looks like a great resource. Thanks Carl! I'd still be interested to know where this accidental came from though.
Comment: To the close vote(r), read this: http://meta.music.stackexchange.com/questions/592/are-questions-on-musicology-on-topic
Comment: Shane, I have never heard a E natural there. Maybe the 2nd violin E-flat suggests that? Can you point to that recording if you have alink?
Comment: The recording I'm thinking of (with the E natural) is by the Taneyev Quartet of Leningrad. I don't know the year off-hand but can look it up later. It's on a vinyl record bought in 1991. Granted, it may be an acoustic illusion, but compared to other recordings it sounds to me as I've described.
Comment: Has anyone ever found the Beethoven autograph/manuscript version of this piece?
Comment: @Dekkadeci I haven't seen the autograph score of this. The first edition appears on imslp (with an Eb), and there's a pdf of what appear to be sketches of the third and fourth movements, but that's all I can see.
Answer: The autograph (page 12 of the PDF) has E flat:

My guess is that the natural in the Breitkopf & Härtel score is either a simple mistake or a hypercorrection; either way it was likely influenced by the E natural in the second violin part.
Comment: That's very interesting and clear. Thank you for the link to the autograph score and resolving this question!
Answer: Something tell me it's linked to Chinese Whispers. In the same way a story is reworded by whoever tells it to their convenience, a script is reworked according to the tastes of who's going to perform it.
The difference of a semitone is strangely noticeable in any music, and makes a difference to how to it sounds. The composer's true intention we will likely never know, but where there is a difference in two scores, you can be fairly sure it was just one little tweak from an orchestra to make a piece sound better (I say better as in, better-sounding to them).
If you had to throw a guess on the composer's likely intention, it is likely to be the least... pleasant sounding note. (I say that very loosely). If one note happily matches a chord and one does not, the former is likely to be the edit. Then again, some tweaks makes pieces sound much harsher.


Bug multiplos modals bootstrap

Question: Tenho dois modais na mesma pagina, uma para alterar e outro para remover informações do banco.
O código do primeiro modal é esse:

Alterar Informações Instituição de Insino

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
        <button type="button" class="btn btn-primary">Salvar alterações</button>

O código que preenche o modal é esse:

Os códigos do segundo modal são esses:

Deseja Apagar Instituição de Insino?

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
        <button type="button" class="btn btn-primary">Remover</button>

O que acontece é o seguinte, quando eu tenho só o modal de editar no código, eu consigo editar normalmente os valores no banco, quando adiciono o modal de deletar, ele passa a não conseguir mais atualizar,  mas o delete funciona normalmente.
O que pode estar causando esse erro?
Comment: Eu faço essa modal de deletar de uma forma mais simples, não precisa fazer a modal na página, chama ela via js.
Comment: Vou postar uma resposta explicando
Answer: Tenho uma modal que aparece dentro de um js:

$(document).ready(function(){
    $('a[data-del]').click(function(ev){
        var href = $(this).attr('href');
        if(!$('#confirm-Del').length){
            $('body').append('    Deseja Deletar?  ×    Não há como recuperar dados apagados.   Não Sim    ');

            }
        $('#dataDelOK').attr('href', href);
        $('#confirm-Del').modal({show: true});
        return false;

    });
});

Então chamo ela pelo php:
 Del
e faço um link do arquivo js no final da página ou coloco ele dentro da página já, sem ser externo. Coloca a tag "" chamando a página dentro do while.
Explicando o script:
No código js, se o botão com o atributo "data-sair" for clicado chama o código. Que cria na página uma modal referente ao id. E há dois botões com 2 atributos de sair ou dar ok que chama o php de delete pra deletar. Ou alguma outra página, no meu caso crio uma conexão com o bd, e apago o id referente.
funcionando online: https://jsfiddle.net/PH7Jack/1u29gpfb/

Bug multiplos modals bootstrap


Is this in row echelon form?

Question: We are supposed to get the following matrix in Row Echelon Form
Original
$$
\left(
\begin{matrix}
-2 & -4 & 7\\
-3 & -6 & 10\\
 1 & 2  & -3\\
\end{matrix}
\right)
$$
I got
$$
\left(
\begin{matrix}
-2 & -4 & 7\\
0 & -6 & 10\\
 0 & 0  & 0.5\\
\end{matrix}
\right)
$$
Is this correct?
Answer: $$
\left(
\begin{matrix}
-2 & -4 & 7\\
-3 & -6 & 10\\
 1 & 2  & -3\\
\end{matrix}
\right)
$$
after $\frac{-3}{2}R_1+R_2\to R_2$ and $\frac{1}{2}R_1+R_3\to R_3$
$$
\left(
\begin{matrix}
-2 & -4 & 7\\
0 & 0 & \frac{-1}{2}\\
 0 & 0  & 0.5\\
\end{matrix}
\right)
$$
then $R_2+R_3\to R_3$
$$
\left(
\begin{matrix}
-2 & -4 & 7\\
0 & 0 & \frac{-1}{2}\\
 0 & 0  & 0\\
\end{matrix}
\right)
$$
Note that determinant of given matrix is zero but the one you have calculate has nonzero determinant so you have to be sure it isnot correct.

Is this in row echelon form?


Python -- Creating an if statement relating to a key/value pair from an outside variable

Question: Within python I am trying to create an if statement which checks if an outside variable is a key connected to a specific value within a dictionary.
I am working with a list of ID's that corresponds to a dictionary of True/False statements relating to those IDs, (for example {22935:False, 29023:True} etc.)
What I originally wanted to do was something like this (sorry I am a bit of a newbie to python):
 if id in dict is True:
Then I realized that statement is literally impossible, have been searching around and haven't been able to find an answer not sure if I'm just looking up the wrong thing or if what I am looking to do is impossible. Would really appreciate any help with this, Thanks!
Comment: If you want to check whether `id` is linked with the value True in your True/False dictionary, then do `if mydict[id]:`; or `if mydict.get(id):` if you think that the id might not be in the dict at all. Is that what you are trying to do?
Answer: Don't name the variables dict and id (which are keywords) but just do:
if dict[id]:

or
if dict.get(id):

Answer: I don't know if i'm understaning perfectly but maybe you want something like this?:
if id in dict:
    if dict.get (id): #this gets the value of if and if it's true you don't need to wring `== True`
        doStuff ()

Comment: If you're using `get` then you don't need the `if id in dict:`.
Comment: This would cause an exception. There's no such method as `dict.Value`.
Comment: Yep, sorry i confues the method values for the method get, updated the answer


Windows Server edition mixing

Question: I am a linux person by trade, so this windows stuff confuses me.
I am going to setup a PDC and BDC, and I need another windows server license for a storage server.
I have a MAPS license which includes WinSrvr Standard 2008 (not R2), Enterprise R2. I have been quoted for a WinSrvr2008R2 OEM license with the new BDC.
Can I use, for example, Server 2008 R2 standard as the PDC, and Enterprise R2 as a BDC or vice versa, or do they have to be the same edition of windows?
The Storage Server can be 2008 Std (non-R2)
Answer: To answer your questions yes you can do what you propose. I would however if possible swap to enterprise for your PDC but at the end of the day it shouldnt matter to much for you.
Comment: Thanks, yes I will take enterprise as the 'PDC' or as I understand it now I can use multimaster mode, so get the new server in and installed, add it to the domain , do some $voodoo, and drop the 2003 SBS box.
Comment: If you are migrating away from SBS you will need to make sure you switch on it's "Migration Mode" as running another server with any of the FSMO roles will cause SBS to shutdown randomly! Good Luck :)

Windows Server edition mixing


How to reduce server load with Apache PHP

Question: Our Linode server load has increased in the last month running CentOS 7. I have upgraded to MariaDB 10.3 with PHP 7.2 now on CentOS 7.5 with 16GB of ram and 6 cores. MariaDB also on the server using 5372.81 MB according to apache2buddy perl script. I'm using default MaxRequestWorkers which the script says is too high, but I've tried within its range and doesn't make a difference. We have put the entire site under HTTPS recently but a lot of it already was before the issue. Where the server used to run mainly around a server load of 1, it now averages 3-4 with spikes to 8+.
top - 12:39:15 up 10:26,  2 users,  load average: 3.27, 3.57, 4.08
Tasks: 181 total,   2 running, 117 sleeping,   0 stopped,   0 zombie
%Cpu(s):  9.3 us,  6.0 sy,  0.0 ni, 54.2 id,  4.2 wa,  0.0 hi,  0.9 si, 25.4 st
KiB Mem : 16419324 total,   462908 free,  7237284 used,  8719132 buff/cache
KiB Swap:   524284 total,   524284 free,        0 used.  8808064 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 3614 mysql     20   0   10.1g   5.2g  21372 S  45.2 33.5 259:48.57 mysqld
15613 wmnf_ad+  20   0  842992 178644  95772 S  20.9  1.1   0:03.67 httpd
15650 wmnf_ad+  20   0  792196 131184  97048 S  16.6  0.8   0:10.31 httpd
15636 wmnf_ad+  20   0  837444 179280 101916 R  15.9  1.1   0:15.06 httpd
15634 wmnf_ad+  20   0  870480 136836 100236 S   7.0  0.8   0:16.07 httpd
15632 wmnf_ad+  20   0  794060 125052  89772 S   5.6  0.8   0:12.00 httpd
 1937 root      20   0       0      0      0 D   2.3  0.0   7:03.28 jbd2/sda-8
    1 root      20   0  191432   5732   3856 S   1.0  0.0   1:01.34 systemd
15654 wmnf_ad+  20   0  795988 123584  88628 S   1.0  0.8   0:05.54 httpd
    8 root      20   0       0      0      0 I   0.7  0.0   3:45.27 rcu_sched
   34 root      20   0       0      0      0 S   0.3  0.0   1:13.51ksoftirqd/5
 3207 root      20   0  492880  15488  12152 S   0.3  0.1   0:17.17 NetworkManager
15254 root      20   0  161992   4632   3856 R   0.3  0.0   0:03.46 top
15604 wmnf_ad+  20   0  799320 141524 104940 S   0.3  0.9   0:17.32 httpd
15628 wmnf_ad+  20   0  794284 128708  95872 S   0.3  0.8   0:17.75 httpd
15951 wmnf_ad+  20   0  796216 124368  89456 S   0.3  0.8   0:09.05 httpd
    2 root      20   0       0      0      0 S   0.0  0.0   0:00.12 kthreadd
    4 root       0 -20       0      0      0 I   0.0  0.0   0:00.00 kworker/0:0H

I mostly doubled these numbers in the httpd conf when Linode gave us the 16GB from 8GB previously:
StartServers        4
MinSpareServers     20
MaxSpareServers     40
MaxClients          200
MaxRequestsPerChild 4500

Apache memory usage looks like this after about an hour since last restart:
[root@archives conf.d]# ps -ylC httpd | awk '{x += $8;y += 1} END {print "Apache Memory Usage (MB): "x/1024; print "Average Process Size (MB): "x/((y- 1)*1024)}'
Apache Memory Usage (MB): 6136.5
Average Process Size (MB): 109.58

Looking at the Apache server status page, it does not look like there are a huge amount of requests and it's certainly not using all the resources I've allowed:
Server Version: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_fcgid/2.3.9 PHP/7.2.6
Server MPM: prefork
Server Built: Apr 20 2018 18:10:38
Current Time: Monday, 28-May-2018 12:27:12 EDT
Restart Time: Monday, 28-May-2018 12:26:14 EDT
Parent Server Config. Generation: 1
Parent Server MPM Generation: 0
Server uptime: 57 seconds
Server load: 4.54 4.76 4.67
Total accesses: 324 - Total Traffic: 127.9 MB
CPU Usage: u47.7 s18.95 cu0 cs0 - 117% CPU load
5.68 requests/sec - 2.2 MB/second - 404.3 kB/request
30 requests currently being processed, 30 idle workers
WKWR__W._W__WWW_RWK_W______RK._.K_R_K_R___K_RW__.R_..___W__KWRRW
.W_.............................................................
................................................................
........

I used pmap on a couple of the processes and notice a lot of modules and I probably do not need but a few of these, do all these modules load by default? Of course I installed php7, fcgid, status and others...
[root@archives conf.d]# httpd -M
Loaded Modules:
 core_module (static)
 so_module (static)
 http_module (static)
 access_compat_module (shared)
 actions_module (shared)
 alias_module (shared)
 allowmethods_module (shared)
 auth_basic_module (shared)
 auth_digest_module (shared)
 authn_anon_module (shared)
 authn_core_module (shared)
 authn_dbd_module (shared)
 authn_dbm_module (shared)
 authn_file_module (shared)
 authn_socache_module (shared)
 authz_core_module (shared)
 authz_dbd_module (shared)
 authz_dbm_module (shared)
 authz_groupfile_module (shared)
 authz_host_module (shared)
 authz_owner_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 cache_module (shared)
 cache_disk_module (shared)
 data_module (shared)
 dbd_module (shared)
 deflate_module (shared)
 dir_module (shared)
 dumpio_module (shared)
 echo_module (shared)
 env_module (shared)
 expires_module (shared)
 ext_filter_module (shared)
 filter_module (shared)
 headers_module (shared)
 include_module (shared)
 info_module (shared)
 log_config_module (shared)
 logio_module (shared)
 mime_magic_module (shared)
 mime_module (shared)
 negotiation_module (shared)
 remoteip_module (shared)
 reqtimeout_module (shared)
 rewrite_module (shared)
 setenvif_module (shared)
 slotmem_plain_module (shared)
 slotmem_shm_module (shared)
 socache_dbm_module (shared)
 socache_memcache_module (shared)
 socache_shmcb_module (shared)
 status_module (shared)
 substitute_module (shared)
 suexec_module (shared)
 unique_id_module (shared)
 unixd_module (shared)
 userdir_module (shared)
 version_module (shared)
 vhost_alias_module (shared)
 dav_module (shared)
 dav_fs_module (shared)
 dav_lock_module (shared)
 lua_module (shared)
 mpm_prefork_module (shared)
 proxy_module (shared)
 lbmethod_bybusyness_module (shared)
 lbmethod_byrequests_module (shared)
 lbmethod_bytraffic_module (shared)
 proxy_ajp_module (shared)
 proxy_balancer_module (shared)
 proxy_connect_module (shared)
 proxy_express_module (shared)
 proxy_fcgi_module (shared)
 proxy_fdpass_module (shared)
 proxy_ftp_module (shared)
 proxy_http_module (shared)
 proxy_scgi_module (shared)
 proxy_wstunnel_module (shared)
 ssl_module (shared)
 systemd_module (shared)
 cgi_module (shared)
 fcgid_module (shared)
 php7_module (shared)

I also checked PHP modules and found apc loaded, which should not be with the new opcache running? It's probably been around since earlier versions, but all in all nothing makes a difference. Is there more I can do or how can I determine the cause of this higher load? The load does subside when Apache is stopped.
Running iotop, I see this [jbd2/sda-8] process sites at the top constantly between 10-60% IO. If this is a journal related process, could there be an underlying issue with disk. Perhaps a disk clean in single user mode needed?
    Total DISK READ :       0.00 B/s | Total DISK WRITE :     181.41 K/s
Actual DISK READ:       0.00 B/s | Actual DISK WRITE:     272.12 K/s
  TID  PRIO  USER     DISK READ  DISK WRITE  SWAPIN     IO>    COMMAND
 1937 be/3 root        0.00 B/s    0.00 B/s  0.00 % 27.02 % [jbd2/sda-8]
 3648 be/4 mysql       0.00 B/s  151.18 K/s  0.00 %  4.66 % mysqld
 3645 be/4 mysql       0.00 B/s    0.00 B/s  0.00 %  1.40 % mysqld
19502 be/4 mysql       0.00 B/s   18.14 K/s  0.00 %  0.53 % mysqld
    1 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % init
    2 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % [kthreadd]
    4 be/0 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % [kworker/0:0H]
    6 be/0 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % [mm_percpu_wq]
    7 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % [ksoftirqd/0]
    8 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % [rcu_sched
<snip>

Comment: Why are you looking at Apache iso. MySQL?
Comment: MySQL doesn't seem to be overworked, responds quick. Some more digging with iotop shows jbd2/sda-8 process pinned at the top between 10-60%, this is not right? I'll edit to show.
Comment: Have you considered that maybe your application just needs more resources and/or optimization? You can't config-tweak your way around genuine increases in traffic/load.
Comment: Yeah, and we have ticked up according to stats and fully implemented full site https recently. However, the numbers I see in the server stats don't seem to show a dramatic change in activity. This was kinda all of sudden last week and could be after the Linode upgrade and related to the iotop issue. I was just looking for ways to lower the server load if higher traffic is the case. It doesn't seem like Apache and MySQL are using all the resources available.
Comment: Mysql is the first line in top output, is the only user process writing. What is it writing?
Answer: I also think MySQL is causing the load. The jbd2 process is a kernel thread that updates the filesystem journal as you surmised. Looks like MySQL is writing to disk heavily and that is causing the load on jbd2.
MySQL sometimes needs to create temporary tables to process queries, notably queries with a group by clause. That could explain your load if those temp tables are being created on disk. This command will show you how many temporary tables are being created on disk in and memory SHOW GLOBAL STATUS LIKE 'created_tmp%tables';.
Also from that link, these are the two reasons why MySQL creates a temp table on disk rather than memory:

The result is bigger than the smaller one of the MySQL variables max_heap_table_size and tmp_table_size.
The result contains columns of type BLOB or TEXT.
Comment: Yes, this is the culprit I guess, thanks. Created_tmp_disk_tables shows 301506. This is a WordPress site, no real changes to designover time but I guess it perhaps got worse over time. I've read now about optimizing mariadb and mysqltuner is saying a few things need to be adjusted, I need query_cache_size, join_buffer_size, tmp_table_size and max_heap_table_size increased. I've tried this a bit on the dev server here. Following the tuner script suggestions and adjusting these variables higher should help?
Comment: You're quite right. He's got a bad database design and mysql can't keep up with his queries.
Comment: I believe so, yes. I'm guessing what happened is there's some query result that's been getting bigger gradually due to increasing comments on a post or increasing number of posts on your site. At some point you crossed over the threshold that triggered writing the temp table(s) for this query to disk, and that caused the sudden increase in load.
Comment: Like the tuner script keeps suggesting higer and wanting 16M or higher for query_cache_size and join_buffer_size, but I read some say you should raise so high globally as it takes too much to create on every query. And I see more info about raising these even higher. I know it depends on the resources on what you can do, but will these higher sizes actually cause more load issues?
Comment: 16M doesn't strike me as a lot on a system with 16GB of RAM. Your top(1) output shows that about half the memory is in use.  The thing to watch for is any increase in swap use. Any use of swap will probably slow things down severely unless your swap is on some fast SSDs.
Answer: Yes, the mysqld process was the issue, but due to waiting for the host of this virtual server. The high 'st' number in my top was an indicator of the host being very busy with other virtual machines....
top - 12:39:15 up 10:26,  2 users,  load average: 3.27, 3.57, 4.08
Tasks: 181 total,   2 running, 117 sleeping,   0 stopped,   0 zombie
%Cpu(s):  9.3 us,  6.0 sy,  0.0 ni, 54.2 id,  4.2 wa,  0.0 hi,  0.9 si, 25.4 st
                                                                        ^^^^^^^

After pointing this out to the hosting provider, our vm was migrated to a new host. Problem solved, now load very low as usual.
Comment: Good catch. What does "normal" st look like?
Comment: Zero most of the time, I've yet to see it reach one since resolved.


Views : Rewrite results - Edit content

Question: Is there a way to rewrite the content of a field displayed in a view?
E.g. If my title is long, like "[Product ID:5739] Ninja Stars" and I want it to display just "Ninja Stars" in the view, how can I do it?
Answer: You can in views rewrite the result of any field, or trim most fields, but if there is some logic to what you want to remove you would need to do with with a preprocess hook in your theme. In this case it sounds like you need to do the latter. Something like this should do the trick:
<code>function theme_preprocess_views_view_fields(&$vars) {
  if ($do_your_checks) {
    $vars['fields']['field_name'] = preg_replace(...) // Use regular expression to change title.
  }
}
</code>

Views : Rewrite results - Edit content


VBA Userform Command Button to copy row to sheet before editing information

Question: I have a secondary user-form which can edit cell data based on a double click selection from a list-box.
The user-form has an 'update' button which will execute change in data in the cells based on the input to text boxes and combo boxes.
Everything is working perfectly, however I would like to keep an 'archive' of the data before the row is updated. (Essentially copy the row to 'Archive' sheet4)
I have tried to include the .Selection method however this change my active worksheet and the update information doesn't appear.
Here is the code:
Private Sub cmdUpdate_Click()
' To write edited info of userform2 to Sheets("Data")
    Dim LastRow As Long
    Dim ABnum As Double
    Dim ABrng As Range
    Dim WriteRow As Long

    'error statement
On Error GoTo errHandler:
'hold in memory and stop screen flicker
Application.ScreenUpdating = False
' Make sure we're on the right sheet
Sheets("Data").Select
    With ActiveSheet
' Get the last row used so can set up the search range
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' Set the range to search for the AB number
        Set ABrng = .Range("A1:A" & LastRow)
' Get the AB number from what is selected on userform2
    ABnum = txtup1.Value

' Get the row of sheet for this AB number
    WriteRow = Application.Match(ABnum, ABrng, 0)

' Make this AB number the active cell
        Cells(WriteRow, 1).Select
' Write in all the editable options
        With ActiveCell
            .Offset(0, 4) = cboup3.Value
            .Offset(0, 5) = cboup4.Value
            .Offset(0, 6) = cboup5.Value
            .Offset(0, 7) = cboup6.Value
            .Offset(0, 8) = Date
            .Offset(0, 12) = txtup9.Value
            .Offset(0, 13) = txtup8.Value

        End With

End With
' Filter the Data
    FilterMe
' Close the form
    Unload Me

    MsgBox ("Enquiry E0" + Me.txtup1.Text + " has been updated")

errHandler:
'Protect all sheets if error occurs
'Protect_All
'show error information in a messagebox
    If Err.Number <> 0 Then
    MsgBox "Error " & Err.Number & " just occured."
    End If

End Sub

Answer: I'm not entirely sure what you are asking, but here is a best guess. I have only made a stab at where you want one piece of data stored, but if I am on the right lines then the code can be amended to cover the others. If you can clarify the destination Archive sheet that would help.
Private Sub cmdUpdate_Click()
' To write edited info of userform2 to Sheets("Data")
Dim LastRow As Long
Dim ABnum As Double
Dim ABrng As Range
Dim WriteRow As Long

'error statement
On Error GoTo errHandler:
'hold in memory and stop screen flicker
Application.ScreenUpdating = False
' Make sure we're on the right sheet
With Sheets("Data")
' Get the last row used so can set up the search range
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' Set the range to search for the AB number
    Set ABrng = .Range("A1:A" & LastRow)
' Get the AB number from what is selected on userform2
    ABnum = txtup1.Value
' Get the row of sheet for this AB number
    WriteRow = Application.Match(ABnum, ABrng, 0)
' Make this AB number the active cell
    With .Cells(WriteRow, 1)
' Write in all the editable options
    Sheets("Archive").Range("A" & Rows.Count).End(xlUp)(2).Resize(, 14).Value = .Resize(, 14).Value
        .Offset(0, 4) = cboup3.Value
        .Offset(0, 5) = cboup4.Value
        .Offset(0, 6) = cboup5.Value
        .Offset(0, 7) = cboup6.Value
        .Offset(0, 8) = Date
        .Offset(0, 12) = txtup9.Value
        .Offset(0, 13) = txtup8.Value
    End With
End With
' Filter the Data
FilterMe
' Close the form
Unload Me

MsgBox ("Enquiry E0" + Me.txtup1.Text + " has been updated")

errHandler:
'Protect all sheets if error occurs
'Protect_All
'show error information in a messagebox
If Err.Number <> 0 Then
    MsgBox "Error " & Err.Number & " just occured."
End If

End Sub

Comment: I would like the found row from the `ABnum = txtup1.Value` to be copied to sheet 4 (Archive) before editing the data in 'data' sheet, there are 14 columns to copy, starting from A
Comment: Not sure I follow, can you elaborate as to what you mean by the "found row" - which sheet, which cells?
Comment: I was hoping to just do `entire.copy` but that was creating the problem. I think your solution works but i need to copy the information from 14 columns to the data sheet
Comment: OK have amended a line above so try again and let me know how you get on.
Comment: It hasn't copied anything across, Would you like me to send the entire Document?
Comment: Could you try again, I missed something.
Comment: Glad to hear it.


How can I find out which woodwind instruments have the same (or almost the same) fingering so it makes transitioning between those instruments easier?

Question: Just for fun, I want to begin learning woodwind instruments. Unfortunately, I have to put some financial constraints on that project. Therefore, I am looking into learning how to play the recorder, because it is a relatively inexpensive mistake to make - in case I fail. However, if I am at least semi-successful, I might want to get other instruments like a flute, clarinet or saxophone.
For this reason, I was thinking it would be a good idea to know which instruments share the same (or almost the same) fingering, so I will have it easier to transition between them. If I am getting a soprano recorder, for example, how can I find other matching woodwind instruments?
(Of course, I do realize that to know how to actually play an instrument, there is more to it than just the fingering. However, it has to make things easier, right? If I'm totally mistaken here, please let me know.)
Comment: IMO the fingering is the least of your problems when you are learning a new woodwind instrument. Controlling your breath to achieve a nice tone over the different octaves is much more of a challenge.
Answer: Those wind instruments that are frequently "doubled" are usually the ones that have identical fingerings. For instance, the 2nd or 3rd flute in a professional orchestra will often alternate playing the piccolo part, because the piccolo is essentially a regular flute shrunk to half size (there are minor differences because not all parts of the full Böhm system can be miniaturized accurately). Similarly, the clarinet in B and A, but also in C and E flat and even the bass clarinet play almost identically.
In fact, not having to learn new fingerings when doubling is the major reason why many instruments use transposing notation in the first place - so whenever you find an instrument that is traditionally written as transposing, that is probably one of them.
Comment: I do not think the question was meant like "What families of instruments have the same fingerings?" but rather "if I learn this instrument, what other instrument can I learn without having to learn a totally different fingering system?", where "this instrument" is most likely recorder.
Answer: Saxophones have the most similarities of fingerings. Alto and Tenor, and Bari, all have the same fingering concepts, and are widely used instruments. (Soprano seems to be an outlier in that family...)
Clarinets have similar fingerings, but the Bb clarinet is the only really common one of that family.
C flute and piccolo, as @Kilian Foth answered.
We could claim that, in principle, violin, viola, cello, and bass have the same fingering scheme... but, at the very least, the bass' open strings are a fourth apart, not a fifth.
I do not know about fingering system differences between "baritone" and "tuba/sousaphone".
Comment: The bass clarinet is common enough that I won a pass to switch to it in elementary school and still played it in my other 2 school concert bands. There seems to be 1 or 2 bass clarinet players in every Albertan school band, in my experience, along with a bass clarinet part in every concert band piece.
Comment: While I agree that Saxophone is a good choice for a recorder player I think you have misunderstood the question. The question is not about families with the same fingering, but about different instruments sharing a similar fingering, e.g. instruments that finger similar to a recorder. By the way soprano sax fingers just the same as any other sax out there.
Comment: Violin and viola have similar fingerings, but the cello.is different from them because of the bigger distance between the notes. Also the hand position is different.
Comment: As a pianist who plays a lot of chamber music, I have noticed that some viola players coming from the violin have difficult with double stops  because of the bigger distances. I played the Bb clarinet in grade school, bass clarinet in high school and contrabass in college, finding the progression  very easy, mainly because the lower instruments rarely have very high notes written for them (all clarinets have basically identical fingerings).
Answer: Usually with most wind instruments the "basic" diatonic fingering is the same, but they will differ in how you play chromatic notes and how they overblow. Reed instruments with cylindrical bore like clarinets will behave like a closed flute and overblow into a 12th instead of an octave, which makes them somewhat harder to learn.
Thus regarding reed instruments I'd suggest going single reed (double reed is harder) and conical, which means something like Saxophone.
Comment: @Aaron Should have been Duodecime, but there my german got the better of me. We like to call intervals in latin based expressions, so Prima→Prim(1), Secunda→Sekund(2), Tertia→Terz(3), Quarta→Quart(4), Quinta→Quint(5), Sexta→Sext(6), Septa→Sept(7), Octava→Oktav[e](8), Nona→Non[e](9), Decima→Dezim(10), Undecima→Undezim(11), Duodecima→Duodezim(12), Tredecima→Tredezim(13), Quattuordecima→Quattuordezim(14), Quindecima→Quindezim(15), and so on. It is nice because a) it sounds cools and b) it saves all of the –th you get with the english way (in german this would mean tons of –te).
Answer: TLDR: get a good quality soprano baroque recorder. If at all possible book a few lessons with a teacher. And play at least 15 minutes every day.
The recorder family basically comes in two different fingering systems, generally known as the baroque fingering and the german respectively. There are subtle differences on some notes which may make you believe the German system to be easier, which is not. Tuning is generally better for the baroque fingering.
The recorder family basically comes in two different tunings, as a C instrument or as a F instrument. The F instruments are, in my mind at least, played transposed. So get a C instrument, a good starting point will be a Soprano recorder (the one about a foot long). It is tuned in C and when you see a C (sic) tone you play a C. The lowest note, all fingers is a C.
As for fingerings the second octave and above is different from the first octave, as for most wind instruments. And the recorders second octave is in my experience different from every other wind instrument. Meaning essentially that you should not take that into account.
One wind instruments that come closest to the recorder in fingering in the first octave is the flute. In the second octave and up it is different.
Another wind instrument that is close in fingering in the first octave is any of the saxophone family (alto, tenor, baritone and to a degree the soprano and bass). They come with a twist though, that if you read and play a C the sound coming out will be either a Eb or Bb depending on instrument -- this is very easy to get used to. From an acoustic "theoretical" point of view the Saxophone family is the "best" instrument with least problems in tuning and sound production.
The clarinet family of instruments have quite different fingerings in the lowest octave.
The oboe family of instruments have similar fingerings in the first octave. They take a lot of work on the double reed and you need a teacher to get you started there if you want to make any real progress (I know, there are exceptions of course, but very rare).
And the bassoon is very different in fingering (I play mostly bassoon and contrabassoon).
The whistle family has different fingerings, but I find it generally easy to convert.
There are further wind instruments but they are less common in Western music. I like the Ocarina as example.
Answer: I would categorize woodwind fingering systems into three main categories:

The traditional system, used by the recorder and more primitive instruments, which can still be recognized on the modern oboe and some clarinets
The Boehm system, originally developed for flute, which came to be used on most modern clarinets as well as the saxophone
Bassoon

The traditional system basically plays a D major scale when removing one finger at a time from the bottom. Originally, the oboe followed this fingering system exactly, but over time added keys to reduce the number of awkward cross and half-hole fingerings needed to play the full chromatic scale. In particular, pinky keys to achieve D♯ and G♯ proved immediately useful and simple to make.
Theobald Boehm invented a mechanism for flutes for automatically closing pads, and used this to convert the fingering for F♯ into F♮ (while leaving F♯ still easy to play). In conjunction with an extension to low C, this meant that the instrument tends to play a C major scale instead, which seems more natural. Adolphe Sax utilized this fingering system on the saxophone, and so did many clarinet makers. Oboists stuck to tradition.
So for most woodwind instruments, D, D♯, E, G, G♯, A, and B are fingered the same. There's a schism about what to do with F and F♯, there are a few different ideas about what to do with B♭ (with most instruments having multiple options built into their keywork), and C and C♯ at the top of the scale are also different across instruments.
And then bassoon is its whole own thing. It has a similar kind of shape in many ways, but it's shifted by a fourth and has confounding things like flick keys, the whisper key, and despite having an abundance of keys still uses half-holing sometimes. There's a reason that many people double on all of the treble woodwinds but won't touch bassoon.
Answer: DISCLAIMER: I speak from the viewpoint of a saxophonist who has doubled on other instruments.
I interpret the question as asking for similarities between instruments of different families. Until you get into the extremities of an instrument's range, fingerings are going to be virtually identical across all varieties of an instrument (soprano/alto/tenor/baritone/bass). Across different families, I'd make the following observations:

Flutes and saxophones are fairly similar in the middle and lower ranges, but the difference in embouchure/tone production is vastly different.
Clarinets and saxophones are somewhat similar, except for the fact that the clarinet overblows a 12th rather than an octave. Consequently, saxophonists are likely to get caught up in the collection of clarinet keys for the little fingers.

As for the OP's financial issue, it would be great (if possible) for him/her to get one of the many MIDI wind controllers on the market that can be switched from one fingering system to another. That way, he/she might get a better feel for which fingering systems feel best. (Granted, building a MIDI rig with tone module, controller, amplification, software, etc. is probably not in the OP's budget.)


Heroku Slug Size is 237MB the Repo Size is 70MB

Question: Statistics
Stack: Cedar
Framework: Ruby
Repo Size: 78.3MB
Slug Size: 237MB of 300MB

Letter to Heroku Support
My Slug Size has ballooned all the way up to 237MB. My repo size is only around 75MB. I've determined that the reason deals with my assets being stored multiple times in my slug, taking up unnecessary space.
I precompiled my assets the first time, so my images would appear on Heroku. I wanted to reduce my slug size, so I optimized my images. Trying to decrease loading time, I reduced the size of my images. I then precompiled them again. Instead of having the old images being replaced by the new ones, my slug size stored both sets of images.
I've ran heroku run bash, to open up my Application's Command Prompt. After that, I CD'd into my assets/images directory and ran ls. I discovered that in the path
app/assets/images

There are 3 sets of images.
and in the path
public/assets/images

There are 2 sets of images
This is an enormous albatross on my application and if I could fix this, I could reduce my slug size by at least half. I tried running in those directories
rmdir Dirname

but I can't delete them, because they have files in them.
I am trying to delete the unnecessary files that I didn't want in the first place. I've searched your documentation but you don't describe how to delete files from your slug.
I also don't want to lose any of the data in my app because it's taken a ton of time to build that data.
Please get back to me with answers to this question.
END LETTER
BASICALLY, this is an enormous albatross, and it's driving me crazy. I've tried running
heroku run bash

to enter the Command Prompt for my application
I cd'd into my application's app/assets/images directory and I didn't like what I saw. Under each subdirectory I saw THREE copies of every image. ARGHHHH! And under public/assets/images I saw two copies of every image.
I want to know if there's a way I can remove this albatross, because this is just such a waste of my time.
Comment: The old images will still be in your git history.
Comment: You may want to use a `.gitignore` file. https://devcenter.heroku.com/articles/slug-compiler
Comment: Then how do I delete them? They are an albatross that's eating up space.
Comment: Old versions of images in git history will not take up space in the slug. Only files in the head commit that are not ignored in `.gitignore` will be there.  This means two copies of every image (one in apps/assets, the other in public/assets).
Answer: One thing that helps is adding a .slugignore file to the root of your project to tell Heroku not to compile certain files or directories into the slug. Mine looks like this:
*.psd
*.pdf
test
spec
features
doc
public

The public entry is in there because I serve all static files from Amazon's S3 service; just leave that line off if you're not using an external content-delivery system.
Answer: I may have this wrong (and if I do, please correct me!), but here's what I've been doing with my assets when there have been any changes to them:

Clear out the existing asset manifest:
rake assets:clean

Delete all files from the "public\assets" folder
Precompile production-version of assets:
RAILS_ENV=production rake assets:precompile

Then commit & push to Heroku

You should end up with only one copy of the assets on Heroku this way.
Comment: This literally reduced my slug size by 2/3.  Well done!
Comment: I've been out of the Heroku loop for over two years now. I can't believe this still is useful info. :D
Answer: The slug size includes the size of the gems you are using:
https://devcenter.heroku.com/articles/slug-compiler#slug-size
I would run a couple $ du commands on where ever your gems are installed and and try to find large ones.
http://www.computerhope.com/unix/udu.htm
With that in mind, if you are done adding gems to your project, it might not matter that you are close to the limit because 60 MB is a fair amount of code/image space to work with.  If you do have many more images to add, you might consider hosting them somewhere else.


What is your optimal configuration for a conference room/training room?

Question: We are looking at enhancing our conference/training room.  We currently use a set of 10 laptops that are set up when training is in session.  A portable projector is brought in and connected to a presenter laptop or a laptop that a trainer might bring with them.
We are considering mounting a projector in the back of the room and providing a system for presentations or training.  This could be:

A desktop attached to projector with wireless keyboard/mouse
A laptop wirelessly connected to projector
Some combination of the two or something else entirely

What have you set up for your conferencing/training needs?
Our room only holds roughly ten people so an extensive configuration is not needed.  I am looking for something flexible enough for training with outside people bringing their own equipment that is also easy to use for normal presentations where someone might just have a presentation on a thumb drive.
Comment: Great question .. I have similar needs for a conference room.
Comment: This question is off-topic under current topicality rules.
Answer: This is one of our room configurations, it could help you as an idea.  We didn't do the install, but these were our specifications:
Projector in ceiling
(ability to handle multiple connections: VCR-DVD/Desktop/Laptop/Document-Camera.  We've had good luck with Hitachi)
Presenter station
This is pretty close to what we have:
alt text http://www.exactfurniture.com/imgs/mm1200pic.jpg
Inside presenter station:

8-Port switch (one cable connects to desktop, another is just there in case someone brings their laptop and either can't connect to wireless or prefer a wired connection)
Desktop computer with dual-monitor capable video card (one will go to monitor, the other to projector)
DVD/VCR

On top of the presenter station:

17" LCD Monitor
Document Camera (with VGA in for a possible Laptop connection).  You would be suprised how many people still use those!
Audio/Video Switcher (this was installed by the AV company we hired**)

The *desktop computer is setup to auto-login.  It is not part of our domain, nor is able to touch any of our agency networks due to being in it's own VLAN.  It is also 'frozen' with DeepFreeze, so any changes (good or bad) will be gone whenever the computer reboots.  We have most applications and browser plugins presenters will need.
**The A/V company that did the install took care of pulling all the video/audio cables to the projector.  If you have the time and expertise with multimedia equipment you could do this yourself.
... Now, if you had asked me about our videoconferencing room, I would need WAY more time to share how we did that monster.
Answer: If you want outside people bringing in their own equipment my best advice is to make sure the room is on its own "dirty" VLAN that only routes out to the internet.  If required to access local LAN resources lock down VLAN ACLs to only allow access to the servers they need access to.
Answer: Every conference room needs:

whiteboard with good markers, eraser and cleaning tools (you would not believe how may rooms are missing a simple washcloth)
good lighting and good blinds
projector
screen that can cover the whiteboard or roll up (optional)
computer with wireless keyboard and mouse
phone with conference ability
webcam (for virtual meetings)
network outlets on the table with

Internet access
enough ports for everyone at the table to connect a laptop
restricted LAN access available

power outlets on the table
AV switch between the projector and PC to allow laptop hookup without unplugging the PC

If the room is beg enough add:

podium with its own lcd screen keybaord and mouse connected to the PC
microphone and amp
Comment: Also, make sure the PC is turned on at least one night a week so it gets updated regularly, not when I'm in the middle of using it.
Comment: I'm surpised that you want the screen to cover the whiteboard, i noticed atlot (although more on a education basis) that the presenters ocasionaly want to write something down/do a diagram and a having to open/close the screen all the time would be a pain.
Comment: As a developer, I find that it's often convenient to review code via a projector and whiteboard.  Having the screen in front allows you to roll it up and annotate what's being projected.  That said, I'm sure having the screen and whiteboard on different walls is also useful.  IMHO, **every surface** in a conference room should be a whiteboard.  We have been known to use conference room windows when the board was full. ;-)
Comment: I guess i ment lmore like having a larger whiteboard so that the pulldown screen over covers about half, that way you can still lift up the screen to write on the projection ans such.
Answer: We use a domain desktop in a specially built cupboard (it was cheaper than the fancy tackle l0c0b0x has!!) from our local desk place. Domain PC means folk can just log in and run their ppt off their own desktop.
This is attached via a wallplate to the ceiling mount projector. Have someone else install this. It is a pain in the backside, and not over expensive to outsource to the experts. Wallplate lets us switch out for external users' laptops.
Network is via floorboxes, which all hit the same PoE switch. This can be patched to internal or "training" net depending on the room's use.
Final touches - a clock at the back (essential!) and cheap whiteboards on 2 walls (for smaller presentations looking "sideways").
Answer: In the past we used a ceiling mounted projector with connectors in the front of the room.  AN instructor could connect a laptop to it and get going fast.  I would also dedicate a laptop to the room just to make sure you have something that an instructor can use if needed.
Answer:
Screen (recommend NOT using a whiteboard for this)
Ceiling projector (why have it on the table where it is in the way and can be bumped)
Multiple lighting configuration - dim, full, off, and everywhere in between
Conference call ability where all ten people in the room can both hear and be heard (i.e. additional microphones)
Enough power for everyone to have their laptops and phone chargers

If/when used for training, a direct link to the Internet is a must. Be sure to protect your own network as suggested by TheCleaner.


Implementing deployment strategies

Question: Is it possible to configure apache server (using proxy mod for example) so that it works with blue/green (all trafic to one server, if its down we redirect to the other one) or canary (for example 10% users are redirected to A server, while others to B server) deployment strategies? Or, if it's not possible with apache, how can i achieve this? I know apache can work like a simple load balancer (same amount of requests to each app-server). My app architecture looks like this (without any balancing):
apache -> app-server(wildfly).
Answer: Yes, you can do that with Apache load balance please refer below url.
apache load balancer server backup
if your willing to use another technology , my recommendation is Nginx. Because, it's really simple.
your 1st question is  --> all trafic to one server, if its down we redirect to the other one
yes, you can do that using Nginx with backup connection.
in that case one of the server marked as a backup server and does not receive requests unless other server is unavailable.
upstream app_server
{

       server 10.10.10.1:8080;
       server 10.10.10.2:8080 backup;
}

server {

        listen 80;
        server_name example.com;

        location / {

                proxy_pass http://app_server;

        }
}

your second question is --> you can do that with Nginx + Server Weights
upstream app_server
{

       server 10.10.10.1:8080;
       server 10.10.10.2:8080 weight=9;
}

server {

        listen 80;
        server_name example.com;

        location / {

                proxy_pass http://app_server;

        }
}

With this configuration of weights, out of every ten requests, nine are sent 10.10.10.2 (server B) and one to 10.10.10.1 (server A)
Comment: for more information --> https://www.nginx.com/resources/admin-guide/load-balancer/

Implementing deployment strategies


Do I need P value Adjustment for 100 pairwise comparisons?

Question: I made 100 comparisons by applying chi-square test (tajima relative rate test) and got 100 p values. Do I need P-value adjustment?
If yes then which one correction will be suitable?
I have explored internet and also on this forum but didnt get answer of this particular question.
Answer: I would have thought you definitely need an adjustment. It's difficult to give advice without knowing more about the problem. If you are using the p-value as a guide to whether there is a real effect or not, you would expect 5 out of 100 p-values to be less than 0.05 if there is actually no effect/relationship at all. If you have a lot more "significant" p-values than 5, that may be an indicator that there is something interesting in the data, but it also depends on how highly correlated all your 100 outcome measures are.
Answer: There are many acceptable ways to do p-value adjustment.  But some like Bonferroni are more conservative than others.  Because you are doing so many pairwise tests you don't want conservative tests.  In fact you may want to think about whether you want the criterion be control of FWER type I error or control of FDR.  When large numbers of hypotheses are being tested it is common these days to look at false detection rate (FDR).  Resampling p-value adjustment as described in the book by Westfall and Young is an approach that I would recommend.


Nginx reverse proxy through wireguard tunnel

Question: I set up a wireguard tunnel between an AWS instance (acting as server) and a personal computer acting as client. Wireguard is installed on both in a docker container (using linuxserver image). On the local computer I have a website that I would like to access from the server using a proxy with Nginx. Basically I want to connect to the ip of the AWS instance and be redirected through the Wireguard tunnel to the website on my local machine. I can curl my website from the docker container of Nginx on the AWS instance but the proxy doesn't work. How can I solve this problem?
AWS instance (Wireguard server and Nginx proxy)
version: "3"
services:
  reverseproxy:
    container_name: reverseproxy
    build: .
    restart: unless-stopped
    network_mode: service:wireguard

  wireguard:
    image: lscr.io/linuxserver/wireguard:latest
    container_name: wireguard
    cap_add:
      - NET_ADMIN
      - SYS_MODULE
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Europe/Rome
      - SERVERURL=188.8.131.52 #optional
      - SERVERPORT=51820 #optional
      - PEERS=1 #optional
      - PEERDNS=auto #optional
      - INTERNAL_SUBNET=10.0.0.0 #optional
      - ALLOWEDIPS=0.0.0.0/0 #optional
      - LOG_CONFS=true #optional
    volumes:
      - /home/ubuntu/wireguard/config:/config
      - /lib/modules:/lib/modules
    ports:
      - 51820:51820/udp
      - 80:80
    sysctls:
      - net.ipv4.conf.all.src_valid_mark=1
    restart: unless-stopped

Nginx configuration of the proxy:
worker_processes 1;

events { worker_connections 1024; }

http {

    sendfile on;

    upstream docker-proxy {
        server 10.0.1.2:80;
    }

    proxy_set_header   Host $host;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;

    server {
        listen 80;
        resolver 127.0.0.11 ipv6=off;
        location / {
            proxy_pass         http://docker-proxy/;
            proxy_redirect     off;
        }
    }
}

Local machine with Wireguard and local website:
version: '3'

services:
    nginx:
        container_name: nginx
        #depends_on:
            #- reverseproxy
        image: nginx:alpine
        restart: unless-stopped
        ports:
            - 80:80
        networks:
            vpn:
                ipv4_address: 10.0.1.2
    wireguard:
        image: lscr.io/linuxserver/wireguard:latest
        container_name: wireguard
        cap_add:
            - NET_ADMIN
            - SYS_MODULE
        environment:
            - PUID=1000
            - PGID=1000
            - TZ=Europe/Rome
            - SERVERURL=wireguard.domain.com #optional
            - SERVERPORT=51820 #optional
            - PEERS= #optional
            - PEERDNS=auto #optional
            - INTERNAL_SUBNET=10.0.0.0 #optional
            - ALLOWEDIPS=0.0.0.0/0 #optional
            - LOG_CONFS=true #optional
        volumes:
            - /home/user/dev/nginx-proxy/config:/config
            - /lib/modules:/lib/modules
        ports:
            - 51820:51820/udp
        sysctls:
            - net.ipv4.conf.all.src_valid_mark=1
        restart: unless-stopped
        networks:
            vpn:
                ipv4_address: 10.0.1.5

networks:
    vpn:
        ipam:
            config:
                - subnet: 10.0.1.0/8

Comment: At the first sight I don't see any problems. Did you try packet capturing to see how packets go (or don't go) through the network?
Comment: No, how could I do that? Should I use ```tcpdump``` on the host or on one of the containers?
Comment: Try doing it everywhere. For example, when you're going to listen on the wireguard interface, you have to run it wherever wireguard is running. And on both sides, to confirm that packets that entered the tunnel exit it and then entered the correct Nginx container. I don't really know your complete network layout, so it's hard to give better suggestions.
Answer: If all you want is port forwarding from your AWS server, you don't need nginx, you can just use an iptables rule in your WireGuard container to forward port 80.
On your AWS server, save this WireGuard config file in some directory, like as server/wireguard/wg0.conf:
# server/wireguard/wg0.conf

# local settings for AWS server
[Interface]
PrivateKey = <server private key>
Address = 10.0.0.1/32
ListenPort = 51820

# port forwarding to Docker `nginx` service on `vpn` network on personal computer
PreUp = iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.1.2
# masquerading for Internet traffic to Docker `vpn` network on personal computer
PreUp = iptables -t nat -A POSTROUTING -d 10.0.1.0/24 -j MASQUERADE

# remote settings for personal computer
[Peer]
PublicKey = <client public key>
AllowedIPs = 10.0.0.2/32, 10.0.1.0/24

Replace <server private key> with the WireGuard private key you generated for your server, and <client public key> with the WireGuard public key you generated for your client.
Then save this Docker Compose file in the directory above it, like as server/docker-compose.yml:
# server/docker-compose.yml

version: '3'
services:
  wireguard:
    image: procustodibus/wireguard
    cap_add:
    - NET_ADMIN
    ports:
    - 80:80
    - 51820:51820/udp
    volumes:
    - ./wireguard:/etc/wireguard

And run docker-compose up from the same directory as the Docker Compose file.
Next, on your personal computer, save this WireGuard config file in some directory, like as client/wireguard/wg0.conf:
# client/wireguard/wg0.conf

# local settings for personal computer
[Interface]
PrivateKey = <client private key>
Address = 10.0.0.2/32
ListenPort = 51820

# masquerading for WireGuard traffic to Docker `vpn` network on personal computer
PreUp = iptables -t nat -A POSTROUTING -d 10.0.1.0/24 -j MASQUERADE

# remote settings for AWS server
[Peer]
PublicKey = <server public key>
AllowedIPs = 10.0.0.1/32
Endpoint = <server ip address or domain name>:51820
PersistentKeepalive = 25

Replace <client private key> with the WireGuard private key you generated for your client, and <server public key> with the WireGuard public key you generated for your server. Replace <server ip address or domain name> with the public IP address or domain name of your AWS server.
Then save this Docker Compose file in the directory above it, like as client/docker-compose.yml:
# client/docker-compose.yml

version: '3'

services:
  nginx:
    image: nginx
    networks:
      vpn:
        ipv4_address: 10.0.1.2

  wireguard:
    image: procustodibus/wireguard
    cap_add:
    - NET_ADMIN
    networks:
      vpn:
        ipv4_address: 10.0.1.5
    ports:
    - 51820:51820/udp
    volumes:
    - ./wireguard:/etc/wireguard

networks:
  vpn:
    ipam:
      config:
      - subnet: 10.0.1.0/24

And run docker-compose up from the same directory as the Docker Compose file.

However, if you do need nginx on your AWS server (for example to preserve the real IP address of HTTP clients, or to terminate TLS, etc), skip the port-forwarding iptables rule in your AWS server's WireGuard config:
# server/wireguard/wg0.conf

# local settings for AWS server
[Interface]
PrivateKey = <server private key>
Address = 10.0.0.1/32
ListenPort = 51820

# masquerading for Internet traffic to Docker `vpn` network on personal computer
PreUp = iptables -t nat -A POSTROUTING -d 10.0.1.0/24 -j MASQUERADE

# remote settings for personal computer
[Peer]
PublicKey = <client public key>
AllowedIPs = 10.0.0.2/32, 10.0.1.0/24

Add save your reverse-proxy nginx config file on the AWS server in a directory that's a sibling of your WireGuard config, like server/reverseproxy/nginx.conf:
# server/reverseproxy/nginx.conf

events {}
http {
    server {
        listen 80;
        location / {
            proxy_pass http://10.0.1.2:80;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

Use whatever proxy directives (or other nginx config) you want in this config file (the original reverse-proxy config from your question should work fine) -- just make sure the upstream server address and port matches the address and port used by the Docker nginx service in the vpn network on your personal computer.
Then add this reverseproxy service to the Docker Compose config on your AWS server:
# server/docker-compose.yml

version: '3'

services:
  reverseproxy:
    image: nginx
    network_mode: service:wireguard
    volumes:
    - ./reverseproxy:/etc/nginx

  wireguard:
    image: procustodibus/wireguard
    cap_add:
    - NET_ADMIN
    ports:
    - 80:80
    - 51820:51820/udp
    volumes:
    - ./wireguard:/etc/wireguard

On your personal computer, use the same "client" WireGuard and Docker Compose config from the first part of this answer.
Comment: Thank you for the clear response! I tried both methods but I wasn't able to get any of them to work. Without using a proxy on the AWS I get `Empty reply from server` when running `curl localhost` on the AWS server itself and nothing when running curl from my computer. Adding the proxy I get the web page of my local machine but only when running `curl localhost` on the AWS server.
Comment: 1) Do your EC2 security-group rules allow you to connect to port 80 on the AWS server from your computer? (try running a plain nginx container on port 80 of the AWS server to double-check) 2) When testing, make sure you always (re-)start the "client" containers (on your computer) after you (re-)start the "server" containers (on the AWS server) -- otherwise you may have to wait a couple minutes for the client to forget its old WireGuard connection state and re-connect to the server
Comment: Sincerely thank you for this clear answer, really saved me from hours of googling


somebody please explain about strings in c?

Question: how to store two strings one after other without concatenation (we can increment the address)
char str[10];
scanf("%s",str);
str=str+9;
scanf("%s",str);

NOTE: Here if I give first string as BALA and 2nd as HI, it should print as HI after BALA . But HI should not replace BALA.
Comment: `str=str+9;` is error in your code because `str` is constant name
Answer: You cannot increment (or change in any other way) an array like that, the array variable (str) is a constant which cannot be changed.
You can do it like so:
char str[64];

scanf("%s", str);
scanf("%s", str + strlen(str));

This will first scan into str, then immediately scan once more, starting the new string right on top of the terminating '\0' of the first string.
If you enter "BALA" first, the beginning of str will look like this:
     +---+---+---+---+----+
str: | B | A | L | A | \0 |
     +---+---+---+---+----+

and since strlen("BALA") is four, the next string will be scanned into the buffer starting right on top of the '\0' visible above. If you then enter "HI", str will start like so:
     +---+---+---+---+---+---+----+
str: | B | A | L | A | H | I | \0 |
     +---+---+---+---+---+---+----+

At this point, if you print str it will print as "BALAHI".
Of course, this is very dangerous and likely to introduce buffer overrun, but that's what you wanted.
Comment: How to write the diagram by using text only like that?
Answer: If I understand what you want to do correctly perhaps you want to put the strings in an array.
So a modified version of your code would look something like
char strings[ARRAY_LENGTH][MAX_STRING_LENGTH];
char* str = strings[0];
scanf("%s",str);
str=strings[1];
scanf("%s",str);

Then to print all the strings you would have to loop over the array like this
int i;
for(i = 0; i < ARRAY_LENGTH; i++)
{
    printf(strings[i]);
}

(you would have to define ARRAY_LENGTH and MAX_STRING_LENGTH)
Answer: May be you are looking at some thing like this
    char arr[100] = {0,}, *str = NULL;
    /** initial String will be scanned from beginning **/
    str = arr;

    /** scan first string **/
    fgets(str, 100, stdin);

    /**  We need to replace NULL termination with space is space is delimiter  **/
    str += strlen(str)-1;
    *str = ' ' ;

     /** scan second string from address just after space,
            we can not over ride the memory though **/

     fgets(str, 100 - strlen(str), stdin);

     printf("%s",arr);

Well incase you need the same with scanf
char arr[100] = {0,}, *str = NULL;
/** initial String will be scanned from beginning **/
str = arr;

/** scan first string **/
scanf("%s",str);

/**  We need to replace NULL termination with space is space is delimiter  **/
str += strlen(str);
*str = ' ' ;

/** scan second string from address just after space,
 *                 we can not over ride the memory though **/
str++;
scanf("%s",str);

printf("%s",arr);

Comment: I think you've misunderstood the restrictions of `scanf`'s `%s` directive.
Answer: Moving in a similar direction to unwind, you can use the %n directive to determine how many bytes have been read. Don't forget to subtract any leading whitespace. You may also want to read your manual regarding scanf very carefully, but paying particular care to the "RETURN VALUE" section. Handling the return value is necessary to ensure a string was actually read and avoid undefined behaviour.
char str[64];
int whitespace_length, str_length, total_length;

/* NOTE: Don't handle errors with assert!
 *       You should replace this with proper error handling */
assert(scanf(" %n%s%n", &whitespace_length, str, &total_length) == 1);
str_length = total_length - str_length;
assert(scanf(" %n%s%n", &whitespace_length, str + str_length, &total_length) == 1);
str_length += total_length - str_length;


Markov's like inequalities

Question: This sounds trivial but unfortunately I kind of feel lost in proving these:
which of the followings inequalities holds:
\begin{align}
&P(X\ge a)\leq\frac{E(X)}{a}\\
&P(X\ge a)<\frac{E(X)}{a}\\
&P(X> a)\leq\frac{E(X)}{a}\\
&P(X> a)<\frac{E(X)}{a}
\end{align}
For a non-negative constant $a$ and a random variable $X$.
I know the first one is Markov's inequality so it does hold, but what about the others?
Answer: All of them are false. If $0<a<EX$ the $\frac {EX} a >1$ and probability of an event cannot exceed $1$.
Answer for the reviser version of the question:
You also need $X$ to be non-negative. Otherwise the first one is also false.
Take $X=a$ w.p. $1$ to see that the second one  is false.
$P(X>a) \leq P(X \geq  a) \leq \frac {EX } a$.
To see the the fourth inequality can fail take $X=\pm \frac a 2$ with probability $\frac 1 2 $ each.
Comment: Oops!, I revised the question, there was some typo!, thanks for mentioning them.
Comment: Is it possible that from 1 or 3 one can conclude $P(X<a)\ge 1-\frac{E(X)}{a}$ and $P(X\leq a)\ge 1-\frac{E(X)}{a}$ respectively?
Comment: @Jason Yes, of course.

Markov's like inequalities


software for one class classification with a Bayesian Network

Question: I'm looking for a software package that would allow to do a one class classification with a Bayesian Network (anomaly detection).
I was planning to use bnlearn but so far I'm unable to find out if the library supports it.
Basically all I need is to get a measure of probability of an unseen data to belong to the distribution represented by the Bayesian Network.
All libraries I found so far only allow to query for some unknown variable given partial evidence.
Does someone know about a library that would support such a query? (The ideal case would be one that also supports Laplace smoothing)
Answer: So far this is the best I could find on the topic. It's preferably used together with bnlearn and allows log-likelihood computation without rules:
https://github.com/nezezime/bnAnomaly
Comment: Did you manage to use this library on same real sample data?
Comment: I integrated it for a test run, but I couldn't get it to run straight away and I didn't invest more time in it


How can I print current user role in Twig?

Question: I'm trying to get my user role thanks to a function in my theme.theme file.
function theme_get_user_role(){
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
}

then in my view :
{% set roles = theme_get_user_role() %}
{{ dump(roles) }}

But I have this error :

Twig_Error_Syntax : Unknown "theme_get_user_role" function. dans
  Twig_ExpressionParser->getFunctionNodeClass()

What do I miss ?
Comment: A lot. Well, that's not the way how you would pass something into your template. You'd rather need to use a preprocess function.
Comment: I've also tried this (theme_template_preprocess_user) but nothing else append if I override the function
Comment: Yes, as you don't want to preprocess the user. You want to preprocess a view (at least that's what it sound like, correct me if wrong). So it probably would be something like `theme_preprocess_views_view(&$variables)` where you'd do your logic and then add the output to `$variables['foo'] = 'bar'` and in the corresponding template then access it via `{{ bar }}`.
Comment: I've added this theme_template_preprocess_views_view(&$variables) into theme.theme, but this is returning null (I tried to display "title", also returning null)
Answer: You can use below without any function. Because the User module provides the variable in preprocess for all templates: :
{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

If you want to do anything only for the particular role then do this:
{% if 'ROLENAME' in user.getroles(TRUE)  %}

The user has the role "ABC".

{% endif %}

Comment: already tried. This is giving me the list off all roles, I need current user role :)
Comment: If you want to exclude "authenticated" role you have to write some logic to get that. Drupal by default will provide "authenticated" role for all users. Updated answer to get current role.
Comment: I just need to get roles from my current user, I've added some roles and I want to show them, no matter if it's authenticated or not
Comment: What are the roles that your current user have? Can you list down here?  If you want to get all roles user `user.getroles()` and if you want to get all roles excluding of `authenticated` role use `user.getroles(TRUE)`
Comment: Commercial and Director
Comment: Then above edited answer will be perfect to use. It will give all roles of user excluding `authenticated` and print only `Commercial and Director` roles in twig.
Comment: This is working, but it's returning "directeur", but I need "Directeur", I believe this is taking the value in base but not the label, how can I get this ?
Comment: Sorry, No Idea on that.
Comment: @MorganTartreau – You could solve the upper case issue with mere CSS.
Comment: I did this directly in twig


Can the Arzelà–Ascoli theorem be generalized for functions from a compact to a complete metric space?

Question: Can the Arzelà–Ascoli theorem be generalized for functions from a compact metric space to a complete metric space?
Comment: Yes, it can be generalized, see [here](https://en.wikipedia.org/wiki/Arzel%C3%A0%E2%80%93Ascoli_theorem#Generalizations)
Comment: No, you need totally boundedness. $\mathbb{R}$ is a good counterexample
Answer: As mentioned in the comment, there are generalizations, some of which can be found here.


Lilypond: natural+flat accidental in front of the note

Question: I can not find a way to have both a natural and a flat accidental in front of a single note.

How can I get this in LilyPond?
Comment: Why do you want it at all? Such a notation is not used very much these days (I think). However, Lilypond by default uses this if there has been a double accidental before. So if you just write `beses4 bes4`, the first note will have a double flat and the next one a natural + flat. Outside of these cases, such a notation would be extremely rare or nonexistent in actual use.
Comment: @Ramillies  In fact this notation is quite common when the previous time that pitch was in the music it was either sharped or double-flatted.   this  natural + {flat, sharp} notation is useful
Comment: In American notation?
Answer: This might be what you are looking for:
<code>\tweak Accidental.restore-first ##t
</code>
https://lilypond.org/doc/v2.23/Documentation/snippets/pitches#pitches-force-a-cancellation-natural-before-accidentals
Comment: Great!  I needed this too.  I found a part in Bruckner's 7th symphony (Adagio) that used this to specify a `cis!` after a `cisis` in the previous measure.
Answer: As Ramillies says in the comments, this is a pretty rare occurrence; I'd be curious to see the context of your example. But the main reason I can think of these accidentals happening is to cancel out a prior double accidental (with the natural) while still giving a single accidental to the new pitch.
But LilyPond has various accidental styles that automates how accidentals appear in your scores. Depending on your specific example, you may find that one of these styles fits your needs the best.
Comment: As I understand it, a prior double accidental is a valid reason for cancellation, but the other accidental type (sharp in this case) might be the much more frequently encountered one.
Comment: I don't think one would use it to cancel a double accidental while giving a new single *accidental* to the same pitch, but rather in cases where a key signature has a single flat and it's necessary to cancel a double-flat and play a note with the single flat *that's in the key signature*.  Some editors would regard the use of a single flat mark as adequate for the purpose, but performers may not consistently recognize that a note with a single-flat accidental should sometimes represent a higher pitch than a note which isn't marked with any accidental.  The natural makes things IMHO clearer.
Comment: https://www.srichinmoysongs.com/hai-mane-mahi-pare
Comment: here it is the song. It is a transcriptions of an Indian Mantra of the 70's