Como formatar valores monetários para ser exibido em formato brasileiro com chartjs

Question: Como formatar valores monetários para ser exibido em formato brasileiro com chartjs, no tooltip e no eixo Y do gráfico abaixo eu queria exibir :
R$199,99 e R$2.888,99

Mas não achei isso na documentação.
var options = {
            scaleFontFamily: "'Verdana'",
            scaleFontSize: 13,
            animation: false,
            scaleFontColor: "red",
            responsive: true,
              title: {
                display: true,
                text: 'Receitas x Despesas'
              }
        };

        var data = {
            labels: ["Despesas", "Receitas"],
            datasets: [
                {
                    backgroundColor: [ "#FF0000","#3CB371"],
                    label: "Population (millions)",
                    strokeColor: "rgba(0,145,255,1)",
                    pointColor: "rgba(0,145,255,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(0,145,255,1)",
                    data: [199.99, 2888.99]
                }

            ]
        };

    var ctx = $("#pie-chart");
    var myPieChart = new Chart(ctx,{
        type: 'pie',
        data: data,
        options: options
    });

Answer: Para formatar dados no tooltip use Tooltip Callbacks
tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
         //Format data
      },
},

Para acessar os valores do tooltip: data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]
Fonte da função formatMoney() aqui
Exemplo

var options = {
  tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
        return formatMoney(data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]);
      },
    },
  },
  scaleFontFamily: "Verdana",
  scaleFontSize: 13,
  animation: false,
  scaleFontColor: "red",
  responsive: true,
  title: {
    display: true,
    text: 'Receitas x Despesas'
  },

};

var data = {
  labels: ["Despesas", "Receitas"],
  datasets: [{
      backgroundColor: ["#FF0000", "#3CB371"],
      label: "Population (millions)",
      strokeColor: "rgba(0,145,255,1)",
      pointColor: "rgba(0,145,255,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(0,145,255,1)",
      data: [199.99, 2888.99]
    }

  ]
};

var ctx = $("#pie-chart");
var myPieChart = new Chart(ctx, {
  type: 'pie',
  data: data,
  options: options
});

function formatMoney(n, c, d, t) {
  c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

<canvas id="pie-chart" height="230" width="680"></canvas>
Comment: Como ficaria a formatação monetária do eixo Y do gráfico ?


How do I fetch only records created in the past year from a table within SSIS package?

Question: I have a column CT_DT in a  table. I have to process only transactions created within the past 365 days.
For example, suppose the current date is Nov 7, 2012, I have to process only those transaction that were created since Nov 7, 2011. I am using conditional filter within the SSIS package.
Comment: There is no reason to load every record into the buffer and then filter if CT_DT is the transaction date. This will cause the database to return more data than is required, unnecessary memory usage, and a slower processing time. See Siva's first option on filtering out older transactions in the source query.
Answer: You can filter the data in the query you might be using on the data source within the data flow task.
Query to filter the data on the source:
SELECT  column1
    ,   column2
    ,   column3
FROM    dbo.MyTable
WHERE   DATEDIFF(YEAR, CT_DT, GETDATE()) <= 1

If you absolutely want to filter the data on the Conditional Split transformation within the Data Flow task, create a new output and set it to the following expression:
Expression for Conditional Split:
DATEDIFF("yy", CT_DT, GETDATE()) <= 1

Your conditional split will look something like this.
Comment: In my case CT_DT is contain current date and older date too...I tried your logic but it won't work here..I update some of my date 2011/12/31 and this logic filters my this date too....


How to union many tables with same name but different schema without dynamic sql?

Question: Microsoft SQL Server

[dbo].[MyTable]
[schema1].[MyTable]
[schema2].[MyTable]
[schema3].[MyTable]

I want to union them. For example:
select * from [*].[MyTable]

Can I do that?
Answer: Something like this
select * from [dbo].[MyTable]
UNION
select * from [schema1].[MyTable]
UNION
select * from [schema2].[MyTable]
UNION
select * from [schema3].[MyTable]

Comment: Unfortunately, I cannot list the names of the tables without using dynamic SQL.


Select dentro de Select

Question: Estou desenvolvendo uma página de produtos que lista dentro de cada categoria todos os produtos relacionados (são várias categorias e vários produtos). Como o código abaixo, ele 'roda' todas as categorias e o que eu preciso fazer, e onde preciso de ajuda, é listar os produtos.
    <?php do { ?> //Listagem das Categorias
        <div class="row" id="<?php echo $row_ListaCategoria['descricao'];?>">

<?php echo $row_ListaCategoria['descricao']; ?>

CHICOTE PARA REPARO ALTERNADOR VW/CHICOTE P/REPARO SENSOR PRESS

Código: 101.1152

                            Aplicação: 400

                            Obs: N/F

    <?php } while ($row_ListaCategoria = mysql_fetch_assoc($ListaCategoria)); ?>

Para buscar as categorias utilizo:
mysql_select_db($database_Conect, $Conect);
$query_ListaCategoria = sprintf("SELECT * FROM tbl_categoria WHERE id_empresa = %s ORDER BY descricao", GetSQLValueString($colname_listaFabrica, "int"));
$ListaCategoria = mysql_query($query_ListaCategoria, $Conect) or die(mysql_error());
$row_ListaCategoria = mysql_fetch_assoc($ListaCategoria);
$totalRows_ListaCategoria = mysql_num_rows($ListaCategoria);

Banco:
(Categoria)
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `descricao` varchar(32) NOT NULL,
  `data_cadastro` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `id_empresa` int(11) NOT NULL,
  PRIMARY KEY (`id`)

(Empresa)
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(100) NOT NULL,
  `data_cadastro` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ativo` int(1) NOT NULL,
  PRIMARY KEY (`id`)

(Produto)
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(255) NOT NULL,
  `tbl_categoria_id` int(11) NOT NULL,
  `tbl_empresa_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`tbl_categoria_id`)
    REFERENCES tbl_categoria(id)
    ON DELETE CASCADE,
  FOREIGN KEY (`tbl_empresa_id`)
    REFERENCES tbl_empresa(id)
    ON DELETE CASCADE

Um exemplo de como seria mostrado:

Não consegui resolver este problema ainda, tentei desenvolver uma function para selecionar os produtos porém não deu certo ainda.
Estou aberto caso tenham alguma sugestão, ideia ou solução.
Agradeço desde já a todos!
Comment: Porque você não cria os selects de acordo com suas categorias? Ex.: select * from produto p where p.categoria='Pecas carros' - select * from produto p where p.categoria='Pecas motos'. ai na sua página você imprime a lista dentro de cada categoria referente ao select.
Comment: Porque é um sistema de uma representada, então tenho várias empresas com categorias diferentes. Aí fica inviável fazer um select para cada. Se eu não te entendido errado.
Comment: Os Produtos e as Categorias compartilham alguma chave (key) ?
Comment: Sim, tbl_produto possui ID de tbl_categoria e de tbl_empresa @FleuquerLima
Comment: Para vc selecionar a categoria você já tem que ter selecionado a empresa certo? O produto seria filtrado pela id_empresa e id_categoria. Sua duvida é em como montar esta Query?
Comment: @FleuquerLima, sim, é isso mesmo, eu já estou selecionando as categorias de acordo com a empresa, me mostra as categorias de forma perfeita, mas dentro de cada categoria eu preciso mostrar todos os produtos dessa. não sei se seria feito na mesma query. A Principio tentei fazer uma função que recebesse o valor da categoria e selecionasse os produtos, mas não deu certo. Se for possível realizar na mesma query seria ótimo.
Comment: Da pra fazer na mesma Query sim, só precisa saber o que passar de parametro.
Comment: @FleuquerLima, certo, eu atualizei com mais informações caso possa me ajudar com essa query
Answer: Você pode fazer na mesma Query sim.
Você pode fazer a comparação diretamente adicionando as duas tabelas e dando-lhes apelidos com "AS", e quando for chamar os campos basta colocar o apelido na frente para referenciar de onde vem o campo.
Exemplo:
select C.campo_tabela_categoria, P.C.campo_tabela_produto
from tbl_categoria AS C, tbl_produto AS P
where id_empresa = %s AND C.id_categoria = P.id_categoria
order by C.descricao

Ou podes usar (o que seria ate mais correto) INNER JOIN, por exemplo:
select C.campo_tabela_categoria, P.C.campo_tabela_produto
from tbl_categoria AS C INNER JOIN tbl_produto AS P on C.id_categoria = P.id_categoria;

Se quiser saber mais sobre joins veja este post: Qual é a diferença entre INNER JOIN e OUTER JOIN?
Espero que isto ajude;
Att;
Comment: Ainda não consegui entender esse raciocínio para o que eu descrevi. Tenho que selecionar _em cada categoria de tal empresa todos os produtos_. Utilizando JOIN eu não conseguiria mostrar somente uma vez Categoria e abaixo todos os produtos, e logo depois outra categoria com todos os produtos novamente..

Select dentro de Select


A certain number when successively divided by $8$ and $11$ leaves remainders of $3$ and $7$, respectively.

Question: A certain number when successively divided by $8$ and $11$ leaves remainders of $3$ and $7$, respectively. What will be the remainder when the number is divided by the product of $8$ and $11$, $88$?
Comment: Chinese remainder theorem?
Answer: $n=8a+3=11b+7$. So 8 divides $11b+4$, so $b=4\bmod 8$. Hence $n=11(8k+4)+7=51\bmod88$. Check: $51=6\cdot8+3=4\cdot11+7$.
Comment: Please can you explain this, I've found this theorem....   when a number is divided by two divisor d1 and d2 the two reminders are r1 and r2 are obtained , the reminder that will be obtained by the product of d1 and d2 is given by the relation 'd1r2 + r1'.....therefore d1r2 + r1= 8 * 7 +3 =59


Eclipse Strange Errors

Question: my eclipse  galileo installation has started giving me problems all of a sudden.
yesterday I was unable to start my tomct6 server and today I am unable to create a dynamic web project.
I get the following error
<code>    The selected wizard could not be started.
  Plug-in "org.eclipse.jst.servlet.ui" was unable to instantiate class "org.eclipse.jst.servlet.ui.project.facet.WebProjectWizard".
  java.lang.NullPointerException
</code>
My eclipse is shared with my colleagues, is that an issue ? Also I recently installed m2 sonatype plug in for maven 2.
Comment: The stack trace of the NPE might give a clue ...
Comment: I had the same issue. Galileo, unable to start tomcat, unable to create dynamic web project and recently installed m2 sonatype. I followed the suggestion below.
Answer: Have you updated from eclipse recently? From some quick googling it seems like mixing Galileo with updates for Helios in some modules is causing this error message. I would suggest to download eclipse Helios and point to your current workspace.

Eclipse Strange Errors


Google Script E-mail confirmation

