Soma total com vários valores de forma dinâmica usando jQuery

Question: Estou tentando fazer uma função que pegue os valores de todas
 faça a soma total e popule na
.
Fiz a função que separa o valor número do String da div, mas não estou conseguindo fazer com que a apresentação do total seja dinâmico.
Preciso que sempre que o valor de cada campo
 seja alterado, diretamente o do
 também seja, fazendo um calculo automático.
Lembrando que, sempre que o usuário clica no botão "Add", é criada outra div com os mesmos campos da primeira, ou seja, pode haver vários
. Alguém consegue me dar uma luz de como posso mudar meu código para que isso ocorra ?
index.php:

                        Número:

1

                        ID:

0

                        Selecione um produto:
                        <select class="selectpicker form-control teste" data-show-subtext="false"
                                data-live-search="true" name="select_produtos[]" onchange="initProdutos(this)">
                            <?php
                            foreach ($result2 as $item_produtos) {
                                echo '<option data-subtext="' . $item_produtos['desc_produto'] . '" value="'
                                    . $item_produtos['desc_produto'] . '">' . $item_produtos['desc_produto'] . '</option>';
                            }
                            ?>
                        </select>

                        Embalagem:

                        <input type="text" maxlength="2" class="edit-input font-pop" name="embalagem[]" value="">

                        Preço:

                        <input type="text" maxlength="5" name="preco[]" class="edit-input font-pop" value="0">

                        Quantidade:

                        <input type="text" maxlength="3" class="edit-input font-pop" value="0"
                               name="quantidade-produto[]">

                        Preço do Produto:

R$ 0

                        <button class="remover">X</button>

            <button id="add-button" onclick="">+</button>

                Assinatura

                Preço total:

JQuery:
function initProdutos(e) {
    var wraper = $(e).closest(".produtos-wrap"); // pega a div principal
    var letras_produtos = $(e).val()
    const $preco = $("[name='preco[]']", wraper);
    const $qtd = $("[name='quantidade-produto[]']", wraper);
    const $total = $(".preco-produto", wraper);
    const $final = $('#total');

    function recalculate() {
        const total = Number($preco.val() || 0) * Number($qtd.val() || 0);
        $total.text("R$ " + total);
    }

    function sub(){
        $($preco).on('change',function () {
            var sub = $(this).val().replace(',', '.');
            $(this).val(sub);
        })
    }

    function split(){
        $($total).each(function () {
            var str = $(this).html();
            var res = str.split(" ");
            $($final).text(res[1]);
        })
    }

    function total(){
        $('.preco-produto div').on('change',function () {
            var t = 0;
            $('.preco-produto').each(function (i,e) {
                if ($(e).val()){
                    if (isNaN(i)) {$(e).val(''); return; }
                    t += parseFloat(i);
                    $($final).text('R$ ' + t.toFixed(2));
                }
            })
        })
    }

    $.ajax({
        type: "GET",
        url: "API.php",
        data: {
            "mode": "produtos", letras_produtos
        },
        dataType: "JSON",
        //CASO DÊ TUDO CERTO
        success: function (data) {
            $('[name="embalagem[]"]', wraper).val(data[0]['embalagem']);
            $('.number_id_produto', wraper).text(data[0]['id_produto']);
            recalculate();
            sub();
            total();
        },
        error: function (request, error) {
            console.log(error);
        }
    });
    $preco.on('input', recalculate, sub());
    $qtd.on('input', recalculate);
    $total.on('div',split(),total());
    $final.on('div',split(),total());
    recalculate();
    sub();
    split();
    total();
};

Answer: Primeiro você precisa criar um event handler para os campos de preço e quantidade usando o evento input (esse evento é disparado em tempo real sempre que você alterar os campos).
Crie também uma função separada para formatar o valor no formato "R$ X,XX" usando .toLocaleString().
E crie outra função para fazer o cálculo geral (calculos()). Essa função você irá chamar também quando remover uma div da lista.
No event handler você irá percorrer todos os elementos com a classe .preco-produto e ir somando os valores. Basta inserir o código abaixo (com comentários explicativos):
function calculos(){
   // variável do total
   var total = 0;
   // soma tudo e coloca na div do total
   $(".preco-produto").each(function(){
      // pega apenas o valor e ignora o "R$", remove o ponto e substitui vírgula por ponto
      var p = parseFloat($(this).text().match(/[\d|,|\.]+/)[0].replace(".", "").replace(",", "."));
      total += p;
   });
   // coloca o valor total na div "total"
   $("#total").text(formataMoeda(total));
}

$(document).on("input", "[name='preco[]'], [name='quantidade-produto[]']", function(){
   // pega a div principal
   var wraper = $(this).closest(".produtos-wrap");
   // pega a quantidade
   var qtd_produto = $("[name='quantidade-produto[]']", wraper).val();
   // pega o preço
   var preco_produto = $("[name='preco[]']", wraper).val().replace(",", ".");
   // div com o valor do produto
   var total_produto = $(".preco-produto", wraper);
   // coloca o valor total do produto
   total_produto.text(formataMoeda(qtd_produto * preco_produto));
   calculos(); // chama a função para calcular o total geral
});

