Order confirmation with attachment

Question: I'm sending order confirmation messages via the module message-notify. As mail system i'm using MimeMail.
Is there a possibility to add an attachment to the email with the key: commerce_order_order_confirmation?
I tried to add the attachment in hook_mail()
function mymodule_mail($key, &$message, $params) {

    if(isset($key)) {
        if($key == 'commerce_order_order_confirmation') {
            $attachment = array(
                'filecontent' => file_get_contents(DRUPAL_ROOT . '/sites/default/files/pdf/myattachment.pdf'),
                'filename' => 'myattachment.pdf',
                'filemime' => 'application/pdf',
            );

            $message['params']['attachments'][] = $attachment;
        }
    }
}

Answer: You want to change the email before it is sent.
So try this as a starting point (put together with the help of:
1. your post
2. https://drupal.stackexchange.com/a/98559/34326
3. https://www.drupal.org/node/2057703#comment-8343071):
function mymodule_mail_alter(&$message) {

    if ($message['id'] == 'message_notify_commerce_order_order_confirmation') {
        $file = file_create_url(file_build_uri('path-to-file-relative-to-your-files-folder.pdf'));
        $attachment = array(
            'filecontent' => file_get_contents($file),
            'filename' => 'test.pdf',
            'filemime' => 'application/pdf',
        );

        $message['params']['attachments'][] = $attachment;
    }
}

The file should be located in sites/default/files or whatever applies to your site.
You should also change filemime to what matches your file.
I am getting errors "realpath() expects parameter 1 to be a valid path" and "is_file() expects parameter 1 to be a valid path", but the email with the attachment is sent anyway, which is why I am posting this.The errors seem to be related to the 'filepath' parameter which is mentioned in the 3rd link, because depending on what I define, the results vary:
eg. 'filepath' => $file,, which gives me no attachment and no error or 'filepath' => $file->uri,, which gives me an additional error about a "non-object" and no attachment.
http://passivemanagement.net/blog/2014/01/let-drupal-send-email-attachment-using-mimemail-module uses a different markup for the file, but right now I can't figure out, how to adapt it to the task at hand.
Comment: This lead to the correct way. I managed with `'filepath' => '/path/to/file.pdf'` instead of `'filecontent' => ...`.
Comment: The "realpath()" error is a problem with Mime Mail. There is discussion and patches here:  https://www.drupal.org/project/mimemail/issues/2904611

Order confirmation with attachment


How to use com.thoughtworks.selenium.DefaultSelenium in eclipse while writing the scripts?

Question: While writing the scripts in eclipse by using selenium RC i got an error in com.thoughtworks.selenium.DefaultSelenium.And the com,thoughtworks.selenium class in missing in my library. Could any one suggest the remedy?
Answer: Download the jar file supported for selenium RC and related java client libraries. Import these jar into project. Many sources are available online .
Comment: I have already downloaded the jar file and imported it to the eclipse. And then build the path, but it shows the error in the corresponding line.and there is no such package,how can i add that?


Get parameters JSON Rails

Question: I am having this POST request:
app/controllers/videogames_controller.rb:10:in `search'
Started POST "/videogames/search" for 127.0.0.1 at 2018-09-04 10:39:10 +0200
Processing by VideogamesController#search as JSON
Parameters: {"user"=>{"param"=>"FIFA"}, "videogame"=>{}}

and the following controller:
def search
   @p = Videogame.where(name: params[:param])
   render :status => 200, :json => { :data =>  @p}
end

def videogame_params
   params.permit(:user, :param)
end

What I am trying to do is to send a string to the rails backend (in this case FIFA), so to make a query in the database and to return some objects.
The problem is that I can't figure out how to get the string "FIFA" from the parameters, in order to make the query with it. If I use params[:params] I get a NULL value.
Comment: If you look at the `params` in your request, the value you are looking for `FIFA` is associated with key `param` which is a child to `user`. So you should be trying to do `params[:user][:param]`
Answer: @p = Videogame.where(name: params[:user][:param])

Get parameters JSON Rails


Bootstrap datetimepicker mindate

Question: I am using https://github.com/Eonasdan/bootstrap-datetimepicker in my web app to show datetimepicker.
I have 2 controls - startDate and endDate
I want to set minDate for 'endDate' as greater than 'startDate'.
This plugin provides an option of 'minDate'.
However, how do I set the value for it from another datetimepicker field?
I tried to do as follows.
$('#start-date-time-datepicker').datetimepicker({
    minDate: moment(),
    sideBySide: true,
    daysOfWeekDisabled: [0,6]
});

$('#end-date-time-datepicker').datetimepicker({
    minDate: $('#start-date-time-datepicker').val(),
    sideBySide: true,
    daysOfWeekDisabled: [0,6]
});

But it is not working.
Can someone please provide some pointers?
Answer: You need to bind the date pickers
$(function () {
    $('#start_date').datetimepicker({
     // custom config
    });
    $('#end_date').datetimepicker({
        // custom config
    });
    $("#start_date").on("dp.change", function (e) {
        $('#end_date').data("DateTimePicker").minDate(e.date);
    });
    $("#end_date").on("dp.change", function (e) {
        $('#start_date').data("DateTimePicker").maxDate(e.date);
    });
});

ref: http://eonasdan.github.io/bootstrap-datetimepicker/#linked-pickers
Answer: You can use either $("#start-date-time-datepicker").data("DateTimePicker").date() or $("#start-date-time-datepicker").find("input").val() to get the value you want.
Here's a simple demo.

var $start = $('#start-date-time-datepicker'),
    $end1 =  $('#end-date-time-datepicker1'),
    $end2 =  $('#end-date-time-datepicker2')

$start.datetimepicker({
    minDate: moment(),
    sideBySide: true,
    daysOfWeekDisabled: [0,6]
});

$end1.datetimepicker({
    minDate: $start.data("DateTimePicker").date(),
    sideBySide: true,
    daysOfWeekDisabled: [0,6]
});

$end2.datetimepicker({
    // note that this is not in a recognized RFC2822 or ISO format
    // $("#start-date-time-datepicker").find("input").val()

    minDate: new Date($start.find("input").val()),
    sideBySide: true,
    daysOfWeekDisabled: [0,6]
});

$start.on('dp.change', function(){
  // $start input change event
  var startDate = $(this).data("DateTimePicker").date();

  // set $end1 and $end2 to $start's date and set the minDate
  $end1.data("DateTimePicker").options({
    date: startDate,
    minDate: startDate
  })

  $end2.data("DateTimePicker").options({
    date: startDate,
    minDate: startDate
  })
})

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

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" />

  <input type='text' class="form-control" />

  <input type='text' class="form-control" />

  <input type='text' class="form-control" />

Comment: Hikarunomemory, thanks for the reply. However, if I first select the start date, I want my end date to be automatically set to the start date. This is not happening. I want user to put restriction that end date should be greater than start date. Is it possible?
Comment: @VishalBhavsar I updated the snippet. Please take a look.

Bootstrap datetimepicker mindate


C#: Try, Catch not catching exception

Question: I have a try catch that should catch an exception if the string has invalid characters for a Windows path.
         try
            {
                Result = Path.GetFullPath(pathname);
            }

            catch (System.IO.IOException e)
            {
                CatchResult = (e);
            }

But an exception is still being thrown, and the application crash's. Any ideas?
Comment: What is the exception which is being thrown?
Answer: The MSDN states that the Path.GetFullPath() throws 5 kinds of exceptions but not IOException. You must catch the correct type of exception. See documentation for more information.
Comment: [`PathTooLongException`](http://msdn.microsoft.com/en-us/library/system.io.pathtoolongexception%28v=vs.110%29.aspx) is derived from `IOException`, so his catch would get that one.
Answer: Path.GetFullPath(string) does not throw IOException as one of it's available exceptions.
Please review the Exception list at Path.GetFullPath MSDN
Exceptions thrown:

ArgumentException
SecurityException
ArgumentNullException
NotSupportedException
PathTooLongException.
Comment: To be fair, [`PathTooLongException`](http://msdn.microsoft.com/en-us/library/system.io.pathtoolongexception%28v=vs.110%29.aspx) is a descendant of `IOException`, so the catch would get that one.

C#: Try, Catch not catching exception


Comparing beta coefficients from a GLMM

Question: I have a logistic mixed-effects model with multiple predictors:
y ~ (x1 + x2 + x3)*x4 + x5 + (x1 + x2 + x3 | id), family = "binomial"

I would like to know whether the interaction between, let's say, x1 and x4 (both continuous variables), is statistically significantly different from the interaction between x2 (also continuous) and x4. Is it possible to do so? What methods should I use?
Notes based on EdM's comment: x1 and x2 represent differences between two options based on a certain aspect of each option. To make this more concrete, let's say (as a toy example) that you are choosing between apples and oranges. y is whether you choose apples (0) or oranges (1). x1 could be the difference (oranges-apples) in calories between apples and oranges. x2 could be the difference in tastiness between oranges and apples. Your choice of what to eat will depend on both x1 and x2. However, the two may interact with x4 - let's say that x4 is time of the year. The later in the year, the stronger/weaker the effects of x1 and x2 may be. I want to know whether the interaction between x1 and x4 is different than that between x2 and x4. x1 and x2 are roughly on the scale, because they are both divided by their own standard deviation. However, the values are not exactly z-scored because the 0-value is meaningful, so I did not center them.
Thanks!
Comment: @gimi You sure are ;) no need for categorical variables for contrasts to work; see Ed's answer.
Comment: check out "contrasts".
Comment: Please look at the second paragraph of [this answer](https://stats.stackexchange.com/a/272285/28500). This comparison _might_ make sense if `x1` and `x2` are effectively on the same scale, but otherwise such comparison is tricky. It would help if you could edit the question to provide more details about the model, the variables involved, and what you hope to gain from comparing the interactions. Please provide such extra information by editing the question, as comments are easy to overlook and can be deleted.
Comment: @EdM please let me know if this helps
Comment: @JohnMadden could you expand?
Comment: for background: https://en.wikipedia.org/wiki/Contrast_(statistics) to do it in R: https://cran.r-project.org/web/packages/contrast/vignettes/contrast.html
Comment: thanks @JohnMadden! Looks like that would work well for categorical variables, but not so much for continuous ones. Am I missing something?
Answer: If the predictors x1 and x2 are on the same scale, one approach would be to examine whether the interaction-coefficient estimates $\beta_{x_1 :x_4}$ and $\beta_{x_2 :x_4}$ can be distinguished statistically. The null hypothesis would be that $\beta_{x_1 :x_4}-\beta_{x_2 :x_4}=0$. A linear combination of variables that equals 0 is called a contrast in statistics.
To test that hypothesis you need to estimate the standard error of that difference. For that you need to use the formula for the variance of a weighted sum of correlated variables. In this case:
$$\text{Var}(\beta_{x_1 :x_4}-\beta_{x_2 :x_4})= \text{Var}(\beta_{x_1 :x_4}) + \text{Var}(\beta_{x_2 :x_4})-2\text{Cov}(\beta_{x_1 :x_4},\beta_{x_2 :x_4})$$
The variances and covariance on the right side of the equation are found in the coefficient variance-covariance matrix provided by the model. Take the square root of the result for the standard error, SE. With a generalized linear model the coefficient estimates have an asymptotic multivariate normal distribution, so you use a z-statistic $(\beta_{x_1 :x_4}-\beta_{x_2 :x_4})/\text{SE}$ to evaluate whether the difference in coefficients is statistically different from 0.
There are software tools that can make this easier and less error-prone, particularly for more complicated comparisons. This page illustrates the linearHypothesis() function of the R car package.
You should be very careful in the case of your model, however. The above will only evaluate the fixed-effect interactions, while you have random slopes involving those variables. It also assumes that x3 is constant. The usefulness of the comparison also depends on having both x1 and x2 on the same scale.
It might be more informative to illustrate predictions from the model under specific scenarios. See the help page for predict.merMod() in the lme4 package. If you are going to include random effects in your predictions, also see the bootMer() help page.
Comment: Thanks! Could you explain why the assumption that x3 is constant is necessary, and what you mean by that?
Comment: @gimi `x3` is also in an interaction with `x4`. You say in part: "let's say that x4 is time of the year. The later in the year, the stronger/weaker the effects of x1 and x2 may be." If you are comparing multiple scenarios (e.g., a range values of `x1` against a range of values of `x2` at a set of `x4` values), then the value of `x3` must be the same in all comparisons for the $\beta_{x_1 :x_4}$ and $\beta_{x_2 :x_4}$ coefficients to capture the role of `x4` totally. If $x_3$ varies, you have to add in the contribution from $\beta_{x_3 :x_4} x_3 x_4$ for valid prediction.
Comment: thanks again! How do you do that in r with car::linearHypothesis? So far I have car::linearHypothesis(model, c("x1:x4 = x2:x4")) but I'm not sure how to account for x3
Comment: @gimi if `x3` is constant then you don't have to account for it and you are done. If you want to compare scenarios with different values of the predictors, see the functions in the last paragraph of the answer.

Comparing beta coefficients from a GLMM


Chrome dev-tools is ignoring breakpoints

Question: Trying to debug with Chrome devtools, but my breakpoints are not working.  If I put in a debugger statement, it triggers a breakpoint, but devtools itself doesn't seem to be able to stop at a breakpoint set with the mouse.  This seems to be a new "feature" of dev tools because it has worked in the past.  Has anyone else successfully fixed chrome in regards to this problem?
I'm building with webpack and the app started as a create-react-app
Answer: Hot code reloading overrides code (sends chunks of new code to override functions you were previously using), so your breakpoints become invalid in that case because they are attached to the 'old' code. I don't think you were doing anything wrong, but most probably it looked like this:

You started create-react-app in the browser.
You inserted a breakpoint manually in the inspector.
You modified the code in your code editor.
create-react-app hot reload sent a new code to the browser, which did override your previous code.
Browser was no longer using the code you set breakpoints in and instead was using your new code.
Debugger statement worked because it was still in the code.
After reloading the page it worked again, because Chrome inspector remembered the position of breakpoints you did set manually and applied them to the new code.
Answer: @boatcoder - I had the same problem, again with code running using create-react-app.
I was able to set breakpoints and they would stop execution when hit, but after a dynamic (hot) code change, they no longer worked - only breakpoints in unmodified functions. I found that if I reload the web page (for my app that means logging in again) then the breakpoints work again.


Vuetify size of v-avatar in v-toolbar based on screen width

Question: I am using a v-avatar to display a clickable user profile picture in my toolbar, not too dissimilar to what Google goes in their toolbars. The main problem is, while I am testing different screen widths, the toolbar size changes. I understand this is part of Material Design, and that based on the type of screen, it may be 48, 56, or 64 pixels.
How to dynamically resize my icons based on the screen size? V-avatar takes a size attribute and when I try to do it by % I am getting really wonky results.
Answer: I came out with this solution to avoid the problem, I found no other easier way to resize the v-avatar or the v-icon in vuetify:
<template>
[...]
  <v-avatar :image="user.avatarURL" :size="avatarSize"/>
</template>

Hope it will help others struggling with the same issue.


Which blues scale and 7th chord voicings match up?

Question: Which blues scale goes with which chord voicing? For example, Dm7 (D,F,A,C) does not go with the D pentatonic minor blues scale. So what scales go with Dm7? And then accordingly, which go with DM7 (D major 7th)? And how does one figure this out?
Edit: I previously had "Dm7 (D,F,A,B)" written as a typo, which I have now corrected to "D,F,A,C".
Comment: Dm7 = D,F,A,C, all of which belong in D min. blues.
Comment: @Tim, but it doesn't sound right
Comment: That chord make up gives Dm6, which won't really fit D min. blues. Unless the B is really a German Bb, which won't sound good at all.
Comment: @Tim, Sorry, that was actually a typo, I intended to type C, not B in that Dm7 chord.
Answer: First of all, Dm7 has no B but a C (as already pointed out in a comment by Tim):
Dm7: D F A C
The D minor pentatonic scale clearly fits over a Dm7 chord, because it contains all chord tones and it adds one note (the G), which is a cool-sounding tension on Dm7 (the 11).
Note that the D minor pentatonic scale is not the only pentatonic scale you can play over a Dm7 chord. You could also try the A minor pentatonic scale (implying a Dm9 sound) or the E minor pentatonic scale (for a dorian sound).
Over a Dmaj7 chord you can obviously play the D major pentatonic scale:
D E F# A B
which has the same notes as the B minor pentatonic scale. Also here you have other choices, such as the A major (F# minor) pentatonic scale (emphasizing the maj7 sound), or the E major (C# minor) pentatonic scale, which gives you a lydian sound (it includes the #11, the G#).
Answer: A couple of additional notes that might help answer your question:
The "blues scale" was developed to to play one set of notes over all the chords in a twelve bar blues, so the blues scale based on A minor pentatonic is played over a twelve bar blues starting on A7, even though the major third does not technically occur in the scale (this is why chords with a sharp 9 sound bluesy). In general, either minor pentatonic or the blues scale can be played over dominant 7 chords to achieve a blues feel, although this may not be appropriate depending on the context.
More generally the pentatonic scale, in it's various inversions, can fit over a large number of chords. A good rule of thumb is that whatever key you're in you can construct melodies using the major pentatonic scales starting on the first, fourth or fifth degrees. Notice that the blues usage of the minor pentatonic actually falls outside of this rule, and thus provides a fourth possibility.
To answer your final question, associating scales with chords is a complex subject that can vary with different styles. Typically, though, it depends on the function of the chord, so if a Dm7 is being used as the ii in a ii-V-i you'd play dorian, which would be the same notes as the C Major scale (so, in pentatonic terms, you could use notes from C, F, or G pentatonic).


Solving matrix equations for x

Question: I have a bit of a problem with some matrix equations:
Task 1: $X,A$ arbitrary matrices, $A$ invertible. Solve for $X$:
$XA+A^T=I \Longleftrightarrow XA = I-A^T \Longleftrightarrow X = IA^{-1}-A^TA^{-1} \Longleftrightarrow X = A^{-1}-A^TA^{-1}$
Task 2: Let $X,A,B$ be arbitrary matrices. Solve for $X$:
$X^TC=[(2A(X+B)]^T \Longleftrightarrow X^TC=(2AX+2AB)^T \Longleftrightarrow  X^TC=2A^TX^T+2A^T+B^T$
Task 3: $x\in \mathbb R^n,y \in \mathbb R^d, A \in \mathbb R^{d \times n}$, and $A^TA$ invertible. Solve for $X$:
$(Ax-y)^TA=0 \Longleftrightarrow ((Ax)^T-(y)^T)A = 0 \Longleftrightarrow (Ax)^TA-(y)^TA=0 \Longleftrightarrow (A^T)(x^T)A-(y)^TA=0 \Longleftrightarrow A^TAx^TA-y^TA = 0 \Longleftrightarrow A^TAx^TA=y^TA \Longleftrightarrow x^TA=(A^TA)^{-1}y^TA$
Task 4: As above and $B\in \mathbb R^{n \times n}$,$A^TA$ invertible. Solve for $X$:
$(Ax-y)^TA+x^TB=0 \Longleftrightarrow ((Ax)^T-(y)^T)A+x^TB = 0 \Longleftrightarrow A^Tx^TA-y^Ta+x^TB = 0$
So I tried solving these below each task and I'm quite sure Task 1 is correct but I always get stuck.
Answer: The error you are making is that $$(AB)^T\ne A^TB^T$$
Instead  $$(AB)^T= B^TA^T$$
This will allow you to immediately solve tasks 2-4.

Solving matrix equations for x


Dupla inserção com mssql_query

Question: Estou tendo um pequeno problema e gostaria de ajuda para resolvê-lo. Tenho um código que faz a inserção num banco de dados SQL SERVER através do php. Está tudo direitinho, exceto que dois "INSERT" no banco estão sendo feitos. Não consigo ver o que está errado, por isso gostaria que alguém pudesse me ajudar
A variável $envio é acionada assim que o formulário é enviado. Não sei mesmo o porquê desse duplo INSERT :(
if($envio){

$pastaupload = 'candidatos/';
$arquivoupload = $pastaupload .  time() . $_FILES['arquivo']['name'];

move_uploaded_file($_FILES['arquivo']['tmp_name'], $arquivoupload );
$caminho = "http://meusite.com.br/".$arquivoupload;

$insert ="INSERT INTO CANDIDATO (NOME, DH_NASCIMENTO, CEP, ENDERECO, NUMERO, BAIRRO, MUNICIPIO, UF, TELEFONE, CELULAR, EMAIL, CD_SEGMENTO_CARGO, OBSERVACAO, PATH_CURRICULO, CD_STATUS, CD_USUARIO) VALUES ('$nome', '$datanascimento', '$cep', '$endereco', '$numero', '$bairro', '$cidade', '$uf', '$telefone', '$celular', '$email', $segmento, '$observacoes', '$caminho', 1, 12 )";

mssql_query($insert);

mssql_close($connection);

}

Comment: Esta pergunta já tem resposta algures, deixa-me procurar o link.
Comment: Click duplo no submit? Pode usar o email como unique key para evitar registros duplicados.
Comment: O único problema foi o usuário não ter escolhido uma resposta, daí não ter conseguido marcar como repetida/relacionadas - http://pt.stackoverflow.com/questions/10744/como-n%C3%A3o-gravar-dados-duplicados-no-mysql-com-php/10745#10745
Answer: Descobri o que estava acontecendo, eu estava usando uma função para subir os arquivos, a move_uploaded_file().
Era ela que estava fazendo com que o registro fosse inserido duas vezes. Apenas coloquei ela dentro de um if e funcionou!
Testei o que vocês me sugestionaram, muito obrigado pela atenção de todos!
Answer: Verifique que o form não está sendo submetido duas vezes. Um bom meio de fazer isso é tirar o mssql_query e simplesmente fazer um echo "Test"; ou algo aparecido.
Se não dá, tenta também usar os Developer Tools, disponível em vários browsers. Normalamente há um meio de ver os submissões feitos.

Dupla inserção com mssql_query


Qual a diferença entre animações com css e javascript?

Question: Ultimamente tenho estudado algumas animações com CSS. Porém, pesquisando mais sobre o assunto,  acabei verificando que é possível fazer animações também com javascript.

Qual a diferença?
Qual é mais viável?

Sei que animações com CSS limitam dependendo do navegador, o mesmo ocorre com JavaScript?
Comment: Como assim "animações com CSS limitam dependendo do navegador"? Poderia explicar melhor esse trecho?
Comment: esses tempos eu perguntei o mesmo aqui http://pt.stackoverflow.com/questions/59798/%C3%89-correto-usar-js-para-fazer-os-efeitos-de-um-html
Comment: Relacionado / possível duplicata: http://pt.stackoverflow.com/questions/51542/css-ou-jquery-para-anima%C3%A7%C3%A3o
Comment: @renan, tente executar alguma animação no IE8 ou IE7.
Comment: @AndreyHartung Não é a mesma pergunta porque o meu questionamento não foi sobre usar javascript para manipular css, porém, colocando um contra o outro para a criação de animações. De qualquer modo, a sua questão também ajudou nos meus estudos! Obrigado!
Comment: @bfavaretto Muito relacionado, porém, como foi postado abaixo, o uso de JQuery diminui em questão de performance, diferente do CSS que é mais rápido. E, no caso, eu estava procurando uma animação com javascript mais puro - E sugeriram o GSAP! Obrigado por compartilhar mais um link também!
Comment: @WesleyRedfield mas, se for pensar por esse lado, também há recursos modernos no Javascript para tratar animações que não funcionam nesses navegadores que citou. Mas enfim...
Comment: @renan Por favor, se você tiver fontes que fortaleçam isso que você está dizendo, por favor, compartilhe conosco! Obrigado!
Comment: @WesleyRedfield [`window.requestAnimationFrame`](http://caniuse.com/#feat=requestanimationframe) é um exemplo.
Answer: O CSS3, ainda não esta pronto para animações de nível profissional em grandes projetos escaláveis. Para coisas simples, - CSS3 é o vencedor, não podemos sequer argumentar sobre isso. Se você procura por animações mais robustas vamos analisar os seguintes pontos:
1. O controle de fluxo
Imagine que você passou noites escrevendo códigos de animações incríveis, de ponta em CSS3 puro. E agora - aqui vem a parte difícil. Você quer controlá-los - pausar, parar, voltar, executados de forma assíncrona, um após outro, colocar em uma linha de tempo e horário. Bem, boa sorte com isso. Literalmente, é quase impossível. Com javascript soluções (como GSAP) é fácil como fazer uma torta! Escrever algumas linhas de código javascript e você está pronto para ir!
2. Animar várias propriedades
Imagine que você deseja escalar uma div e no meio dessa animação, começam a rodar-lo e mudar a cor da borda. Você não pode animar propriedades individuais distintamente. No entanto, soluções baseadas em JS permitem que você anime, literalmente, qualquer propriedade numérica em variedade de formas (é só escrever animate para  50% da largura inicial, animate para 0px, animate para -50px e depois para 150px) .
3. Organização
Código para projetos maiores pode facilmente mudar e você poderá ter que escrever animações complexas, é nessa hora que a organização de código é a chave! Com CSS3 é quase impossível agrupar suas animações em pedaços lógicos para gerenciar facilmente, apenas chamando métodos e callbacks.
4. Compatibilidade
Transições CSS3 não funcionam em navegadores mais antigos. E mais - cada browser lida com eles de forma diferente (e adiciona seus próprios erros para seu aplicativo). Com poucas animações em sua página é provavelmente mais fácil para verificar se tudo corra bem, mas pode tornar-se impossível, uma vez que você vá para um projeto maior. Soluções Javascript fornecem uma camada de abstração. Você não tem que se preocupar com comportamentos específicos de navegadores é aqui que as bibliotecas estão fazendo seu trabalho!
Conclusão
Animações CSS são "ruins"? Certamente que não! Na verdade, eles são ótimos para transições simples entre os estados (como rollovers), quando a compatibilidade com os navegadores mais antigos não é necessária. CSS faz transformações muito bem, e animações CSS pode ser muito atraente para os desenvolvedores que preferem colocar toda a sua animação e apresentação lógica na camada CSS. No entanto, a animação baseada em JavaScript oferece muito mais flexibilidade, melhor fluxo de trabalho para animações complexas e interativamente ricas, e que muitas vezes executa tão rápido (ou mesmo mais rápido) do que animação baseada em CSS.
Resumo:
css3:

Ponto positivo: rápido
Ponto negativo: Animação é primitiva

js:

Ponto positivo: Animação (matemática) podem ter métodos sofisticados,
muito mais interativos para o usuário
Ponto negativo: Alguns navegadores podem bloquear js, pode ser
pesado, tem tempo de carregamento

Nesse site tem uma comparação bacana, com animações, teste de performance e muito mais! Dê uma olhada.
Fonte
Comment: Caraca, eu to atras dessa explicação a muito tempo, se eu pudesse eu te dava um caminhão de upvotes!
Comment: Vale uma olhada [neste link](http://css-tricks.com/myth-busting-css-animations-vs-javascript/), originalmente postado [aqui](http://pt.stackoverflow.com/questions/51542/css-ou-jquery-para-anima%C3%A7%C3%A3o#comment104915_51543). Eu também achava que dava pra dizer que animações por CSS são sempre mais rápidas, mas o artigo prova que não.
Comment: Eu já tinha postado o link na resposta :D
Comment: @PauloCosta Tanto a sua resposta quanto a fonte que disponibilizou me ajudaram muito! É ótimo saber que há estudos e preocupações sobre isso! Só para constatar, você digitou errado ali em cima (é GSAP, e não GASP).

Resumindo sua resposta, o bom senso é o que manda no final. E vou pesquisar mais sobre GSAP.


How to deal with interaction terms in regression that cannot have a negative product?

Question: Assume we have the following model: $y = \beta_0 + \alpha_1 * x_1 ^{\beta_1} + \alpha_2 * x_2^{\beta_2} + \alpha_3 * x_1^{\beta_1} * x_2^{\beta_2}$ where as we have the following priors for our IV's $\beta_1 \sim Beta(1, 1), \beta_2 \sim Beta(1, 1)$ thus $0 <= \beta <= 1$
I wonder how I can deal with the multicollinearity issues of the interaction term, notice that we cannot mean center $x_1, x_2$ in our interaction-term due to the exponent(we cannot have $x < 0$ since $\beta <= 1$ and $\beta$ is not an integer), does anyone have some ideas?
Comment: Welcome to CV, Richard.  Your remark about mean centering is puzzling (because that procedure is equivalent to including the intercept term $\beta_0,$ which is explicitly present) and it's not clear there will be much multicollinearity.  But even if there is, so what?  What problems do you anticipate it might create and what specifically do you mean by "dealing" with it?  Also, consider re-expressing your model as $E[y]=(\beta_0-1)+(1+x_1^{\beta_1})(1+x_2^{\beta_2})$ for further analysis, because it reveals the underlying simplicity.
Comment: Perhaps I am not reading your notation correctly, but your beta coefficients here are power terms? As in for each $x$, it gets raised to the power of the beta weight? Perhaps I am naive but I have never seen linear regressions defined this way, only power terms for $x$ (e.g. $\beta_1 x_1 + \beta_2 x_1^2)$.
Comment: yes they are powerterms aiming to capture diminishing marginal returns hence $0 <= \beta <= 1$
Comment: @whuber edited the question a bit to make it clear that mean-centering refers to the interaction terms, thus mean-centering $x_1, x_2$ solely in the interaction-term, not the main effects $\beta_1*x_1 ,\beta_2*x_2$. I also edited the actual equation since i missed out on the coefficients $\alpha$
Comment: The point about mean centering remains obscure.  Your introduction of the $\alpha_i$ introduces another twist: what priors are you assuming for them?  And, again, why are you concerned about multicollinearity in the first place?
Answer: Multicollinearity gets a lot of undue attention. As the Wikipedia entry states:

Multicollinearity does not affect the accuracy of the model or its predictions. It is a numerical problem, not a statistical one.

There is nevertheless a subsequent inferential problem, seen in your scenario with only two predictor variables. If $x_1$ and $x_2$ are correlated, then you won't be able to distinguish their separate associations with outcome very cleanly. But that will be the same problem whether or not $x_1$ and $x_2$ are mean-centered. See this answer, for example, with respect to regression that is linear in the parameters.
From what you describe, mean centering isn't possible in your situation with its nonlinearity in the parameters, anyway. So leave the predictors alone, and recognize the limitations of working with correlated predictors.


Publicar na playStore

Question: Olá,
Eu tenho um app na play store publicado. É possível publicar uma versão desse app com o mesmo ID porém com uma chave de assinatura diferente ?
Answer: Com o mesmo ID você não vai conseguir, o id mais precisamente o package do projeto, é o identificador único do seu app, pode ter aplicativos com o mesmo nome mas não com o mesmo package. Estou presumindo que você perdeu a key store do app, neste caso você vai ter que mudar o package, consequentemente vai mudar o ID do app. Isto implica também que vai ser um app diferente para a play store

Publicar na playStore


What are qualities/features that you think about when thinking of a musical "note"? (For AI/programming purposes)

Question: TLDR, open-ended: What is a set of qualities that a musical "note" can have that are important when playing or analyzing music? Think performance, practice, rehearsal, production, any setting, but be specific in your answer about where and why the quality is useful.
Hey all. Hope this isn't teetering on being inappropriate for this forum. Please cite a bit of the community ruleset if I missed a guideline.
I'm a lifelong musician who's also involved in the the AI/programming community. I'm finding that all programming languages, tools, libraries, etc. don't give me what I want, so I'm taking on making my own simpler but more comprehensive open source Python library for music analysis, info retrieval, AI, DSP, anything you could want from programmatic music.
Well, now I've got to come up with general musical types to program and define them by important qualities. E.g. defining frequencies, pitches, timbres, forms, harmonies, and more, and attaching important properties to them that programmers and working musicians would find crucial.
I want to take a messy comprehensive list of types and features, tighten it up, and port it into simple Python code that anyone can use for music analysis, AI, notation software/file conversion, etc.
So here's my question.
Let's start with just a music "note." For you musicians, what are important qualities that can define a "note" and how you think about that note, including relative to other parts of a song, other members of a band/orchestra/choir/group, the harmony of the song, how the human ear perceives that note, and more?
Here's a follow-up question. What's the least that a note needs to be a note? Obviously if music notation notes are notes, they don't need timbres. Does it even need a duration? Does it even need a pitch? When does a note stop being a note?
Perhaps another follow-up. Do you feel like any books or literature answer these questions well enough to be comprehensive, and can you point them my way?
An incomplete list I've compiled is:

Pitch of the note (e.g. tempered tuning pitch, like A4)
Frequency of the note (especially helpful when doing anything not 12-tone tempered, or N-tone tempered)
Pitch bends/frequency bends
Timbre of the note (as well as how the timbre can change, e.g. wavetables)
Related to timbre, the instrument which plays the note
Duration of the note (in beats, seconds, etc.)
When the note starts (and stops) relative to a starting time (arbitrary time 0, start of a song, start of a measure, etc.)
What the strength/emphasis of the start beat is, or conversely the amount of syncopation, e.g. 1 is obviously a strong beat in a repetitive time signature, while the "ah" of 1 is probably less strong in some contexts and more syncopated.
Dynamics/loudness (and change in dynamics) of that note
Articulation of the note
Misc. expressions (?) that can be notated on that note
Whether the note is tied to other notes, e.g. in a tuple or in a chord
What contains the note, e.g. what measure, section, part, piece of music
Any lyrics on that note
Anything notation-specific (e.g. where on a staff the note is written, note head shape, etc.)

Assuming this question is appropriate and yields interesting conversation, I might be back to ask more about other musical objects, like chords
Comment: The question is just broad enough that answering it would take a book. Some of these books have already been written, have you read them?
Comment: A lot of the answer depends on which particular instrument  - different ones will use different parameters.
Comment: Are you concentrating on written notes, heard notes, or both? You've already explained that some things aren't required for written notes, such as timbre, but some of the things you've mentioned aren't necessary for heard notes (assuming all we see is Synthesia-style bars for MIDI notes), such as whether notes are tied or even articulations(!).
Comment: I see this is as a programming interface design question. You're defining an interface of some module X, and you want the interface to have a concept of "note". But you haven't yet decided on exactly what it is that X _does_. What is its functionality? When you know what the thing does, then you can decide what would be a meaningful definition of "note" in that interface.
Comment: There are two different questions here: what is a note, and what are the characteristics of a note. Please see the help section for suggestions on asking a good question. In particular, questions "yielding conversation" don't fit well in the SE Q/A format.
Comment: @ojs That's why I asked if you knew of any literature you could refer me to! I see the question has been closed due to lack of focus, but that's the problem--the subject of the question is up to interpretation and needs focusing through discussion. Please let me know if you have references. @ user1079505 I did read the help section, and while questions like these aren't explicitly eschewed, I understand why we wouldn't want to have them in the forum. I don't know where it is reasonable to ask questions like these in musical communities anywhere, but at least I got some answers before closing.
Comment: It's a system design problem. You're designing a system, so define what exactly and concretely it should do. What are its inputs and outputs? Do you want to convert files between existing notation application formats, or just import them, or not even import? What exactly does the system produce as output? Should the system be able to perform written pieces? For what exact purpose is it used for? Can you write use-cases for the system? If not, then you don't really know what you're trying to make.
Comment: Broadly speaking, the questions you're asking have already been solved by technology! MIDI is the most common computer format for serializing sheet music and live-performance musical information. Every note is associated with a whole bag of data about the characteristics of its performance and articulation. MIDI also has provisions for multiple streams of data corresponding to elements like dynamics and tone color that can change over the course of a note's duration. It's an extremely mature, well-defined, and powerful format!
Comment: In fact, I'm voting to reopen because I believe "use MIDI" is the unambiguously correct answer for all of the questions OP brought up. An answer to that effect would be perfectly reasonable and deserves to be written.
Comment: Appreciate the vote of confidence, Kevin! However, MIDI is not the answer I'm looking for. MIDI is great for describing music within a strict and symbolic manner, but fails to describe it in a way human musicians would look at music, and fails to consider a lot of musical structures musicians rely on. Otherwise, MIDI would take off with musicologists as well as producers. Being explicit, I'm thinking MIT's Python library Music21, but easier yet more expressive and powerful to use. However, if you think MIDI is a valuable answer, I invite you to answer if the question reopens!
Comment: Finally, I think I'll just keep these (very helpful) comments in mind but move on. What I wanted was a discussion about the building blocks of a note that we could represented. Yes, this is a long-term project, and I want to go for a lot in this system--arbitrary file type conversion, musicological analysis, composition, AI facilitation, etc. While I know what I want, it doesn't seem like this is the setting to have that abstract conversation on what constitutes a "note" so I can distill that into my system. Probably best I build first and only then ask for concrete feedback. Thank you, all!
Answer: Musical notation is, first and foremost, instructions for human performers. One element of that notation is "notes". To know if, when and how to use a note, you need to know how human players will react to those instructions.
The written language of instructions is also used for describing abstract ideas in a music theory context or otherwise without meaning the music to be actually performed like in a concert, but even then, there is an implied idea of a person reading the notation and acting on it. For example, one might try to transcribe sounds of nature like birds singing as musical notation, but the writer must have at least a vague idea of a player with an instrument.
Whether a writer of music wants to use notes or some other forms of instructions, and which qualities the writer considers as important, depends on what the writer wants to achieve. "Make chaotic sounds with your instrument" could be a performance instruction that doesn't use notes, but which would probably end up producing sounds that could be described in terms of notes. Another one could be "slow filter sweep from 50 Hz to 1000 Hz". An instruction "very fast filter sweep from 1000 Hz to 50 Hz" might produce a sound that another person might transcribe as a note.
Answer: You need to be more clear on what "note" means: A black spot in a staff on a sheet of paper or a single musical event from a rather abstract viewpoint? The connection in between is the main subject literate musicians' life on stage is much about.
You're heading tough time teaching that to machines, or having machines learning it themselves. On that topic of AI and machine learning I, for one, am quite sensible: Once machines have the knowledge, would they manage to teach it to little humans and/or machines? (As a philosophical marginal note: I'm afraid some well-known AI apologetes are eager to suck it out of mankind like vampire-gods, all that knowledge about the bad as well as about the beautiful things humans could think and say and do once, leaving them stupid as plastic dolls, Eloi, and put it all into a black-hole waste bin they dream of, called Singularity.)
You are probably better off sticking to a common set of features to read from musical notes: pitch, duration, and stress. Three features should be enough to get your brain running for a start, admitted that depends on what you already have got and achieved.
Keep in mind that few features are actually encoded in notes. Much is to be interpreted measure-wise (e.g. accidentals applied to every note on the same line till natural sign or end of measure), period-wise (keys) or piece-wise (musical practice of the time a piece was written). And when it comes to phrasing, very much is implied as well. Not to forget the queen of implication in all music: the pause. Hence, one having such a list of features of a note or musical events should count the time-offset among them as well. Or is that exactly what you meant with "where in the staff"? Again I am inclined to read it meant in a graphical sense, given the shape of the notehead you also refer to.
Musical notes are like letters of a word. They need to be read together phrase after phrase.
Developping an ASCII-based notation system myself, with associated a likewise text-specified sound-level translation engine to write actual PCM data into a file, I learned that the dots in a sheet you call notes is not more than about 10% of what defines ("organic" versus synthetic) music. The most defining part is made up from the instrument played and the imagination of sound and groove the human playing expresses, performs.
In the process of "making" I wrote my program so that the levels of properties intellectually interpreted from the sheet are kept separate in memory as long as possible on the various structural levels:

common properties of every measure;
measure-specific ones;
specifics to voices in the measure;
chord / motif / whatever a bunch of notes at same offset after the beat-one bar;
finally, the note for length and pitch and specific articulation, much depending on what the sound specification of the associated voice offers in terms of variations accessed by parameters.

Stress, for example, is mostly not described as specific to a note, but implied by its offset and the stress pattern defined on the measure level, only manipulated now and then to shape its presence relative to other notes in the harmonic chord stack (i.e. its weight), or special accent at that offset.
Offset and duration, as another example, are both not reigned by a strictly linearly proportional relationship between beats per minute and the nominal note value, because tempo changes in a small percentage range add their spice to musical expression of a performance, and if swing-patterns are involved, the duration of an eighth or sixteenth might differ slightly from the last and the next.
Having covered subtleties of stress and duration, let us complete these regarding pitch: The tuning of notes in a harmonic chord stack could possibly change along the position in the measure, according the current harmony. Depends on the instrument, say, strings vs. brass. Strings, since fretless instruments, are tempered naturally. So, a nominal pitch, mapped 1:1 to a frequency, could be calculated to Hz as soon as possible. For string and other continuous-pitch voices, if you proceed bottom-up, you can resolve pitches not before you know the harmonic context.
That's why you should start focussing on the prevalent three note features listed above. At least if your music is intended not to scream "Look mum, all is computer-generated" to your audience.
Not before it comes to synthesizing and saving the sound of a distinct tone (meaning the actual musical-acoustical event), these properties from the different levels are calculated from abstract-relative units to the single note being processed, to absolute units, and merged into one set.
The trade-off of repeatedly applying same tones regarding the limited time and memory consumption of rendering music the raytracing-like way I do, is enough I think to have musicians reliably guess it is computer-generated music nevertheless, and rightly so. Quantum computing will turn off-line synthesis to a finger's snip opportunity to practice patience meditation, just early enough.


Smooth invariance of domain

Question: This is Theorem 22.3 in Tu's textbook. There are a multiple of similar questions, but all answers seemed unsatisfactory for me. (One of them used algebraic topology result, but I am unfamiliar with the subject.)
Theorem: Let $U$ be an open subset, $S \subset \mathbb R^n$ an arbitrary, and $f: U \rightarrow S$ a diffeomorphism. Then $S$ is open in $\mathbb R^n$.
Proof: Let $f(p)$ be an arbitrary point in $S$ with $p \in U$. Since $f$ is a diffeomorphism, there is an open set $V \subset \mathbb R^n$ containing $S$ and a smooth map $g: V \rightarrow \mathbb R^n$ such that $g|_S = f^{-1}$.
I am not sure why the bolded statement is true. I agree that $f(U) \subset S$ is open in $S$, but why does it guarantee the existence of such $g$? If $S$ were a closed set, I may extend $f^{-1}: S \rightarrow U$ to $\tilde g: V \supset S \rightarrow U$ with $\tilde{g}|_S = f^{-1}$ using partition of unity, but there is no assumption about $S$.
Comment: What's the definition of diffeomorphism in the book?
Comment: @FormulaWriter A function $f: M \rightarrow N$ is smooth if $\forall p \in M$ there exists a local chart $(U, \phi)$ about $p$ and a local chart $(V, \psi)$ about $f(p)$ with $f(U) \subset V$. $f$ is smooth if $\psi \circ f \circ \phi^{-1}$ is smooth. $f: M \rightarrow N$ is a local diffeomorphism if two charts above are invertible (by shrinking $U$ and $V$ if necessary). Diffeomorphism just means that $f$ is a global diffeomorphism.
Comment: Edit: in local diffeomorphism, in addition to the fact that $f: M \rightarrow N$ is intertible, smoothness of the inverse is imposed.
Comment: $f(U) \subset S$ is open in $S$, so there is some $V \subset \mathbb R^n$ such that $V \cap S = f(U)$. Also, $f^{-1}: f(U) \rightarrow U$ is a smooth map. However, I am still not sure why $f^{-1}$ can be extended to this smooth $g: V \rightarrow U$ with $g|_S = f^{-1}$.
Answer: This is a comment but its to long for a comment.
You have to ask yourself what does it mean for a function to be smooth for arbitrary sets of $\mathbb{R}^n$? one possible definition given in the appendix of Lee introduction to smooth manifolds goes as follows
We sometimes need to consider smoothness of functions whose domains are subsets of
$\mathbb{R}^{n}$ that are not open. If $A \subseteq \mathbb{R}^{n}$ is an arbitrary subset, a function $F: A \rightarrow \mathbb{R}^{m}$ is said to be smooth on $A$ if it admits a smooth extension to an open neighborhood of each point, or more precisely, if for every $x \in A,$ there exist an open subset $U_{x} \subseteq \mathbb{R}^{n}$ containing $x$ and a smooth function $\widetilde{F}: U_{x} \rightarrow \mathbb{R}^{m}$ that agrees with $F$ on $U_{x} \cap A .$ The notion of diffeomorphism extends to arbitrary subsets in the obvious way: given arbitrary subsets $A, B \subseteq \mathbb{R}^{n},$ a diffeomorphism from $A$ to $B$ is a smooth bijective map $f: A \rightarrow B$ with smooth inverse.
You can use partition of unity to construct $g$

Smooth invariance of domain


How to interpret hierarchical regression output that has insignificant IV in step 2, but still shows significant F

Question: I'm working through a 4-step hierarchical regression where the first step is to add grouping variables (student standing, gender, & previous experience) and the 2nd step as adding a psychological dimension (likert scale relating to psych variables).
On the 2nd step of the regression, the total output/f test is suggesting that model is significant, but the actual addition to the step (i.e., the psych variable) is not (see below for the output). If folks are able, I would love some assistance in understanding this, I'm stumped!
<code>> summary(reg1)

Call:
lm(formula = IASMHS80 ~ Gender + Class + PreviousCounseling,
    data = mydatareg)

Residuals:
     Min       1Q   Median       3Q      Max
-1.22725 -0.32881 -0.06004  0.31482  1.39994

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)
(Intercept)         2.631108   0.175667  14.978  < 2e-16 ***

Gender             -0.017129   0.061949  -0.277 0.782444
Class              -0.001098   0.018251  -0.060 0.952099
PreviousCounseling -0.255314   0.071774  -3.557 0.000468 ***

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.441 on 200 degrees of freedom
Multiple R-squared:  0.06208,   Adjusted R-squared:  0.04801
F-statistic: 4.413 on 3 and 200 DF,  p-value: 0.004971

> summary(reg2)

Call:
lm(formula = IASMHS80 ~ Gender + Class + PreviousCounseling +
    IM480, data = mydatareg)

Residuals:
    Min      1Q  Median      3Q     Max
-1.2229 -0.3121 -0.0627  0.2961  1.4703

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)
(Intercept)         2.819675   0.231152  12.198  < 2e-16 ***

Gender             -0.024626   0.062149  -0.396 0.692358
Class              -0.001788   0.018234  -0.098 0.921988
PreviousCounseling -0.254564   0.071675  -3.552 0.000478 ***

IM480              -0.037251   0.029738  -1.253 0.211797

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.4404 on 199 degrees of freedom
Multiple R-squared:  0.06942,   Adjusted R-squared:  0.05072
F-statistic: 3.711 on 4 and 199 DF,  p-value: 0.006151
</code>
Answer: Your R2 is also really low.  Assuming this is survey data, this means that the respondents' IASMHS80 is not explained well considering their reported gender, class, and previous counseling. You have significance at 99% confidence interval, given that your p <  .01. That means that if someone were to survey a sample that represents the same population your study represents, and analyze the results the same way, there is a 99% likelihood that they will find the same results that you have.
As far as what that might look like, the residuals are evenly dispersed around the line of fit, but for the most part, they aren't on the line of fit. Given the coefficients of that regression, you can see that previous counseling is the most evenly dispersed. Whereas the respondents' reported genders and classes are less evenly dispersed.
That being said, I am curious as to how well this data meets the assumptions of multiple linear regression. The residuals' descriptive statistics suggest that there is a likelihood of normal distribution (along with the sample size). How's the variance (homogeneity or homoskedasticity)? How's the independence? Multicollinearity? Outliers?
In the subsequent regression, when you added whatever IM480 represents, The results are extremely similar. You can see that these variables do not explain very much of whatever IASMHS80 is. However, it does suggest that the data consistently doesn't explain this outcome.
Your coefficient of determination (R2) changed from 0.04801 to 0.05072 for a change of about 0.02%. That means that IM480 explains the outcome an additional 0.02%.


Salvar arrays duplicados em um Insert

Question: Tenhos arrays duplicados
produto[] valor[] qtd[] total[]
produto[] valor[] qtd[] total[]

Preciso salvar esses arrays em um insert, assim:
INSERT 'tabela' (produto, valor, qtd, total) VALUES (produto[],valor[],qtd[],total[]) ;

INSERT 'tabela' (produto, valor, qtd, total) VALUES (produto[],valor[],qtd[],total[]) ;

//OBS: sei que isso nos VALUES não funciona mas é isso que preciso...
JÁ FIZ ASSIM:
    foreach ( $produto as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $valor as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $qtd as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $total as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $modalidade as $key => $v) {
    $array[$key][] = $v;
}

    foreach( $array as $value){

echo "INSERT INTO `table` ( `produto`, `valor`,`qtd`,`total`,`modalidade`) VALUES (".$value[0].",".$value[1].",".$value[2].",".$value[3].",".$value[4].")

}

OBS:
Está funcionando, o fato é que nem sempre no value[0] é o produto, e o value[1] é o valor e assim por diante....
Answer: Voce pode fazer algo desse tipo:
$i=0;
$sql= "INSERT 'tabela' (produto, valor, qtd, total) VALUES ";
while(!empty(produto[$i]){
 $sql=$sql."($produto[$i],$valor[$i],$qtd[$i],$total[$i]),";
$i++;
 }
 $sqlFinal = substr($sql, 0, strlen($sql)-1);

Ou uma outra forma seria essa:
$i=0;
$sql= "INSERT 'tabela' (produto, valor, qtd, total) VALUES ";
foreach($produto as $p){
$sql=$sql."($p,$valor[$i],$qtd[$i],$total[$i]),";
$i++;
}
 $sqlFinal = substr($sql, 0, strlen($sql)-1);

Aí você vai ter o sql montado na variavel $sql
Comment: Olá amigo, estou trabalhando com mais dados não apenas os que estão no código de exemplo da pergunta, então verificando se o produto está preenchido não adiantaria pois estou recebendo mais dados pelo $_post
Comment: Acho que não compreendi o que quis dizer...
Comment: Editei ali, ve se é isso...
Comment: editei a pergunta, mostrando como estou fazendo.. pois não consegui do jeito que me falou...
Comment: Não entendi o que você fez ali... Voce tentou da maneira que coloquei ali? porque se a chave dos seus arrays forem numeros, a cada foreach vai sobrepor o valor do foreach anterios, pode dar um `var_dump($array);`para voce conferir o valor qe esta dentro do array
Comment: Fiz um teste com a sua segunda opção e o resultado ficou assim: >" INSERT 'tabela' (produto, valor, qtd, total) VALUES ,(camiseta,99.00,1,99.00),(calca,199.00,1,199.00) " Só que não funciona com a virgula depois do VALUES....
Comment: Editei ali, mudei a virgula,então no final vai sempre ter uma virgula. Depois é só remover com a linha que adicionei, a ultima virgula. Acho que é isso
Comment: Perfeito amigo! Muito obrigado...

Salvar arrays duplicados em um Insert


How to improve upon a vocal recording in GarageBand? (Sample vocal attached)

Question: As an amateur music enthusiast, I like recording vocals for songs I like to sing in GarageBand. I have a Blue Yeti condenser mic for this purpose. However, being the amateur that I am, I have to set up audio tracks, record vocals, and then do basic audio engineering over the sound sometimes to improve upon the quality of recorded vocal so it has more of a studio sound. I don't want to add too much reverb / echo to make my voice sound good though and would like to keep it natural.
My question is: to me this recording sounds acceptable for a small home studio recording in GarageBand, but what would the more experienced / professional musicians / audio experts say about the vocal quality here? Did I overdo / under-do any effects? Any glaring errors / improvements you can observe right off the bat? (I'm using the 'Dance vocal' amp in GarageBand)
Another question: is there a standard GarageBand Amp that you use when recording vocals (I know it depends on the sound but still)? If yes, what settings do you use on that vocal amp in GarageBand? Do you leave it default or make modifications?
My voice recording can be played here:

EDIT:
After suggestions given in answers below, I removed almost all vocal effect and this is close to what my mic naturally records. Just wondering if this sounds acceptable:

Ultimately, I'm trying to reach a standard for myself in all of my recordings. I don't want to over-do the vocal effects.
Answer: I don't know the amps in Garage Band, so can't comment directly on that aspect.
This might all just be "my opinion" as so often these things are, however...
Generally the vocal is all a bit 'pointy' compared to the guitar.
Guitar is reasonably soft - buried most of the time behind the vocal & might be able to come up a bit in the mix.
The vocal is all a bit cold in comparison, too sibilant & not enough warmth at the bottom end. I'd be tempted to pull back the high mids & see how it sounds, before trying to actually push lows into it.
It's also far too wet for me, drop the reverb to half.
Comment: Thank you. I felt that I overdid the vocal effect as well, hence the question. I have added another sample recording below the original trying to follow the suggestions. Please let me know if it sounds better.
Answer: Don't assume any 'enhancement' other than (maybe) a touch of reverb is necessary.  The vocal sounds a bit 'hyped' and the guitar could be louder.
Yes, when you want more of one frequency range, cut the rest instead!
Comment: Thank you for your suggestion. I removed all vocal effects and made a sample 2. Please let me know if this is closer to acceptable.
Comment: Somewhere inbetween the two, I think.


Extract real and imaginary parts of $\operatorname{Li}_2\left(i\left(2\pm\sqrt3\right)\right)$

Question: We know that polylogarithms of complex argument sometimes have simple real and imaginary parts, e.g.
$$\operatorname{Re}\big[\operatorname{Li}_2\left(i\right)\big]=-\frac{\pi^2}{48},\hspace{1em}\operatorname{Im}\big[\operatorname{Li}_2\left(i\right)\big]={\bf G},$$
where ${\bf G}$ is the Catalan constant.
Are there closed forms (free of polylogs and imaginary numbers) for any of the following expressions?
$$\operatorname{Re}\big[\operatorname{Li}_2\left(i\left(2\pm\sqrt3\right)\right)\big],\hspace{1em}\operatorname{Im}\big[\operatorname{Li}_2\left(i\left(2\pm\sqrt3\right)\right)\big]$$
Answer: The dilogarithms $\operatorname{Li}_2(z)$ and $\operatorname{Li}_2(1/z)$ are equal modulo elementary functions:
$$\operatorname{Li}_2(z)+\operatorname{Li}_2(1/z)=-\frac{\pi^2}{6}-\frac{\ln^2(-z)}{2}.$$
Denoting $z_{\pm}=i(2\pm\sqrt3)$, we get in particular
\begin{align}\operatorname{Li}_2\left(z_+\right)+\operatorname{Li}_2\left(-z_-\right)
&=-\frac{\pi^2}{6}-\frac12\ln^2\left(z_-\right)=-\frac{\pi^2}{6}-\frac12\left(\ln |z_-|+\frac{i\pi}{2}\right)^2=\\
&=-\frac{\pi^2}{24}-\frac12\ln^2\left(2-\sqrt3\right)-\frac{i\pi}{2}\ln\left(2-\sqrt3\right).\tag{1}
\end{align}
Taking the real and imaginary part of (1), one finds
\begin{align}
\Re\left(\operatorname{Li}_2\left(z_+\right)+\operatorname{Li}_2\left(z_-\right)\right)&=-\frac{\pi^2}{24}-\frac12\ln^2\left(2-\sqrt3\right).
\tag{$\spadesuit$}\\
\Im\left(\operatorname{Li}_2\left(z_+\right)-\operatorname{Li}_2\left(z_-\right)\right)&=-\frac{\pi}{2}\ln\left(2-\sqrt3\right).\tag{$\clubsuit$}
\end{align}
This already gives $66.67\%$ of Cleo's claim. Note that one could obtain similar relations for any purely imaginary $z_{\pm}$ satisfying $z_+z_-=-1$.

The remaining $33.33\%$ can be proved using another dilogarithm identity:
$$\operatorname{Li}_2(z)-\operatorname{Li}_2(-z)+\operatorname{Li}_2\left(\frac{1-z}{1+z}\right)-\operatorname{Li}_2\left(-\frac{1-z}{1+z}\right)=\ln\frac{1+z}{1-z}\ln z+\frac{\pi^2}{4}.\tag{2}$$
The point is that if we set $z=z_-$ and take the imaginary part of (2), the first two dilogarithms give the contribution $2\Im\operatorname{Li}_2\left(z_-\right)$ whereas the arguments of the other two dilogarithms lie on the unit circle and are characterized by rational angles:
$$2\Im\operatorname{Li}_2\left(z_-\right)+\color{blue}{\Im\left(\operatorname{Li}_2\left(e^{-i\pi/6}\right)-\operatorname{Li}_2\left(e^{5i\pi/6}\right)\right)}=\frac{\pi}{6}\ln\left(2-\sqrt3\right).\tag{3}$$
The piece outlined in blue can be found (this is precisely the place where the specific values of $z_{\pm}$ become important) using the triplication formula
$$\frac13\operatorname{Li}_2\left(z^3\right)=\operatorname{Li}_2\left(z\right)+\operatorname{Li}_2\left(ze^{2\pi i/3}\right)+\operatorname{Li}_2\left(ze^{4\pi i/3}\right).$$
Namely, setting $z=e^{-i\pi/6}$, we get
$$\frac13\operatorname{Li}_2\left(-i\right)=\operatorname{Li}_2\left(e^{-i\pi/6}\right)+\operatorname{Li}_2\left(i\right)+\operatorname{Li}_2\left(e^{-5i\pi /6}\right),$$
which in turn implies
$$\Im\left(\operatorname{Li}_2\left(e^{-i\pi/6}\right)-\operatorname{Li}_2\left(e^{5i\pi/6}\right)\right)=-\frac43 \Im\operatorname{Li}_2\left(i\right)=-\frac{4}3\mathbf{G}.$$
Combining this with (3), we get
$$\Im\operatorname{Li}_2\left(z_-\right)=\frac23\mathbf{G}+\frac{\pi}{12}\ln\left(2-\sqrt3\right)\tag{$\heartsuit$},$$
which finishes the proof. $\blacksquare$
Comment: Do you know if this procedure can be generalized to extract the imaginary part of a dilog with purely imaginary argument?
Answer: $$\Im\operatorname{Li}_2\left(i\left(2\pm\sqrt3\right)\right)=\frac{2\,{\bf G}}3-\frac{\pi\,(2\pm3)}{12}\ln\left(2-\sqrt3\right).$$
For the real part so far I could only establish the following identity:
$$\Re\big[\operatorname{Li}_2\left(i\left(2+\sqrt3\right)\right)+\operatorname{Li}_2\left(i\left(2-\sqrt3\right)\right)\big]=-\frac{\pi^2}{24}-\frac{\ln^2\left(2-\sqrt3\right)}2.$$


creating a random multidimension array using rand() with nddata = fix(8*randn(10,5,3))

Question: I am currently trying to learn MATLAB independently and had a question about a command that used randn().
nddata =  fix(8*randn(10,5,3))

I understand what the fix() function does, and the multi dimension array that is created by randn. However, I am not sure what 8 is doing here, it is not multiplying the outcome of the random numbers and it is not part of the limit. So I just want to know the purpose of the 8 here.
Thanks
Comment: _I am not sure what 8 is doing here, it is not multiplying the outcome of the random numbers_ Yes, it is. That's what it's doing
Comment: Generally on SO; it helps to state what you've tried to help yourself.

Specifically, for example here, I've tried splitting the expression into two.
putting the output of `randn` in `temp`
then comparing `temp`to fix(8*temp)

{a cynic, or an epistemologist may ask how you know that it is not, multiplying the outcome}
Answer: randn generated a standard normally distributed matrix of random numbers (standard in this context is defined as mean = 0 and standard deviation = 1). The 8 factor simply stretches this distribution along the x-axis; a scalar multiplication for each value in the 3D matrix. The fix function then rounds each value to the nearest integer towards 0, i.e. -3.9 becomes -3.0. This will discretise the data and reduces the standard deviation.
To see this for yourself, split the expression up and create temporary variables for each operation, and step through it with the debugger.


backbone.js fetch throwing 500 error on .asmx service

Question: The issue I am having appears to be with the way Backbone.js creates the query string.
Backbone creates the query string like so:
Stats.asmx/GetTarget?domainId=-1&timePeriod=M

This causes the the asmx service to throw a 500 error.
If I change the query string to:
Stats.asmx/GetTarget?domainId="-1"&timePeriod="M"

It works as expected. This is the code I am using which produces the 500 error due to not having quotes around the query string params:
var params = {
            domainId: "-1",
            timePeriod: "M"
    };
    var targetData = new Targets();
    targetData.fetch({
        data: params,
        dataType: "json",
        contentType: "application/json; charset=utf-8"
});

I know I can write a custom function to format the query string the way I want but is there a way to add the "" in the query string with Backbone.js?
EDIT:
This is what I mean by write a custom function.
In the collection add:
domainId: "",
timePeriod: "",
urlRoot: "Stats.asmx/GetTarget",
url: function() {
    return this.urlRoot + "?" + "domainId=\"" + this.domainId + "\"" + "&"
        + "timePeriod=\"" + this.timePeriod + "\"";
},

Then:
var targetData = new Targets();
targetData.domainId = "-1";
targetData.timePeriod = "M";
targetData.fetch({
    dataType: "json",
    contentType: "application/json; charset=utf-8"

But I am sure there is a better way to do it.
Answer: You should not need to modify url because I think your parameter will change. Please try to use $.param:
targetData.fetch({
    data: $.param(params), // <-- here is the change
    dataType: "json",
    contentType: "application/json; charset=utf-8"
});

This is what $.param does:
> $.param({page:1,filter:2})
"page=1&filter=2"


Does it make sense to swich note and mode depending on the chord being played?

Question: So, C Aeolian and A# Mixolydian have the same notes right? That means that the difference is just which notes I emphasize, correct? Like, focusing on A# notes instead of C just makes the sound more 'Mixolydian' but still correct in C, right?
So my question is: let's say I'm soloing over C Ionian. The chord progression is I-V-vi-IV (C-G-Am-F). Does it make sense to play over the chords like this:

C: C Ionian
G: G Mixolydian
Am: A Aeolian
F: F Lydian

Like, I could just play C Ionian over the entire chord progression, but it would probably sound better to emphasize the chords being played by switching modes and emphasizing the current chord being played by targeting that new root note.
Now, if the above is true, then I'm also trying to understand if it makes sense to play G Ionian (over the G chord) and F Ionian (over the F chord). If so, why would I do this? When is this used?
Does this make sense? Am I missing something?
Similar questions:

Playing scales over I IV V progression
How do you modulate between modes?
Answer: Preliminary

C aeolian and A# mixolydian do not have the same notes. However, C aeolian and Bb mixolydian do. Even though A# and Bb mixolydian are enharmonically equivalent, the spelling is important.

It's reasonable to say that the main difference between C aeolian and Bb mixolydian is the "home" note — the emphasized note. There are other differences, but for the purposes of this question, the difference in tonic note is sufficient.

Modes over I-V-vi-IV
Given only the main key (C ionian in this case) and the chord changes, yes, it's perfectly reasonably to play

Ionian with I
Mixolydian with V
Aeolian with vi
Lydian with IV

Further, one could indeed play C ionian over the entire progression, but, for example, emphasizing C against a G chord can give an unpleasant sound.
Matching mode to chord quality
This is a common approach to teaching jazz improvisation: pairing chord types with modes. Thus

Major chord = ionian
Minor chord = aeolian
Dominant seventh chord = mixolydian
Minor seventh chord = dorian
and so on.

Where this has the potential to cause problems is when the larger harmonic context doesn't work for the scale chosen.
As an example, a piece of music in C ionian, and one reaches the IV chord (F major). The chord-scale approach would suggest F ionian. However, F ionian includes Bb, which could create problems depending on the accompaniment. An accompaniment that remains grounded in C ionian might through in B, which would clash with the Bb. In addition, hearing the Bb would suggest a key change (to F ionian), which may not be what the soloist intends.
General "rule"
When choosing a scale/mode to play with a particular chord, the main importance is the chord tones themselves. One can overlay any scale/mode that includes those pitches, and it can "work" as long as that scale fits the larger context — or as long as any accompanying instruments pick up on the scale being used.
Comment: @JacquesThibodeau Yes, exactly. For example, if the music is changing key from C ionian to F ionian, then using F Ionian might work better, because it helps the modulation.
Comment: re: Matching mode to chord quality. Wouldn't playing the IV chord in C Ionian mean that I should probably play F Lydian instead of F Ionian? So you're saying that both work, but F Ionian may cause issues if we end up in a B vs Bb clash? So I *could* use F Ionian, but just need to be careful?
Answer: There's little difference between C Aeolian and B♭ (not A♯) Mixolydian. They use the exact same set of notes, from the parent E♭ key. I guess you call it A♯ as a guitar player?
So saying 'should I use x or y or z' is a minor issue. Using the same notes over all the chords will inevitably work. It's targeting the better notes for each chord that's more of a question. And that involves more to the point in where those better notes are played. It would make some sense to play the root of the appropriate mode on beat 1 where that mode is prevalent, if that's what you're trying to do.
So, for me, thinking in seven different modes for the same solo in one key is somewhat unproductive, from that angle. Particularly as it's quite feasible to play any of the twelve notes available at any point in a solo. Sometimes we want one of those notes to sound 'off', then to sweeten the phrase with a 'good' note.
The concept of using Ionian for every major chord - e.g. bar of F - use F Ionian, bar of G - use G Ionian, isn't a particularly good one, as that heralds some sort of modulation, which in reality isn't going to occur. Having said that, sometimes it's nice to play games with the listener, and do just that, and give them a surprise!
And if one were to follow that through, which minor mode would one use for a bar with a minor chord? For that matter, which major mode should one use for the major bars? Often, soloing, one may use Mixolydian rather than Ionian anyway.
Summing up - as I've said to most students - all 12 notes are up for grabs, just about anywhere. There's a sort of ground rule that diatonic works (as a start point) but not actually in Blues, for instance, but using one's ear rather than a set of 'rules' is a much better bet, and generally speaking, will produce better solos.


How do android "app lock" applications work?

Question: I've tried googling, and looking on stackoverflow as well, but I can't seem to find any satisfying answer as to how the "App lock" applications(eg: ZDBox, App Lock, etc..) work.
Is there a service that runs in the background continuously polling to see if the app is launched and tries to kill it? Or is there a way to intercept launch intents for new activities?
Answer: there is a service running in the background to read the activity stack. if find new activity, will start the passwordActivity
Comment: Where can I find more details on this? I wonder how much battery it would eat up if service constantly keeps running in background.
Comment: @user930177, according to you, the service is running continuously in the background but can you tell me one thing; there are chances when android kills the serivces itself; in that case what is happenning..???
Comment: Thanks for your answer. But I got another problem. After user enters correct password, locked app is open. But the service is running, so password activity starts again.
Answer: they are watching logcat output. whenever you start an activity, you can find specific logcat. like this,
<code>I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}
</code>
if this logcat printed by locked app, locker service starts password screen.
Comment: is it possible method..... ??? can u explain this idea... how we can read the log cat of other application???
Comment: Logs does not a secret, in Android Studio you can catch all logs
Comment: Might this be vulnerable to other apps that use the same tag logging the same data?
Answer: MORE MODERN ANSWER (Nov 2022):
This can be handled by the new app usage API

The system collects the usage data on a per-app basis, aggregating the data over daily, weekly, monthly, and yearly intervals. The maximum duration that the system keeps this data is as follows:
Daily data: 7 days
Weekly data: 4 weeks
Monthly data: 6 months
Yearly data: 2 years
For each app, the system records the following data:
The last time the app was used
The total length of time the app was in the foreground for that time interval (by > day, week, month, or year)
Timestamp capturing when a component (identified by a package and activity name) ?> moved to the foreground or background during a day
Timestamp capturing when a device configuration changed (such as when the device orientation changed because of rotation)

A background service can be used to constantly watch for updates to timestamps for specific apps regarding when they moved to the foreground with the API above.
note: It seems that starting from Android 5/6/7 and higher you cannot read info about other apps, including their status and logs. I believe this makes looking in logcat no longer work. If anyone can confirm this please comment below! Also, the getRunningTasks function to view active activities is now deprecated.


Is a questionnaire with a systematically missing item still usable for analysis?

Question: Due to a glitch a single item of a validated questionnaire was not submitted to the participants. Instead of having 20 questions, only 19 were submitted. The literature about the questionnaire tells that the score range should be between 0 an 80, with a cut-point score between 31 and 33. Now, however, the range is between 0 and 76, with a supposed proportional cut-point score between 29 and 32 (rounded).
The questions:

Is the data still usable?
If yes, how can/should it be handled?

We didn't find any answer in the literature (perhaps because we were not using the proper keywords).
Thanks for the help.
Answer: Sorry to hear about your glitch. I'm not sure about the answer, but I suppose it would depend on a few questions.
A. What is this questionnaire going to be used for? Diagnosis? Research analysis? Medical treatment? I would definitely not use it for any diagnostic criteria that had actionable impact on your participants. For a peer-reviewed paper, that depends on the field, I suppose. It's probably best practice to disclose the glitch in your paper, even if you do end up using the data.
B. How important is to you that the questionnaire be validated? Can you just treat it as an "unvalidated" questionnaire instead? Any questionnaire can be administered in any situation, but you would probably lose the "validation" status if one of the items was consistently missing.
C. How hard is it to go back and ask your participants to fill out the missing item? Impossible? Difficult? Easy? If the latter, perhaps you can just ask them to fill out the missing item, or the entire questionnaire again? Does it matter for the questionnaire at hand that all items be filled out at the same time?
So long as you're not using the questionnaire for diagnostics or any treatment decision (as mentioned in your comment), you can proceed with the research analysis as per usual, and make sure to disclose the erroneously missing data in the paper (e.g. in a footnote or Research Limitations section).
Comment: Thanks for your answer, sorry for the late reply. Below, the answers to your questions:
A. The questionnaire would have been used for research analysis. No actionable impact on any participant. It was/is indeed intended for a peer-reviewed paper.
B. Well, I guess that it is always better to use genuine material rather than truncated one. But it is true that it could be used as an "unvalidated" questionnaire. I haven't thought about that (in fact I did not think it was possible).
C. Impossible to go back to the participants. Unfortunately.
Comment: @pdeli Happy to help. In that case, I would proceed with the analysis as per usual, just make sure to disclose the erroneously missing data in the paper (e.g. in a footnote or Research Limitations section). Editing above. If this answers your question, I would appreciate it if you accepted the answer! Best of luck.
Comment: Sure, however, can I ask you if by any chance you have some references? I would gladly add them in your answer.
Comment: @pdeli No references, just my own common sense. Sorry.


Google Maps não carrega

Question: Criei uma aplicação pra testar o google maps, porém quando eu executo pelo celular o mapa não carrega...a logo da google aparece no canto inferior esquerdo mas o resto da tela fica em branco...Eu adicionei as permissões no AndroidManifest.xml, e o celular está conectado a internet...não sei como proceder
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="etec.googlemaps">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MapsActivity
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

    }
}

Comment: O debug não mostra nada?
Comment: Eu resolvi meu problema com a resposta do Andre Souza no link abaixo https://groups.google.com/forum/#!topic/androidbrasil-dev/gR27Z9bMEWA
Answer: A Api Key que você gerou só vai funcionar se usar a mesma keystore pra gerar o apk. No Android Studio, menu Build -> Generate Signed APK, e escolha a keystore usada para gerar a Api key.
Comment: Como assim cara? Sou novato
Comment: No teu AndroidManifest.xml tem uma tag referente a uma API_KEY, você gerou ela ou só copiou de algum tutorial? Se não gerou dá uma olhada na resposta do Ivo Bruno Silva, pq você vai precisar dela pra ter acesso ao maps.
Comment: Sim, eu gerei a API KEY
Comment: Ok. Pra gerar a API KEY, em algum momento você usou um arquivo .keystore, vá em Build -> Generate Signed APK e use o mesmo arquivo .keystore pra assinar o apk.
Comment: No meu caso eu usei a debug.keystore, localizada na .android...então eu devo assinar o apk com ela?
Comment: Cara, deu certo...VALEU!!!!!
Comment: Estou com um problema parecido. Podem-me ajudar em: http://pt.stackoverflow.com/questions/120345/google-maps-n%C3%A3o-carrega-no-dispositivo-fisico
Answer: amigo a sua aplicação só vai funcionar se tiver a key do maps:
vá nesse  arquivo do seu código "res/values/google_maps_api.xml"
ache essa linha de código:
<name="google_maps_key" translatable="false" templateMergeStrategy="preserve">ADD_API_KEY_HERE   <--
</string>

e troque o ADD_API_KEY_HERE pela fornecida do prósito site do google developer
https://developers.google.com/maps/signup
Comment: Cara, eu fiz isso..ta com a API KEY
Answer: Você precisa criar uma projeto do maps( aqui) para que este te entregue uma chave. Essa chave deve ser adicionada no seu arquivo google_maps_api.xml onde vai estar: ADD_API_KEY_HERE. Para que você consiga uma chave para substituir no arquivo que citei acima você precisará gerar um sha-1 que é mostrado no link que adicionei.

Google Maps não carrega


Nokogiri::XML::document canonicalize method returns empty string

Question: I wanted to get a canonicalized version of a piece of xml by using nokogiri, though its canonicalize method is returnin an empty string.
d= Nokogiri::XML::Document.new '<z></z>e'
d.canonicalize #=> ""

Does anybody know what am I doing wrong? I am using Nokogiri 1.6.7
Comment: I disagree with the way this question was closed. The library is not providing a proper error and the original typo was not the cause for the mentioned problem. The answer matt provided is correct an helpful. Closing this question was abusive moderation.
Answer: Document::new doesn't actually parse the document. You are basically just creating an empty document with a rather odd XML version:
d.to_xml
#=> "<?xml version='<z></z>e'?>\n"

Instead use Document::parse, or the XML() method on the Nokogiri module:
d = Nokogiri::XML::Document.parse '<z></z>e'
d.canonicalize #=> "<z></z>e"


Python - taking a variable and inserting into a mysqlDB

Question: This is probably simpler than I've made it.
basically I'm writing my second python script here.  I want to open a mysql connection, process a for loop, and then insert the x int into a database.
I have everything working, expect, I'm unsure of how to insert the xstring instead of literal xstring.  In C# it would be '" + xstring +"' but i'm not sure how to do this in Python.
Thanks!
#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys

try:
con = mdb.connect('localhost', 'root', 'root', 'PythonTest');
with con:
        cur = con.cursor()
        for x in range(0, 3):
                xstring = str(x)

                    cur.execute("INSERT INTO Testing(KeyColumn,KeyValue) VALUES('Jack London','"xstring"')

except _mysql.Error, e:

print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

finally:

if con:
    con.close()

Comment: Did you try what worked with C#? Besides, since you are *formatting* you may be interested by the [`str.format`](http://docs.python.org/2/library/stdtypes.html#str.format) method
Comment: well yeah because you would do string xstring = x.ToString() and then you would place it in the value, which is simple enough
Comment: What I meant is that writing `"..." + xstring + "  "` **does** creating the concatenation of the strings, exactly as in C#.
Comment: @Bakuriu LOL!!! wow talk about easy...
Comment: @Bakuriu now... how do i get input html controls to python in order to insert what a user puts inside of the input!
Comment: You can also do this `cur.execute("INSERT INTO Testing(KeyColumn,KeyValue) VALUES('Jack London',?)", (xtring,))` is better to avoid SQL injection :), particularly if you want to insert user values
Answer: Python's DB API specification specifies it like this:
cur.execute("INSERT INTO Testing(KeyColumn,KeyValue) VALUES('Jack London', %s), (x,))

Warning: Never, ever use raw string formatting on DB queries, that would allow little Bobby Tables to inject nasty things into your DB. Instead use library methods for parameterizing SQL queries.
Comment: Actually the DB API specifies different type of styles for the parameters of a query. See [`paramstyle`](http://www.python.org/dev/peps/pep-0249/#paramstyle).
Comment: @Bakuriu you're correct, this isnt parameterized, this is simply an insert havinh python cast the string
Comment: But even if you trust the input, the little possible speed gain means nothing in Python. I think its best to stick to best practices. I mean, why not?


css3 tab in css3 tab issue

Question: i would like to make a 4 item tab in a 4 item tab. I don't know what messes the function up, but please take a look here.
For one tab with 4 items it is working properly.

<input id="tab1" type="radio" name="tabs" checked>
Codepen
<input id="tab2" type="radio" name="tabs">
Dribbble
<input id="tab3" type="radio" name="tabs">
Dropbox
<input id="tab4" type="radio" name="tabs">
Drupal

<input id="tab5" type="radio" name="tabs" checked>
Codepen

<input id="tab6" type="radio" name="tabs">
Dribbble

<input id="tab7" type="radio" name="tabs">
Dropbox

<input id="tab8" type="radio" name="tabs">
Drupal

5

5

6

6

 asdf

 asdf

 8

 8

2

 2

 3

   3

  4

 4

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXXXX X XXXXXXX X  XXXXXXX X
Here's a link to the codepen: https://codepen.io/user1010/pen/NzYOqg
Or is it only possible with JS?
Answer: You need to give the radio buttons inside content1 a different name from the others. At the moment, clicking on tab5 (for example) is automatically unchecking tab1 because they're in the same group.
In the pen below, I've given tabs 5, 6, 7 and 8 the name tabs2.
Working fork of your pen: https://codepen.io/anon/pen/KeobPV

css3 tab in css3 tab issue


SEO and migrating to ASP.Net MVC

Question: It's well-past time for The Office's websites to be upgraded and for the main public one, I'm considering migrating the existing .Net 1.1 ugliness up to ASP.Net MVC.
The only real doubt I have is over the fairly extensive work on SEO that has been carried out on the site.
What considerations should I bear in mind regarding SEO when moving from an old webforms site to MVC urls?
Answer: If your question is only about URLs, then the answer is that redirecting the old URLs to new ones with a permanent redirect (301) should do the trick - search spiders should update the results to new links without any SEO hit.
There will be other factors to consider as well - e.g. changed HTML structure of pages (I hope you are not going to mimick the output of the old ASP.NET in your new web app :)).
Comment: It would be fair to say there is a LOT I'm not going to mimick from the old site.
Answer: I would take a long hard look at routing. That's going to be the key to getting the SEO working as desired on the URL's. You may also want to have html helpers for formatting the rich url's.
Answer: You should consider your old links using either a) standard web forms with routing or b) making a large routing table that handles request for all of those old URLs that have already been cached / scraped by Google, Yahoo, Bing, etc.  If, as you say, you already have some good SEO in place, you don't want all of those links to suddenly stop working.

SEO and migrating to ASP.Net MVC


Views: Display users with a gmap attachment

Question: I have location, gmap and profile2 modules installed on my site.
In a profile type I have added a location field so that the user can add his/her location on profile edit.
I want to display all users with a map in the header. The map will have the markers for the currently displaying users.
For this purpose I have created a page view where I displayed all the users with a pager.
Then I added an attachment and select the style format as "Gmap" and in the settings I have tried both for Data source "Location.module" and "lat/long".
And attached it to the page.
But the view does not display any map.
Any one who have some idea about this?
Answer: Try using getlocation module. In order to show gmap with views, you need google api key. Getlocation module comes up with blocks and views with api key already embeded in code.


Draw focus for row in QTreeView

Question: I have to use QTableView for my project, and now I must to draw focus for row selected. I have to draw a dotted rectangle for row. but I don't new how to do this.
can you help me?..
Thanks a lot for any answer.
Answer: Use custom delegate:
Header:
<code>#ifndef ITEMDELEGATEPAINT_H
#define ITEMDELEGATEPAINT_H

#include <QAbstractItemDelegate>
#include <QStyledItemDelegate>

class ItemDelegatePaint : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit ItemDelegatePaint(QObject *parent = 0);

protected:
    void paint( QPainter *painter,
                const QStyleOptionViewItem &option,
                const QModelIndex &index ) const;
    QSize sizeHint( const QStyleOptionViewItem &option,
                    const QModelIndex &index ) const;
    QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void setEditorData(QWidget * editor, const QModelIndex & index) const;
    void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const;
    void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const;

signals:

public slots:

};
</code>
Cpp:
<code>#include "itemdelegatepaint.h"
#include <QPainter>
#include <QLineEdit>
#include <QDebug>

ItemDelegatePaint::ItemDelegatePaint(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

void ItemDelegatePaint::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QString txt = index.model()->data( index, Qt::DisplayRole ).toString();

    if( option.state & QStyle::State_Selected )
    {
        painter->setPen(QPen(QBrush(Qt::red),1,Qt::DotLine));
        painter->drawRect(option.rect);
        painter->drawText(option.rect,txt);
    }
    else
    {
        QStyledItemDelegate::paint(painter, option, index);
    }

}

QSize ItemDelegatePaint::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return QSize( 45, 15 );
}

QWidget *ItemDelegatePaint::createEditor(QWidget *parent,
                                    const QStyleOptionViewItem &option,
                                    const QModelIndex &index) const
{
    QLineEdit *editor = new QLineEdit(parent);
    return editor;
}

void ItemDelegatePaint::setEditorData(QWidget *editor,
                                 const QModelIndex &index) const
{
    QString value =index.model()->data(index, Qt::EditRole).toString();
    QLineEdit *line = static_cast<QLineEdit*>(editor);
    line->setText(value);
}

void ItemDelegatePaint::setModelData(QWidget *editor,
                                QAbstractItemModel *model,
                                const QModelIndex &index) const
{
    QLineEdit *line = static_cast<QLineEdit*>(editor);
    QString data = line->text();
    model->setData(index, data);
}

void ItemDelegatePaint::updateEditorGeometry(QWidget *editor,
                                        const QStyleOptionViewItem &option,
                                        const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}
</code>
Usage:
<code>ui->tableView->setItemDelegate(new ItemDelegatePaint);
</code>
Result:

Draw focus for row in QTreeView


Distribution for an operation of variables with identical distributions

Question: I have this doubt:

Consider $X$~$N(\mu_X,\sigma^2)$, $Y$~$N(\mu_Y,\sigma^2)$ and $Z=X-Y$

I know that $E(Z)=E(X)-E(Y)=\mu_X-\mu_Y$ because the expected value is a linear operator.
And I know that $V(Z)=V(X)-V(Y)=0$
But which distribution does $Z$ have? Can I say that $Z$ has a normal distribution because $X$ and $Y$ have a normal distribution?
Comment: I believe the question you are really asking concerns how to compute variances of differences of (independent) random variables.  That has good answers at http://stats.stackexchange.com/questions/26886.
Comment: That's true too. And I just assumed that $V(X-Y)=V(X)-V(Y)$ which isn't right. Thank you for your advice.
Answer: The variance of Z is equal to V(X) + V(Y) if X and Y are independent (You have to add the correlation term if X and Y are not independent) because V(-X) = V(X). Thus, Z has a normal distribution  with $\mu_Z = \mu_X - \mu_Y$ and $\sigma_Z^2 = 2\sigma^2$.
Answer: You should unaccept bassir's answer because it only addresses the case in which X and Y are independent, and his statement that Z is Normal may not be true if X and Y are not independent.
If X and Y are independent, then EZ and Var(Z) are as stated by bassir.
If X and Y are jointly Normal (i.e., Bivariate Normal), but not necessarily independent, then Z is a Normal random variable, and EZ is the same as for independent case, and
Var(Z) = 2*σ^2 -2*Cov(X,Y)  = 2*σ^2 - 2*(correlation coefficient between X and Y) * σ^2, where Cov(X,Y) is the covariance between X and Y.
If X any Y are not independent, Z does not necessarily even have a Normal distribution. EZ and Var(Z) are per the immediately above case which assumes X and Y are jointly Normal, but in fact, Z may not be Normal.  There are several such examples in http://www.amazon.com/Introduction-Probability-Theory-Applications-Vol/dp/0471257095 .
Comment: +1 There are examples in answers here on CV also (up to a flip of sign on the second variate to convert a sum to a difference). e.g there's some [here](http://stats.stackexchange.com/questions/120861/example-of-two-correlated-normal-variables-whose-sum-is-not-normal/120900#120900); and another [here](http://stats.stackexchange.com/questions/125648/transformation-chi-squared-to-normal-distribution/125653#125653). Nice images [here](http://stats.stackexchange.com/questions/30159/is-it-possible-to-have-a-pair-of-gaussian-random-variables-for-which-the-joint-d) of bivariates with the property.


Recarregar tabela sem refresh com Ajax jQuery

Question: Tenho uma tabela que tem a opção de atualizar registros, porem preciso que ao alterar um registro ele seja alterado dinâmico na tabela sem precisar do refresh..
já esta funcionando a parte do servidor ele já altera o dado e tals.. porem preciso dar refresh na página para poder ver a alteração realizada.. tenho o seguinte JS:
if(e.update){
    $('#insert_form').each(function(){
         $('.alert').removeClass('alert-danger').addClass('alert-success');
                this.reset();
         });

    // Aqui eu preciso recarregar a tabela..
    $('#employee_table') // Refresh!

}

esta dentro de um request, e caso o retorno seja update ele var executar a função que estiver ai dentro..
Answer: Caso escolha por reconstruir a tabela, você poderia remover o conteúdo de tbody e renderizar novamente com o o retorno do jQuery ajax. Algo como:
success: function (result) {
    $('tbody').empty();
    result.forEach(function(item){
       $('tbody').append('
'+item.chave+'
');
    })
})

Comment: exato, porem não existe outra forma sem precisar reconstruir a mesma?
Comment: Sim @Drik, ter um identificador único da linha da tabela e alterar as propriedades dela com o retorno.