Question: My goal is to have a form that fills out a spreadsheet. Part of the form will have an e-mail address and another with is task complete. I want it to be if I switch the spreadsheet from no to yes under task complete to e-mail the user with a confirmation saying so. I don't know if it is possible but any help would be appreciated.
Edit :
This code is what I have down now to do the task. I like the way it is setup up but there are 2 major issues that I want to try and solve. First being when the script runs lets say I skip over a row the script will fail and not keep trying more entries down the rows. Second issue is I am not sure how to control who is sending the script e-mail past where it asks you to okay and run the script the first time.
<code>// This constant is written in column O for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 1000;   // Number of rows to process
  // Fetch the range of cells M2:N1000
  var dataRange = sheet.getRange(startRow, 1, numRows, 1000)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[12];  // First column
    var message = row[13];       // Second column
    var emailSent = row[14];     // Third column
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "Help Desk Completion Response";
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 15).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}
</code>
Answer: The e-mail will always be sent as the user that runs the script. You can have the script run as the result of an installable trigger which you can set on any Google account with access to the script and the script will then send the e-mail as that Google account. For example, have the script run once a day using a time-based trigger and check the values for EMAIL_SENT and TASK_COMPLETE, if the task is complete but the e-mail is not sent, then have the script send an e-mail. This should also solve the empty row problem because when TASK_COMPLETE is empty rather than "Yes" it will not try to send an e-mail.
If you want to make the script send an e-mail immediately you will need an edit-based trigger. In this case you may not even need to load the entire spreadsheet but a simple e.range.offset() may suffice.
Something like:
<code>//This constant is written in column O for rows for which an email
//has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function sendEmails(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var columnNumber = e.range.getColumn(); //check if the changed value is TASK_COMPLETE
  if(columnNumber = 5 && e.value = "Yes") {
    var row = e.range.offset(0, -5, 1, sheet.getLastColumn()).getValues();
    var emailAddress = row[12];  // First column
    var message = row[13];       // Second column
    var emailSent = row[14];     // Third column
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "Help Desk Completion Response";
      MailApp.sendEmail(emailAddress, subject, message);
      e.range.offset(0,9).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}
</code>
Of course the exact offsets depend on where exactly in your spreadsheet things are located.

Google Script E-mail confirmation


How to pull parent taxonomy from nodes

Question: I have a taxonomy list like so...
Parent One
    Subitem One
    SubItem Two
       SubItem Three
Parent Two
    Subitem Four
Parent Three
    SubItem Five
    SubItem Six
I also have a content type that uses subitems in a field, along with other fields.
I need to have a view that will show the parent taxonomy terms in addition to the other fields in the CCK.  Something like
Parent Fields
      Title
      Book
      Subotem 1
   Parent Two - SubItemsTwo
      Title
      Book
      Subotem 3
Please advise
Comment: I think an unordered list showing how your taxonomy is structured would help.
Answer: You should look into Relationships for this.
Comment: I agree, however can you expand? I'm playing with relationships but I must have it incorrect.  I'm not able to pull the parent back in the view

How to pull parent taxonomy from nodes


How to capture git's output in drush make?

Question: We use drush to clone a number of git-repositories during build. Most of the time this "just works", but on (a rare) occasion, a cloning fails.
Unfortunately, all that we get from drush in such cases is:

Unable to clone repository                                 [error]

The DRUSH_BACKEND piece of JSON is shown, but claims no error ("error":null):
DRUSH_BACKEND:{"type":"notice","message":"Command dispatch complete","timestamp":1411582254.5773,"memory":10891736,"error":null,"packet":"log"}

The actual error message generated by the git-executable is not shown. Is there a way to change that? Simply adding --debug to drush's command line does not do it...
This question may not even be drush-make specific -- the spawning of external programs and capturing their stdout/stderr may be a generic drush thing...
Thank you!
Answer: Ok, the short answer is: it is not possible. Not at the moment. Although the code in includes/exec.inc is prepared to output the captured stdout and stderr of the command, it will only do so, if DRUSH_DEBUG is set:
  exec($command . ' 2>&1', $output, $result);
  _drush_shell_exec_output_set($output);

  if (drush_get_context('DRUSH_DEBUG')) {
    foreach ($output as $line) {
      drush_print($line, 2);
    }
  }

The only way to set DRUSH_DEBUG is by giving the --debug flag on drush command-line (it can not be set from drushrc.php). Sadly, in a number of cases -- including git-invocations -- the top-level drush invokes a child drush to do the actual work. It is doing so without passing the --debug flag to it...
I filed a ticket with drush-maintainers and implemented a work-around. We replaced the real git executable with a shell-wrapper, which captures stderr of the real git (and some other info, like environment veriables) into a log-file, then feeds the captured stderr to its own descriptor 2 -- just in case the caller cares. Then, if the real git's exit-code is 0, the log is deleted, otherwise it is retained for investigation.


solving union and intersection of family of sets problem using number line?

Question: though I don't even know high school math properly(I only know about some grade 10 level set-theory,polynomial math knowledge because I didn't study hard...) but I tried to read herstein's "Topics in algebra" just for fun and in the book there is a problem like this:

For instance, if $S$  is the set of real numbers, and if $T$ is the set of rational
numbers, let, for $\alpha \in T, \ A_{\alpha}= \{x\in S\ | \ x\ge\alpha\}$. It is an easy exercise to see that $\cup_{\alpha\in T}A_{\alpha}=S$ whereas $\cap_{\alpha\in T}A_{\alpha}$ is the null set. The sets $A_{\alpha}$ are not mutually disjoint.

I roughly thought like this:
When I imagine a point $\alpha$ on the number line such that $A_{\alpha}= \{x\in S\ | \ x\ge\alpha\}$,
The smaller the size of $\alpha$, the more it goes to the left, the larger the size of $\alpha$, the more it goes to the right.
So, if the point $\alpha$ is gradually moved to the leftmost on the number line, eventually the interval of point $\alpha$ (the entire interval to the right of $\alpha$) becomes the entire rational number. and since $x≥\alpha$ is the condition, irrational numbers between rational numbers are included.
So ∪(a∈T)Aα = S
If I move the point a to the rightmost, there is no overlapping interval, so $\cap_{\alpha\in T}A_{\alpha}$ is the null set.
And I thought the reason why The sets $A_{\alpha}$ are not mutually disjoint is because even though there are no elements common to "all" sets in a family of sets, but "some" sets have elements in common with each other.
I know this is not formal proof at all, but is this right ideas?
And If I study high school math properly or furthermore if I study the prerequisites step by step, will i be able to understand this book easily?
Or is this book actually requiring little background knowledge, and the reason I find it difficult is simply my lack of understanding ability?
Should I just be interested in physics or programming rather than rigorous mathematics?(Actually Math is just a hobby for me by the way. I am considering becoming a programmer. the reason I want to study (undergraduate) mathematics is because of the programming applicability of algebra, combinatorics, analysis and because of my curiosity.)
Comment: Hi! Usually, minus infinity on the number line is pictured at the left. Therefore, paraphrasing your post, the smaller the size of $\alpha$, the more it goes to the *left* (and vice-versa). The set $A_\alpha$ contains real numbers that are bigger or equal to $\alpha$, so the smaller the size of $\alpha$, the more "area" it takes on the number line. It seems to me you've written the opposite.
Comment: Obviously my comment is immaterial if you picture your number line with minus infinity at the right...
Comment: @Marc-André Brochu Oh, I'm sorry I will fix it immediately! Thank you for pointing out!
Answer: You have the right ideas. Here's a more formal proof, in my case it is coming from the same intuition you described in your post. Note that I put in a lot of details that I wouldn't put in usually.
First I show that $S=\cup_{\alpha\in T}A_\alpha$ by double inclusion.
Take some point $x$ contained in $S$ (i.e. $x$ is a real number). Clearly(*) there exists some rational number $\alpha\in T$ such that $\alpha\leq x$. Now by definition of $A_\alpha$ we have that $x\in A_\alpha$. Note that $A_\alpha$ is contained in $\cup_{\alpha\in T}A_\alpha$ by definiton of the union. Since $x$ was an arbitrary point of $S$, we have the inclusion $S\subseteq \cup_{\alpha\in T}A_\alpha$.
The reverse inclusion is easier to write: the sets $A_\alpha$ are all sets of real numbers; therefore their union is also a set of real numbers: $\cup_{\alpha\in T}A_\alpha\subseteq S$.
Since we have $S\subseteq \cup_{\alpha\in T}A_\alpha\subseteq S$, we must have equality, which proves the claim "by double inclusion".
(*) You can actually prove this (exercise) using the Archimedean property of the real numbers if I recall correctly.
Second I show that $\emptyset=\cap_{\alpha\in T}A_\alpha$. Just for fun let's do it by contradiction: suppose on the contrary that there actually is a point $x\in\cap_{\alpha\in T}A_\alpha$. This means exactly that $x$ is greater than all $\alpha\in T$, i.e. $x$ is a real number bigger than any rational number. This is intuitively impossible, of course. Formally it's again because of the Archimedean property. Here we go. Clearly $x>0$. Then $1/x>0$, so there exists an integer $n$ such that $1/x>1/n>0$. Now we get $x<n$, but $n$ is a rational number (every integer is a rational number), so $x\notin A_n$, which is a contradiction with the fact that $x\in\cap_{\alpha\in T}A_\alpha$. This proves that there could be no element in the intersection (because such an element would have contradicting properties), so that it is the empty set.
I hope this helps. Good luck!
Comment: Thank you for your reply and your detail explanation! I appreciate your consideration :) Good luck to you, too!


Is it possible for $(900q^2+ap^2)/(3q^2+b^2p^2)$ to be an integer?

Question: The original problem is: "Find all possible pairs of positive integers $(a, b)$
$$k = \dfrac{a^3+300^2}{a^2b^2+300}\tag1$$
such that $k$ is an integer."
I've tried so many different ways. Now this question comes up from one of them. Let,
$$\left(\dfrac{a}{10} \right)^2=\dfrac{3(300-k)}{kb^2-a}=\dfrac{p^2}{q^2}\tag2$$
If you calculate $k$ in terms of $a, b, p, q,$ then the following question comes up:
"Suppose $a$, $b$, $p$ and $q$ are natural numbers such that $a<300$ and $\gcd(p, q)=1$. Is it possible for
$$k=\frac{900q^2+ap^2}{3q^2+b^2 p^2}\tag3$$
to become an integer?"
I think this is easier than original problem, but I don't know how to proceed from here.
Comment: @TitoPiezasIII yeah, regarding given conditions it has three solutions.
Comment: @PatrickStevens you are right, we can use $a<300$ only. Let me edit the problem.
Comment: You made a typo somewhere as there are many more solutions than that. What are the three you found?
Comment: Solutions are $(a, b)=(10, 2), (20, 1), (30, 2)$.
Answer: While your $(3)$ can be derived from $(2)$, if it is an integer does not guarantee that $(1)$ will be an integer as well. Note that it has the four variables $a,b,p,q$ that can "integerize" your expression, while you're stuck with only $a,b$ for $(1)$.
(For example, $a,b,p,q =3,2,9,5$ makes $(3)$ an integer, but $a,b = 3,2$ does not for $(1)$.)
Also, your original problem should explicitly specify the constraint that $a \neq 300b^2$. If not, then $a = 300b^2$ yields an infinite family which always has $k=300$.
A computer search with $a<10000$ and $b<100$ yields the infinite family and,
$$a,b,k = 10,2,130$$
$$a,b,k = 20,1,140$$
$$a,b,k = 30,2,30$$
which seem to be the only other solutions.
Comment: Thanks Tito. It can be proven that $a<300$ and doing a computer search gives the answers you have provided. So these are the only solutions other than the case $a=300b^2$, but I can't prove it by hand.


Oracle - Como gerar todos os dias (Calendário) entre duas Datas com Anos diferentes (*Sem Tabela de Apoio)