// função para formatar a moeda em Real
function formataMoeda(v){
   return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

Comment: Opa! Blz? Substitua esta linha: `var p = parseFloat($(this).text().match(/[\d|,|\.]+/)[0].replace(".", "").replace(",", "."));`
Comment: Sam, ele está dando um erro na função do '.toLocaleString', seria que coloquei seu código no lugar errado ou algo do tipo ? No console está aparecendo assim:

https://prnt.sc/o1wroo ,

https://prnt.sc/o1wrxa
Comment: Seria melhor eu mudar o elemento '.preco-produto' de DIV para um input ? Ou não terá nenhum problema futuro ?
Comment: A função de formatar a moeda tem que ter um valor. Veja que vc só colocou formataMoeda() sem um valor.
Comment: Deixar como div não tem problema algum, é até melhor porque é um elemento apenas ilustrativo para mostrar o valor.
Comment: Consegui arrumar esta questão, agora ocorre que, sempre que eu removo alguma DIV que estava com seu valor somado no "Total", este valor não é subtraído do valor Total. Como posso fazer essa questão ?
Comment: Alterei a resposta. Basta chamar a função `calculos()` no final da função que remove um item da lista.
Comment: Deu certo, muito obrigado Sam. Você teria uma indicação de algum material ou algo de tipo para eu me aprofundar no estudo em JQuery / Javascript ?
Comment: W3 Schools é um bom lugar pra começar.
Comment: Ok, muito obrigado pela dica e pela ajuda Sam, agradeço de coração !
Comment: Sam, Desculpe o incomodo, mas gostaria de tirar uma dúvida com você a respeito de um bug que está ocorrendo com este código. Se o valor do produto por um valor decimal, no Total ele não lê, e se a quantidade do produto for maior que 100, o Total também buga. O que pode estar ocorrendo ?

Print's: https://prnt.sc/o2wbuf  ,  https://prnt.sc/o2wc2n
Comment: Apenas corrigindo, se o preço do Produto passa do valor de R$999, o preço Total já buga.
Comment: Funcionou, obrigado Sam !
Answer: Você está tentando escutar eventos que não existem em div. Os eventos devem ser escutados diretamente nos botões e inputs do seu carrinho.
Veja o exemplo abaixo e tente adaptá-lo para sua necessidade.

var produtos = [
  {codigo: '001', nome: "Arroz", valor: 1.99},
  {codigo: '002', nome: "Feijão", valor: 12.25},
  {codigo: '003', nome: "Ovo", valor: 6.11},
  {codigo: '004', nome: "Farinha", valor: 7.07},
];

produtos.forEach(function (item) {
  $('<option />')
    .attr('value', item.codigo)
    .text(`${item.nome} - R$ ${item.valor}`)
    .appendTo('#produtos');
});

$(document).on('click', '#btn-add', function () {
  var $dropdown = $('#produtos'), codigo = $dropdown.val();

  // 1. Se dropdown não possui nenhum item selecionado nao faça nada
  if (!codigo.length) return;

  // obter o item pelo codigo
  var item = getProdutoByCodigo(produtos, codigo);

  // 2. Se item selecionado já está no carrinho,
  // incrementar a quantidade se nao tiver adiciona-lo
  if (!$(`tr#${item.codigo}`).length) addProduto(item);
  else incrementarQuantidade(item);

  atualizarTotal();
});

$(document).on('change', '.field-qtd', function () {
  var $this = $(this),
      item = getProdutoByCodigo(produtos, $this.data('codigo')),
      qtd = $this.val(),
      subTotal = (qtd * item.valor).toFixed(2);

  $this.parents('tr').find('.subtotal').text(`R$ ${subTotal}`);
  atualizarTotal();
});

$(document).on('click', '.btn-remover', function () {
  $(this).parents('tr').remove();
  atualizarTotal();
});

function getProdutoByCodigo(produtos, codigo) {
  return produtos.filter(produto => produto.codigo === codigo)[0];
}

function createDropdownQuantidade(item) {
  var $dropdown = $('<select />')
    .attr({name: 'quantidade'})
    .addClass('form-control field-qtd')
    .data('codigo', item.codigo);

   for (var i = 1; i < 100; i ++) {
    $('<option />').attr('value', i).text(i).appendTo($dropdown);
   }

   return $dropdown;
}

function addProduto(item) {
  var $tr = $('
').attr('id', item.codigo);
  $('').text(item.codigo).appendTo($tr);
  $('').text(item.nome).appendTo($tr);
  $('').append(createDropdownQuantidade(item)).appendTo($tr);
  $('').text(`R$ ${item.valor.toFixed(2)}`).appendTo($tr);
  $('').addClass('subtotal').text(`R$ ${item.valor.toFixed(2)}`).appendTo($tr);

  var $button = $('<button />')
    .addClass('btn btn-danger btn-remover')
    .html('×')
    .attr('title', 'Remover');

  $('').append($button).appendTo($tr);

  $tr.appendTo('#cart-body');
}

function incrementarQuantidade(item) {
  var $dropdown = $(`tr#${item.codigo}`).find('select'), qtd = $dropdown.val();
  $dropdown.val(++qtd).trigger('change');
}

function atualizarTotal() {
  var total = 0;
  $('#cart-body').find('tr').each(function () {
    var codigo = $(this).attr('id'),
        qtd = $(this).find('.field-qtd').val(),
        item = getProdutoByCodigo(produtos, codigo);

    total += (qtd * item.valor);
  });

  $('.total').text(`R$ ${total.toFixed(2)}`);
}
.field-qtd {max-width: 100px;}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

 <select name="produtos" id="produtos" class="form-control">
  <option value="">- Selecione -</option>
 </select>
 <button type="button" class="btn btn-primary ml-2" id="btn-add">Add</button>

    Código
    Produto
    Qtd
    Preço unitário
    Subtotal
    Remover

      total
      R$ 0.00


Como extrair strings de 4 arquivos diferente, e inserir numa única linha de um documento HTML

Question: Há horas tô tentando uma maneira de fazer a inclusão do conteúdo de 4 arquivos distintos para um novo arquivo de saída -; "saida.html". Os 4 arquivos que estou buscando extrair informações são:

link.txt
foto.txt
legenda.txt
nome.txt

Importante! - ja que os arquivos e seus respectivos conteúdos estão sobre minha costódia, ou seja, na minha máquina. E não seria viável postar tudo por aqui.

Peço a quem puder dar aquela força tarefa, que crie os arquivos em seu PC: com o comando touch ou echo
Adicione links fictícios ao arquivo link.txt. Exemplo:

www.seusite.comigo
www.seusite.no.ar
seusite.conosco.me
www.nome-do-site.aqui
http://site.saindo.do.ar
ftp://mirror.siteseu.org
https://pediusite.biz
www.saiusite.com.br

Adicione nomes para fotos, no arquivo foto.txt. Exemplo:

1.png
2.png
3.png
4.png
5.png
6.png
7.png
8.png

Adicione legendas qualquer ao arquivo legenda.txt. Exemplo:

Agente 01
Agente 02
Agente 03
Agente 04
Agente 05
Agente 06
Agente 07
Agente 08

E por fim, dê nomes, adicione dentro do arquivo nome.txt. Exemplo:

Marina
Veraz
kiki
Nautila
Keila
Brenda
Patrick
Nilton

Sei que o real problema está no modo como estou tentado conseguir isso. Veja o código:
Shell Script
#!/bin/sh
#
# apagar arquivo, se existir
[ -e saida.html ] && rm -f saida.html

cat link.txt | while read LINK
do
  cat foto.txt | while read FIGURA
  do
    cat legenda.txt  | while read LEGENDA
    do
    cat nome.txt  | while read NOME
    do
        echo -e "\n\n\n\n"
      done
    done
  done
done >> saida.html

cat saida.html

O problema esta na forma de inserir cada linha, numa nova linha do arquivo final
Este arquivo de saída [o arquivo final -ou- novo arquivo] é gerado com duplacidade por várias vezes até esgotar o final do último laço(while).
Alguém sabe uma maneira de corrigir isso? Ou um outro método melhor, de conseguir fazer isso?
Answer: Pelo que pude entender, existe uma linha correspondente em cada arquivo de texto, então você pode fazer um for de 1 até n, onde n representa o total de linhas a serem percorridas em cada arquivo, algo do tipo:
#!/bin/sh
#
# apagar arquivo, se existir
[ -e saida.html ] && rm -f saida.html

total_linhas=$(wc -l link.txt | cut -d' ' -f1)

echo -e "\n" >> saida.html

for linha in $(seq 1 $total_linhas);
do
    link=$(sed "${linha}q;d" link.txt)
    figura=$(sed "${linha}q;d" foto.txt)
    legenda=$(sed "${linha}q;d" legenda.txt)
    nome=$(sed "${linha}q;d" nome.txt)

    echo -e ""
done >> saida.html

echo -e "\n" >> saida.html

Outro ponto é quanto as tags html e body, como só é necessário abrir e fechar uma vez cada, crie antes do for e logo após, isso evita que o arquivo gerado fique incorreto.
Referência
Recuperação de linha específica do arquivo (sed)
Observação
Utilizar head e tail (head -n $linha link.txt | tail -n 1) ao invés de sed também funciona, mas pelo menos nos testes que fiz, foi mais lento.
Comment: Era realmente isso mesmo. Aceite meu Up vote seguido do meu Voto absoluto. Tirou minha dúvidas e sanou meu problema. Obg!


Getting live traffic/visitor analytics when using a reverse proxy

Question: I'm in process of implementing Varnish as a reverse proxy for a Ruby on Rails app and I'm using Google Analytics (JS/client side script to record visitor data) but it's several hours delayed so its useless for knowing what's going on now. I need at a glance live data that includes referring traffic and what current req/sec is. Right now I am using a simple Rack middleware application to do the live stats (gist.github.com/235745) but if the majority of traffic hits Varnish, Rack will never be hit so this won't work.
The closest solution I've found so far is http://www.reinvigorate.net/ but it's in beta (there are also no implementation details on their front page).
Does Varnish have traffic logs that I can custom format to match my Apache logs so I can combine them, or will I have to roll my own JS implementation like GA that shows the data in real time?
Answer: Varnish doesn't log for performance reasons.  They do allow you to access shm using varnishncsa, however, you do have a few options.
If most of your surfers support javascript (which is how Analytics is doing it's work), you could put a small webbug somewhere on your page that updated a process.  Alternatively, you could define a particular image as pass, and then analyze your backend logs since every request would send that request to the backend.
 if (req.url == "^tracker.jpg$") {
    pass
 }

tracker.jpg could easily be a script of some sort to insert data into a local log or you could run log analysis against the backend http webserver's weblogs.  If you're using apache:
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" varnishcombined
CustomLog /var/log/apache2/domain.com-access.log varnishcombined

Will use the X-Forwarded-For header in the column where most log analysis programs are expecting to see the client IP.
Answer: Have a look at varnishncsa, in particular the -c option. It's probably what you want.
Answer: If you want real time info, you should look at the varnishtop and varnishstat commands. Both of these update every second. If you can bear being a few minutes behind you could think about using a charting tool like Monit or Cacti.
See this blog post for an intro to using varnishstat.


Erro no gradle build: "java.exe finished with non-zero exit value 2"

Question: Estou com esse erro no meu Android Studio, isso acontece quando eu executo uma aplicação que estou desenvolvendo.
Alguém sabe o que pode ser?

Segue o meu build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "android.com.br.apptoner"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile files('libs/gson-2.3.1.jar')
    compile files('libs/retrofit-2.0.0.jar')
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'

    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}

Comment: Tente adicionar isso no arquivo build.gradle:  defaultConfig {
    multiDexEnabled true
}
Comment: Apareceu esse erro depois que eu coloquei o comando que você sugeriu: "Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: retrofit2/BuiltInConverters$BufferingResponseBodyConverter.class"
Comment: Poste o arquivo build.gradle.
Comment: @Geferson postado
Comment: Primeira parte do gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "android.com.br.apptoner"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
Comment: Substitua essa linha : compile files('libs/gson-2.3.1.jar') por essa 'com.google.code.gson:gson:2.3.1' e remova essa compile files('libs/retrofit-2.0.0.jar'), veja se dá certo. Não esqueça de dar um limpar e construir no projeto.
Comment: Onde encontro a opção de "limpar e construir" no android studio?
Comment: É na barra superior o ícone do Build, mas pode usar o atalho Ctrl + F9.
Comment: Relacionado ou não, provavelmente é uma boa ideia instalar o JDK 7, que é a maior versão do Java com suporte do Android.
Comment: Atualizei pro jdk8 achando que poderia ser problemas no java, mas mesmo assim vou tentar novamente o JDK7.
Comment: Já estou com mais de uma semana batendo com erros nesse android studio, saindo de um problema e entrando em outro. Enquanto isso meu projeto parado.
Answer: Amigo eu tenho um app ja em uso na play store   e uso essa build.gradle
apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "naovemaocaso.com.br
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 12
        versionName "2.0"

        //para atualizar a versao do app  basta mudar o version code
        //version name não precisa alterar   mas e ele que e exibido na play store
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile files('libs/GraphView-4.0.1.jar')
}

esse ultimo compile e pra gerar graficos no android...
espero ter ajudado


Does it count as an at bat with RISP if a runner steals second?

Question: This question is about the specific definition of the baseball statistic AVG w/ RISP. Suppose there is a runner on first with no outs. When the count is 2-2, the runner successfully steals second base and the pitch is called a ball. On the very next pitch, the batter strikes out. Does this count against the batter's average with runners in scoring position? The runner was only in scoring position for one pitch, but there were five pitches where the runner was not in scoring position.
Answer: I can answer this, but I don't know how to 'source' it.  All at-bat (or plate appearance) statistics only take effect when the plate appearance is over.
In your example, AVG w/ RISP takes into account all at-bats that end with a runner in scoring position.  So yes, even though only one pitch had a runner in scoring position, that was the only pitch that mattered, as it was the last pitch in the at bat.
Similarly, stats such as a batting average on 2-0 counts are unaffected by plate appearances that don't end on the 3rd pitch.  And even an intentional walk only requires the last pitch to be an intentional ball.
Comment: @chepner: That isn't completely true - it depends on the count.  If Smith gets a two-strike count and, Jones pinch hits for him, and Jones goes on to strike out, the strikeout and at-bat are charged to Smith, not Jones.  Rule 9.15(b).  For pitchers, if Brown leaves with 0 or 1 balls, or a 2-2 count, and the new pitcher Johnson walks the batter, it's charged to Johnson.  Rule 9.16(h)(1).
Comment: Similarly, a pinch-hitter entering the game in the middle of an at-bat is credited with any walk or strikeout that results, even if he didn't see all the balls/strikes that contributed to the outcome. (Confusingly, the *opposite* is true for pitchers; the pitcher that *starts* pitching to a hitter is charged with the walk or strikeout that a relief pitcher finishes. It leads to the fun situation where a pitcher can walk/strike-out a pinch-hitter he never throws a pitch to.)


Final Step: Prediction new values using model

Question: I'm about to finish up a machine learning challenge, but I'm suck on the final part. Before running my model I did a simple power transformation ($dependent ~variable^{1/4}$)  on the dependent variable in the training set to make it look more like a standard normal distribution. Do I do the inverse transformation ($predicted~scores^4$) to my prediction scores (my test set does not have the dependent variable)?
I had negative values in my original dependent variable in my training set, will I not be able to predict these?
Comment: First of all the back transformation should be $predicted~scores^4$.
Answer: It sounds like something has gone wrong a bit/the transformation does not achieve entirely what you want it to do, because I would guess that the model "thinks" that values <0 correspond to values of the back-transformed variable <0 (when they probably should just be closer to zero), but with the inverse transformation being $f(y) = y^4$, they actually end up being values that are higher than (some) values >0. Some transformation can be okay for inferential analyses, but problematic for prediction (e.g. square-root transformation for integer valued count data).
I would be tempted to consider an alternative transformation - e.g. if all values are strictly positive a log-transformation could be a candidate (then a machine learning model can predict any number in $(-\infty, \infty)$ and they all map to a number in $(0, \infty)$).
Alternatives include using an output-/final-activiation-/link-/loss-function in your machine learning model that implicitly does a meaningful transformation.
Answer: The answer is yes you should. The model you have fitted is of the form $g(y)=f(x)$, and hence you predicted values are of the form $\hat{g(y)}$. To get $\hat{y}$ the back  transformation  is necessary.


PHP Get Values Out of Checkbox Array

Question: I am trying to figure out how to get values out of a checkbox array. The checkbox array var_dump looks like the following:
array (size=50)
0 => string '104702|0' (length=8)
1 => string '52278|1' (length=7)
2 => string '69891|1' (length=7)
3 => string '153335|1' (length=8)
4 => string '131140|1' (length=8)
. . .

I am sending two different IDs in each array value, separated by a pipe and would like to assign each part to different variables, $variable1, $variable2, so I can use them in a database query. How can I do this?
Thanks for your help.
EDIT: Even though I've accepted an answer below, here is the complete answer I was looking for:
To get the values out of the above array so I can use them in my database query, I did the following to first break them apart:
foreach ($input as $key => $value) {
    $this->combinedIds[] = explode('|', $value);
}

Then, to get the values into separate variables, I did the following:
foreach ($this->combinedIds as $key => $value) {
    $firstId = $value[0];
    $secondId = $value[1]

    // do something with the values ...
}

Comment: Considering that you put an `explode` tag on the question, I am guessing that you at least have some idea as to how to approach this.  Can you show what you have done so far and indicate specifically where you are having problems?
Comment: No. This wasn't helpful at all.
Answer: Use foreach loop on the array and explode each value with pipe symbol. Something like this :
foreach ($arr as $val)
{
    $newData = explode("|", $val);
}

Comment: Thank you! This is what I did initially but didn't know how to get the values out.
Answer: A different variant (using an anonymous function) would be something like:
$values = array_map(function ($input) { $tmp = explode("|", $input); return ["id1" => current($tmp), "id2" => end($tmp)]; }, $array);.
This is written for PHP 5.4+. If you need a version compatible with PHP 5.3 and downwards, just substitute the brackets with its corresponding array(...) equivalent.
Comment: As far as my understanding of anonymous functions goes, yes but it depends where you want to use it. I use it as a parameter of the `array_map()` function, but you can define it in other places. You can do things like `$a = function($input) { return $input + 6; }` and the execute it like `$c = $a(5)` to get `11` as a result :P
Comment: Thank you. This is very interesting -- I wish I understood it. Can I use anonymous function inside a function in a class?

PHP Get Values Out of Checkbox Array


CSS or jquery on background image over

Question: I'm trying to place a play button over an image that has a 3px border. When the user rolls over the image I want the play button to :hover and also the image border to :hover.
Problem is that the play button only engages when I roll over it. Not when I roll over the image.
My HTML:

Play

My CSS:
.views-field-field-thumbnail img {border: 7px solid #333;}

.views-field-field-thumbnail img:hover {border: 7px solid #000;}

.thumbnail-play {
    text-indent: -9999px;
    background: url(VideoPlayerOff.png) 0px 0px no-repeat;
    position: relative;
    height: 50px;
    width: 50px;
    margin-top: -95px;
    margin-bottom: 0px;
    margin-left: 0px;
    }

.thumbnail-play:hover {
    text-indent: -9999px;
    background: url(VideoPlayerOn.png) 0px -50px no-repeat;
    }

Update: Looks like I can alter the code a bit and place the play image wherever I need it to be. Just a bit confused where its best placed.
Comment: I want the play button to engage when I roll over the image (not the play image, but the individual.png image). If I make the play button a block and extend it to the size of the image then I lose my link. Make sense?
Comment: maybe you will need some jquery for this, is jquery an option? or you have to change the markup :(
Comment: Either would work. I already have jquery running, but there has to be a CSS way. I don't mind changing the markup. The only thing I cant remove is the main image.
Answer: You need to put your play image inside your .views-field-field-thumbnail div so you that can access it with :hover.

Play

.views-field-field-thumbnail:hover img {border: 7px solid #000;}
.views-field-field-thumbnail:hover .thumbnail-play {
    text-indent: -9999px;
    background: url(VideoPlayerOn.png) 0px -50px no-repeat;
}

If you can't do this, I'm afraid you'll have to resort to javascript.
$('.views-field-field-thumbnail').hover(function()
{
   $(this).next('.thumbnail-play').addClass('hover');
},
function()
{
   $(this).next('.thumbnail-play').removeClass('hover');
});

and change .thumbnail-play:hover to .thumbnail-play.hover in your CSS.
Comment: Thanks @Plynx, but unfortunately I can't put it inside as my CMS (Drupal) is creating these 's. I'll check out the javascript.
Comment: +1 Nice trick with the `...thumbnail:hover .thumbnail-play` selector.
Comment: @Plynx I was able to change the html like above and use CSS, but my VideoPlayerOn.png image shows up behind my main image. I can't get it in front.
Comment: @Dan it's probably a stacking conflict from somewhere else in your CSS. You can always try setting a `z-index:9999` or something on your `thumbnail-play` and see if that works before trying to debug your CSS.
Answer: Using jQuery you just need to add this lines:
$('document').ready(function(){
    $('.views-field-field-thumbnail img, .thumbnail-play').hover(
      function(){
        $('.thumbnail-play').css('background', 'url(VideoPlayerOn.png) 0px -50px no-repeat');
    },function(){
        $('.thumbnail-play').css('background', 'url(VideoPlayerOff.png) 0px 0px no-repeat');
        }
    );
});

The css is the same, just delete the .thumbnail-play:hover style.
Comment: I'm getting a syntax error on the 4th line: $('.thumbnail-play').css('background', 'url(VideoPlayerOn.png) 0px -50px no-repeat';
Comment: @Dan: I forgot to close the css function with `)`, check now. PD. You should be able to fix details like the parenthesis ;)
Comment: Tom thats close, but when you roll over the box, then the photo, it changes back. I'd want the image to stay rolled over till the cursor left the box.
Comment: Tom I don't know what to tell you. When I mouse over the large image, the small image changes. But then when I put my mouse over the small image, it changes back to the first image. I'd want it to stay on the 2nd image the whole time.

CSS or jquery on background image over


VB.NET Console.foregroundcolor as boolean?

Question: i am making a console application and I want to make the Console.foregroundcolor code into a boolean, so that if the value is true, the text color will be green, and if it is false it will be red.
Thank you!
Comment: `Console.foregroundcolor code into a boolean` you cannot do that... What you may want to do is to have a boolean flag to determine the `Console.Foregroundcolor`
Comment: What you are looking for is the `if` statement. https://msdn.microsoft.com/en-us/library/752y8abs.aspx
Answer: Another way is using an extension method.
Module ExtensionMethods

    <Runtime.CompilerServices.Extension>
    Public Function ToColor(ByRef b As Boolean) As System.ConsoleColor
        If b Then
            Return ConsoleColor.Green
        Else
            Return ConsoleColor.Red
        End If
    End Function

End Module

Then you can just call .ToColor() on your boolean
Dim myBool As Boolean = True

Console.ForegroundColor = myBool.ToColor
Console.WriteLine("This is green")

myBool = False
Console.ForegroundColor = myBool.ToColor
Console.WriteLine("This is Red")

Console.ForegroundColor = ConsoleColor.White

Answer: Simply making a variable and an if statement will help you out here, I'll do an example as you haven't specified what its for:
Dim False As String = console.foregroundcolor = consolecolor.Red
Dim True As String = console.foregroundcolor = consolecolor.Green

Then do your coding around and when it comes to the moment whether it needs to be verified just either make:
Verification = False
OR
Verification = True
Then do the following 'If' statement:
If Verification = True
True                                       (To change the text colour)
Console.Writeline("This is True!")
ElseIf Verification = False
False                                      (To change the text colour)
Console.Writeline("This is False!")
EndIf

This will either display green text with "This is True!" written, or red text with "This is False!" written.


What convergence criterion was used in this proof?

Question: I have this proof of Raabe criterion for convergence in my notebook, but only 1 final conclusion is what I fail to understand(since it doesn't mention what criterion was used) so I will keep it concise with the other parts.
Statement: If $\lim_{n \to \infty}n\cdot(\frac{a_n}{a_{n+1}}-1)=\alpha>1$, then the series $\sum_{n=1}^\infty a_n$, $a_n>0$, converges.
Proof.
We pick a $q \in \mathbb{R}$ such that $\alpha > q > 1 $. Eventually, there is some $K$ so that for all $n>K$ we get  $$na_n-(n+1)a_{n+1} > (q-1)a_{n+1} > 0\tag{$*$}$$
hence $na_n > (n+1)a_{n+1}$. Therefore, the sequence $\{na_n\}_{n=1}^{\infty}$ is decreasing and bounded, so it means it converges. Now, let $\lim_{n \to \infty}na_n=c$.
From $(*)$ it follows $a_{n+1}<\frac{na_n-(n+1)a_{n+1}}{q-1}$. We observe the series $S=\frac{1}{q-1} \sum_{n=k}^{\infty}na_n-(n+1)a_{n+1}$. Eventually, the sequence of partial sums $S_n=ka_k-(k+n)a_{k+n}$, and $S=\lim_{n \to \infty}ka_k-(k+n)a_{k+n}=ka_k-c$, and so the series $S$ converge, and since $a_{n+1}<\frac{na_n-(n+1)a_{n+1}}{q-1}$, (by comparison criterion?) the series $\sum_{n=1}^{\infty}a_{n+1}$ converge, hence $\sum_{n=1}^{\infty}a_n$ converges.
End of proof.

My question:
How does the convergence of $\sum_{n=1}^{\infty}a_n$ follow from $\sum_{n=1}^{\infty}a_{n+1}$ ? We know $na_n>(n+1)a_{n+1}$ and by that $a_n>a_{n+1}$, so it shouldn't be the comparison criterion which enabled us to make the conclusion, right ?
Note: The proof is very messy written in the notebook, so there may be some mistakes, sorry for those.
Answer: We simply have that
$$\sum_{n=1}^{\infty}a_{n+1}=\sum_{n=2}^{\infty}a_{n}=-a_1+\sum_{n=1}^{\infty}a_{n}$$
Comment: Yes exactly it is the same series without the first term. We could apply direct comparison test if we want but it is not necessary. The argument is $$\sum_1^\infty a_n=a_1+ \sum_1^\infty a_{n+1}=a_1+L\in \mathbb R$$
Comment: Is this the case where adding a finite number of terms won't affect the convergence of series ? Would that be a proper justification for  concluding that the desired series converges too ?
Answer: Let, for $ n\ge 1 $,
$$S_n=\sum_{k=1}^na_k$$
$$=a_1+a_2+...+a_n$$
and
$$T_n=\sum_{k=1}^na_{k+1}$$
$$=a_2+a_3+...+a_{n+1}$$
$$=S_n+a_{n+1}-a_1$$
then
$$\sum_{n\ge 1}a_{n+1} \;\text{converges} \; \implies \lim_{n\to +\infty}T_n\in \Bbb R \; \text{and} \; \lim_{n\to \infty}a_{n+1}=0$$
$$\implies \lim_{n\to\infty} S_n =\lim_{n\to\infty}T_n+a_1$$
$$\implies \sum_{n\ge 1} a_n \; \text{converges}$$
Comment: Shouldn't it be $lim_{n \to \infty}S_n=\lim_{n \to \infty}T_n - \lim_{n \to \infty}a_{n+1} - a_1$, and then since $a_{n+1}$ is decreasing and bounded, there is some $x\in \mathbb{R} $ such that $x=\lim_{n \to \infty}a_{n+1}$, and therefore $\sum_{n=1}^{\infty}a_n$ converges ?
Comment: @GrigoriPerelman No, it is $ +a_1$.
Comment: @GrigoriPerelman $S_n=T_n-a_{n+1}+a_1$
Comment: Yeah I made a mistake there its $+a_1$. But then $\lim_{n \to \infty}S_n=\lim_{n \to \infty}T_n -a_{n+1}+a_1$ and not $\lim_{n \to \infty}S_n=\lim_{n \to \infty}T_n + a_1$ as you said ? I mean $-a_{n+1}$ is missing in your post at that part, and then we have to prove the convergence for the sequence $a_{n+1}$ like I explained in first comment ?


how to use Views Datasource to export view in JSON

Question: I am new in Drupal. I am using Drupal 7 and i have created a view based on the terms and displaying it as Block to display it in the website. But, I want to export the view data in the JSON format.
I have installed Views Datasource module and enabled it in the Module administration.
But, i can't see the way to export my current view data to JSON through this module.
Can any one please help? is there any settings i am missing?
or is there any easy way like modules or plugins i can use?
Answer: You can achieve this by combination of two modules. Views data export and Views data export - JSON support. Once you install these two modules create a view as data export and select format as JSON.
Comment: Hi, I have installed both modules but how to make it work? what i have to do to export my view to json?
Comment: You're trying to export view data right? I have updated my answer above to include screenshot. I don't have JSON support installed but it should be same as setting up CSV option.
Comment: Thanks for your answer. I can now display the data in JSON. Just one quick question. I am loading values from 2 terms and i want o create different arrays in the JSON file for example:
{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}
Comment: Can you please elaborate what you're trying to achieve...
Comment: But right now, i am getting this result
[      {"no name":"Red<\/a>"}  ,    {"no name":"white<\/a>"}]
Answer: To use Views Datasource to output JSON:

Enable the views datasource sub-module views_json
Add a new Page display to your view
Under "Format" switch to "JSON data document"
Set the path for your display


LessCss dynamic variables based on ancestor class

Question: I have a page template which has a branding class on the body element:

Africa

Using the following Less, I can use a variable for the brand colour and apply it to the color of a CSS selector:
@brand-default: #649d84;
@brand-africa: #df6f20;
@brand-nz: #444;

.brand-color {
    .brand-default & {
        color: @brand-default;
    }
    .brand-africa & {
        color: @brand-africa;
    }
    .brand-nz & {
        color: @brand-nz;
    }
}

h1 {
    .brand-color;
}

This works well, but sometimes I want to apply the color to another CSS declaration - such as background-color, and to do this with the above code I'd need to duplicate the .brand-color mixin to instead apply background-color.
Ideally I'd like the mixin to return a variable - I know it's possible, but I can't work out how to use the classname to determine the returned value.
Answer: Well, no, you can't use class name to determine a variable or a return value. So it's usually done in reverse, for example like this:
@brand-default: #649d84;
@brand-africa:  #df6f20;
@brand-nz:      #444444;

h1 {
    .brand-colors();
}

h2 {
    .brand-colors(background-color);
}

.brand-colors(@property: color) {
    .color(default);
    .color(africa);
    .color(nz);

    .color(@name) {
        .brand-@{name} & {
            @value: 'brand-@{name}';
            @{property}: @@value;
        }
    }
}

Or like this:
@brand-default: #649d84;
@brand-africa:  #df6f20;
@brand-nz:      #444444;

h1 {
    .brand-colors({
        color: @color;
    });
}

h2 {
    .brand-colors({
        background-color: @color;
    });
}

.brand-colors(@style) {
    .brand-color(default);
    .brand-color(africa);
    .brand-color(nz);
}

.brand-color(@name) {
    .brand-@{name} & {
        @value: ~'brand-@{name}';
        @color: @@value;
        @style();
    }
}

Or even like this:
.brand(default) {@{color}: #649d84}
.brand(africa)  {@{color}: #df6f20}
.brand(nz)      {@{color}: #444444}

h1 {
    .brand-colors();
}

h2 {
    .brand-colors(background-color);
}

.brand-colors(@color: color) {
    .-(default);
    .-(africa);
    .-(nz);

    .-(@name) {
        .brand-@{name} & {
            .brand(@name);
        }
    }
}

Or something in between. Or... oh wait, there's whole family of methods for this stuff (incl. various combinations), see for example:

https://stackoverflow.com/a/23660124
How to thematize in lesscss
https://stackoverflow.com/a/20072967
etc.

Usually list/array/loop based methods are more compact, though personally I prefer something dumb like this:
.themed({

    h1 {
        color: @color;
    }

    h2 {
        background-color: @color;
    }

});

.themed(@styles) {
    .-(default, #649d84);
    .-(africa,  #df6f20);
    .-(nz,      #444444);

    .-(@name, @color) {
        .brand-@{name} {
            @styles();
        }
    }
}

Comment: Thanks, this is a fantastic approach. I'm going with the last suggestion - not sure about why some of it works (".-"?) but it's working!
Comment: `.-` is just a mixin (I often use this short mixin name for utility/auxiliary mixins to not clutter the code).
Comment: Oh, of course. Makes perfect sense, thanks a lot for your help!


Display Suite code field – how to use another image field conditionally

Question: In my content type I want to show the main image if the thumbnail field is empty. So I use the Display Suite code field and I enter the following code:
<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    print_r('Thumbnail missing');
    // What code to put here to enable or render another image field
}
?>

When the tumbnail is missing the above code works, but instead of text I want to display another image field, when the thumbnail is missing. I have tried everything I can think of, but the main image dose not show :-(.
Answer: It's because you have nothing in renderable format yet.
Look at function field_view_field

Returns a renderable array for the value of a single field in an
  entity.

Then change your code like this:
<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    $renderable = field_view_field('node',$entity,'field_main_image',array('settings' => array('image_style' => 'thumbnail')));
    print drupal_render($renderable );
}
?>

Note that this is not the only way to get html from field values. You can use theme functions and load that with values you find on $entity object and print that if you wish.
Comment: Thanks a lot! That made my day! I also added 'label' => 'hidden' and that was that. I will dig into field_view_field, another tool in the toolbox :-). Tried to give you an upvote apart from the right answer tick, but apparently my reputation is to modest for that so far. But many thanks again.


How to prove some insights regarding a new pca coordinate system

Question: I've a question regarding pca variant.
Let $X ∈ \Bbb R^{D×n}$ be a data matrix, $\{u_i\}^{d}i=1$ be the $d$ principal components of $X$, and where $μ ∈ \Bbb R^d$ is the sample mean vector and $1_n ∈ \Bbb R^n$ is the $n$-dimensional ones vector.
We can define the new PCA based coordinates as $α_i = u^T_i(X − μ1^T_n ), i = 1, ..., d$.
can u explain why the new PCA features $α_i, α_j$ have zero mean and are uncorrelated.
Comment: I did my best to reformat your post, but I don't understand what {ui}di is supposed to mean. For future reference, see [this page](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) regarding how mathematical expressions are supposed to be formatted.
Comment: i'vei change it. thanks for your response but i not understand yet
Comment: Please explain what you don't understand. While I'm at it, note that askers are generally expected to provide context for their answers, as is [explained here](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). So, please [edit] your question to say a bit about where you encountered this problem, what your thoughts are on this problem, and what you have tried so far.
Answer: Hint: A row-vector $v$ has mean zero iff it satisfies $v1_n^T = 0$. The lack of correlation between $\alpha_i,\alpha_j$ amounts to the observation that $\alpha_i\alpha_j^T = 0$.


Select and Insert Query Records in same query

Question: SELECT user_id, description, SUM( Credit ) AS cre, SUM( debit ) AS deb,
CASE WHEN credit > debit
THEN SUM( credit - debit )
END AS del, price, created
FROM accounts
WHERE created
BETWEEN  '2013-11-04'
AND  '2013-11-11'
AND description LIKE  '%Amount Earned%'
OR description =  'S'
OR description =  'B'
GROUP BY user_id

Problem with this query is that this query is Selecting all records according to user_id from accounts table. I want to select records only created
BETWEEN  '2013-11-04'
AND  '2013-11-11'
I want to select these records and need to Insert records also in the same query

Requirement: I want to select record from accounts table from last week group by user_id, Sum(Debit) and SUM(Credit) and Del ->(credit - debit) put the Sum and Insert records in same accounts table.
Answer: insert into (other table )
  SELECT user_id, description, SUM( Credit ) AS cre, SUM( debit ) AS deb,
     CASE WHEN credit > debit
     THEN SUM( credit - debit )
  END AS del, price, created
FROM accounts
WHERE
( created BETWEEN  '2013-11-04' AND  '2013-11-11' )
AND
( description LIKE  '%Amount Earned%'
  OR description =  'S'
  OR description =  'B' )
GROUP BY user_id, created

Comment: One more condition in this query, select all records where del value is greater than 0, and if del is 0 then don't show that record


Everyday guitar routine

Question: I'm learning how to play the guitar and it's been a year and a half I think. I play both acoustic and electric guitar.
I would like to get my playing to the next level with an everyday guitar routine. So I've looked around and this is what I'm doing now everyday:

Untune guitar and tune by ear.
Play all notes and say their name out loud (to learn where each note is).
Practice a "simple" song. What I mean by simple is just chords progressions. I stick to the same song until I get the right sound with each chord (no buzzing) and the chord changes right. (For example now I'm on Karma Police)
Play a scale in one key up and down. (Now I'm on the blues scale)
Start over 1-4 with a pick. First time I use my fingers.

Is there something particularly important that I left out?
As a self-taught guitarist, I feel I've been having to much fun just playing songs I like, even just part of songs I like. So now I really want to take a step back and learn the fretboard, maybe reading notes (and not tablatures), the scales, develop a good ear, play chords fast and clean and whatever your suggestions will be :)
Thanks in advance to anyone taking some time to answer.
Comment: Have a quick read of the Related links in the bar to the right -->
Comment: Also have a look at [this](http://music.stackexchange.com/questions/32200/should-i-learn-the-notes-of-all-the-scales/32201#32201) and [this answer](http://music.stackexchange.com/questions/31232/how-can-i-produce-any-melody-on-my-guitar-as-effortlessly-as-i-do-with-my-voice/31234#31234).
Comment: This inspired me the first time I read it: http://www.musicfanclubs.org/rage/articles/g-one.htm
Comment: Warm up exercises should be number one on your list. I'm surprised no one has suggested this. It's not going to take your guitar playing to the next level but your hands will thank you down the road.
Comment: A dedicated half hour of theory work will also do you well.
Answer: Keep playing songs you like also, and more importantly make part of your routine learning new songs you like. Also I would add something 100% creative, whether it's writing a new riff or chord progression, improvising over changes, or coming up with different sounds, or even better all of the above.
You shouldn't have to detune before tuning. If you have a guitar that is not a little off every day then either your ears are still developing, your strings are super old, or I want to know what kind of guitar you have (Modulus?). Also I would check and fix tuning with electronics after doing it by ear since that will help your ears hear what better tuning sounds like.
Comment: ^^^ This, 100% ^^^  I was going to say "keep having fun learinign & playing songs you like". Get more adventurous, and get creative. Pretty much what Todd suggests. One thing NOT to do is keep the same routine so that you get bored and disinterested. Keep it fun, and you'll be learning without realising it :-)
Answer: Aside from Todd's suggestion, I also recommend:

Trying to play something from ear (listen to something, then try playing it without looking for the tab/score). Playing by ear is an incredibly useful skill.
Try a bit of sight reading every day. Both from tab and standard/classic notation.

These are both skills that may not be essential in the short term, but in the long run they will prove very useful.
Answer: I admire and respect your dedication to continued improvement.  One thing I have learned after many years of playing guitar is that no matter how good you get, there is always ample room for improvement.  That's a good thing because it keeps the guitar fresh and interesting.  I can continue to improve until I am no longer on the north side of the grass.
How quickly you make gains depends on how focused and intentional you are at improving your skills.  From your question, it appears that you are deliberately seeking to avoid the trap many guitarist fall into where they learn to play a few songs they like and never try to challenge themselves to get outside the comfort zone they create for themselves - thus they never get any better.
For me personally, I find it more inspiring to develop new skills by learning to play songs that I will enjoy playing.  I am always working on several that are more challenging than the ones already in my repertoire.  By gearing my "practice" ("homework") around a goal of learning to perform a particular song I like and want to play, there is a tangible reward continually visible on the horizon.  Once I finally master the difficult parts that allow me to add that song to my repertoire, I find more songs to work on.
I find that once I master a difficult lick or run in a particular song - I discover many more songs that I can suddenly now play - that I could not before - because they had similar passages or riffs.
This works for me because I play guitar to perform and to accompany my singing as both a solo performer and part of a band.  Your goals may differ but even lead guitar players have a repertoire and building your list of songs you can play (rhythm or lead) provides a tangible and measurable sense of accomplishment!
One thing I have recently started doing more of that you might also enjoy, is playing along to guitar backing tracks.  Getting the band together to rehearse or practice is logistically challenging - so practicing with other musicians is not something that I can do on a daily basis.  But practicing or playing to a backing track is the next best thing.
You can find free backing tracks on line and download them to a file folder on your computer.  Or you can create your own with some simple recording software.
The sites I use to find backing tracks are Guitar Backing Tracks dot com for Mp3 tracks or Betty Lou's Guitar Music Site which has MIDI backing tracks to go along with the lead sheets for thousands of songs organized by genre and searchable on the site.
There are free programs for converting MIDI to MP3 if you prefer to convert the MIDI backing tracks to MP3 - but I just store them all in the same file folder and play them on my computer with external speakers.  I can also connect my computer to my PA and play the tracks through there if I want to.
Playing with other musicians or to a backing track helps with your timing and makes practice a little more interesting.  You still have to work on the repetitive runs to master a given lick.  But you can use Audacity (Free open source software program), to slow down the playback speed of any sound file without changing the pitch. Gradually increase the playback speed until you can play it at an increased speed - then you have it mastered!
You can click the link to download audacity if you don't have it already.
I wish you the best of luck and great enjoyment as you continue your never ending journey of improving your guitar playing!
Answer: I've answered the following numerous times to questions like these.
If you really want to take your musicianship to the next level, spend time understanding classical western harmony rather than doing "shortcuts" like saying the note of each fret out loud.  Once you have a firm grasp on theory fundamentals, you won't have to "memorize" notes; rather you will understand the different relationships between notes, chords, and harmonic progressions.
In terms of physical training on your instrument, you really can't achieve full competence without being able to play scales and arpeggios in all scales.  Of course playing just one scale a day helps, but if you can afford the time, you should play all major and minor scales (or, at the very least, play all blues scales rather than just one).  Once you get good enough (it doesn't take that long, trust me), the time required to do your daily scale playing is greatly diminished (you will be able to play it faster, and with fewer mistakes, so you finish much quicker).
I know a lot of musicians that don't know their theory, don't really know what a scale is, and say things like "I prefer the sound of E major over the sound of D major"* <- in my non-professional-and-very-amateur opinion, these people are poor musicians.
Comment: First off: Music came first, then there was theory. Second: How is it a "shortcut" learning every tone on the fretboard? This is not something theory will help you with, but will be a great help in applying theory. Third: Music is basically all opinion, it's things like preferring the sound of a certain chord over another that makes great musicians great. A E major sounds different from a D major, even if the intervals are the same, and one whole step is not a lot (in theory).
Comment: I know this, and it should be clear by my comment. But in reality, there _is_ a difference in sound between an E and D major chord, no matter what the theory tells you. It's what sounds good that matters, not what theory tells you. Theory has its place, I use it a lot myself, but some people exaggerate its importance. It should be clear that t's not necessary to know theory to perform music.
Comment: So playing a tune in A one day and E in another will make no difference, except to people with absolute pitch? We will have to agree to disagree on this one.
Comment: An E major and D major are both major chords, they sound the exact same if one lowers their tuning by a whole step. What he's getting at is that people don't know the relative difference between types of chords like a sus2 or sus4 vs major vs minor etc
Comment: I agree that it is not necessary to know theory to perform music, or even to perform it very well (I believe McCartney never learned any theory, for example) and become a great musician; the fact is theory is the better way to take musicianship to the next level as the OP asked.  I disagree with your statement on the difference in chords.  Aside from the frequency, both chords are exactly the same when played separately (i.e. with no other chord to create tonal context) <- an exception would probably people with synesthesia or perfect pitch.
Comment: I should also state that obviously as a musician you must know where each note is on your instrument, and what the OP is doing is a good thing by learning where those notes are.  What I suggested is that instead of memorizing where every single note one-by-one simply by pure repetitive memorization, it would be more efficient to understand what makes a scale "a scale", and how that relates to other scales, and how one key in a certain scale relates to another key in a certain scale.  Recognizing relationships like these help to take musicianship to the next level.  Good discussion!!!
Comment: Regarding D versus E: Take a guitar tuned in E strike and strike an open E chord. Detune it one whole step and strike the same chord. Even for people without perfect pitch (like me, my relative pitch is sketchy too), there is a difference. There is a lot of difference in different voicings of the same chord too. Compare the open E to a barred E at the 7th fret, or chords in different octaves for the piano. If it was all the same, one key would be sufficient, right?
Comment: Meaningful, you forget that by doing that, you have created harmonic context (playing E and then D).  Just by doing that, you have created an implication that you are not in certain keys (e.g. DbMajor), and that you may be in certain keys.  In response to your other statement, everything you described are examples of differences in **frequency**, not **quality**; of course a chord played an octave higher will sound "different" in the sense of pitch, but not in the sense of harmony.  **Without harmonic context**, any major chord will sound the same as any other chord in the sense of harmony.
Comment: From the perspective of harmony, that is correct :)
Answer: I think the best strategy is by setting clear goals and measuring progress. Seems simple and some people just do it naturally, and then after years of rinse and repeat we perceive them as "naturally talented"

Set Goals - what is it you want to achieve. It has to be concrete and measurable like: I want to be able to play locrian scale in all places on the neck in 150 bpm or I want to play Karma Police so it sounds exactly like on recording. I want to improvise over blues progression so it sounds ok when i record myself.
Measure which comes down to record yourself. There's no fairer and harsher judge than recording. Do it as often as you can. Hate your own playing? Good - you've just seen the room for improvement that you haven't seen before.
Try to identify problems with your playing, narrow them down and focus practice hours on this problem. Great classical instrumentalists are the kind of people who would spend a day on going repeatedly through two bars of a piece.

Everyday guitar routine


Set Musescore 4 chord style to jazz by default

Question: I'm working with hundreds of jazz lead sheets in musicxml format, and when I load them into Musescore 4.1.1, the chord symbols don't load properly.  The chord types show, but not the root.  I can fix this by manually going into the menu Format > Style > Chords, and selecting the "jazz" option, however, this is time consuming, and I'd like to set things up to select this option by default. Can anyone help?
A screen capture of the problem looks like this:

I can fix this problem in Format>Style>Chords and clicking on the "jazz" option, and then my score looks like this:
Comment: I'm not familiar with Musescore so I will not answer, I'll just comment with some general suggestions that the program may have. Maybe you can have your default song contain the jazz option or maybe you can create a key command for selecting the jazz option. Apart from that it sounds like all you have to do is select one option from a few drop down menus, how time consuming is that? Also what's with all the grace notes? :)
Comment: What do you do with hundreds of files? It sounds like you're mass-printing things or something, and so you probably already have some kind of a script running that automatically. Or if not, you should have. Add the jazz chord option thing to the script.
Comment: Thanks for these suggestions.  I looked into defining a keyboard shortcut for this, but it Musescore doesn't seem to support this particular feature in that way.  The reason I need this is because I'm working with over 300 musicxml scores that I analyze using custom Python scripts.  I then want to visualize features (and listen to them) using Musescore.  I go back and forth between dozens of scores at a time, and those few clicks add up to quite a lot of repetitive work.
Comment: @piiperiReinstateMonica, adding the jazz chord option in a script sounds good... do you know how to do that?  As that a tag I can add to my musicxml files?
Comment: I meant GUI automation, making a script use the MuseScore application like a robot, clicking buttons and menus etc. There are many kinds of GUI automation solutions for different languages and operating systems.
Answer: Click the <code>...</code> menu next to the Font heading in the properties panel, and "Save as default style for this score".
This also works for most other properties, and mirrors the S button in MuseScore 3.
Comment: I thought that only applied to the current score. So that also sets the default for the any score opened?
Comment: Thanks, but that doesn't seem to work.  First, in the properties panel, there is no "Font" heading in my version of Musescore (4.1.1).  There is a "Save style..." in the Format menu with a corresponding "Load style..." entry.  But when I save a style and then try loading it, there is no apparent effect.
Comment: @TheKid Just to make the bottom-of-the-barrel dummy check, you selected a text element first? I don't know what else to tell you, I'm running 4.1.1 as well.
Answer: I haven't tried this for MU4, but it works fine in MU3.6.

Create an dummy score
Go into Format|Style|Chord Symbols
Select "Jazz"
Do "Save Style..." and save this style wherever you want
Go into Preferences|Import
Set "Use style file" field pointing to the style sheet you saved at (4).
Optional: close MU and reopen it.

When you import a score from midi, musicXml, ... it will have the jazz-style chords.
Answer: This problem has been resolved in MuseScore 4.2.
Comment: Please add more detail, so others will know how to do it.
Comment: It isn't a problem in 4.2 so it just works.
Comment: Here are the details: download MuseScore 4.2, and then it works out of the box.


Cakephp Find doesn't output correct data

Question: I'm trying to create a query using several form inputs in cakephp.
In this form the user can use some values which i want to use to filter the results from my subscriptions.
From the form i receive 4 values which i want to use.
My find method looks like this:
<code>$subscriptions = $this->set('subscriptions',
    $this->Subscription->find('all', [
        'conditions' => array(
            'and' => array(
                'Subscription.provider' => $provider,
                'Subscription.subscription_duration' => $length,
                'Subscription.subscription_allowance_minutes >=' => $minutes,
                'Subscription.subscription_allowance_sms >=' => $sms,
                'Subscription.package_internet_bundle_mb >=' => $data
            )
        ),
        'order' => 'Abonnement.subscription_price ASC'
    ])
);
</code>
As you can see i want to query the set value and everything higher then that to give the user a broader selection.
The $provider and $length are arrays and contains, "Vodafone", "Ben", "Tele2", "T-Mobile" etc. There is no problem with these two values but with the ones with which i want to query equals and greater then.
As i am a starter with cakephp i would like someone to verify if my find method is correct? if it's correct i will troubleshoot further and post the rest.
Comment: _There is a problem with this, somehow the equal or greater then doesn't work correct._ You are not describing your problem well enough for anyone to troubleshoot. If changing your greater than operators to less than operators does not fix the problem, then you need to better describe your problem. For instance, show sample data, along with sample selection criteria (i.e., $provider, $length, etc) and your expected results. Or show the Cakephp generated SQL and describe how you would like it to be.
Comment: Also: You should always mention the exact cakephp version you are using.
Answer: The problem with the breaking filter was the fact that i was trying to query a varchar field with integers. There is a model field overload with: $this->Model->_schema but this didn't work for me so i changed the type in my table of the fields to int.


Chosing the right time series model

Question: Can someone help me to find the right time series model. I am not able to figure out the right hyper parameters for the model. Please see attached ACF and PACF graphs. I can provide more information if someone is willing to help.
I am using monthly data from 2013 to august 2019
Link to the uploaded csv data http://www.sharecsv.com/s/7e254bfa6a0c8c44c357dc48e52a64fa/TimeSeries_Data.csv
Comment: Have you tried an automated model selection method, like `ets()` or `auto.arima()` in the `forecast` package for R? If not, why is manual model selection important to you?
Comment: Please find the uploaded csv. [link](http://www.sharecsv.com/s/7e254bfa6a0c8c44c357dc48e52a64fa/TimeSeries_Data.csv)    -    In the above example I was trying to forecast compact category.  Yes, I have tried using Auto.Arima and ets in alteryx (R package)
Comment: you have 6 series each with 81 monthly values. The appropriate model for each series is likely to be similar with subtle differences between then . Pick one series  ...the one that you are having the most trouble with and I will analyze that .. pursuing a potential hybrid model using both memory (arima) and latent deterministic structure. Please select one.
Comment: @ IrishStat , Thank you for your reply again sir. I think my pick would be Compact. I would love to understand the methodology and the thought process. Looking forward
Comment: I will try to accomplish that ... my post might be quite long as modelling is an iterative process much like peel an onion.
Answer: There is nothing wrong whatsoever in using computerized aids as long as you understand the strengths and the shortcomings. Building a model is much like washing both sides of your face .. one needs to deal with both potential auto-projective (memory/arima) structure and deterministic structure ( pulses, level shifts , seasonal pulses and local time trends ). The approaches you have been investigating only deal with memory and are often flawed with over-parameterization and resultant statistical non-significance.
I have looked at your 7 series and perhaps the least complicated/thorough model formulation is the one you selected ...compact car sales over 81 periods . For pedagogical reasons I would have selected a more "difficult" series but life is short and I have analyzed the one you selected.
I will present the results of AUTOBOX's ( a piece of software that I have helped to develop ) and show critical results ...and then in a second phase actually try and unveil the logic behind the steps.
Initially the acf of the original series is here  clearly suggesting strong seasonal auto-regressive structure akin to the classic airline series of Box and Jenkins. The suggested model is (2,0,0)(1,0,0)
a quite simple model in thew span of possibilities. I can't imagine why even band-limited procedures wouldn't deliver a similar model because the identified anomalies are VERY small BUT highly significant.
The Iterative modelling process https://autobox.com/pdfs/ARIMA%20FLOW%20CHART.pdf evolved to the following potentially useful model .
 and here in more detail  withmodel statistics here
The Actual/Fit and Forecast is here  with monte-carlo driven re-sampling prediction limits for the next 36 periods .
The model residuals are here  with an ACF here
The forecasts are here
The Actual and Cleansed  graph is helpful to visually sipport the identification of the anomolous data  points
I will now take a deep breath and attempt to detail the steps as you indicated that is what you really want.
STEP 1 : examine possible models following two mutually exclusive and distinctive paths ... Path 1 .. investigate possible arima models using a superset of the aic/bic ... auto.arima  approach and for each possible prospect identify and incorporate additional deterministic structure that is statistically significant THEN take Path2 which identified deterministic structure and then incorporates/adds any evidented arima structure..... Select the most promising path penalizing models for excessive parameters
Note that models of the form  are also considered as a wide search is made for an equation that is as good as the human eye or at least similar as possible.
In this case the best model had an a seasonal ar(12) and a 2 parameter ar polynomial

STEP 2  possible deterministic structure via the Tsay procedure http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html

Continuing  we test for constancy of error variance over time .. suggesting constant error variance over time ( one of the Gaussian assumptions ignored by others ! ) Note that some of your other automotive series series required this GLS OPTION .

We now more closely examine the need for just pulses ....and obtain

stepping down ( always a good idea ! ) we get

In terms of why your current approaches are failing , I can only suggest that you closely read @Adamo's wise reflections
"The correlogram should be calculated from residuals using a model that controls for intervention administration, otherwise the intervention effects are taken to be Gaussian noise, underestimating the actual autoregressive effect."
See @Adamo's response here
Interrupted Time Series Analysis - ARIMAX for High Frequency Biological Data?

Chosing the right time series model


Como pegar o valor "src" de uma tag "img" através de Javascript e copiá-lo para área de transferência?

Question: Galera quero fazer com que quando ao clicar em cima de uma imagem, a sua url seja copiada para a área de transferência, tentei utilizar Clipboard mas apenas consegui realizar a cópia do texto.
var a = document.getElementById('id' + img).src.toString();
alert(a);

quero fazer isso mas sem o usuario ter que apertar o ctrl c, quero que seja copiada o valor quando o usuario clicar na img que chama essa funcao.
function getsrc(img) {
   var a = document.getElementById('id' + img).src.toString();
   window.prompt("Copie para área de transferência: Ctrl+C e tecle Enter", a);
}
Valor mostrado no alert : http://localhost:8084/aplicacao/2/img.jpg .
Esse valor deve ir para a area de transferencia,ao ctrl+v deve ser colado.
Com este código aparece o caminho que quero que vá para a área de transferência, mas não consigo copiá-lo para a área de transferência automaticamente quando uma img é clicada.
Comment: seu link não vai funcionar ederjc, pois está no localhost
Comment: é apenas um exemplo pode ser qualquer url, e funciona sim, ao copiar manualmente uma img do src ela aparece normalmente.
Comment: rsrs, quando eu disse que não vai funcionar, é quando alguém clicar aí. Isso o que você quer fazer eu tava vendo um dia desses, se eu achar a referência, posto aqui para você
Comment: O que você quer esta aqui : http://pt.stackoverflow.com/questions/89139/como-copiar-para-%C3%A1rea-de-transfer%C3%AAncia-em-javascript, [Leitura Adicional](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Browser_compatibility)
Comment: entendi obrigado :D
Answer: Você pode usar a biblioteca clipboard.js, clique aqui pra ver sua documentação.
Solução usando clipboard.js:

// Inicia o Clipboard no elemento "button"
var copiar = new Clipboard('button', {

    // Define o texto a ser copiado
    text: function(trigger) {

        // Obtem "src" da "img" que está no mesmo nível do "button"
        return $(trigger).siblings('img').attr('src');
    }

});

// Retorna um alert se copiar com sucesso.
copiar.on('success', function(e) {
   alert('Copiado para a area de transferencia!');
});

// Retorna um alert se copiar com erro.
copiar.on('error', function(e) {
   alert('Houve um erro ou navegador não suportado');
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="btn btn-block btn-primary">
   COPIAR
  </button>

  <button class="btn btn-block btn-primary">
   COPIAR
  </button>

Outros métodos de uso:
Você pode usar o clipboard.js de várias outras formas, não se limitando à demonstração postada, para complementar estarei postando alguns exemplos, que também estão contidos no site da documentação
Copiar valor do input:

// Inicia o Clipboard no "button"
new Clipboard('button');

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <input id="id" class="form-control" value="Digite algo, ou clique em Copiar para copiar isso!">

      <button class="btn  btn-block" data-clipboard-target="#id">
           Copiar
      </button>

Nesse caso o data-clipboard-target="" é o responsável por copiar o valor de outro elemento, nesse caso do input. Assim ao clicar o usuário irá copiar o conteúdo escrito no elemento definido no data-clipboard-target.
Copiar texto pre-definido no elemento:

// Inicia o Clipboard no "button"
new Clipboard('button');

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <button class="btn btn-block" data-clipboard-text="Você copiou esse texto :O">
      Copiar!
  </button>

Nesse caso o data-clipboard-text="" é o responsável por definir o texto a ser copiado. Assim ao clicar o usuário irá copiar o conteúdo escrito no elemento data-clipboard-text.
Compatibilidade:

Lista de suporte oficial da biblioteca:

Chrome 42+
Mozilla 41+
Internet Explorer 9+
Opera 29+

Licença:
Imagens estão sob "Public Domain":
https://pixabay.com/pt/sapo-adeus-viagens-bagagem-holdall-897420/
https://pixabay.com/pt/sapo-adeus-viagens-bagagem-holdall-897418/
Clipboard.js está sob "MIT License":
https://zenorocha.mit-license.org/
Answer: Abaixo um exemplo feito com puro Javascript.

var reply_click = function()
{
    alert("Copiado para a área de transferência");

  //Criando um "hidden" input
  var aux = document.createElement("input");

  // Atribuir-lhe o valor do elemento especificado
  aux.setAttribute("value", this.src);

  // Anexá-lo ao corpo
  document.body.appendChild(aux);

  // Highlight conteúdo
  aux.select();

  // Copiando o highlighted text
  document.execCommand("copy");

  // Removendo do corpo
  document.body.removeChild(aux);
}
//imagem 1
document.getElementById('1').onclick = reply_click;
//imagem 2
document.getElementById('2').onclick = reply_click;

<input type="text" placeholder="Cole aqui após clicar na imagem acima" />
Answer: Neste link tem um exemplo que usei e funcionou.
Obs.: Utilizando somente JQuery.
var src = $('img[alt="example"]').attr('src');
alert("caminho da imagem = " + src);

Answer: Usando jquery deve funcionar assim:
var imagem = $("#id-da-imagem").attr('src');
alert(imagem);

Comment: Ricardo, ele está querendo copiar para a área de transferência, aí você só pegou o atributo src
Comment: @PedroCamaraJunior não foi substituído, simplesmente juntaram um método novo para propriedades do DOM e o `.attr` é indicado para atributos do HTML.
Comment: A partir do jQuery 1.6 a função `attr` foi substituída pela `prop` - http://api.jquery.com/prop/
Comment: ah, entendi agora
Comment: Pedro Camara, já vi casos em que attr() ainda é usado, mas de fato, prop() veio para ficar


Adding new rows on a draggable table via jquery

Question: I have a draggable table with preloaded "new items" - sorta like the Power Edit feature of the menu_editor module. Everything works perfect.
However, I want to have a button that adds a new row via jquery. I was able to do this via the following code. However, the new rows added by jquery are not draggable. What can i do to make it work? Is it even possible?
var preloaded_items_count = '.$preloaded_items_count.';
$("#edit-add-new-item").click(function(){
  var append_tr = $("#guide-pages-table tr:last").clone();
  var replace_pattern = new RegExp("new-" + preloaded_items_count, "g");
  var new_item_id = "new-" + (preloaded_items_count + 1);

  //append_tr.find("a.tabledrag-handle").remove();
  append_tr.html(append_tr.html().replace(replace_pattern,new_item_id));
  preloaded_items_count = preloaded_items_count + 1;

  //Drupal.tableDrag.prototype.makeDraggable(append_tr);
  $("#guide-pages-table > tbody:last").append(append_tr);
  return false;
});

Answer: As I can not reproduce your case, this answer just is a suggestion:
look at misc/tabledrag.js:
Drupal.tableDrag.prototype.makeDraggable = function (item) {

So you need re-running necessary javascript after adding new row.
Drupal.attachBehaviors($('#guide-pages-table > tbody:last'));

Comment: Yes, this is where I got the `Drupal.tableDrag.prototype.makeDraggable(append_tr);` idea. However, i still cannot make it work. I tried the `makeDraggable` function on my table, instead of the row, to no avail. Thanks btw.
Comment: Drupal.attachBehaviors($(this));
Comment: I am not entirely sure what `.attachBehaviors` will do. I tried adding `Drupal.attachBehaviors($('#guide-pages-table > tbody:last'));` at the bottom of my code but it still won't work :P
Answer: This is how you can do it:
(For D7, I hope it is the same or similar in D6)
var $table = $('
').appendTo($container);
var $tbody = $('
').appendTo($table);
var drupalTableDrag = new Drupal.tableDrag($table[0], {});
var $newRow = $('
').appendTo($tbody);
drupalTableDrag.makeDraggable($tr[0]);

The essential thing to learn is that Drupal.tableDrag acts as a class constructor, and you are supposed to call makeDraggable() from the constructed object.
If Drupal already created this object for you, you will find it in Drupal.tableDrag[base], where base is whatever key was used in the settings.


Are Functions Smooth Sections?

Question: In differential geometry we often identify $\Omega^0(M)$ with the smooth functions on
a smooth manifold $M$. But for every $i>0$ we know that:
$$\Omega^i(M)=\Gamma(\Lambda^i(T^*M))$$
I imagine with $i=0$ then $\Lambda^i(T^*M)$ would be the trivial line bundle since constant functions exist on $M$. So can we think about functions as smooth sections of this trivial line bundle? If this is true, does that mean for every smooth function $f$ there is a projection such that:
$$\pi\circ f=\text{Id}_M$$
If so, it would be very helpful to a problem I am currently working on...
Answer: Ok never mind, this is easy. Let $M\times \mathbb{R}$ be the trivial line bundle, then for any smooth function $f$ on $M$, we can easily obtain a map:
$$\begin{align}
M&\longrightarrow M\times\mathbb{R}\\
p&\longmapsto (p,f(p))
\end{align}$$
The projection onto $M$ denoted by $\pi_M$ then satisfies the above requirement.

Are Functions Smooth Sections?


View Paid Sorting

Question: I wanted to do something like following scenario.
So for example I have a view of content type 'mycontent'.
Bob wants to be on the top and he is paying me money for it. Is there any way I can show paid node first in the View Display ? Based on what they pay.
Any help would be appreciated.
P.S : I am using Drupal 7. And I already have 1000 nodes of the content type.
Answer: You could create a field on the node to track how much has been paid. Use hook_field_access() or field_permissions to make this field so that it can't be modified by the user. Use rules or custom code to set this field with the amount paid when the node is paid for. Then order your view by this field descending.

View Paid Sorting


How to test all three piano pedals

Question: How to demonstrate easily and clearly that all three pedals on a piano are working as expected?
It is a digital piano but probably the pedal action should be identical or similar. I am new with piano and only used the sustain pedal so far. I am not fully aware that exactly the others two must do.
Comment: It is Roland FP-80, http://www.roland.com/products/en/FP-80/, to be precise. The RPU-3 is visible on the picture. I have connected the three pedal unit, replacing the default single pedal unit. Sustain works as before. I can assign unusual functions like pitch bend for the remaining two pedals but the default action seems not doing anything. I already own that instrument.
Comment: Found! Sostenuto works as damper, but only for keys that have been kept depressed while pressing down the pedal (this is different from that I have imagined). And una corda actually also works, but to hear this I need to strike keys stronger than I usually do.
Comment: You want to do that in a new piano you're about to buy?
Comment: What make/model of piano is in question ? The third pedal of acoustic pianos doesn't serve the same purpose on each . It can be a practice pedal or for sostenuto.                     On digitals, the sockets for the pedals can be assigned for several different facilities.
Answer: Roland FP-80 Connectors section at Specifications tab contains the following:

PEDAL (DAMPER/R, SOFT/L *, SOSTENUTO/C *)

So I'll presume, that those are the pedals required for the answer.
As stated at Piano pedals article on Wikipedia:

Modern pianos usually have three pedals, from left to right, the soft
  pedal (or una corda), the sostenuto pedal (mainly found in
  American-made grands), and the sustaining pedal (or damper pedal).

To test the damper (or sustain) pedal You should:

press the damper pedal (obviously)
play some notes staccato
the result is all notes that You've played should continue to sound
until You release it

To test the soft pedal:

press the soft pedal
play some composition
you will hear, that it sounds quieter (comparing to playing the same
composition without pressing the soft pedal)

FYI: soft pedal is also called una corda
tre corde means three strings. On a non-digital piano the hammer strikes all the three strings that correspond to some single key that You press. This is the state of the piano when soft pedal is not pressed.
una corda means one string. This is the state of the piano when soft pedal is pressed.
So, basically, this is tre comparing to una. This should give You the idea of how much softer (quieter) the composition fragment should sound when You press the soft pedal.
FYI 2: You can find una corda remarks in urtexts of compositions written by Ludwig van Beethoven.
For example, in Ludwig van Beethoven, Sonate für Klavier (B-Dur) op. 106, Artaria, 2588 in third movement, Adagio Sostenuto on page 25 at Beethoven-Haus in Bonn - Digital Archives here.
To test the sostenuto pedal:

play some chord, for example, C-major and hold it while You press
the sostenuto pedal
now release the chord (but do not release the pedal)
now play the C-major scale
the result is You still hear the C-major chord, but not the C-major
scale

Piano pedals > Sostenuto pedal:

By using this pedal, a pianist can sustain selected notes, while other
  notes remain unaffected.

How to test all three piano pedals


Use another pipe after sanitize pipe

Question: I need to get 200 characters from data which I get from sanitized pipe.
Now my code looking like:

Sanitize pipe`s code:
transform(content: any): any {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }

So, I need to pass data which I get from first pipe (sanitized data) to another pipe, like so:

But when data come from sanitizeHtml its not have  string type and I cant get 20 characters after sanitazing from getFirst20Ch pipe
Answer: bypassSecurityTrustHtml is not doing what you expect.
Create an element in memory only and add the HTML, then use the textContent or innerText getter to get the text content.
let div = document.createElement('div');
div.innerHTML = '

abcc

';
this.content = div.textContent;

and display it with

{{content | getFirst20Ch}}

StackBlitz example
You can also implement this as pipe of course.
Comment: Thanks! You save my day =)
Comment: If i do this, then i will get first 20 characters with markup elements
Comment: `sanitizeHtml` is probably not doing what you expect. All it does is applying a special marker for Angular to know it is safe to add the content to the DOM. It doesn't manipulate the content in any other way. Please explain what the expected behavior is.
Comment: i have data, which contains markup, like Data. And i need to remove markup and get first 3 character from 'Data' like 'Dat'
Comment: Glad to hear :)

Use another pipe after sanitize pipe


How to set $LD_LIBRARY_PATH for a Tomcat webapp after it is automatically unset?

Question: I have a Tomcat webapp that needs LD_LIBRARY_PATH to be set.
I'm using RHEL6 and Tomcat6 (from yum package manager), the webapp is called adore-djatoka.
I'm starting tomcat by using a supplied script that exports a number of environment variables, but it appears that LD_LIBRARY_PATH is being unset, I think this is a security feature, as the init script is run by user "root" but tomcat is running as "tomcat".
When I restart tomcat I see the following line in the logfile "djatoka.log"
2013-01-04/10:25:04.118/EST [main] DEBUG envParams: LD_LIBRARY_PATH=null | null/kdu_compress

Which I read as telling me that the app is expecting LD_LIBRARY_PATH to be set, but finds it to be null, and hence it'll look for kdu_compress in the directory null/.
I have littered the startup script with echo so I can see that LD_LIBRARY_PATH is being set and exported, so I'm assuming it must be being unset.
There are a couple of scripts bundled with the webapp to test it's installed correctly and they run fine from the command line, but they are very short, they simply export the environment vars (including LD_LIBRARY_PATH) and make a call to java.
I've tried adding
LD_LIBRARY_PATH="/opt/adore-djatoka-1.1/lib/Linux-x86-64"
export LD_LIBRARY_PATH

to /usr/share/tomcat6/bin/setenv.sh
I've tried adding
LD_LIBRARY_PATH="/opt/adore-djatoka-1.1/lib/Linux-x86-64"

to `/etc/tomcat6/tomcat6.conf
LD_LIBRARY_PATH is already exported in the startup script which goes on to call /etc/init.d/tomcat6 [start/stop/restart]
I'm quite new to a few subjects here, so some guidance on how to get a better idea of where to look next, or which information would be useful to post will also be appreciated. I've already read "why LD_LIBRARY_PATH is bad"
So my question is how can I start up tomcat, so that it doesn't set LD_LIBRARY_PATH to null? or how can I re-set it to what I want, after it has been set to null? or how can I stop the webapp from being dependent on it?
Cheers,
Answer: What you actually needed was to put an appropriate flag into your JAVA_OPTS (which is a bit counterintuitive).
On a RHEL box, put this in /etc/sysconfig/tomcat6 or /etc/tomcat6/tomcat.conf
JAVA_OPTS="-Xminf0.1 -Xmaxf0.3 -Xms1536m -Xmx1536m -XX:MaxPermSize=512m -Djava.awt.headless=true -DdjatokaUri=//thing.example.com/adore-djatoka -Dkakadu.home=/opt/adore-djatoka/bin/Linux-x86-64 -DLD_LIBRARY_PATH=/opt/adore-djatoka/lib/Linux-x86-64"

You can verify that this is set in Java using the following:
# tr '\0' '\n' < /proc/$(pidof java)/environ

as well as seeing the following in the djatoka log:
2015-08-31/08:33:01.683/NZST [http-bio-8080-exec-1] DEBUG envParams: LD_LIBRARY_PATH=/opt/adore-djatoka/lib/Linux-x86-64 | /opt/adore-djatoka/bin/Linux-x86-64/kdu_expand

Or you can just set it globally (in a file such as /etc/ld.so.conf.d/adore-djatoka)
# echo "/opt/adore-djatoka/lib/Linux-x86-64" > /etc/ld.so.conf.d/adore-djatoka
# ldconfig

Answer: I eventually worked-around this issue by grabbing the source of the webapp, hardcoding the required path into the relevant line, compiling and redeploying.
The path in question was simply pulled out as a string in the source, so it wasn't required that it was stored in LD_LIBRARY_PATH.
To make it more portable, I should remove the hardcoding and replace it with a call to a custom environment variable set in a config script.
This means, to the best of my knowledge, the answer to "How do I set LD_LIBRARY_PATH environment variable, after it is unset within the scope of a setuid program" is, "You can't, unless the program itself has a facility for passing in this info after execution".
Answer: With TOMCAT 7, simply setting a couple of lines in the $CATALINA_HOME/conf/tomcat.conf solved the issue (where a library named e.g. Crypto becomes libCrypto.so) :
JAVA_OPTS="-Djava.library.path=/usr/share/tomcat/sharedLibs"
# NOTE: the above instructs only the JVM, the next is ALSO required by native libs to load dependent native libs!
LD_LIBRARY_PATH="/usr/share/tomcat/sharedLibs"

Fact is, every <tag>="<value>" line in tomcat.conf becomes an "export <tag>=<value>" (e.g. reverse-engineer the Tomcat service start script: /etc/init.d/tomcat).
You can also overload the value globally in /etc/sysconfig/tomcat for all TOMCAT services you may have configured.
Hence, if the settings in tomcat.conf looks like having no effect, check what the /etc/sysconfig/tomcat possibly overload ...


Sum of the thirteenth power of the roots of given polynomial

Question:
Find the sum of the thirteenth powers of the roots of $x^{13} + x - 2\geq 0$.

Any solution for this question would be greatly appreciated.
Answer: If $r_i$ is a root, then $r_i^{13}=2-r_i$. Add up, $i=1$ to $13$. Note that $\sum r_i=0$, because the coefficient of $x^{12}$ is $0$.
Comment: If $r$ is a root, then $r^{13}+r-2=0$, so $r^{13}=2-r$. So
Comment: sorry i did not get you..
Comment: so the final answer is?
Comment: We want $\sum_{i=1}^{13}(2-r_i)$. This is $\sum_{i=1}^{13} 2-\sum_{i=1}^{13}r_i$. The first term is $26$. The second term is $0$, since the sum of the roots is the negative of the coefficient of $x^{12}$, divided by the coefficient of $x^{13}$.  So the answer is $26$.
Answer: Any root $r_i$ of $x^{13} + x - 2 = 0$ satisfies $r_i^{13} + r_i - 2 = 0,$ or $r_i^{13} = 2 - r_i.$ A polynomial of degree $13$ has $13$ roots (counting repititons). See here and here. Sum them up:
$$ \sum_{i = 1}^{13} r_i^{13} = 26 - \sum_{i = 1}^{13} r_{i} .$$ Also observe that the $x^{n-k}$th coefficient of a polynomial is the $k$th symmetric polynomials in the roots (see this), with $$\text{ceoff of } x^{12} = r_1 + r_2 + \ldots + r_{13} = 0.$$
(to convince yourself of the latter fact, expand a smaller example: $(x-r_1)(x-r_2)(x-r_3),$ and observe the coefficient of $x^2$.)


how to plot member of object with different color?

Question: i want to plot  this python object using matplotlib. this object has three different labels i want to plot each label with different color
{1.0: [[-1.9242, 1.0], [-2.0039, 1.0], [-2.0259, 1.0], [-1.8096, 1.0], [-1.9083, 1.0]],
 2.0: [[0.53616, 2.0], [0.56647, 2.0], [0.50042, 2.0], [0.31371, 2.0], [0.61207, 2.0], [0.93016, 2.0], [0.27571, 2.0], [0.14968, 2.0], [0.2886, 2.0], [0.3646, 2.0]],
 3.0: [[1.1139, 3.0], [1.1449, 3.0], [1.5837, 3.0], [1.7038, 3.0], [1.192, 3.0], [1.6529, 3.0], [1.3052, 3.0], [2.2981, 3.0], [1.3196, 3.0], [1.3439, 3.0], [1.3795, 3.0], [1.5595, 3.0], [1.6977, 3.0], [1.2672, 3.0], [1.4191, 3.0], [1.719, 3.0], [1.6339, 3.0], [1.4335, 3.0], [1.4942, 3.0], [1.574, 3.0]]}

Comment: You need to tell which part of your 'object' should be where on the graph and what part of the object is the 'label'. Also What have you already tried to accomplish this and where is the problem?
Answer: You can just issue separate plot statements specifying the color with c=...:
from matplotlib import pyplot as plt

d = {1.0: [[-1.9242, 1.0], [-2.0039, 1.0], [-2.0259, 1.0], [-1.8096, 1.0], [-1.9083, 1.0]],
 2.0: [[0.53616, 2.0], [0.56647, 2.0], [0.50042, 2.0], [0.31371, 2.0], [0.61207, 2.0], [0.93016, 2.0], [0.27571, 2.0], [0.14968, 2.0], [0.2886, 2.0], [0.3646, 2.0]],
 3.0: [[1.1139, 3.0], [1.1449, 3.0], [1.5837, 3.0], [1.7038, 3.0], [1.192, 3.0], [1.6529, 3.0], [1.3052, 3.0], [2.2981, 3.0], [1.3196, 3.0], [1.3439, 3.0], [1.3795, 3.0], [1.5595, 3.0], [1.6977, 3.0], [1.2672, 3.0], [1.4191, 3.0], [1.719, 3.0], [1.6339, 3.0], [1.4335, 3.0], [1.4942, 3.0], [1.574, 3.0]]}
plt.scatter(*zip(*d[1.]), c='b')
plt.scatter(*zip(*d[2.]), c='r')
plt.scatter(*zip(*d[3.]), c='g')
plt.show()


How to update flask frontend instantly when MongoDb database updates?

Question: I am updating a MongoDb database from a streaming application. And I want the changes in the database to reflect in the frontend.
On the frontend, I am currently queering the database, but I have to refresh manually to get new updates. Refreshing periodically is not a good option as the updates can be too quick many times a sec or even very slow a few times an hour.
I came across SSE(server sent events). But don't know if it can be used in my case.
Answer: What I was searching for is a good PUSH based method. Where the backend server can change to a frontend client.
What I used:
A PULL based method instead.
Usually, in such cases, AJAX requests with a setInterval() in javascript can be used. In this case, one doesn't have to refresh the whole page. But just use an ajax request periodically to check for updates at regular intervals. And in case of an update can append/fill the corresponding Html in the concerned .
Here is what I used:
<code>function update(){ // This functions is called repeatedly
    $.ajax({
        url: "/update/",
        type: "POST",
        success: function(resp){
            $('div.stats').html(resp.data); // append/fill to appropriate div
        }
    });
}

var myVar = setInterval(update, 1000); // update every 1sec
</code>
This is very commonly used to the method.
This kind of served my purpose.
Also there are ways to have a PUSH based approach instead. See COMET programming. But I could not find a proper tool to do that in sync with the web frameworks.