Question: Como gerar o intervalo de todas as dias dos meses entre duas datas?
Considerando apenas os parâmetros:
Data Inicial: 10/01/2014
Data Final: 29/12/2018
Exemplo:
01/01/2014
02/01/2014
03/01/2014
...
26/12/2018
27/12/2018
28/12/2018
29/12/2018
30/12/2018
31/12/2018
Comment: Eu encontrei uma solução em:(https://sqlshow.wordpress.com/2013/05/13/calendario-em-sql-oracle/#comment-61) e alterei um pouco sugerindo melhorias!
Comment: @RovannLinhalis alguma sugestão, devo remover o artigo e comentar no outro? Dei uma olhada e são situações semelhantes, mas não há presença da pessoa no meu caso, apenas dois intervalos de data
Comment: não sei se é necessário remover esta, até porque serve como outro caminho para se chegar a um resultado, só achei válida a menção como duplicata porque a solução é praticamente a mesma.
Comment: Como o @RovannLinhalis cita a resposta é uma outra maneira, está relacionada com a outra pergunta, mas é de uso mais genérico, pois a resposta aqui pode ser aplicada em uma view por exemplo, enquanto que a outra pergunta usa conceitos avançados e tem uma tabela de relacionamento
Answer: Os seguinte código pode ser usado:
<code>SELECT
 CAL.DATA

,TO_NUMBER(TO_CHAR(CAL.DATA,'DD')) AS Dia

,TO_NUMBER(TO_CHAR(CAL.DATA,'MM')) AS Mes

,TO_NUMBER(TO_CHAR(CAL.DATA,'YY')) AS "AnoYY"

,TO_NUMBER(TO_CHAR(CAL.DATA,'YYYY')) AS "AnoYYYY"

,TO_CHAR(CAL.DATA,'day') AS "Descr_Dia"

,TO_CHAR(CAL.DATA,'dy') AS "Descr_Dia_abrev"

,TO_CHAR(CAL.DATA,'Month') AS "Descr_Mes"

,TO_CHAR(CAL.DATA,'Mon') AS "Descr_Mes_abrev"

,TO_CHAR(CAL.DATA,'dd month yyyy') AS Data_texto

FROM (
SELECT
  (
    TO_DATE(SEQ.MM || SEQ.YYYY, 'MM/YYYY')-1
    -- Subtrai 1 por SEQ.NUM não começar em zero
  ) + SEQ.NUM AS "DATA"
    FROM
    (
        SELECT RESULT NUM,
        TO_CHAR(( -- Data Mínima
            TO_DATE('01/01/2014', 'DD/MM/YYYY')
            ) , 'MM') AS "MM",
        TO_CHAR(( -- Data Mínima
            TO_DATE('01/01/2014', 'DD/MM/YYYY')
            ) , 'YYYY') AS "YYYY"
        FROM
          (
          SELECT ROWNUM RESULT FROM DUAL CONNECT BY LEVEL <= (
                (
                -- Data Máxima
                LAST_DAY(TO_DATE('31/12/2018', 'DD/MM/YYYY'))
                -
                -- Data Mínima
                TRUNC(TO_DATE('01/01/2014', 'DD/MM/YYYY')) -- Sempre primeiro dia do mês
                ) + 1 -- Último dia do último ano
            )
          ) -- Quantas sequências para gerar pelo MAX

    ) SEQ
) CAL
;
</code>


Proving/Disproving injectivity with $f(x,y,z) = (x+z, y-2z, -x-y+z)$

Question: I know this is really simple, but it's aggravating the hell out of me.
Say we have $(a,b,c),(x,y,z)\in\mathbb R^3$ such that $f(a,b,c) = f(x,y,z)$.
This means that:
\begin{align}a+c &= x+z \\
b-2c &= y-2z\\
-a-b+c &= -x-y+z\end{align}
I can't find solutions to these, which tells me its probably injective. To make sure, I'd like to find a value to show that it's not, but I don't have the intuition. What should I be doing in these cases? Thanks.
Answer: The function is linear so $f(a,b,c)=f(x,y,z)$ iff $f(a-x,b-y,c-z)=0$.
So to prove that $f$ is injective it is sufficient to prove thta $f(x,y,z)=0 \Rightarrow (x,y,z)=(0,0,0)$ ( the same method can be used for any linear function).
So you only have to solve the system:
\begin{align}
&x+z=0\\
&y-2z=0\\
&-x-y+z=0
\end{align}
Comment: Thanks for your response. That's actually quite interesting, I've never looked at it that way.
Answer: The linear map $f\colon \mathbb{R}^{3}\to \mathbb{R}^{3}$ is given by the matrix
$$ \begin{bmatrix}1 & 0 & 1\\0 & 1 & -2 \\ -1 & -1 & 1 \end{bmatrix} $$
Its determinant is $0$. Hence the kernel is non trivial and the map is not injective.
Comment: Thanks for your response. Would you mind doing this without using matrices/determinants, but just linear systems? It's more of a conceptual problem for me; I don't know what to do after I reach the point where I can't show that a = x, b = y, c = z. How can I determine that it's injective when I can't do that?
Answer: To show it is not injective, you have to show ONE of the following:

that there is a vector in $ \mathbb{R}^3 $ for which there is no vector that maps to it.
that the dimension of the range is less than the dimension of the domain.  You can do this by noting that the mapping is from $ \mathbb{R}^3 $ to $ \mathbb{R}^3 $ but the dimension of the null space is greater than zero.

and there are a bunch of equivalent ways of showing it.  The bottom line is that the natural way to show all this is to formulate the problem as a set of linear equations, with a matrix.  So, don't fight that.  Embrace it.
Comment: Thanks for your reply. Maybe I'm confused, but I thought that proving that there's an unmapple vector disproves surjectivity, and to disprove injectivity, you have to show that there's an vector which is mapped by more than vector, no?
Comment: @user494405 If you show that the kernel is nontrivial, then you have a whole bunch of vectors that all get mapped to zero.


PointerToPointer : How to return the modified values/structure back to the original list?

Question: While writing the add function for Linked List I came up with the following piece of code
    int addNode(node ** head)
        {
1.      node * ptr = *head;
        if(ptr==NULL)
        {
            ptr = (node *)malloc(sizeof(node));
            ptr->next = NULL;
            ptr->val = (char *)malloc(10);
            strcpy(ptr->val,"1");
2.          *head = ptr;
        }//Rest omitted

Now as far as my understanding of pointer to pointer goes, when i call this function

addNode(&n)

(n is defined as node * n) I send the address of the pointer n. head = &n as of now? At 1 I make ptr point to n i.e. ptr = &n? Is that right? What I don't understand is why do I need to set *head = ptr? Isn't ptr already directly making changes to n? And don't both ptr and *head point to n?
Thanks!
Answer: ptr is the working copy of *head. with
node *ptr = *head;

you make a copy. If you use ptr, no changes to head are done, because you have copied the pointer but not the ptrptr. head is the same as n, it's just the name of n in your function. So ptr does not change n - you use the line
*head = ptr;

to change n.
Answer: If you want to add your node at the begining, you may do that :
int     addNode(node **head)
{
  node  *ptr;

  if ((ptr = malloc(sizeof(*ptr))) != NULL)
    {
      ptr->val = (char *)malloc(10);
      strcpy(ptr->val,"1");
      ptr->next = *head;
      *head = ptr;
    }
}


How to test for a statistically significant difference between multiple unbalanced groups

Question: I have 4 groups that are not normally distributed. I would like to know if they are significantly different, with the aim of knowing if they would make a good feature to base a classification on.
I've made box&whisker plots and by looking at them, just by intuition, I feel that they are similar, statistically. That is not very satisfying though and probably not a good way to pass judgment, so I want a way to quantify this. I have been using the Kruskal Wallis test on the groups. Because of the unbalanced group sizes, I don't trust the results. The size of the samples is: 4756, 4018, 1116 and 171. I'm currently getting a p-value of 0.000104, and an H of 21.02
Is there a rule of thumb to follow to know when it is appropriate to test groups with different sizes? I really feel it is unfair to compare a group of 171 to 4756 - that this imbalance should make the comparison invalid. Is the 'solution' to simply say there is not enough data to make a comparison, and wait till more is taken? At what point then would there be 'enough' data or the point when the groups are similar enough size?
Comment: It is _inefficient_ to design an experiment so that you're comparing one group with 171 observations and another with 4756, but not _wrong._ Inefficient because the power of the test will depend more of the smaller group than on the larger. If you had resources to make about 5000 observations, you would have best power with about 2500 in each group.  // Some nonparametric tests behave badly when one of the groups is _very_ small, but you are nowhere near that problem with 171.
Answer: Comment continued: Notice that the small sample inmmy first example is very much smaller than you
are suggesting in your Question.
Demonstration of K-W test where one level has very small sample size.
With sample sizes 4, 200, 100, and a difference of 15 between population
group means, the K-W test does not give a significant result
set.seed(1121)
x1 = rnorm(4, 95, 10)
x2 = rnorm(200, 110, 10)
x3 = rnorm(100, 110, 10)
x = c(x1,x2,x3)
g = rep(1:3, times=c(4,200,100))
kruskal.test(x ~ g)

        Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 5.2646, df = 2,
 p-value = 0.07191

In a similar situation with 100 observations at each level, the
difference is found to be very highly significant.
set.seed(1122)
x1 = rnorm(100, 95, 10)
x2 = rnorm(100, 110, 10)
x3 = rnorm(100, 110, 10)
x = c(x1,x2,x3)
g = rep(1:3, each=100)
kruskal.test(x ~ g)

        Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 97.804, df = 2,
 p-value < 2.2e-16

Notches in the boxplots below are nonparametric confidence intervals
calibrated so that, roughly speaking, non-overlapping CIs suggest
a difference in location between two levels. (In the first example, it
would be problematic to make a boxplot with only 4 observations at the first
level.)
boxplot(x ~ g, col="skyblue2", notch=T)


Show that the likelihood ratio test statistic is 34.7.

Question: A question from my class:
Ask students whether they are vegetarian. Of n=25 students, y=0 answered "yes". For testing Ho: p=0.5 and Ha: p <> 0.5. Show that the likelihood ratio statistic equals 34.7.
I have tried SEVERAL ways to calculate this and I am getting nothing near 34.7.
In the notes, the test statistic is calculated by -2(L(po) - L(p1)). However, when I calculate this, I am getting 6.24.
PLEASE HELP!
Answer: $$
LR = -2\ln\left[\frac{\sup_{\theta\in\Theta_0} \mathcal L(\theta)}{\sup_{\theta\in\Theta_1} \mathcal L(\theta)}\right].
$$
Note that $\mathcal L(\theta)=(1-\theta)^{25}$, $\Theta_0=\{0.5\}$, $\Theta_1=[0,1]\setminus\{0.5\}$, and
$$\sup_{\theta\in\Theta_1}(1-\theta)^{25}=\sup_{\theta \neq 0.5}(1-\theta)^{25}=1$$
since for $\theta=0$ this probability attaines maximum value. So
$$
LR=-2\ln (1-0.5)^{25} = -50 \ln 0.5 = 34,657359028.
$$
Comment: I realized that I was using the log function instead of the ln function. Thank you!!


how to migrate "repo init/sync" to "git" server?

Question: I have a questions about "repo" to "git" migration including .repo dirs.
< 1st Action >
In order to prevent .git conflict, I delete all .git and .repo directories.
After I delete .repo, the original source does not compile successfully.
< 2nd Action >
So, I need to upload all .repo information to my new git server.
I git add, git commit and git push all source and .repo manually.
But the new git service source code does not compile successfully as well. recipe build error occurred.
< need to solution >
I received a project source using repo init ~~~ and repo sync.
I have a Gitlab test server. Gitlab is using Git repo address as git@<IP>:project/test.git.
I would like to clone (mirror? duplicate?) repo, and sync all source and histories to my Gitlab server at the same time.
I would like to find solution, how do I replicate repo init/sync to git server?
Thank you.
Comment: You need to repo sync against google servers, then update the manifest file so that it uses your server. After that is done, you can do a push using the repo tool.
Comment: unfamiliar with repo, but the fact that your source code is not compiling has nothing to do with the versioning system used. Either [tag:git] or [tag:repo] are versioning systems, designed to help you track the changes you make to the code. They don't help you writing good or runnable code...
Comment: @DaemonPainter In some cases, the repository may fetch code from some remote repository during the compiling. So if the local repository is corrupted, it could fail.
Answer: I'm not familiar with repo, but if I recall correctly, a repo directory is a git repository.
You can git push ssh://git@<IP>:project ... without further modifications.

By the way : the .git/ folder contains the database for your local git repo ; removing this folder means erasing all the history and all the branches of your repo. Don't do that :)
Answer: The repo in repo init and repo sync is a launcher script. You can find what it is by which repo.
repo init creates .repo in the current folder, clones the repo-tool repository from the url to .repo/repo and checks out its branch. The url and the branch are specified by REPO_URL and REPO_REV in the launcher, or by options --repo-url and --repo-branch. The repo-tool repositoy contains the launcher and other sub-command scripts.
repo init accepts options -u <url_to_manifest_repository>, -b <branch> and -m <manifest>. -u specifies a repository which contains manifests. -b specifies the repository branch and -m specifies which manifest to use. <branch> defaults to master and <manifest> defaults to default.xml. The manifest repository is cloned to .repo/manifest.git and its working tree is .repo/manifests.
The manifest specified by -m instructs repo sync to fetch metadata of defined repositories. The metadata are stored in .repo/project-objects and .repo/projects. After metadata are fetched, the involved repositories' codes are checked out to paths defined in the manifest. The paths are also git repositories, but their .git folders are linked to .repo/projects and .repo/project-objects.
You want to push all repositories to Gitlab. First, create Gitlab repositories for all synced repositories. Second, create local orphan branches if you don't want to keep original history. Third, push local branches to Gitlab repositories.
The repo-tool has a sub-command forall. repo forall iterates all repositories and runs the commands specified by the option -c <commands> in each repository. You could also parse the manifest and use a loop to do the same job, which is more flexible. -c is convenient for a simple command. But for complicated commands, it's better to write a script.
Suppose there is a local repository whose name is foo.git and path is foo.
cd foo

# create an orphan branch if you don't want to keep the original history
git checkout --orphan <branch>
git commit

# create Gitlab repository with Gitlab API
# curl .....

# push the local revision to Gitlab repository
git push http://mygitlab.com/xxx/foo.git <branch>:refs/heads/<branch>

After all repositories are uploaded, you need to create a manifest to keep a record of Gitlab repositories so that you can use the repo-tool to download them from Gitlab. Based on the original manifest, you need to modify <remote/>, <default/>, and <projects/> according to the Gitlab repositories. After that, upload the manifest to your own manifest repository. For the manifest format details, you can find the doc in .repo/repo/docs/manifest-format.txt.


Agora OnAudioDeviceVolumeChanged not called on android devices (unity sdk)

Question: Hy all,
I have implemented OnAudioDeviceVolumeChanged call back. It works great on pc with windows but it is not called on android device. Is there a way to check when device volume is changed? Thanks
Comment: Does this answer your question? [Unity3D: is it possible to check the volume of both Android and iPhone devices?](https://stackoverflow.com/questions/37057723/unity3d-is-it-possible-to-check-the-volume-of-both-android-and-iphone-devices)
Answer: This API is indeed only available to Windows.  The Agora team will update the documentation to reflect that.


Some Swift class properties are not found when accessed from Objective-c project

Question: I'm trying to bring some Swift code into my older obj-c project. Swift class is accessible from obj-c class, but not all of it's properties though. For example
public var menuTitleColor: UIColor!

works perfectly fine, but
public var cellHeight: CGFloat!

is not found. I think it's because CGFloat is not an object. Is there a way to access this property without changing Swift file?
Answer: Primitive types in Objective-C
Look at this Swift class
@objc class Foo: NSObject {
    var myCGFloatOptional: CGFloat? = 1
    var myCGFloat: CGFloat = 1
}

If I use it in Objective-C only the myCGFloat property is available.
Foo * foo = [Foo new];
foo.myCGFloat;
foo.myCGFloatOptional; // Compile Error

This because in Objective-C CGFloat is a primitive type (like float). And Objective-C does not allow nil values for a primitive type.
Just like you cannot write this in Objective-C
float number = 1;
number = nil; // compile error

References to instances of classes
In your Objective-C code you are able to see a property of type UIColor! declared in Swift because UIColor is a class. So you are declaring a pointer that could reference an instance of UIColor or nothing.
And in Objective-C the same concept does exist.
Note
You could note that int is a primitive type as well in Objective-C but, "unexpectedly", the compiler does allow you to write
int number = 1;
number = nil;

However in this case nil is simply interpreted as the integer 0 (still a value, not really nil).
Comment: Great explanation, thanks a lot! I accepted your answer instead of the first one, since it provides a lot more info on the subject and will be a lot more useful to anyone stumbling upon same issue.
Comment: Simple and easily understandable
Answer: You can try this code:
public var cellHeight: CGFloat = 0 //(or some other number)
Comment: I never bridged Swift stuff to ObjC but it might have something to do with the property being a primitive value type. And it is unable to treat it as a force unwrapped reference type.
Comment: Primitives can't be nil in ObjC, so optional primitive properties are not imported. See https://stackoverflow.com/a/26366289/72176 for a more detailed discussion.


Proper use of D.C. al Coda with repeat voltas

Question: I have a score template like this...

I expect this to be the performance by measure numbers and rehearsal marks...

A

     1-8, 1-7, 9

B

     10-25

C

     26-33, 26-31, 34-38

D.C. al Coda

A

     1-7, 9

B

     10-24

Coda

     39-40

This template is in MuseScore 3.6. It plays it once according to the order or measure I expect, but then it plays the whole sequence again but playing only the volta second endings, ignoring the D.C al Coda, and moving from the trio to the coda ending mm. 38-40.
Have I made a mistake with the repeat signs or is MuseScore playing it wrong? I suspect it's my mistake, but I don't know what I've done wrong.

EDIT
Screen shots of the inspector, MuseScore 3.6...
Comment: I made the template. It based on Chopin's short Mazurkas B.16,  1 & 2. Although he didn't use exactly that series of repeats.
Comment: Oops. Meant to vote to close, not actually close. Anyway, see my answer in the duplicate. If that doesn't fix things, send me a comment, and I'll vote to reopen.
Comment: ...and if it does work, please feel free to update my answer to reflect that it was verified in MuseScore 3.6.
Comment: @Aaron. The issue isn't playing the repeats for the D.C. I actually don't want that. I tried it anyway, but it still isn't playing right. It gets to the final coda but then starts over again.
Comment: Well, first of all, apparently I can just reopen, so ... done. So the problem is that it ignores the "to coda" after taking the DC repeat, or it never takes the DC repeat to begin with? Obviously, I'm not clearly understanding the problem.
Comment: As with @ElementsinSpace, I created a score that matches yours, and it works fine. MuseScore 3.6.
Answer: Your repeat signs are right, it's a MuseScore issue.
Use the Inspector on the all the jump signs, and make sure the Jump settings are right:

Update
Here is a link to a copy of the template that I made, and which seems to work as expected:
Mazurkas - TEMPLATE
Comment: I tried taking out the system break between mm. 38, 39 but still plays the same. I'll post over at the MuseScore site, because it seems to be a software issue. Thanks for looking at it.
Comment: I think I figured out the MuseScore issue. Your template worked in my MuseScore. So, I made a brand new page with the same repeats. My new page worked. Then I realized I had imported my original file from an older version of MuseScore and had been editing it. Something about the import from an older version seems to have messed it up. Ugh! Thanks for answering my notation question _and_ troubleshooting MuseScore!
Comment: Thanks for the inspector tip. I added a second screen shot of the inspector settings. It makes sense in terms of what I expect, but MuseScore 3.6 still plays it wrong. I check for updates. It says I'm on the latest.
Comment: @MichaelCurtis I made my own copy of the template (not shown), with all the structure in yours (other than the fancy mid-line system break). It seems to work just fine (and without having to adjust the Jump settings), so I'm not sure what's gone wrong.
Comment: @MichaelCurtis I've added my (working) copy of the template to the bottom of my answer.  However, it doesn't explain why your copy didn't playback properly.  If you can find out what the problem was, that'd probably make a more useful answer.


Prove property involving successor function

Question: Let $a \in \mathbb{N} $ and $s: \mathbb{N} \longrightarrow \mathbb{N} $ be the successor function defined in Peano postulates. Then, prove the following
$$ 1 + a = s(a) = a + 1 $$
Now, there is a theorem, which says that there is a unique binary operation $+: \mathbb{N} \times \mathbb{N} \longrightarrow \mathbb{N} $ that satisfies the following two properties for all $n, m \in \mathbb{N} $.
$$ n + 1 = s(n)$$
$$ n + s(m) = s(n + m) $$
So, using this theorem, its trivial that $ a + 1 = s(a)$. I can not assume Commutative Law for Addition. But I can assume Cancellation Law for Addition and Associative Law for Addition. So, how can I proceed ?
Comment: Hint: proceed by induction on $a$.
Comment: Thanks Greg....
Answer: Doing induction on the natural numbers means exploiting the fact, that any subset $A\subseteq\mathbb N$, which contains $0$ and is closed under successors, is already the whole of $\mathbb N$.
So let us consider the subset $A = \{a \in \mathbb{N} \mid 1+a = s(a) = a+1\}$.
For $a=0$ you find by the definition of the maps $1+\bullet:\mathbb{N}\rightarrow\mathbb{N}$ and $0+\bullet:\mathbb{N}\rightarrow\mathbb{N}$ that
$$1+0 = 1 = s(0) = 0+1,$$
hence $0 \in A$.
The second condition on $+$ gives you
$$1+s(a) = s(1+a) \overset{ind}{=}s(s(a)) = s(a)+1.$$
This shows $s(a) \in A$ for any $a\in A$.
This shows $A=\mathbb{N}$.


How can I prove this inequality using Cauchy-Schwarz inequality

Question: I am reading introduction to functional analysis with application of Kreyzig.
The question in excercise is
"Show that Cauchy-Schwarz inequality implies that
$$(|a_{1}|+|a_{2}|+...+|a_{n}|)^2\leq n(|a_{1}|^2+|a_{2}|^2+...+|a_{n}|^2).$$"
The Cauchy-Schwarz inequality is
$$\sum|\zeta_{j}\eta_{j}|\leq (\sum|\zeta_{j}|^p)^{\frac{1}{p}} (\sum|\eta_{j}|^q)^{\frac{1}{q}}$$
 Thanks in advance
Comment: First, write down the Cauchy Schwarz inequality that you know. This will help those who are trying to answer your question.
Answer: Due to Cauchy Schwartz,
$[\sum_{i=1}^{n} {|a_i|}^2][\sum_{i=1}^{n} {|b_i|}^2\geq \sum_{i=1}^{n} {(|a_i||b_i|)}^2$
put $b_i=1$ for all i you get your answer.
Answer: Hint:
Observe we may suppose $a_i\ge 0$ for all $i=11,\dots n$. Next apply Cauchy-Schwarz to the vectors $\;(a_1,a_2, \dots, a_n)\;$  and $\;(1,1,\dots, 1)$.


Finding the dot product.

Question:
Finding the dot product of $(-2w) \cdot w$ where $w=(0,-2,-2)$
  $$ \text{dot product} = \frac{v . u}{\| v \| . \| u \|} $$

So
$$-2 (0,-2,-2)=(0,4,4) \\
(0+4+4) = 8 \\
 (0,-2,-2)=-4
\\ 8 \times -4=-32$$
$$\| v \|= \sqrt{0^2+(-2)^2+(-2)^2}=2 \sqrt 2 \\
\|-2w \|= \sqrt{0^2+4^2+4^2}= 4 \sqrt 2\\
\frac{-32}{2 \sqrt 2 \times 4 \sqrt 2} = -64$$
Is this correct?
Comment: The dot product of $w = (w_1, w_2, w_3)$ and $-2w = (-2 w_1, -2w_2, -2v_3)$ is $$ -2 w_1^2 + -2 w_2^2 + -2 w_3^2 = -2(w_1^2 + w_2^2 + w_3^2).$$
Answer: You have several mistakes here:
The formula in your question is for the cosine of the angle between two vectors, not the dot product. The numerator in the right-hand side of the formula is the dot product.
To calculate the dot product of two vectors, you multiply corresponding entries in these vectors and then sum the products. You seem to be summing the components and then multiplying the sums.
So in this case:
\begin{align*}
(0, -2, -2) \cdot (0, 4, 4) &= 0\times0 + (-2)\times4 + (-2)\times4 \\
&= -16
\end{align*}
Comment: Ah silly me. Thank you for this. :)
Answer: What you have written as the dot product isn't the dot product.
The dot product of $v=(v_1,v_2,v_3)$ and $w=(w_1,w_2,w_3)$ is simply
$$v\cdot w=v_1w_1+v_2w_2+v_3w_3.$$
In your problem, we have $w=(0,-2,-2)$. Computing $-2w$, we have
$$-2w=-2(0,-2,-2)=\bigl(-2\cdot0, -2\cdot(-2), -2\cdot(-2)\bigr)=(0,4,4).$$
Then
$$(-2w)\cdot w= (0,4,4)\cdot(0,-2,-2) =0\cdot0+(4)\cdot(-2)+(4)\cdot(-2)=-16.$$

Your expression at the end of your post demands that we find the norm of two vectors. The norm of $w$ is
$$\Vert w\Vert=\sqrt{ 0^2+(-2)^2+(-2)^2}=\sqrt {8}=2\sqrt2.$$
The norm of $-2w$ can be calculated in a similar manner; but you could also compute it using the rule $\Vert \alpha v\Vert=|\alpha|\Vert v\Vert$:
$$\Vert -2w\Vert=2\Vert w\Vert=2(2\sqrt2)=4\sqrt2.$$
Finally, if you wish to compute $(-2w)\cdot w\over \Vert w\Vert \Vert 2w\Vert$, just substitute:
$$
{ (-2w)\cdot w\over \Vert w\Vert \Vert 2w\Vert} ={-16\over (2\sqrt2)(4\sqrt2)}=-1.
$$
This should come as no suprise, since $  (-2w)\cdot w =-2(w\cdot w)=-2\Vert w\Vert^2$ and $\Vert -2w\Vert =2\Vert w\Vert$; we could have arrived at the result with no computations:
$$
{ (-2w)\cdot w\over \Vert w\Vert \Vert 2w\Vert} ={-2\Vert w\Vert^2 \over2\Vert w\Vert\Vert w\Vert}={-2\Vert w\Vert^2 \over2\Vert w\Vert^2}=-1.
$$

Finding the dot product.


Como preencher todo um vetor com malloc(sizeof(int)) com algum valor

Question: Estou com um problema, não tenho ideia de como preencher este vetor com algum valor, por exemplo, eu quero preencher ele todo com -1 (iniciar ele todo com -1).
O problema aqui é que eu não sei exatamente qual o tamanho do meu vetor.
<code>    typedef struct argumentosThread {
        int dim, queens, posicoes, total;
        int *posicCertas;
        int head;
    }ArgumentosThread;
</code>
La no meio do codigo eu inicializo ele, eu coloquei o sizeof(int) porque eu não sei qual vai ser o tamanho do vetor, ele pode ser bem pequeno ou então MUITO grande.
<code>    argumentos->posicCertas = malloc(sizeof(int));
</code>
Comment: Tem que saber de alguma forma, não existe milagre. O que fez não é criar um vetor, está criando um único elemento, neste caso você sabe o tamanho, é 1.
Comment: Qual vetor ? Se está a falar do `argumentos->posicCertas` ele é iniciado como um ponteiro para um inteiro apenas e  não um vetor propriamente dito
Answer: No momento em que alocar esse vetor usando malloc, armazene também seu tamanho na estrutura...
E faça um laço for para preencher conforme deseje.
<code>argumentos->posicCertas = (int*)malloc(sizeof(int)*n_pos);
argumentos->n_pos = n_pos;
</code>
Depois só fazer um for preenchendo o vetor.
É interessante também fazer um casting do retorno do malloc.


How to launch android plugin app within nativescript

Question: I'm trying to launch Android app that I've packed inside a plugin for nativescript
I followed this tutorial and I imported everything correctly, but I can't find anywhere how could I launch the android app in the way that I have it(i.e. launch onCreate() or even displayMessage()).
Here is how my main activity looks like
public class MainActivity extends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);

        //etc..
    }

    private void displayMessage(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title)
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //do things
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

How do I show(or launch) my android app content from within nativescript in that case? What steps am I missing? I'm very new ns..
Answer: You may just start the MainActivity via an intent.
Here is the pseudocode.
const intent = new android.content.Intent(application.android.context, your.package.name.MainActivity.class);
application.android.foregroundActivity.startActivity(intent);

Comment: thank you so much! It's now showed me that I'm missing DemoActivity in AndroidManifest.xml so I added it in App_Resources/Android/src/main/AndroidManifext.xml, but then I got an error `ClassNotFoundException: Didn't find class "your.package.name.R$layout" on path: DexPathList[[zip file "/data/app/org.nativescript.TnsApp-1/base.apk"],nativeLibraryDirectories=[/data/app/org.nativescript.TnsApp-1/lib/arm64, /data/app/org.nativescript.TnsApp-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]`   Is it because I didn't properly created jars?
Comment: Could be, the activity class should be public, so it could accessed from JS runtime.
Comment: the activity class is declared as public indeed, I think that the program crashes on the line `setContentView(R.layout.activity_demo);`. Does it mean that I will have to put into plugin libs folder all android jar files(android.arch, com.android.support etc.)?  But I don't think it should work like that..
Comment: Your layouts will be compiled as part of JAR, if may crash only when it doesn't find the layouts.
Comment: So does this ClassNotFoundException mean that the layouts weren't properly exported to jar?
Comment: I didn't say that. You had mentioned it crashes on the specific line `setContentView(R.layout.activity_demo);`, may be the layout was not found or something. But if you get `ClassNotFoundException` in the log, then it's different, your class is not visible. If you using plugin, make sure you run a clean build. Any updates on the JAR may not auto sync sometimes.
Comment: I did run `Tasks>build>clean` ad then `Tasks>other>createFullJarRelease` on both my android app modules but still same error. Then I put both modules `full.jar` from /build/intermediates/intermediate-jars/release/ into plugins libs folder. Did I miss anything?
Comment: I meant clean build the NativeScript app, assuming this exception was at runtime when you tried to launch the activity from NativeScript Activity.
Comment: ran `tns platform clean`, removed node_modules and platforms dirs, reimported plugin and same error
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/195145/discussion-between-kyrylo-lukeniuk-and-manoj).
Comment: an tns platform clean, removed node_modules and platforms dirs, reimported plugin and same error
It was happening during the runtime. I also did tns build android. If there is something else I could do please let me know. Thank you!
Comment: I'm not sure what else could be the issue without debugging the code, but I can confirm there are many plugins launches Activity on a plugin method call.
Comment: there was an issue on my side, I didn't include resources. Had to generate .aar file instead of .jar


Multiple Regression - Converting Standardized Coefficients to Unstandardized

Question: I recently performed a multiple linear regression using a standardized set of data, and I was wondering if it possible to convert the standardized coefficients from the regression into usable unstandardized coefficients. I found and attempted to implement the method found here: https://www3.nd.edu/~rwilliam/stats1/x92.pdf
but I got significantly different (and very wrong) results compared to what I got using the standardized coefficients and standardized data. All I did was convert each coefficient by multiplying by the ratio of the standard deviations of y and the corresponding x. To calculate the results, I then multiplied each new unstandardized coefficient by each corresponding unstandardized entry in the data set, summed them, and added the intercept (which I believe does not change through the unstandardization process). Is there something I'm doing wrong. Any help would be greatly appreciated!
Comment: Did you handle interaction variables properly?
Comment: I think so. Here is my data and calculations, sorry if it's a bit ugly: https://docs.google.com/spreadsheets/d/1ZUDAFnDjf2p21YJPyFHr-_EOnykN-iCAaYTRtIv6PxU/edit?usp=sharing
Comment: Where did your "Intercept" term come from? The spreadsheet suggests it is the constant term in a regression involving the standardized variables--but in that case it should have been zero rather than $-2.45$. To make progress on this question we really need to see the calculations you made to standardize the data and to perform the regression.
Answer: Let's say a model is: $y=1+x+xz+z^3$, and $\sigma_y,\sigma_x,\sigma_z$ - standard deviations of variables. You would transform the equation like follows: $Y=\sigma_y+\frac{\sigma_y}{\sigma_x}X+\frac{\sigma_y}{\sigma_x\sigma_z}XZ+\frac{\sigma_y}{\sigma_z^3}Z^3$
Comment: I believe that's what I did. My calculations are in the comment link above.


Pentatonic Terminology Box versus Position

Question: I'm late to the party. Is it incorrect to refer to "Box 2 of the Am pentatonic scale" as "Position 2 of the Am pentatonic scale"? I am aware of a classical guitarist would say position 1 if the root of the scale starts on the 5th fret. Let me know as I may be inadvertently causing confusion.
Comment: Not certain about a classical guitarist saying about position 1. Which classical guitarist..?  Each 'box' has its higher notes in the same place as the next box up's lower notes, so they all intermingle. Probably best to keep your own labels. In 50 yrs of teaching, I've not labelled 'boxes' or 'positions' with anything but reference to fret numbers or chord shapes, named from the basic open shapes. Different publications use different terminology, so it appears there's no standardisation anyway.
Comment: https://www.google.com/search?q=boxes+in+the+caged+system+for+guitar
Comment: I had played guitar for 30 years when I first heard of "boxes". But then again, I largely learned it by myself.
Comment: I still don't know what boxes are, 26 years in.
Comment: doing some looking, "boxes" may be a blues guitar method, not specifically CAGED.
Answer: The problem you are running in to is that there are very many different approaches to teaching the guitar, each with their own and often conflicting terminology. Even in classical guitar approaches there will be different definitions of what "position one" is.
The term "position" on the guitar is used in many ways. In some case the position refers to what fret the chord or scale is starting from, so position 5 would be 5th fret. In other cases the positions are specific to the method being taught, and can be oriented around different chord shapes, scale shapes or arpeggio locations. I'd recommend not trying to make a direct correlation, and only refer to the "boxes" as boxes when discussing the method you are working with.
Ultimately all of the various guitar systems are designed to let the student develop the knowledge of where the notes are on the guitar and how they fit into  scale and chord patterns of western music.  Don't get too locked down to the terminology you are starting with, as different players that you work with will have learned different systems, but we all seem to manage to figure it out once the music starts.
EDIT:
In the CAGED system the A shape is referred to as position 4.  The use of the term "boxes" is new to me, and may be specific to the book or web page you are working out of.
Some of the instructions I looked at show the A form for C major/A minor starting in the second zone/box up, which may be called second position in that instance.
You may be working with a Blues guitar method that uses the term "boxes", in which case stick with the terms the method uses to avoid confusion.


How do I modify Request_URI using Apache or PHP?

Question: I'd like some help with some URL rewriting magic. I am having trouble modifying the Request_URI variable.
I would like to switch between two sites http://host.com/alpha and http://host.com/beta. They are both handled by the same php script. This script is http://host.com/index.php.
The index.php expects to be given a GET variable SITE to tell it which site to display. It also uses the REQUEST_URI to determine which content to display. In order for this to work, the alpha or beta need to be removed from the original request. This is where I am stuck.
So the REQUEST_URI starts at /alpha/content/file and needs to become /content/file.
I've tried this using mod_rewrite in .htaccess:
RewriteCond %{REQUEST_URI} /(alpha|beta)(.*)
RewriteRule .* index.php?site=%1

index.php:
<?php
echo "Site: " . $_GET['site'] . "
";
echo "Request_URI: " . $_SERVER['REQUEST_URI'] . "
";
//get_html($_SERVER['REQUEST_URI']);
?>

I'm hoping to have better luck with Apache's SetEnvIf and Alias.
Any ideas on how to do this would be greatly appreciated. Thanks.
Answer: Quite easy to manage:
RewriteRule ^(alpha|beta)/?(.*) /$2?site=$1 [R,L]

This will temporarily redirect (HTTP status code 302) any URLs beginning with "alpha" or "beta" to a resource without "alpha" or "beta" in the beginning but being appended as a query string, associated to the query variable "site".
Example:
// Will be redirected to http://host.com/shoes/nike/order.php?site=alpha
GET http://host.com/alpha/shoes/nike/order.php

EDIT
This won't account for query strings provided by the original GET call. If you need those the following would do:
RewriteRule ^(alpha|beta)/?(.*) /$2?site=$1 [QSA,R,L]
RewriteRule .* index.php [NC,L]

Cheers!
Comment: yeah that's what I am looking for. I haven't got it work just yet tho. I'm seeing a 404 error..
Comment: You would have to map the redirect to point to your index.php in your root directory (just a guess, I dont know your layout) with another rule. This would let you handle everything in your index.php and would have the correct REQUEST_URI to know what the client requested.


How to limit the execution of a rule for sending an email to only run once in a day?

Question: I have a rule that sends an email out to subscribers on the 28th of each month. The rule is executed when cron is run, I have cron set to automatically run once a day.
I also use linkchecker, which uses cron to check the links on the site. Right now I have to remember on the 28th of the month not to run cron for the linkchecker, otherwise my subscribers will get multiple emails that day for each time cron was run.
How can I limit the rule to only run once in any specific day, so that I don't have the potential to accidentally run cron manually and spam my subscribers?
Comment: Any feedback about my answer? Did it help somehow?
Answer: Have a look at the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt your "rule that sends an email" to run ... once a day, on any day, including the 28th of each month.
Comment: Never heard of this module, until now.
Comment: @NoSssweat : didn't realise I included "sound" in my answer here, did I? ... long live contributed modules, instead of wasting time on disposable custom code ... (I know, Drupal developers who care about job security will disagree with me on that, but hey, one can't downvote comments, right?)


jQuery storing and referring to an array of items

Question: I'm not exactly what I'm looking for in jQuery/Javascript terms. The behavior I'm looking for is akin to your typical lightbox slide show with the following elements:

a list of items
clicking on an item will bring up a new element that references the item in the list
while the new element includes next/prev navigation that refers back to the list of items.

I'm building something like that and am looking for the technical approach for handling the above.
I have this for sample code:

item 1

item 2

item 3

I have things set up so that each LI A gets a click event that creates a new overlay DIV on the page, then does a .load($(this).attr('href)) into it.
All that works great.
What I don't know how to do is, pass which index of LI I clicked on to the new div so I can add the proper prev/next links and actually refer to the next/prev element in the original list. Specific example, if I click on the second list item, in the new DIV I create, how do I pass into it the information that "it was the second link that opened this".
Answer: In your div code you can select your item again matching on passed href value and use next() and prev() to get the other siblings for given element.
Comment: how should I get the href value into the div to match against it? I suppose I could pass it to a hidden link each time.
Answer: Try this:

item 1

item 2

item 3

next
prev

Answer: When you create the div use the jQuery data feature to basically "link" the two DOM elements:
$("ul li a").click(function(e){
    var $this = $(this);
    $("

")
        .data('trigger', $this)
        .appendTo(body)
        .load($this.attr('href'));
    e.preventDefault();
});

Then you can just use a .live event to capture clicks for next and previous in your overlay divs:
$("div.overlay a.next").live('click', function(e){
   var $div     = $(this).closest('div.overlay'),
       $trigger = $div.data('trigger'),
       $next    = $trigger.parent().next();

   if($next.length){
      // It got the next li
      // $next.find('a') would select the link

   } else {
      // It reached the end
      $next = $("ul li:first"); // Grab first now
      // $next.find('a') would select the link
   }
});

Write pretty much the opposite for prev.


Integrating the Euler-Lagrange equation

Question: Let us have a Lagrangian $L(y,y') = f(y)\sqrt{1+y'^2}$, where $y=y(x)$. The corresponding Euler-Lagrange equation is
$$\frac{f'}{\sqrt{1+y'^2}} - f\frac{y''}{(1+y'^2)^{3/2}}=0$$
This expression should be possible to recast in the following form
$$\frac{d}{dy}\left(\frac{f}{\sqrt{1+y'^2}}\right) = 0$$
which can be integrated to get the stationary solution for $y'(x)$. I am not able to figure out how to get this equation from the first one above. Any idea?
Comment: It appears you are looking for the standard substitution for time-independent differential equations. It goes as
$$y'=v$$
$$y''=v'=\frac{dv}{dt}=\frac{dv}{dy}\frac{dy}{dt}=v\frac{dv}{dy}$$
I hope it helps.
Comment: Differentiate the second expression and you get the first
Comment: Just using integral by parts and note that $f$ is function of $y$.
Comment: hrmmmm... I've tried working this out and have ran into a couple of issues: are we to consider $y'$ also a function of $y$? If so, should there be a $y'$ in the numerator of the second term?
Comment: DanZimm, $y$ and $y'$ are both functions of $x$. We are not to think of $y'$ as being a function of $y$.
Comment: Urgje, I don't get the first equation by differentiating the second. This would give me $f'/\sqrt{1+y'^2}=0$. See my comment above.
Comment: The part $y''/(1+y'^2)^{3/2}$ represents the curvature of $y(x)$. The second equation in the problem statement above is obtained simply by neglecting this curvature or, more precisely, by assuming that the second term is negligible compared to the first. This would yield
$$\frac{\partial{f}}{\partial y}\frac{1}{\sqrt{1+y'^2}}=0 \quad.$$
Since $y'$ is a function of $x$ and not of $y$, we can write this as the total differential
$$\frac{d}{d y}\left(\frac{f}{\sqrt{1+y'^2}}\right)=0 \quad.$$
This is the only way I can think of now but I don't like the assumption of zero curvature.
Answer: I just found the solution to this problem. We are given the Lagrangian  $L(y,y')=f(y)\sqrt{1+y'^2}$. Since this is not an explicit function of $x$, the Euler-Lagrange equation simplifies into this form:
$$\frac{d}{dx}\left(L-y'\frac{\partial L}{\partial y'}\right)=0$$
(see the Wikipedia page "Beltrami identity") for the derivation. In our case, this will give us
$$\frac{d}{dx} \left( f\frac{1}{\sqrt{1+y'^2}} \right) = 0\,.$$
Again, the term in the bracket is not an explicit function of $x$ and thus this total differential can be written as $d/dx = y'(\partial/\partial y)+y''(\partial/\partial y')$. Instead of doing the derivative $d/dx$ above,  we use the right-hand side of this identity. This yields:
$$y'\left[ f' \frac{1}{\sqrt{1+y'^2}} - f \frac{y''}{(1+y'^2)^{3/2}}\right] = 0\,.$$
The last step is to multiply the last two equations by $dx/dy\equiv1/y'$. This will change the variable with respect to which we differentiate in the first and will remove the prefactor $y'$ in the second. The results are
$$\frac{d}{dy} \left( f\frac{1}{\sqrt{1+y'^2}} \right) = 0$$
$$f' \frac{1}{\sqrt{1+y'^2}} - f \frac{y''}{(1+y'^2)^{3/2}} = 0$$
The second equation was obtained using the indentity (total differential) and is thus necessarily the same as the first. However, from the second, it is not obvious how one would obtain the stationary solution $y'(x)$, while this is straightforward from the first.

Integrating the Euler-Lagrange equation


How to create aliases for file paths?

Question: In my content type there is a file field; when I upload files, it creates a file path like sites/default/files/uploaded_file.zip.
Is there a way to change this path to something like dl.example.com/uploaded_file.zip? I checked the PathAuto module, but it doesn't seem to have this feature.
Answer: you have these steps:

create virtual host for dl.example.com domain and point it to something like sites/default/files/dl/
create some module and implement this hook: hook_filefield_paths_process_file(). have a look at FileField Paths module.
function filefield_paths_filefield_paths_process_file($new, &$file, $settings, &$node, &$update) { ... }
Answer: You can try File Aliases

The File Aliases module allows you to use token customizable aliases
  for your uploaded files, giving you the ability to keep your file
  system organized as per usual while providing clean looking paths
  (i.e., no more '/sites/default/files/').

How to create aliases for file paths?


Why is for(;;); an infinite loop?

Question: I've written infinite loops like this numerous times over the years in both C and C++, but today is the first time I really thought about it -- why is it an infinite loop when the condition clause is empty? One would expect you'd have to write something like for(;true;); to get a valid infinite loop?
while(); doesn't compile nor does while(;);
Anyways, I like the for(;;); syntax and use it often, but is it a special case to treat an empty condition block as true or are there other cases in C or C++ where an empty condition expression is interpreted as true?
Comment: Because when a condition clause is empty it defaults to true, hence the loop. That's how C++ specifies `for` to behave. Mostly the same reason why water is wet.
Comment: With what compiler and settings does `while(true)` test true against true? I can't manage to get anything other than an unconditional jump.
Comment: while needs a condition unlike for loop in C++, in while there is no default value.
Comment: Just because `for`'s condition may have a default does not require `while` to have a default too. Why does `for`'s condition have a default, and `while` doesn't? Who knows... Who cares... Not something to lose any sleep over. Just have to remember that this is how  C++, then flip the page to the next chapter in your C++ book.
Comment: Note [infinite loops are undefined behavior](http://stackoverflow.com/q/3592557/1708801) outside of the for case and if the loop contains observable behavior. C11 makes an exception for [controlling expressions that are constant expressions](http://stackoverflow.com/a/28681034/1708801)
Comment: `while();` is a compilation error so an empty condition clause does not always default to true.
Comment: @charunnera  "I've written infinite loop  like this numerous times over the years in both C and C++, but today" I asked myself: "What was I doing?":)
Comment: Thanks guys. I'll just chalk it up to another special case. @VladfromMoscow, yes I was smiling as I wrote that...I'm sure I had this same question when I first saw the for(;;) syntax, figured out the answer and used the syntax without thinking...and then one day (today) someone asked me and I was like "good question".:)
Comment: @BenjaminLindley, I only compiled for(;;); to asm and it used an unconditional jump.  While researching this question, someone else mentioned that while(true); tested each loop and I bit. I removed that statement since I didn't actually verify it. Thanks for calling that out.
Answer: The C Standard explicitly describes this behavior of for loops:

C11 Draft Standard §126.96.36.199 2

Both clause-1 and expression-3 can be omitted. An omitted expression-2
  is replaced by a nonzero constant.

Similarly, for C++:

C++14 Draft Standard §6.5.3
  2
Either or both of the condition and the expression can be omitted.
  A missing condition makes the implied while clause equivalent to
  while(true).
Comment: Thanks for pointing there is an explicitly defined behavior for omitting the expression.
Comment: This question has been asked many times before and has many duplicates, including highly upvoted ones. You are a member with a lot of reputation, and thus have been given privilege and understanding to do the following. Improving StackOverflow by reducing duplicates by voting to close as a duplicate instead of answering. Such action will greatly improve the community at the negligible disadvantage to yourself. Thank you.
Comment: @2501-- I agree that this question is a duplicate; in fact I knew that it was a duplicate of the question that you linked to, since that was my first question on SO! When I asked that question, I found no other questions that asked about the _nature_ of this behavior (a result of the evaluation model or defined behavior). When I answered, it seemed to me that one duplicate is not a bad thing. Of course, the answer turns out to be mundane.
Answer: The behaviors are defined by the language (C++). For the for loop, the condition part is optional:

Syntax
formal syntax:
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement

and (emphasis mine)

The above syntax produces code equivalent to:
{
    init_statement
    while ( condition ) {
        statement
        iteration_expression ;
    }
}

Except that
3) Empty condition is equivalent to while(true)

For while loop, the condition part is necessary, it can't be ommitted.

Syntax
attr(optional) while ( condition ) statement

Comment: Thank you for your response
Comment: This question has been asked many times before and has many duplicates, including highly upvoted ones. You are a senior member with a lot of reputation, and thus have been given privilege and understanding to do the following. Improving StackOverflow by reducing duplicates by voting to close as a duplicate instead of answering. Such action will greatly improve the community at the negligible disadvantage to yourself. Thank you.

Why is for(;;); an infinite loop?


Prove $ \lim \limits_{(x,y) \rightarrow (x_{0}, y_{0})} f(x, y) = L \implies \lim \limits_{(x,y) \rightarrow (x_{0}, y_{0})}(f(x, y))^{k} = L^{k} $

Question: How exactly would I approach this? How similar is it to the method used for functions of one argument?
Answer: So I can see two approaches here.
If your $k$ is a positive integer, then it is enough to show that the limit of the product of two functions is the product of the limits. The approach is the same as for one variable.
If your $k$ is any real number (I guess if you want to allow for negative you require $L \neq 0$), you need to show that the function $G_k(x)=x^k$ is continuous on the real line. Then it follows that the composition $G_k \circ f$ is continuous on $\mathbb{R}^2$, from which the result follows. Hope it helped.


assign value from two input to a single input type hidden

Question: I am trying to get the value of first input or second input and assign it to a hidden input type. When the value updates from the above default value.
HTML
 <input id="amount2" name="s_value6" type="number" value="48">
 <input id="amount3" name="s_value11" type="number" value="500">
 <input id="mak" type ="hidden" name="distance" value="">

jQuery
if(mafsForm.find("#amount3").val().length !== 0 || mafsForm.find("#amount2").val().length !== 0) {
      var s_value11 = mafsForm.find("#amount3").val();
      var s_value6 = mafsForm.find("#amount2").val();
      var dist = $('#mak').val($(this).val());
}

Comment: simply do `$('#mak').val(s_value11+", "+s_value6 )` this will set value as comma separated.
Comment: I see typo in your code what is `makkah` or is it `mak` ? Also , what is `$(this).val()` ?
Comment: its mak just miss here
Comment: by `$(this).val()` I am trying to assign the above two values
Comment: I need one of them not both
Answer: Hope this is what you are looking for. To test this, remove 'hidden' from the hidden input field. Then change the value of any of the first two input boxes. On every change, 3rd input box will be updated with latest value. Below code only shows latest value from the last updated input box
$("#amount2, #amount3").change(function(){
    var changedVal = $(this).val();
    if(changedVal !== '0'){
      $("#mak").val(changedVal);
    }
  });

Comment: The most easy way. Thanks for your help bro!
Answer: This is a working example of pure javascript ...

<input id="amount2" name="s_value6" type="number" value="48">
<input id="amount3" name="s_value11" type="number" value="500">
<input id="mak" type="hidden" name="distance" value="">

Comment: Thanks for your help I have put the script in footer and html code in my template but its not working you can check on my site [link](https://www.ashshariyah.com/travel/umrah-packages)
Comment: I had a look, you have multiple "amount2" fields in the page, change names ? Make sure all the names are unique.
Comment: Please check it now thanks for your time I can give you access if you have time
Comment: i had another look - the problem is you have 2 "amount2"  - remove the one then it should work
Comment: your solution is to remove the 2 input fields - you already have sliders with those id's  - I did that and your page worked perfectly.
Comment: I change the ids but still no luck
Comment: can I give you access to do it for me please ?
Comment: yes sure, send me an email to: antonpublic70 @ gmail . com, with a user name and password.
Comment: i had another look and sorry to say, but you changed the wrong stuff ... send me an email or something and I will give you instructions to fix - i tried pasting it here but it's too long.
Comment: I sent email please check
Answer: The mafsForm variable was not assigned a selector in your code, so instead of mafsForm.find(selector).val() I wrote $(selector).val(). Also, I used the parseInt() method to convert the value to a number for summation. You can easily adapt this code for yourself.

$('#amount2, #amount3').on('change', function() {

  var s_value11 = $("#amount3").val();
  var s_value6 = $("#amount2").val();

  if(s_value11.length !== 0 || s_value6.length !== 0) {
        value_sum = parseInt(s_value11) + parseInt(s_value6);
        console.log(value_sum);
        var dist = $('#mak').val(value_sum);
  }

});

<input id="amount2" name="s_value6" type="number" value="48">
<input id="amount3" name="s_value11" type="number" value="500">
<input id="mak" type ="hidden" name="distance" value="">
Comment: Thanks for your reply but I need one of them either first or second
Answer: Your issue is that $(this) is referencing the window object. Here's a working solution:

var mafsForm = $('#mafsForm');
var dist;
if(mafsForm.find("#amount3").val().length !== 0 || mafsForm.find("#amount2").val().length !== 0) {
    var s_value11 = mafsForm.find("#amount3").val();
    var s_value6 = mafsForm.find("#amount2").val();
    dist = $('#mak').val(s_value11);
};

console.log(dist.val());

// Now if you want to update the value of the hidden value when changing the value of a filed you can do this
mafsForm.find("#amount3").on('input', function() {
    var s_value11 = mafsForm.find("#amount3").val();
    dist = $('#mak').val(s_value11);
    console.log(dist.val());
});

<form id = "mafsForm">
     <input id="amount2" name="s_value6" type="number" value="48">
     <input id="amount3" name="s_value11" type="number" value="500">
     <input id="mak" type ="hidden" name="distance" value="">
 </form>
Comment: Thanks for your reply and time but I want to change the hidden field by both not only one


CSS min-width and max-width and flexible layout

Question: I need some help in building a flexible html layout. I've defined minimum and maximum width of the page wrap. Inside the wrap, I have two columns, content and right.
I want to have fixed width right column. But, I want to make the content width flexible, so that depending on min-width and max-width, its width should increase or decrease.
Here's my html structure:

...

...

Here's CSS, I'm trying:
.wrap{
    min-width: 780px;
    max-width: 1140px;
    margin: 10px auto;
}

.right{
    float:left
    width: 200px;
}

.content{
    float: left;
    width: ?? //what should i do here?

}

Answer: When making floated columns in CSS there's a few things to learn.
First, the container (in your case .wrap) should also be cleared for floats.  Here's a good Stackoverflow question on "clearfix".  "Clearfix-ing" will ensure that the container height will stretch to match the longest floated column.  Useful for doing the "faux columns" design.
What methods of 'clearfix' can I use?
Second, is the need to know how many columns are you looking to do?  2 columns?  3 Columns?
There are different ways to skin that cat.  You can do 2 columns and then sub-divide one of those columns by another 2 column layout.   Or you can put 3 block containers and float each of them to a percentage of the total width.  Ie. for a 3 column layout you'd theoretically want each to be 33.33% wide (depending on how you want to do gutters or margins).
Third, you talk about "flexible layout".  Well, a flexible layout can't work with pixel width as pixels are static values.  Ie. If you say the width is 200px, it's always 200px, no matter how big or small your container or window is.
What you need to do is use percentages.  Of course, to do a correct flexible layout you want to have a base dimension.   So, you do need to have a fixed with design that you will say is your "optimal design" (I have to use that term loosely as a true flexible and responsive design should look good for the most part).
So, lets say your design is set to have the main content area .wrap be 1000px.  You want a 2 column layout using the golden ratio. http://en.wikipedia.org/wiki/Golden_ratio
Basically, you want one column to be 618px and the other to be 1000px - 618px = 382px.
For CSS you then want to set them in terms of percentages.  To get the percentage you take the parent width and divide it by the width you want.
618px / 1000px = .618 * 100(for percentage) = 61.8%
382px / 1000px = .382 * 100(for percentage) = 38.2%
.left {
    float: left;
    width: 61.8%
}

.right {
    float: right;
    width: 38.2%
}

Joseph Silber is correct, you don't need to float the right column, but not doing so can cause other unexpected issues of how the box model acts and wraps around the floated left item, especially if one is shorter than the other.
You can apply a margin to offset one column to another columns width, but I find that to just be messy and there could still be problems with poor CSS implementations in browsers (as much as I say I don't support IE6 anymore, it's still used by our visitors enough to need to support it).
Also note, when dealing with % is that you run into rounding errors.  Some browsers will round down or up when they hit ".5%".  This can cause your floated columns to wrap because it becomes 1px larger than the container element.  So, to be safe, you will want to probably shave off a little bit of the width to give you a 1-2px buffer for wrapping.
A common approach is to give an "empty" gutter or margin between the left and right column of say 10px.  And 10px in our design is:
10px / 1000px = 0.01 * 100(for percentage) = 1%
You can now take 0.5% off each column or take a full 1% off one column.  I'll just do the later.
.left {
    float: left;
    width: 60.8% /* removed 1% to give a gutter between columns */
}

.right {
    float: right;
    width: 38.2%
}

This now gives you a nice safety zone and you will avoid rounding errors.
Also, now that we're working in %, the layout will be fluid.  Your 2 columns will re-size with your browser until you hit the min/max pixel value.
Also, don't forget to "clearfix"

There are, of course, a lot of other considerations to take into account when dealing with fluid/flexible grids.
One thing you can do is not re-create the wheel but use a CSS framework like Yahoo! or Blueprint.  I believe they have these built-in and have been robustly tested.
Also, I recommend reading up on Responsive Web Design.  There's an A List Apart article on it: http://www.alistapart.com/articles/responsive-web-design/ as well as a book written by Ethan Marcotte (the other of the article and published by the ALA website) that is a great read.
The only real drawback about the book is that it didn't cover the drawbacks of a Responsive design and how, despite the "cool" factor, many big name web designers/developers have chosen to still use a separate mobile/desktop website design.
Which is slight off-topic as the original question was only talking about a fluid design and not a media target size.
Hope that helps!
Cheers!
Comment: He wanted a fixed width column, your answer doesn't allow this.
Answer: HTML:

...

...

CSS:
.right {
    float: right;
    width: 200px;
}

.content {
    padding-right: 200px; /* or margin */
    /* No need to float this */
}

Comment: @user1117313 - Unfortunately, this is the only way to do it without relying on JavaScript.
Comment: Why won't it work if I place content before the right div in HTML? How should I make that work? Thanks


SQL como fazer select em 2 colunas diferentes

Question: Estou tentando fazer um SELECT para selecionar 2 colunas diferentes da mesma tabela, exemplo:
   id   |   name   |      tags
-----------------------------------
    1   |   acao   |      null
    2   | aventura |      null
    3   |   rpg    |  acao,aventura

Tentei de diversas formas fazer este SELECT mas não consegui que funcionasse:
SELECT * FROM jogos WHERE
name LIKE "%acao%",
tags LIKE "%acao%"

Quero que quando pesquisado "acao" retorne desta forma:
   id   |   name   |       tags
-----------------------------------
    1   |   acao   |       null
    3   |   rpg    |  acao,aventura

Não tenho mais nenhuma ideia de como fazer isso funcionar.
Comment: Não falta o operador OR, não? SELECT * FROM jogos WHERE
name LIKE "%acao%" OR tags LIKE "%acao%"
Answer: Para juntar instruções na cláusula WHERE você deve usar a palavra AND:
SELECT *
  FROM jogos
 WHERE name LIKE "%acao%"
   AND tags LIKE "%acao%"

Caso queira testar a busca em qualquer uma das colunas, independente do valor da outra, utilize a palavra OR:
SELECT *
  FROM jogos
 WHERE name LIKE "%acao%"
    OR tags LIKE "%acao%"

Comment: Usando desta forma ele não me retorna nada de nenhum dos campos, usando `AND` a linha precisa ter "acao" tanto no campo name como no tag para retornar algo. Usando "OR" funcionou, não acredito que esqueci disso hahahahh
Comment: Veja com o `OR`


Brew on MacOs for PhP version

Question: i need to install Homebrew on MacOs to upgrade my php version with :
-
echo 'export PATH="/email@example.com/bin:$PATH"' >> ~/.bash_profile
echo 'export PATH="/email@example.com/sbin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

but when i try to install to install homebrew i don't see some change i try this :
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
from homebrew doc site but when i use that i dont see where brew was instal and zhs says again that brew is not found so
Answer: Homebrew is normally installed in /usr/local (or if you're using an M1 Mac, /opt/homebrew).
Try running /usr/local/bin/brew or /opt/homebrew/bin/brew. If neither of those work, there was most likely a failure during the installation of Homebrew. What was the output you got when you ran the install command?
Comment: I dont fint it in usr/bin/local when i started the instalation its says that the script explains what it will do and then pauses before it does it. But when i run the cmd for installation its says that i need to press return to continue but it dosnt work :
```Press RETURN to continue or any other key to abort
XXXXX@MacBook-Air-XXXXXX ~ %  ```
Comment: J'ai trouvé j'inversais la touche return j'appuyais sur retour arrière au lieu d'entrée persuadé par ma connerie merci :)

Brew on MacOs for PhP version


Why I get high observation when I generate data from t-distribution in R

Question: I want to generate 200 samples from t-distribution with the degree of freedom=1 and sample size is 10 and in R
I use this code
set.seed(1234)
B <- matrix(rt(10*200, 1), 200)

But when I see the sample number 167 (B[167,]) I found this high number 602.1691029
And this strange thing in the t-distribution. What is wrong here?
Comment: Bottom line, *nothing is wrong*. This is how the student's t distribution (among many) works: while a low-probability, it is definitely feasible to get really high (positive) or really low (negative) numbers with a small sample such as this.
Comment: The support of the t-distribution is `-Infinity` to `Infinity`, even though is rare is it possible to generate very high ou very low numbers
Comment: See `set.seed(667); matrix(rt(10*200, 1), 200)[90,]` (it includes `-636967`).
Comment: ... or `set.seed(9586); matrix(rt(10*200, 1), 200)[150,]` (`-2264546`).
Comment: Further context: while many things claim that something is Normally distributed (e.g., [human height](https://ourworldindata.org/human-height)), it's rarely in fact perfectly true. If that were true, then: (1) height could be negative; (2) height could be zero; (3) height could be infinite; (4) humans could be 1mm tall; etc. While there is claim to a [16ft tall human](https://www.guinnessworldrecords.com/records/hall-of-fame/robert-wadlow-tallest-man-ever), I hardly expect a 200ft tall human. Perhaps it should be "truncated-Normal"?
Comment: Have a look at [What is the difference between finite and infinite variance](https://stats.stackexchange.com/questions/94402/what-is-the-difference-between-finite-and-infinite-variance/100161#100161)
Answer:
And this strange thing in the t-distribution.

No, it isn't, not with $1$ degree of freedom.
The tails in the Cauchy are so heavy even its mean is undefined (not finite). Very, very large deviations happen reasonably often -- the more values you generate the bigger the largest-magnitude value will tend to be; indeed with the Cauchy it grows roughly linearly with sample size (e.g. $\text{median}({\max_i}(|X_{i}|))$ increases approximately in proportion to $n$; with $2000$ standard Cauchy values the median of the distribution of the largest-magnitude one is over $1800$ and the median of the distribution of the second-largest-magnitude observation is over $750$).
Note that $P(|X|\geq 602)\approx 0.001$. If you generate $2000$ of them you expect roughly about $2$ of those observations to be at least that large in magnitude.
Rather than being surprised to see one of that size, you would often see even larger ones.

What is wrong here?

Nothing, this is typical. You might like to read more about the Cauchy and other t distributions with low d.f.
https://en.wikipedia.org/wiki/Cauchy_distribution
https://en.wikipedia.org/wiki/Student's_t-distribution
A number of posts on site here discuss interesting properties of the Cauchy ($t_1$) distribution.
Comment: If I recall correctly from the uniform distribution the median of the largest order statistic  comes out to $\frac12^{1/n}$, so you would just take $F^{-1}$ of that. Which looks to correspond. That it then comes out almost proportional to $n$ isn't then hard to see.
Comment: +1 This is an important rejoinder to the comments, all of which (at present) suggest $602$ is *possible* (or "feasible") but *unusual.*  As you show, absolute values this large are to be *expected* in the sample.
Comment: (+1). Indeed, the median of the maximum of $n$ absolute values of a standard cauchy rv is $\tan(2^{-1-1/n}\pi)$ according to Mathematica.
Comment: Thanks. It should be possible to derive the exact value pretty directly from the transformed median of a beta (specifically one with second-shape parameter $\beta=1$ -- so it should be fairly doable once you account correctly for the $|X|$ part), but I figured the exact value was not needed.
Answer: Number 135 is even larger.
I guess the problem comes from the fact you're using df = 1, which looks odd. Because the uncertainty is just too large with one observation..
You won't get these large numbers starting at e.g. df = 5.
Comment: You could expand on this.  `df=1` represents a **Cauchy distribution**, which has an infinite mean (and thus this behaviour is entirely expected).
Comment: @BenBolker "infinite" or just "undefined"?
Comment: @Ben An accurate and useful characterization is that the Cauchy distribution has an infinite *absolute* first moment.  Therein lies the source of the difficulties.  The variance need not be defined as variation around a mean, btw: it can be expressed in terms of the expectation of $(X-Y)^2$ where $(X,Y)$ are *iid.*  However, when the mean is undefined, perforce the variance will be infinite.
Comment: Technically, undefined, I guess.  It's all a mess.  It would be nice to describe the Cauchy as having an "infinite variance" (which, naively, is it how it seems to behave), but that doesn't make sense since the variance is the variation around the (undefined) mean ...


What is this scratchy sound on the acoustic guitar called?

Question: This is surely a basic question, but I have no idea about guitars.
Take the following song as an example:

At the 7 second mark, but more prominently between 8 and 9 seconds (and many other times) you can hear some kind of "transitioning" screechy sounds.
Does this have a name? Is it intentional and part of the music or an undesirable byproduct? It seems to give some "texture" to the sound, but I have no idea. I do hear it often in many songs though.
Answer: It's caused by sliding the fingers along the wound (usually bottom three or four) strings. It often can't be helped, and is just part of guitar playing. There are strings available that are smoother, so don't produce anywhere near that sort of string noise, and some modern players use a plectrum to make those sounds on purpose.
It's never actually prescribed for most performances on guitar, and more discerning (?) players will try to avoid making those sounds.
String noise or string scratch is about as technical a term as it gets.
Comment: "Fret noise" is the term I've heard and read most often.
Comment: @ToddWilcox - could be. Another misnomer, as it really has nothing to do with frets themselves. I suppose it follows tremolo and vibrato - it wasn't coined by a Mr. Fender, was it..?
Comment: Probably helped along by the fact that one of the 128 General MIDI instrument numbers (#121) is "Guitar Fret Noise".
Comment: I think "fret noise" is a shortened version of a phrase like, "the noise made when changing frets or when fretting notes". Also, it seems to be more recording engineers who use the term "fret noise" than musicians, so perhaps that's not the most helpful term.
Answer: I have always called it string squeak. It is particularly noticeable on acoustic guitars. It seems that others use the term.
How to get rid of guitar string squeak
Answer: I don't think it has a name.
It's an unintentional byproduct but for many it's strangely comforting element of music as it adds a bit of grit and "natural" feel to the performance.
In classical guitar world modern players rather strive to minimize those sounds and a fluid and quiet transitions are a mark of modern virtuosos. As an example check out Marcin Dylla performances.
Comment: There are some rock songs that use this sound purposefully.
Comment: Yes but then it's something different and it even has a name (pick slide or pick scrape)