Inserir virgula automaticamente enquanto digita

Question: Quando se digita um valor, ha alguma forma de ja efetuar a correção inserindo virgulas e pontos ao vivo??
EX: pressionei 4 + 3 + 6 no teclado
Input ja mosta = 4,36
EX: pressionei 4 + 3 + 6 + 8 + 8 + 8 no teclado
Input ja mosta = 4.368.88
Consegui fazer usando o plugin mask do jquery, mas gostaria de saber se é possível usando jquery, sem plugins.
$( '#preco' ).keyup( function() {
   $('#preco').mask("#.###,##", {reverse: true});
});

Answer: Sempre utilizo essa funçãozinha que vou deixar aqui na resposta. Ela dispensa o uso de plugins e é feita com um simples jQuery.
Serve para CPF, CNPJ e outros diversos tipos de formatações que você quiser.
Você pode até mesmo criar sua formatação própria, de acordo com sua necessidade. Assim como eu fiz com "INSCRIÇÃO ESTADUAL" quando precisei.

//Essa função é para verificar se o valor passado pelo input é String. Se for String não é aceito (é apagado)
function MascaraInteiro(num) {
  var er = /[^0-9/ ().-]/;
  er.lastIndex = 0;
  var campo = num;
  if (er.test(campo.value)) { ///verifica se é string, caso seja então apaga
    var texto = $(campo).val();
    $(campo).val(texto.substring(0, texto.length - 1));
    return false;
  } else {
    return true;
  }
}

//Formata de forma generica os campos (Essa é a função que realmente formata os campos, com a exceção do campo de MOEDA)
function formataCampo(campo, Mascara) {
  var boleanoMascara;

  var exp = /\-|\.|\/|\(|\)| /g
  var campoSoNumeros = campo.value.toString().replace(exp, "");
  var posicaoCampo = 0;
  var NovoValorCampo = "";
  var TamanhoMascara = campoSoNumeros.length;
  for (var i = 0; i <= TamanhoMascara; i++) {
    boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") ||
      (Mascara.charAt(i) == "/"))
    boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(") ||
      (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
    if (boleanoMascara) {
      NovoValorCampo += Mascara.charAt(i);
      TamanhoMascara++;
    } else {
      NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
      posicaoCampo++;
    }
  }
  campo.value = NovoValorCampo;
  ////LIMITAR TAMANHO DE CARACTERES NO CAMPO DE ACORDO COM A MASCARA//
  if (campo.value.length > Mascara.length) {
    var texto = $(campo).val();
    $(campo).val(texto.substring(0, texto.length - 1));
  }
  //////////////
  return true;
}

//Essa função é para o caso da formatação ser em MOEDA. Entao você deverá chamá-la no INPUT.
function MascaraMoeda(i) {
  var v = i.value.replace(/\D/g, '');
  v = (v / 100).toFixed(2) + '';
  v = v.replace(".", ",");
  v = v.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
  v = v.replace(/(\d)(\d{3}),/g, "$1.$2,");
  i.value = v;

}

//O segundo parâmetro desta função, é o nome que você coloca lá na chamada dela no INPUT. Isso determina em qual condicional (if, else if, else) a função entrará e qual formatação ela executará.
function MascaraGenerica(seletor, tipoMascara) {
  setTimeout(function() {
    if (MascaraInteiro(seletor)) {
      if (tipoMascara == 'CPFCNPJ') {
        if (seletor.value.length <= 14) { //cpf
          formataCampo(seletor, '000.000.000-00');
        } else { //cnpj
          formataCampo(seletor, '00.000.000/0000-00');
        }
      } else if (tipoMascara == 'DATA') {
        formataCampo(seletor, '00/00/0000');
      } else if (tipoMascara == 'CEP') {
        formataCampo(seletor, '00.000-000');
      } else if (tipoMascara == 'TELEFONE') {
        formataCampo(seletor, '(00) 0000-0000');
      } else if (tipoMascara == 'CELULAR') {
        formataCampo(seletor, '(00) 00000-0000');
      } else if (tipoMascara == 'INTEIRO') {
        formataCampo(seletor, '00000000000');
      } else if (tipoMascara == 'CPF') {
        formataCampo(seletor, '000.000.000-00');
      } else if (tipoMascara == 'CNPJ') {
        formataCampo(seletor, '00.000.000/0000-00');
      } else if (tipoMascara == 'INSCRICAOESTADUAL') {
        formataCampo(seletor, '00.000.00-0');
      }
    }
  }, 200);
}

CNPJ:
<input onKeyPress="MascaraGenerica(this, 'CNPJ');" type="text">

CPF:
<input onKeyPress="MascaraGenerica(this, 'CPF');" type="text">

CEP:
<input onKeyPress="MascaraGenerica(this, 'CEP');" type="text">

MOEDA:
<input onKeyPress="MascaraMoeda(this);" type="text">

CELULAR:
<input onKeyPress="MascaraGenerica(this, 'CELULAR');" type="text">

TELEFONE:
<input onKeyPress="MascaraGenerica(this, 'TELEFONE');" type="text">

INSCRIÇAÕ ESTADUAL:
<input onKeyPress="MascaraGenerica(this, 'INSCRICAOESTADUAL');" type="text">

Evento keypress -> O evento keypress é disparado quando uma tecla que produz um valor do tipo caractere é pressionada.
O código dá resposta poderia ter ficado bem menor, se eu respondesse só a questão levantada na pergunta. Mas eu preferi deixar a resposta mais completa e abrangente.
Segue o link para futura consulta: Github
Assim que eu achar o site onde achei essa função, prometo referenciar aqui.
Espero que ajude!
Answer: Você pode utilizar o JQuery.mask e passar o formato que você deseja, exemplo:
$('.classeNoInput').mask("#.##0,00", {reverse: true});
Segue o link da documentação
Essa solução serve para outros formatos também como data, cep, telefone e etc.
Comment: a parte ao vivo nao funciona usando ele     $( '#preco' ).keyup( function() {
        $('#preco').mask("#.###,##", {reverse: true});
    });
Comment: nao tem necessidade de usar keyup, ele faz automaticamente, só precisa aplicar a mascara no input
Answer: **Use a biblioteca

jquery e jquery.maskMoney.min.js
**

No seu script fica  :
**
$("#valorPrimeiroPedido").maskMoney({
        prefix: "R$:",
        decimal: ",",
        thousands: "."
    });

no Html
<input class="form-control" type="text" id="valorPrimeiroPedido"  />

Answer: Fala Arsom, tudo beleza? (:
Cara, não sei como faria com jQuery, porém no JavaScript puro a partir do ECMAScript 6 tem uma funcionalidade especifica para fazer essa conversão, e ela tem alguns atributos bem bacanas. Segue o exemplo:
Primeiro eu declaro uma variável, que vai receber o valor em dinheiro (no nosso exemplo, 1.000,00).
var din = 1000;

Depois disso, vou invocar a funcionalidade que vai realizar essa conversão, passando a nossa variável declarada acima por parâmetro:
new Intl.NumberFormat('pt-BR',
  { style: 'currency', currency: 'BRL' }
).format(din); // "R$ 1.000,00"

Pronto! A função vai retornar o valor formatado e convertido em Reais. (:
Você pode alterar os atributos para converter para outras moedas do mundo todo. E não tem problema você usar junto com seu código em jQuery, afinal, no fim das contas é tudo JavaScript. XD
Se quiser saber um pouco mais sobre, vou deixar aqui o link do artigo que eu li falando sobre, segue: https://www.samanthaming.com/tidbits/30-how-to-format-currency-in-es6/
Espero ter ajudado, abração!


if hermitian matrices can not have complex eigen values, then what is this? kindly explain

Question: I encountered the following and I am puzzled!... where am I wrong?
basic definition of hermitian matrix $H$ is
$H=H^*$
if I take the outer product of the following complex vector V and its conjugate I get this
$V=\begin{bmatrix}{\rm e}^{j d_1},&  {\rm e}^{j d_2},& {\rm e}^{j d_3}, &\ldots,& {\rm e}^{j d_N}\end{bmatrix}^{\rm T} $
$V^*=\begin{bmatrix}{\rm e}^{-j d_1},&  {\rm e}^{-j d_2},& {\rm e}^{-j d_3}, &\ldots,& {\rm e}^{-j d_N}\end{bmatrix} $
therefore
$$H = V V^* = \begin{bmatrix}
1 & {\rm e}^{j (d_1 - d_2)} & {\rm e}^{j (d_1 - d_3)} & \ldots & {\rm e}^{j
(d_1 - d_N)} \\
{\rm e}^{j (d_2 - d_1)} & 1 & {\rm e}^{j (d_2 - d_3)} & \ldots & {\rm e}^{j (d_2 - d_N)} \\
{\rm e}^{j (d_3 - d_1)} & {\rm e}^{j (d_3 - d_2)} & 1 & \ldots & {\rm e}^{j (d_3 - d_N)} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
{\rm e}^{j (d_N - d_1)} & {\rm e}^{j (d_N - d_2)} & {\rm e}^{j (d_N - d_3)} & \ldots & 1
\end{bmatrix}$$
Now testing $H$ it is a hermitian, $H=H^*$.
However its determinant is zero, i.e. it is singular.
Testing for eigenvalues, we get one eigenvalue as zero and the rest is not zero.
For any $N$
the charcteristic equation has the following form regardless of changes in the values of  variables $d_n$.
{[(1-lambda)^N]+(N-1)}-N=0
[(1-lambda)^N]-1= zero
this equation results in a one zero eigenvalue and the rest are both real eigen values and pairs of complex conjugates...if these add...the trace is always real value since the complex conjugates when added produce real values
I am confused... I am having complex eigen values for a hermitian matrix that satisfies all the definition properties?? kindly help...with refernces please
Comment: How did you compute the eigenvalues? It seems something must have gone wrong there. Your matrix is an outer product of two vectors, hence it is rank one. Therefore, it has one eigenvalue that is non-zero and all others are zero. The non-zero one should be equal to $N$.
Comment: I computed my eigen valuesby getting the charcteristic equation as determinant of ( H-lambda*Ìdentity matrix)=0.                                        it gives me along the diagonal (1-lambda)...when computing the determinant by the conventional method... diagonals result in (1-lambda)^N....other generated values are ones (N-1)  minus N see the generated equation above...I tested this result manually and is willing to see if your test gave different results
Comment: Please don't send me files. ;-) I think there is no need to. What software are you using? In Matlab, it's these two lines: v = exp(j*d(:)); disp(eig(v*v'));
Answer: Your matrix $\mathbf H$ is equal to $\mathbf H = \mathbf v \mathbf v^*$. Therefore, it is easy to see that it has one eigenvalue equal to $\left\|\mathbf v\right\|^2 = N$, since: $$\mathbf H \cdot \mathbf v = \mathbf v \cdot \mathbf v^* \cdot \mathbf v  = \|\mathbf v\|^2\cdot\mathbf v.$$
All other eigenvalues are zero since your matrix is rank one.
If you are getting complex eigenvalues then very likely something has gone wrong in their computation.
Comment: I am surprised and puzzled because I am aware of this...
Comment: thanks...it is ckear now (I do things the old way...leaving computer program to last steps :-)...)


How Use a Property of a Model in Eloquent Querying Relations

Question: I have three Models. University, Professor and Student.
They have some relations.

University Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class University extends Model
{
    protected $fillable = ['name', 'user_id'];

    /**
     * Get the user that owns the university.
     */
    public function owner()
    {
        return $this->belongsTo(User::class);
    }
}

Professor Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\University;
use App\Models\Student;

class Professor extends Model
{
    protected $fillable = ['name', 'surname', 'university_id'];

    /**
     * Get the university where the professor teaches.
     */
    public function university()
    {
        return $this->belongsTo(University::class);
    }

    /**
     * Get the student associated with the professor.
     */
    public function student()
    {
        return $this->hasOne(Student::class)->withDefault();
    }
}

Student Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\University;
use App\Models\Professor;

class Student extends Model
{
    protected $fillable = ['name', 'surname', 'age', 'university_id', 'professor_id'];

    /**
     * Get the university where the student is studying.
     */
    public function university()
    {
        return $this->belongsTo(University::class);
    }

    /**
     * Get the professor of the student.
     */
    public function professor()
    {
        return $this->belongsTo(Professor::class);
    }
}

Every professor belongs to a university.
Every student belongs to a university.
Every student has exactly one professor, but a professor may not have a student.
The Question :
How can I have a list of students who are at the same university with their professor?
The following code is incorrect!
$students = Student::select('id', 'name', 'surname', 'age', 'university_id')
->whereRelation('professor', 'university_id', '=', ***'student.university_id'***)
->with(['university', 'professor'])
->orderBy('id', 'desc')
->paginate(20);

Thanks.
Comment: in what case would a student be at a different university than their professor?
Comment: maybe A visiting professor at a university
Answer: If you pass the $universityId, you should follow the 1st example. Otherwise, you can get all students by grouping university_id
1st example:
$students = Student::with(['university', 'professor'])
              ->where('university_id', '=', $universityId)
              ->orderBy('id', 'desc')
              ->paginate(20);

2nd example:
$students = Student::with(['university', 'professor'])
              ->groupBy('university_id')
              ->orderBy('id', 'desc')
              ->paginate(20);


Como criar um elemento com níveis e depois adicionar elementos em um dos seus subníveis com jquery?

Question: Preciso criar o objeto com a  estrutura abaixo e inserir options.

 myElem = $("

 Teste
<select id='multiple-selected' multiple='multiple'>

");

E depois inserir option nesse objeto.
Não quero fazer concatenando texto puro (montando o html na mão).
Tem como fazer isso com append? Pensei no appendTo() mas o objeto ainda não foi inserido no html alguém teria uma dica?
Answer: Mesmo sem o elemento estar inserido no DOM podes usar os métodos do jQuery.
Testa com var $select = myElem.find('select');
var myElem = $("

 Teste
<select id='multiple-selected' multiple='multiple'>

");
var $select = myElem.find('select');
console.log($select); // dá [select#multiple-selected, prevObject: jQuery.fn.init[1], context: undefined, selector: "select"]


In △PQR, ∠PRQ=60° and PS=SR. If ∠PQS=x°, compare x with 60

Question:
In △PQR,  ∠PRQ=60° and PS=SR. If ∠PQS=x°, compare x with 60 (i.e, greater, equal or the relation can't be determined)
To keep ∠PRQ fixed, I first thought of an equilateral triangle, so that x=30°. Now if I increase angle ∠QPR, angle ∠PQR will decrease. Though I don't understand here whether ∠PQS will be greater than 30° or less than 30°. But, ∠PQS will definitely be less than 60°. Now if I extend RP to the left, let upto T point, so that ∠QPR decreases, while ∠PQR will increase, in which case I think ∠PQS (=x) can be greater than 60°.
But, can't grasp the whole picture here. Can anyone clarify, how to deal with it?
Comment: In fact, the largest possible value of $ x^{\circ} $ is $ \cos^{-1} \! \left( \dfrac{9 \sqrt{2} - 1}{14} \right) = 33.10104 \ldots^{\circ} $.
Answer: Consider a circle $\omega$ passing through points $P$ and $S$ that is tangent to line $RQ$ at point $X$. Then $Q$ lies outside the circle or coincides with $X$. Therefore $$\angle PQS \le \angle PXS.$$

The problem reduces to showing that $\angle PXS < 60^\circ$.
Since $\angle RPX = \angle RXS$ and $\angle XRP = \angle SRX$, triangles $RPX$ is similar to triangle $RXS$. Therefore $$\frac{PR}{RX}=\frac{RX}{RS}$$ which implies $XR^2 = PR \cdot SR = 2SR^2$. Denoting $SR=x$ we find $PR=2x$ and $XR = \sqrt 2 x$.
Let $PX = y$. Using law of cosines in triangle $PXR$ we calculate
$$y^2 = (2x^2) + (\sqrt 2 x)^2 - 2 \cdot 2x \cdot \sqrt 2 x \cdot \cos 60^\circ = (6-2\sqrt 2)x^2.$$
Using similarity of $RPX, RXS$ again we get $\frac{XS}{PX} = \frac{XR}{PR} = \frac 1{\sqrt 2}$.
Finally, law of cosines in triangle $PXS$ yields
$$\cos \angle PXS = \frac{y^2 + \left(\frac{y}{\sqrt 2}\right)^2-x^2}{2\cdot y \cdot \frac{y}{\sqrt 2}} = \ldots = \frac{9\sqrt 2-1}{14}.$$
$\cos$ is a decreasing function on $[0,\pi]$ so you only need to check that $\cos \angle PXS > \cos 60^\circ = \frac 12$. I'll leave it to you.
More geometric way:
As we calculated above, $y^2 = (6-2\sqrt 2)x^2 > 2x^2$, therefore $XP>XR$. Therefore $\angle PXS < \frac 12 \angle PXR$. This is because the angle bisector of $PXR$ cuts $PR$ in a point $Y$ such that $$\frac{PY}{YR} = \frac{PX}{XR} >1$$

(this is called angle bisector theorem). So
$$\angle PXS < \frac 12 \angle PXR = \frac 12 (180^\circ - \angle XRP - \angle RPX) = \frac 12(120^\circ - \angle RPX) < \frac 12 \cdot 120^\circ = 60^\circ.$$
Comment: I'll attach a picture, maybe it will be clear then
Comment: Thank you for replying, but I din't understand! can you please clarify a bit?
Comment: I finished the proof. What exactly don't you understand?
Comment: I missed it from the beginning-- "Consider a circle ω passing through points PP and SS that is tangent to line RQ at point X. Then Q lies outside the circle or coincides with X"
Comment: Using coordinate geometry, one can show that the largest possible value of the angle is $ \cos^{-1} \! \left( \dfrac{9 \sqrt{2} - 1}{14} \right) = 33.10104 \ldots^{\circ} $.
Comment: Transcendental, you're right, I made a mistake in my calculations. I'll edit the answer


PHP fopen() function does not create a file

Question: I am trying to create a file in my PHP application using the following code:
$file = @fopen(Data::$FILE_PATH, 'w'); //I also tried with 'x'
if(!$file)
{
    new ErrorReporter('Error 3');
    return;
}

It always displays the Error 3 text.
PHP script has chmod 777, I tried to make $FILE_PATH:

/var/www/data.json
/var/data.json
/root/data/data.json
/var/test/data.json

But none of the following worked, the file is never created.
I tried to make a file manually and I debugged it using the following function:
    private function debug()
    {
        $file = Data::$FILE_PATH;

        error_reporting(E_ALL);
        ini_set('display_errors', true);
        echo 'phpversion: ', phpversion(), "\n";
        echo 'uname: ', php_uname("s r"), "\n"; // name/release of the operating system
        //echo 'sapi: ', php_sapi(), "\n";

        echo $file, file_exists($file) ? ' exists' : ' does not exist', "\n";
        echo $file, is_readable($file) ? ' is readable' : ' is NOT readable', "\n";
        echo $file, is_writable($file) ? ' is writable' : ' is NOT writable', "\n";

        $fp = fopen($file, 'w');
        if ( !$fp ) {
            echo 'last error: ';
            var_dump(error_get_last());
        }
        else {
            echo "ok.\n";
        }
        die('done');
    }

The file:

existed
is readable
ISN'T WRITABLE

The error that appears in the debug function is:
failed to open stream: Permission denied in /path/to/the/file on line 108
Line 108 content:
$fp = fopen($file, 'w');
But as I previously said, chmod of the script is 777 and $FILE_PATH file is 664.
Can anyone help me in this case?
Comment: you are not allowed to write in these directories...  it couldn't be more obvious or could be better explained nobody can "fix" for you, use another directory in which you're allowed to write.
Comment: Even in /var/www/data.json?
Comment: The permissions of the script file are irrelevant. It's the permissions of the folder you're attempting to write to that matters, as well as what "user" the script is running as.
Answer: After some tries, I finally found a solution:
I had to change chmod of the destination folder. I did 777, but you can find more secure chmods.
So as a summary - you need to change permissions of a PHP script and the destination folder.


$\log_6(x)= \log_6(x-1)-\log_6(2)$ Solve for X

Question: $\log_6(x)= \log_6(x-1)-\log_6(2)$  I have to solve for x.  Is $\log(a) = \log(b)$ a logarithm rule?  I was wondering why the equation can only have 1 log on one side of the equal sign and one log on the other side?
This method works $$\log_6(x)=\log_6\bigg(\frac{x+1}{2}\bigg)$$
The next steps are are easy just solve $$x = \bigg(\frac{x+1}{2}\bigg)$$ $$2x=x+1$$ $$x=1$$
I understand when subtracting logs with the same base the log can be simplified into a quotient or when adding two logs the logs can be simplified into a product.  I guess that is a good thing.  The log rules are different than algebra and may be this is just the standard order of treating logs with the same base.
I was following this hyper link while studying and was looking to see why an equation has to  be stated as log(a) = log(b) before x can be solved for?  Help with logarithms website
Comment: In the original equation, you wrote $\log_6(x - 1)$.  You later changed it to $\log_6(x + 1)$.  Check your work.
Comment: In the title, there's an equation in $x$, which we are asked to solve for $X$. This is impossible to do, unless we are given some relation between $x$ and $X$.
Answer: Demand $x>0$ and $x>1$,then rewrite the Eq.
$$\log_6 x=\log_6 \frac{(x-1)}{2}
\implies 2x-(x-1)=0 \implies x=-1.$$
So no solution as it contradicts the demand.
Answer: since the logarithm function is an injection we have log a = log b and we have log a - log b = log a/b
therefore:
$$\log_6 x = \log_6 (x-1) - \log_6(2) = \log_6(\frac{x-1}{2}) \Rightarrow x = \frac{x-1}{2} \Rightarrow x = -1 $$
but since the domain of the logarithm is $\mathbb{R}^+$ there are no solutions.


How this c program is evaluating

Question: #include <stdio.h>
#define dprintf(expr) printf(#expr "=%d\n",expr)

int main()
{
    int x=7;
    int y=3;
    dprintf(x/y);
    return 0;
}

I am getting output as x/y=2
I am confused how "x/y" is getting printed
Comment: That's what the `#` stringizing operator (which works only in macro definitions) does. Consult any C decent reference for more information. http://en.cppreference.com/w/cpp/preprocessor/replace (scroll down to **# and ## operators**).
Comment: What you expect from `printf("x/y" "=%d\n",x/y);` ?
Comment: its #expr how is it evaluating to "x/y" it should be #x/y
Comment: http://msdn.microsoft.com/en-us/library/7e3a913x.aspx
Comment: If you want `#x/y` to be printed you need `printf("#" #expr "=%d\n", expr)`
Comment: [ISO/IEC 9998/1999](http://cs.nyu.edu/courses/spring13/CSCI-GA.2110-001/downloads/C99.pdf)$18.104.22.168
Answer: In a macro the # stringifies the operands so #expr will take the arguments and turn them into a string and since adjacent string literals are concatenated it will be then be concatenated to "=%d\n" so you end up with:
printf( "x/y" "=%d\n",expr)

which will become:
printf( "x/y=%d\n",expr)

For complete sake from the draft C99 draft standard section 18.104.22.168 The # operator paragraph 2 covers the # it is rather long and hard to read so I won't quote it but section 184.108.40.206 Translation phases paragraph 6 says:

Adjacent string literal tokens are concatenated
Answer: dprintf(x/y);

expands to
printf("x/y" "=%d\n", x/y);

which is evaluated as:
printf("x/y" "=%d\n", 7 / 3);

now since x and y are integers, the result of x/y is 2 (an integer)
so the output is x/y=2
Note the c preprocessor # directive replaces #expr with "expr".
Note also the c compiler will simply concatenate adjacent string literals into one string, i.e. printf("Hello " "World\n"); is equivalent to printf("Hello World\n");
see http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification for more details.

How this c program is evaluating


Method for importing System.Data.Dataset XML file into SQL Server using T-SQL

Question: Background: I am updating scripts in PowerShell that routinely export large amounts of data from a non-MS database to SQL Server on a different host.
On the export side, I have chosen the .NET System.Data.Dataset object as the format for the data. The transfer file is created using the WriteXml method with the WriteSchema option. This approach supports multiple tables and retains database schema information for the receiving server all in a single file.
Per request, a basic DataSet file might be:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="table1">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="col1" type="xs:string" minOccurs="0" />
                <xs:element name="col2" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element name="table2">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="col1" type="xs:string" minOccurs="0" />
                <xs:element name="col2" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <table1>
    <col1>tkshrq</col1>
    <col2>6krrtq</col2>
  </table1>
  <table1>
    <col1>k60stu</col1>
    <col2>sqnhp9</col2>
  </table1>
  <table2>
    <col1>6k1thw</col1>
    <col2>n2ocgz</col2>
  </table2>
  <table2>
    <col1>26kmw5</col1>
    <col2>ym3iwd</col2>
  </table2>
</NewDataSet>

On the receiving side, I have an import script that utilizes Write-SqlTableData to bulk load tables from the DataSet file into temporary tables and then run a stored procedure to provide transaction isolation while data moves to the "live" tables.
I am hoping to find a method to directly access the DataSet file from within T-SQL so the import can be done by a single stored procedure.
I am aware how to set up linked servers for flat, "rowset" files (CSVs, DataTable, etc) and query them with OPENROWSET. But I have not been successful in accessing the multi-tabled DataSet file.
I am not interested in changing the transfer file format. It has several desired features and I'd rather deal with a zillion temporary tables than wrangle a zillion transfer files.
I am also aware of third party XML ODBC providers for SQL Server. But third party software is not permissible in this instance.
Comment: Please provide a minimal sample of your Dataset XML file.
Answer: Please try the following solution.
It is using T-SQL and XQuery methods .nodes() and .value().
I saved your XML as 'e:\Temp\NewDataSet.xml' file.
SQL Server XML data type can hold up to 2GB size wise.
If the performance of the suggested method is not that good, depending on the volume of the data, it is possible to load the entire XML file into a temporary table with one row and one column.
SQL
DECLARE @tbl1 TABLE (ID INT IDENTITY PRIMARY KEY,  col1 VARCHAR(50), col2 VARCHAR(50));
DECLARE @tbl2 TABLE (ID INT IDENTITY PRIMARY KEY,  col1 VARCHAR(50), col2 VARCHAR(50));

DECLARE @xml XML;

SELECT @xml = XmlDoc
FROM OPENROWSET (BULK N'e:\Temp\NewDataSet.xml', SINGLE_BLOB, CODEPAGE='65001') AS Tab(XmlDoc);

INSERT INTO @tbl1 (col1, col2)
SELECT c.value('(col1/text())[1]', 'VARCHAR(50)') AS col1
   , c.value('(col2/text())[1]','VARCHAR(50)') AS col2
FROM @xml.nodes('/NewDataSet/table1') AS t(c);

INSERT INTO @tbl2 (col1, col2)
SELECT c.value('(col1/text())[1]', 'VARCHAR(50)') AS col1
   , c.value('(col2/text())[1]','VARCHAR(50)') AS col2
FROM @xml.nodes('/NewDataSet/table2') AS t(c);

-- test
SELECT * FROM @tbl1;
SELECT * FROM @tbl2;

Output
Table1
+----+--------+--------+
| ID |  col1  |  col2  |
+----+--------+--------+
|  1 | tkshrq | 6krrtq |
|  2 | k60stu | sqnhp9 |
+----+--------+--------+

Table2
+----+--------+--------+
| ID |  col1  |  col2  |
+----+--------+--------+
|  1 | 6k1thw | n2ocgz |
|  2 | 26kmw5 | ym3iwd |
+----+--------+--------+

Comment: Nice, @Yitzhak!  I'll play with this and let you know. -thanks
Comment: Thanks, Yitzhak. As asked, this is a good solution so I accept it.  For my purposes, however, I cannot use it.  I need a solution that will import the schema from `DataSet` object as well as the data and was hoping for some means of establishing a linked server to the `DataSet` file such that column typing is implicit in a query.  I am baffled, given that these are both MS domains, that I can find no documentation on how to perform this obvious task.
Comment: @Frobozz, as an alternative solution it is possible to generate `INSERT` statements as a dynamic SQL on the fly from the `` fragment.
Comment: If it can be wrapped in a transaction and adapt to the source schema changing (which will happen), I am very interested in any example you can offer.
Comment: @Frobozz, Please ask it as a separate new question.


Single view on multiple pages

Question: 1) I created a content type Portfolio-Item. In this type a text field Project-Url was defined.
2) I created a view containing a gallery using jQFX module displaying content of Portofolio-Item elements which where published.
I wan't to add this view to different pages containing different projects portfolios.
a) Is it possible to add a "filter criteria" or "contextual filter" that would compere the Project-Url field with page URL and filter available Portfolio-Item's to display only proper one's. ?
b) Is there any easy way to achieve this?
c) Can contextual filter's be used with regular expressions?
Answer: I would recommend you to use a Viewfield or the EVA Module. With both of them you can attach a view to an entity and add arguments. I personally prefer EVA to do stuff like this. Very handy and allows you to use the same in different contexts without exposing it to the site admin directly.
Answer: Install the sandbox project Views arguments in filters (download it via Git)
With this module you can move a contextual filter down into the normal filters so that everything that you can do with normal filters can then be applied to the contextual filter.

How to use this module
To make use of this module, configure your view as usual, but use the
  following steps when adding arguments.

Use the argument "Global: Null" to denote the input arguments your    view will make use of. This argument not alter your query in any way,
  but you can still use validators and actions if no argument is
  present as usual. And title, breadcrumbs, et cetera. Sweet.
Add a filter, and instead of adding a filter value manually, you    enter %1, %2, et cetera to filter on the first or second input
  argument. That's it!

Single view on multiple pages


Is there a measure on any measurable space $(X,\mathcal{S})$? ("Measure, Integration & Real Analysis" by Sheldon Axler.)

Question: I am reading "Measure, Integration & Real Analysis" by Sheldon Axler.
Let $X$ be a set.
Let $\mathcal{S}$ be a $\sigma$-algebra on $X$.
Then, $(X,\mathcal{S})$ is called a measurable space. (See the following definition in this book.)

The word measurable is used in the terminology below because in the next section we introduce a size function, called a measure, defined on measurable sets.

2.26 Definition measurable space; measurable set

A measurable space is an ordered pair $(X,\mathcal{S})$, where $X$ is a set and $\mathcal{S}$ is a $\sigma$-algebra on $X$.
An element of $\mathcal{S}$ is called an $\mathcal{S}$-measurable set, or just a measurable set if $\mathcal{S}$ is clear from the context.

$(\mathbb{R},\mathcal{B})$ is a measurable space and outer measure is a measure on $(\mathbb{R},\mathcal{B})$.
$(\mathbb{R},2^\mathbb{R})$ is a measurable space and outer measure is not a measure on $(\mathbb{R},2^\mathbb{R})$.
If $X$ is a set and $\mathcal{S}$ is a $\sigma$-algebra on $X$, then we call $(X,\mathcal{S})$ a measurable space.
So, we expect there exists a measure on any measurable space $(X,\mathcal{S})$.
Is there a measure on any measurable space $(X,\mathcal{S})$?

I noticed that the zero function $\mu:\mathcal{S}\to [0,\infty]$ is a measure on $(X,\mathcal{S})$.
Let $\mu:\mathcal{S}\to [0,\infty]$ be a function such that $\mu(E)=\infty$ for any $E\subset X$ which is not empty and $\mu(\emptyset)=0.$
I think this $\mu$ is also a measure on $(X,\mathcal{S})$.
But these functions are trivial.
Is there a nontrivial measure on any measurable space $(X,\mathcal{S})$? (But I cannot define a trivial measure exactly.)

I am very sorry.
The author wrote very interesting examples of measures in Example 2.55 on p.41.
The second bullet point in Example 2.55 and the third bullet point in Exmaple 2.55 are nontrivial measures on any measurable space $(X,\mathcal{S})$.
Comment: Let $\mu:\mathcal{S}\to [0,\infty]$ be a zero function. Then $\mu$ is a measure on $(X,\mathcal{S})$. Is this right?
Answer: If you want a nontrivial measure, the point mass
\begin{align*}
\delta_x(E) &= \begin{cases}
    1 & \text{if } x\in E; \\
    0 & \text{if } x\not\in E
\end{cases}
\end{align*}
for any fixed $x\in X$ is a measure for any $\sigma$-algebra ${\cal S}$ on $X$.
Comment: @tchappyha or the counting measure
Comment: anomaly, Thank you very much for your answer.
Comment: @tchappyha: No thanks are necessary, but you're welcome.
Comment: @peek-a-boo The author wrote: If $X$ is a set, then counting measure is the measure $\mu$ defined on the $\sigma$-algebra of all subsets of $X$ by setting $\mu(E)=n$ if $E$ is a finite set containing exactly $n$ elements and $\mu(E)=\infty$ if $E$ is not a finite set. But I didn't notice this is a measure on any measurable space $(X,\mathcal{S}).$ If $\mu$ is a measure on $(X,2^X)$, then $\mu:\mathcal{S}\to [0,\infty]$ is also a measure on any measurable space $(X,\mathcal{S}).$ Thank you very much for your answer.
Comment: The author wrote: "Suppose $X$ is a set, $\mathcal{S}$ is a $\sigma$-algebra on $X$, and $w:X\to [0,\infty]$ is a function. Define a measure $\mu$ on $(X,\mathcal{S})$ by $\mu(E)=\sum_{x\in E} w(x)$ for $E\in\mathcal{S}.$ [Here the sum is defined as the supremum of all finite subsums $\sum_{x\in D} w(x)$ as $D$ ranges over all finite subsets of $E$.]" I noticed if $w:X\to [0,\infty]$ is a function such that $w(x)=1$ for any $x\in X$, then $\mu$ which is defined above is the counting measure on $(X,\mathcal{S}).$ Thank you.


No rows in result set when trying to deploy a business network

Question: I get the following error when trying to deploy a fabric composer business network archive to a 0.6 local hyperledger fabric setup.
<code>BusinessNetworkDefinition:fromArchive()             < [object Object]
HFCConnection            :deploy()                  Deploying business network email@example.com
FSConnectionProfileStore :load()                    Loaded connection profile hlfabric {
    "type": "hlf",
    "membershipServicesURL": "grpc://localhost:7054",
    "peerURL": "grpc://localhost:7051",
    "eventHubURL": "grpc://localhost:7053",
    "keyValStore": "/tmp/keyValStore",
    "deployWaitTime": 300,
    "invokeWaitTime": 30,
    "certificate": null,
    "certificatePath": null
}
HFCUtil                  :deployChainCode()         function init force true concerto
HFCUtil                  :deployChainCode()         onError {"error":{"code":2,"metadata":{"_internal_repr":{}}},"msg":"Error: sql: no rows in result set"}
ConnectorServer          :Error: Error: sql: no rows in result set() undefined
ConnectorServer          :connectionDeploy()        <
</code>
Answer: When you enroll with a hyperledger fabric instance, the credentials are stored in the keyValStore directory defined in your connection profile. If you then try to interact with a different hyperledger fabric instance or your stop and restart the docker containers for a locally running hyperledger fabric instance (effectively defining a new instance) with the same connection profile and this the credentials already stored in the keyValStore you get this error. This is because the credentials are not valid for that instance.
To fix the problem, either change your connection profile to use a different directory for keyValStore or remove that directory and it's contents and try again.


Securing outgoing emails with logs of a web server

Question: On the web server I am going to run rkhunter, tripwire, OSSEC, fail2ban and psad. All of those applications need to be able to send emails to notify the sysadmin.
Therefore, I've:
sudo apt-get install -y mailutils postifx

Then I configured postfix to catch mails sent to root@localhost and send those mails to firstname.lastname@example.com :
sudo nano /etc/aliases

and I have added this alias (after postmaster: root):
root:  firstname.lastname@example.com

I have allowed outgoing traffic on port 25/tcp (since my default UFW policy is DROP on both INPUT, OUPUT and FORWARD)
sudo ufw allow out 25/tcp

I am now able to send-only emails, and I am going to use postifx/mail only for those applications listed aboIve, while I will use PHPMailer for the web application itself (login notifications, email verification, password change notification, etc, etc).
At this point, I wonder:

Is postfix/mail, as I set it above, a safe way to send logs in terms of security? Assuming that an attacker wants to get my logs, how hard will be for him with my current configuration?
Does anyone know a good link where to learn something that can help me in this stuff?

My postfix TLS configuration lines:
smtp_enforce_tls=yes
smtp_use_tls=yes
smtp_tls_security_level=encrypt
smtp_tls_mandatory_ciphers = high
smtp_tls_loglevel = 1
smtp_tls_session_cache_timeout = 3600s
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
tls_random_source = dev:/dev/urandom
smtpd_tls_received_header = yes
smtpd_tls_loglevel = 1
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Comment: It's near impossible to judge security on such a narrow focus. Whether your Postfix setup as described is secure depends on lots of details and circumstances like, what kind of attacker do you need to protect against, is the server itself protected against physical access, how secure is the communication link between this server and the server handling the firstname.lastname@example.com mailbox. It is also not clear what you mean by "get my logs". Do you want to prevent the attacker from reading the logs? From altering them? From blocking them reaching you?
Comment: The server is not accessible physically..also, the communication link between our server and firstname.lastname@example.com (actually handled by Google, it runs our mail server) uses TLS.  Moreover, with "get my logs" i mean he's not able to catch and read the emails containing logs and, as consequence, also altering them.. Blocking them from reach me isn't a case i have thought, but it's obviously desirable that he will not able to do so too..
Answer: The security of your current setup against interception, and consequently possible disclosure and modification, of your mails on their way from your server to the destination mailbox, depends on the security of your server's DNS resolution. If an attacker is able to forge DNS replies to your server she can divert your mails to her own TLS-enabled SMTP server. Your Postfix daemon will log a certificate verification failure but deliver  the mail anyway. To protect against that sort of attack you need to use one of the higher smtp_tls_security_level values (dane-only, fingerprint, verify, secure) and/or use DNSSEC.
Security against blocking your mails depends mainly on the reliability and security of your Internet connection, but also of your DNS resolution, and of course on the destination mail server hosting the email@example.com mailbox. For example, if the destination server has an overly strict antispam policy it may be possible to block your mails by falsely reporting your server as a spam source.
Last but not least, once the mails are delivered to the firstname.lastname@example.com mailbox their security depends of course entirely on the security of that mailbox. For example, if an attacker gets hold of the access credentials for that mailbox (through phishing) she can read, delete or replace any mail in it.
Comment: Considering that my hosting and domain provider provides me a DNSSEC by default, i will have only to look into smtp_tls_security_level . About the 2nd paragraph, my reply would be too long, anyway, i am safe here. About the security of my mailbox, it's obvious and of course i will keep an eye on it. Thank you for your reply Herr Schmidt.


How likely is a difference of final conversion between two randomly split groups who have passed the same sales funnel?

Question: I'm having a discussion with a friend regarding an interview question (neither of us got the job :):
An ecommerce gets 40,000 visitors on 1 day. They are randomly split into 2 groups (A/B) of 20 000 each. And by the end of the day it's measured that group A purchased for \$442,000 and group B purchased for \$408,000. How probable is this outcome, in as plain English as possible? (we're obviously not statisticians)
Answer: I'll try to give an answer which doesn't require statistical knowledge.
On average, group A spend \$11.05 each and group B \$10.20 each. How plausible this difference is will depend on the variance in how much visitors spend on the site per visit.
For an extreme high variance case, if the site sells extremely expensive cars, then maybe only two purchases in total were made: a single person in group A bought a \$442,000 car, and a single person in group B bought a \$408,000 car. These data wouldn't be surprising.
For an extreme low variance case, suppose that every visitor spends either exactly \$10.20 or exactly \$11.05. For the numbers to add up, everybody in group A would have had to spend \$11.05 and everybody in group B \$10.20 - which is extremely unlikely to happen by chance.
If you knew the sample variance, you could use statistical hypothesis testing to quantify how suspicious the difference in mean spending between the groups is. (It's possible that the interviewer was expecting you to make a guess about what the sample variance might plausibly be based on your intuition about visitor behaviour patterns on ecommerce websites.)
Comment: Thanks. Sorry, we do know those things, I was too quick. We know that 3360 purchased in A and 3570 in B. We also know stddev is 118400 in A and 120900 in B. Can we then get an exact answer? And what method would you use?


Edit length of increment_id in sales_order table on Magento 2

Question: I want to decrease length of order increment #00000000001 to #00001.
I found some tutorials for magento 1 but not for Magento 2.
Please help if someone is aware how to perform this task.
Thanks
Comment: checkout the table "eav_entity_type". I am not sure but its seems this table is responsible for that.
Comment: ya, I have decreased the increment_ped_length value but still don't reflect any change.
Answer: In the etc directory of your module, add a di.xml file with this content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\SalesSequence\Model\Sequence">
        <arguments>
            <argument name="pattern" xsi:type="string"><![CDATA[%s%'.05d%s]]></argument>
        </arguments>
    </type>
</config>

This way Magento will pass a 5 digit pattern instead of its default pattern made by 9 digits.
This is because the first and the last %s symbol are replaced respectively with the prefix and the suffix values stored in the sales_sequence_profile table. The matching is done with the meta_id of your store (you can check yours by reading from the sales_sequence_meta table). The %'.05d pattern means that you want an integer with 5 padding digits on its left which is replaced with the next order number calculated by Magento.
For example, assuming that you have:

Prefix: PX
Suffix: SX

with the above pattern, the first order number will be PX00001SX
Comment: file location - app/etc/di.xml   Cay you explain your code %s%'.05d%s so other patterns can be created from your answer?
Comment: The cleanest approach to this problem. I was not convinced with the other solutions to override the actual PHP file. Thank you for sharing.
Answer: you can decrease length of order increment #00000000001 to #00001.
Try this: https://store.emizentech.com/magento2/custom-order-and-invoice-number-magento-2-0.html
Answer: Solved with a custom developed plugin:
I already had an observer to save the customer as new customer automatically after placing an order and before rendering the success page:
On the events.xml (already existing observer i've previously made)
<event name="sales_order_place_after">
    <observer name="customcheckout_customer" instance="Dufry\CustomCheckout\Model\Observer\SaveCustomer"/>
</event>

On the observer SaveCustomer.php (already existing observer i've previously made):
    $order = $observer->getOrder();

    $increment = $order->getIncrementId();
    if(strlen($increment) > 9){
        $newIncrement = substr($increment, -8);
        $newIncrement = substr($increment,0,1).$newIncrement;
        $order->setIncrementId($newIncrement);
    }

    ...

    $order->save()

And worked like a charm.
I did the second "substr" part to keep the prefix the was previously configured.


How can I specify a path and filename for my files with meteor and collectionfs filesystem

Question: I'm using CollectionFS to store files uploaded from my meteor app. I'm using the cfs-filesystem package to save my files using the local filesystem.
Right now, when I upload a file, it gets saved to ~/uploads/images-h9jWnALqSZMpAX4h4-IMG_3737.JPG
I have an existing filesystem structure that I need to work with and we need the files to be easy to traverse by hand if necessary.
Suppose I want to customize that path to be something like this ~/uploads/jaredtmartin/IMG_3737.jpg. And when a different user uploads, it goes to a new folder with his name, for example, ~/uploads/suzyq/IMG_1234.jpg. Can that be done? If not, where can I dig in to modify the code to make it happen?
Comment: Did you find a solution to your problem? I am have the same issue, and the answer below does not show how to create the directory for each user.
Answer: You can use the fileKeyMaker, see here
var imageStore = new FS.Store.FileSystem("images", {
  fileKeyMaker: function (fileObj) {
    // Lookup the copy
    var store = fileObj && fileObj._getInfo(name);
    // If the store and key is found return the key
    if (store && store.key) return store.key;

    // TO CUSTOMIZE, REPLACE CODE AFTER THIS POINT

    var filename = fileObj.name();
    var filenameInStore = fileObj.name({store: name});

    // If no store key found we resolve / generate a key
    return fileObj.collectionName + '-' + fileObj._id + '-' + (filenameInStore || filename);
  }
});

Comment: Please provide full text instead of a link, or this answer will be deleted by the community.
Answer: I found a simpler solution (IMHO).
In the declaration of the storage adapter you can do something like this:
var photoStore = new FS.Store.FileSystem("photos", {
  transformWrite: function(fileObj, readStream, writeStream) {
    gm(readStream, fileObj.name).resize(100,100,"^").gravity('Center').crop(100,100).quality(100).autoOrient().stream().pipe(writeStream);
  },
  beforeWrite:function (fileObj) {
    var post = Posts.findOne(fileObj.postId);
    if (post.type==='Dog') return {name:slugify(post.name)};
    else return {name:slugify(post.title)};
  },
});

In this example, some of the images for my were named using the name property and others using the title property. In the example above, I didn't preserve the extensions, but I think you get the idea. I removed that for clarity.  If you need that code, let me know. I have it.
Now this doesn't actually put the images in different folders, but it does allow you to name the files.


Lilypond: Convenient code for basso continuo horizontal lines?

Question: In basso continuo you sometimes want to place horizontal lines to indicate stable harmony. This is done in LilyPond using \bassFigureExtendersOn:
\version "2.18.2"

\score {
    <<
        \new Staff {
            4
            <c'' g' e'>4
            2
            |
            4
            <c'' g' e'>4
            <d'' g' d'>2
        }
        \new Staff { \clef bass
            d4
            e8 c
            g2
            |
            d4
            e8 c
            b,2
        }
        \figures {
            \bassFigureExtendersOn
            <4 3>4
            <6>8 <6> % <- this is problematic
            r2
            |
            <4 3>4
            <6>8 <6> % <- this is problematic
            <6\!>2 % <- this is problematic
        }
    >>
}

However, this has two drawbacks:

the <6> for c is incorrect technically-speaking (it will show rubbish things if \bassFigureExtendersOn is not used.
the b in the second bar needs \! to show the proper thing.

So I wonder whether it's possible to activate an extender manually. Something like <6>8~ q would be great, because while the c shouldn't have a <6>, this would already make the code clear. (This would basically have the opposite effect of \!.)
Answer: In Lilypond there is no off-the-shelf way of doing this. However, these things don't strike me as problematic. The extra 6 on the c here does not mean that the chord is in first inversion, it simply tells the engraver how far to print the line - i.e. it tells it where to 'tie' to. It's not harmonic semantic content, it's a markup instruction. Using q here would be the same as writing the 6 so I'm not sure how that helps conceptually - nor does it save much typing. q would also not help if the next figure was <6 x> and needed an extender. \bassFigureExtendersOn effectively puts a ~ after each <> If you don't want to use \! then just turn the extenders on and off as required (fwiw this is how I deal with extenders).


Getting string from WCF service

Question: I want to get the string generated by the WCF service, both synchronously and asynchronously. I know that with the bitmap, for instance, it's a piece of cake - you can add the event handler to BitmapImage on e.g. IsDownloaded or something. How about strings? How can I achieve that? Assume that I want to use URi for calling the WCF service.
What is the best approach for that?
Thanks in advance for the reply!
Cheers
Comment: Can you provide a little more  information?  What string are you talking about?  Can you post your servicecontract and/or datacontract?
Comment: I think of a simple string, passing back and forth, say:

[OperationContract]
void f(string a);
[OperationContract]
string f2();
Answer: Consider using the Default Message Contract sample from MSDN.
Comment: I will take a glance at that stuff

Getting string from WCF service


Proving that in an homogeneous DTMC $i\leftrightarrow j$ and $j$ is recurrent $\implies f_{ij}=1$

Question: I'm struggling to understand the proof of the following theorem:
Theorem: Let $\big\{\mathsf X\big\}_{n\in\mathbb N}$ be an homogeneous DTMC, P its transition matrix and $\mathsf S$ its states space; let $i,j\in\mathcal S\mid i \leftrightarrow j$, then $f_{ij} = 1$
Proof: Let $m\in\mathbb N\;\lvert\; P^{(m)}_{ji} > 0$. Then
$$1 = f_{jj} = \mathbb P\big( \mathsf X_n = j \text{ for infinitely many } n\mid \mathsf X_0 = j \big) \\= \mathbb P\big( \mathsf X_n = j \text{ for some } n > m+1 \mid \mathsf X_0 = j \big) = \cdots$$
And so on, I won't report the remaining part cause this one right here is the only one giving me a bad headache.
Now, why is the third equality true? I mean, to me the events in the probability argument sound totally different. I saw alternative proves involving renewal processes but we didn't study them in our class and aren't part of our program, I need to understand this one right here.
EDIT: Supposedly the two arguments should be equivalent, i.e.
$$\mathsf X_n = j \text{ for infinitely many } n \iff \mathsf X_n = j \text{ for some } n > m+1$$
The "$\implies$" part is obvious, but I can't see why the "$\impliedby$" holds.
We saw and proved a theorem asserting that if a state $k\in\mathsf S$ is recurrent then paths starting in $k$ are a.c visiting $k$ at least once ($f_{kk} = 1$) and then if $k$ is recurrent the paths starting in $k$ return a.c. infinitely many times in $k$, may this have something to deal with it?
Comment: I think there is something slightly amiss because after the second equality there is no more $i$. Presumably you want $X_0=i$?
Comment: @lan: You're indeed correct, it has to be $1 = f_{jj}$, I'll edit that!
Answer: The point of the third equality is that if you a.s. return once, then you a.s. return infinitely many times, because of the Markov property. This equality would not be true if the probability to return once were merely positive and not 1.
Comment: @lan: I'm aware that "a path starts in $j$ and it a.c. visits $j$ at least once $\iff$ a path starts in $j$ and it a.c. visits $j$  infinitely many times" but I had no clue about the fact that if you a.c visit $j$ once (assuming that the starting state can be any) then you a.c. visit it infinitely many times. Why is that?
Comment: @Bafforasta I didn't say that if you a.s. visit once then you a.s. visit infinitely many times. I said if you a.s. *return* once then you a.s. *return* infinitely many times. And this is simple, because once you have returned, you have another independent chance to return again, which you will do with the same probability (1) again. In general it is not true that if you a.s. visit once then you a.s. visit infinitely many times. This will fail when the starting state and $j$ are both transient (which must necessarily happen together since transience is a class property).
Answer: $\def\F{\mathscr{F}}\def\peq{\mathrel{\phantom{=}}{}}$The property used in the equality is actually:\begin{gather*}
P(X_n = j \text{ for infinitely many } n \mid X_0 = j) = 1\\
\Longleftrightarrow P(X_n = j \text{ for some } n > m + 1 \mid X_0 = j) = 1.
\end{gather*}
For $\Longrightarrow$, it is obvious by$$
\{X_n = j \text{ for infinitely many } n\} \subseteq \{X_n = j \text{ for some } n > m + 1\}.
$$
For $\Longleftarrow$, define$$
τ_0 = 0, \quad τ_{n + 1} = \inf\{k > τ_n + m + 1 \mid X_k = j\}, \quad \forall n \geqslant 0
$$
then$$
\{X_n = j \text{ for infinitely many } n\} = \bigcap_{n = 1}^∞ \{τ_n < ∞\} = \lim_{n → ∞} \bigcap_{k = 1}^n \{τ_k < ∞\}.
$$
So it suffices to prove by induction on $n$ that$$
P(τ_1 < ∞, \cdots, τ_n < ∞ \mid X_0 = j) = 1. \quad \forall n \geqslant 1
$$
For $n = 1$,$$
P(τ_1 < ∞ \mid X_0 = j) = P(X_n = j \text{ for some } n > m + 1 \mid X_0 = j) = 1.
$$
Now assume that it holds for $n$. Denote $A_k = \{τ_1 < k - m - 1, \cdots, τ_{n - 1} < k - m - 1\}$ for $k \geqslant m + 2$, then$$
\{τ_1 < ∞, \cdots, τ_n < ∞\} = \bigcup_{k = m + 2}^∞ (A_k \cap \{τ_n = k\})
$$
and\begin{align*}
&\peq P(τ_1 < ∞, \cdots, τ_n < ∞, τ_{n + 1} < ∞ \mid X_0 = j)\\
&= \sum_{k = m + 2}^∞ P(A_k \cap \{τ_n = k\} \cap  \{τ_{n + 1} < ∞\} \mid X_0 = j)\\
&= \sum_{k = m + 2}^∞ \sum_{l = k + m + 2}^∞ P(A_k \cap \{τ_n = k\} \cap \{τ_{n + 1} = l\} \mid X_0 = j). \tag{1}
\end{align*}
Note that $\{τ_n = k\} \subseteq \{X_k = j\}$, so\begin{align*}
&\peq P(A_k \cap \{τ_n = k\} \cap \{τ_{n + 1} = l\} \mid X_0 = j)\\
&= P(A_k \cap \{τ_n = k\} \cap \{X_k = j\} \cap \{τ_{n + 1} = l\} \mid X_0 = j)\\
&= P(A_k \cap \{τ_n = k\} \cap \{X_k = j\} \mid X_0 = j)\\
&\peq · P(τ_{n + 1} = l \mid A_k \cap \{τ_n = k\} \cap \{X_k = j\}).
\end{align*}
By the Markov property,\begin{align*}
&\peq P(τ_{n + 1} = l \mid A_k \cap \{τ_n = k\} \cap \{X_k = j\}) = P(τ_{n + 1} = l \mid X_k = j)\\
&= P(X_{k + 1} ≠ j, \cdots, X_{l - 1} ≠ j, X_l = j \mid X_k = j)\\
&= P(X_1 ≠ j, \cdots, X_{l - k - 1} ≠ j, X_{l - k} = j \mid X_0 = j)\\
&= P(τ_1 = l - k \mid X_0 = j),
\end{align*}
combining with$$
P(A_k \cap \{τ_n = k\} \cap \{X_k = j\} \mid X_0 = j) = P(A_k \cap \{τ_n = k\} \mid X_0 = j)
$$
and the induction hypothesis yields\begin{align*}
(1) &= \sum_{k = m + 2}^∞ \sum_{l = k + m + 2}^∞ P(A_k \cap \{τ_n = k\} \mid X_0 = j) P(τ_1 = l - k \mid X_0 = j)\\
&= \sum_{k = m + 2}^∞ \sum_{l = m + 2}^∞ P(A_k \cap \{τ_n = k\} \mid X_0 = j) P(τ_1 = l \mid X_0 = j)\\
&= \left( \sum_{k = m + 2}^∞ P(A_k \cap \{τ_n = k\} \mid X_0 = j) \right) \left( \sum_{l = m + 2}^∞ P(τ_1 = l \mid X_0 = j) \right)\\
&= P(τ_1 < ∞, \cdots, τ_n < ∞) P(τ_1 < ∞ \mid X_0 = j)\\
&= P(τ_1 < ∞, \cdots, τ_n < ∞) = 1.
\end{align*}
End of induction.
Comment: Hi, thank you for your comment. I'd like to note that in our course we didn't see what you called "strong Markov property" (or if we did, not by this name). Also, what are $E_j$, $I$ and $\mathscr F$ in your notation? Thanks.
Comment: So is $E_j$ the expectation with respect to the probability $\mathbb P_j$? I know what an indicator function is but we never saw filtrations too so I really don't know what that is... it makes me want to choke my teacher ahah
Comment: I massively appreciate your effort! I'm trying to understand few things: does $\tau_n$ represent the time of the $n$-th visit after the time $m+1$? And does $A_k$ represent the fact of "having the first $n-1$ visits within the time $k-m-1$"? (My intuition would suggest that it should be "within the time $k-1$ since $k\geq m+2$). Thanks again!
Comment: $τ_n$ is the next visit to $j$ after $m+1$ steps after $τ_{n-1}$, and $A_k$ is indeed what you mean before the parentheses. Although $τ_1$ might be forced to take negative values on the event $A_k$, it doesn't matter since the event would by an empty set then.
Comment: So my idea that $A_k$ should be $A_k = \{τ_1 < k - 1, \cdots, τ_{n - 1} < k - 1\}$ for $k \geqslant m + 2$ is wrong? Cause if I assume yours is correct then picking $k = m+2$ (first possible value) would give me $A_{m+2} = \{τ_1 < 1, \cdots, τ_{n - 1} < 1\} = \emptyset$ cause there aren't even $n-1$ different times before time 1.
Comment: @Bafforasta Your reasoning on $A_{m+2}=\varnothing$ is exactly correct, but such details can be dismissed in the summation since $P(\varnothing)=0$.
Comment: which property are you using to go from line two to three from the block after the (1)? If I call $A= \{ A:k \cap \tau_n = k \cap X_k =  j\}, B = \{ \tau_{n+1} = \ell\}$ and $C = \{X_0 = j\}$ that would be $\mathbb P(A \cap B | C) = \mathbb P(A|C)\mathbb P(B|A)$ but I don't recognize this as a general conditional probabilities property.
Comment: Are you just using the fact that $\mathbb P(A\cap B|C)=\mathbb P(A|C)\mathbb P(B|A\cap C)$ along with the Markov property for that one? This is the last doubt I have
Comment: If you can, please confirm I got it correctly, then I'm going to assign the bounty :)
Comment: I assigned the bounty, thanks. Just to confirm that I got it right, you use Markov property to turn $\mathbb P( A \cap B | C) $ from $\mathbb P(A|C)\mathbb P(B|A\cap C)$ to $\mathbb P(A|C)\mathbb P(B|A)$?
Comment: @Bafforasta Yes. Actually I skipped a small step there, and to write it out completely it needs the Bayes' formula to expand the event $A_k\cap\{τ_n=k\}\cap\{X_n=j\}$ as the union of events in the form $\{X_1=\cdots,\cdots,X_n=\cdots\}$. But intuitively, this is easy to understand since the Markov property is just saying that the conditional expectation given the history up to the current moment is equal to that given the current moment only.
Comment: Got it, thanks, you're a life saver :)
Comment: @Bafforasta You're welcome :)


REST API Headers value in multivaluemap

Question: I have a situation condition.
Create a RestAPI. value received from header
ResponseEntity<String> methodname(@RequestBody String request, @RequestHeader MultiValueMap<String, String> headers)

Condition
if (!headers.containsKey("receiverKey")){
            throw new restException(null, "Receiverkey", "Receiverkey not comming in Header", null, BAD_REQUEST);
        }
        if (headers.get("receiverKey").toString().equals("[]")){
            throw new restException(null, "Receiverkey", "Receiverkey is not comming in Header", null, BAD_REQUEST);
        }

From above code, I am able to achieve the functionality. But I have to refactor the above code means combined into single if condition.
Can any one has help me?
Answer: if (!headers.containsKey("receiverKey") || headers.get("receiverKey").toString().equals("[]")){
        throw new restException(null, "Receiverkey", "Receiverkey not comming in Header", null, BAD_REQUEST);
    }

REST API Headers value in multivaluemap


Stability of the unit interval under the binary operation $x*y=x+y-xy$

Question: Let $I=[0,1]$ the unit interval. I want to show that If $x\in [0,1]$ and $y\in [0,1]$ then $x+y-xy\in [0,1]$
My first attempt is to write $x+y-xy= (1-y)x+y.1$ which is a point in the segment $[x,1]$ since $[x,1]$ is convex. Hence $x+y-xy\in I$.
My second attempt is to use a direct method without mentioning the notion of convexity: we have that $x-xy=x(1-y)\geq 0$ so $x\geq xy$ and similarly $y\geq xy$
hence $x+y\geq xy$ so $x+y-xy\geq 0$. But I don't see how to show that $xy-xy\leq 1$.
Comment: Can't you just test endpoints? Find $\sup \{x+y-xy\}$ and $\inf \{x+y -xy\} : x,y \in [0,1]$?
Comment: Palio's second attempt already shows that $\text{inf} \{x+y-xy\}\ge 0$. As for checking the $\text{sup}$, consider your first attempt: $x+y-xy=(1-y)x+y$, and see if you can find an $x$ such that the expression $(1-y)x+y$ is maximized.
Answer: Write $x+y-xy$ as $1-(1-x)(1-y)$. Now note that $1-x,1-y \in [0,1]$ and conclude what you want.
Comment: Thank you, is what i find here correct : for the law $x*y=x+y-xy$, No element other than zero is invertible, and that all elements $a\in [0,1]$ ,except $1$, are regular (in the sense that $a*b=a*c$ implies $b=c$)?
Answer:
You can use geometry too. There's a unit square. Assume point D has coordinates $(x,y)$, so D locates inside (or on the borders of) this unit square.
Notice that $x=area(OGEF)$, $y=area(OABC)$, $xy=area(OGDC)$, and the unit square's area is 1, we get
$$
0 \leq x+y-xy \leq 1
$$


Como definir uma Tray Icon (ícone na bandeja) numa aplicação PyQt?

Question: Ainda sou iniciante em PyQt e gostaria de esclarecer uma dúvida:
Existe alguma forma de se definir um Tray Icon (Ícone na Bandeja) em uma aplicação PyQt?  Se tem, como eu posso fazer?
Preciso definir algumas opções nesse ícone de bandeja. Tem como fazer isso também?
Answer: A classe QSystemTrayIcon serve para isto.

http://doc.qt.io/qt-4.8/qsystemtrayicon.html

Supondo que sua aplicação seja qApp, eis um pequeno exemplo:
trayIcon = QtGui.QSystemTrayIcon( QtGui.QIcon('icone.png' ), qApp)
trayIcon.setTooltip('eu sou um ícone de bandeja')

sair = menu.addAction("Sair")
menu = QtGui.QMenu()

trayIcon.setContextMenu(menu)
trayIcon.show()

Pontos de interesse:

setTooltip serve para definir a "dica" que aparece, por exemplo, quando você passa o mouse sobre o ícone;
setContextMenu, como o nome já diz, serve para adicionar um menu de contexto ao ícone. Consulte a documentação do QMenu para mais detalhes;

Se quiser animar o ícone, pode fazer chamadas para o método setIcon(const QIcon & icon), usando um QTimer, por exemplo. Só convém não querer fazer nada muito complexo, para não sacrificar a responsividade do OS.
Ainda, vale notar que existe o método showMessage, se quiser exibir uma mensagem para o usuário. Por exemplo, no Windows 7, é usado um balão:


How to delete a user via REST

Question: I'm trying to delete user account via REST API.
Here is my code:
// .xml asks for xml data in response.
$service_url = 'http://www.example.com/rest/user/login';

$post_data = [
  'username' => 'test',
  'password' => 'pass',
];

// Format post data as application/x-www-form-urlencoded.
$post_data = http_build_query($post_data, '', '&');

// Set up the request.
$curl = curl_init($service_url);

// Have curl_exec return a string.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// Do a POST.
curl_setopt($curl, CURLOPT_POST, TRUE);
// POST this data.
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// Output to command line
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);

// Make the request.
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name . '=' . $xml->sessid;

// Get token.
$curl_get = curl_init();
curl_setopt_array($curl_get, [
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL            => 'http://www.example.com/services/session/token',
]);
$csrf_token = curl_exec($curl_get);
curl_close($curl_get);

// A user ID.
$id = 1500;
// The token.
$token = $csrf_token;

// Set up the curl resource
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/rest/user/$id?access_token=$token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

$response = curl_exec($ch);

// Close curl resource to free up system resources.
curl_close($ch);

It returns:

Access denied for user anonymous

How do I need to write the code to delete a user?
Answer: First you need to login:
$loginData = ['username' => 'yourusername', 'password' => 'yourpassword'];

$ch = curl_init("http://pathtodrupal.com/endpoint/user/login.json");

curl_setopt_array($ch, [
  CURL_OPT              => TRUE,
  CURLOPTRETURNTRANSFER => TRUE,
  CURLOPT_HTTPHEADER    => ['Content-Type: application/json'],
  CURLOPT_POSTFIELDS    => json_encode($loginData),
]);

$response = curl_exec($ch);

$responseData = json_decode($response, TRUE);

Once you send a POST request to login you get the following response back:

{u'session_name': u'SESScxx45656f30', u'sessid':
  u'mOE9NdG6Bk3EADSvKJHGGy8jgkQ', u'token':
  u'-HVkXhARIynpmJxow5NUIYTRXSc', u'user': {u'status': u'1', u'picture':
  u'0', u'uuid': u'514c987e7-15f0-43cc-9c6f-53279c216f30', u'uid': u'1',
  u'language': u'', u'created': u'1310006971', u'init':
  firstname.lastname@example.com', u'timezone': u'America/New_York', u'access':
  u'1429109927', u'theme': u'', u'roles': {u'2': u'authenticated user'},
  u'signature': u'', u'signature_format': u'1', u'mail':
  email@example.com', u'login': 1429111638, u'data': {u'ckeditor_width':
  u'100%', u'form_build_id': u'form-60703ffc3';lk6c0fe03cebe9',
  u'ckeditor_lang': u'en', u'ckeditor_show_toggle': u't',
  u'last_category_id': 1, u'ckeditor_auto_lang': u't',
  u'ckeditor_default': u't', u'site_access': {u'1': u'1'},
  u'last_site_id': 1}, u'name': u'bewmrn'}}

In your subsequent requests you want set the the set in the header the X-CSRF-Token to $response['token'] and Cookie to $response['session_name'].=.$response['sessid']. This should work.

How to delete a user via REST


Can I insert the version number in the info file of a module for internal use?

Question: The documentation on the creation of custom modules says,
# Note: do not add the 'version' or 'project' properties yourself.
# They will be added automatically by the packager on drupal.org.

so I never put a version number in my module. But then I add difficulties writing database update scripts, I never managed to get an N in hook_update_N() that the update would recognize.
Also, my module really doesn't have any utility outside of my organization, since it has very specific domain requirements; therefore it is not, and never will, be released as a contributed module.
So, can I use a version number in my info file, and use it to generate the name of the update function? And if I insert it in an update of my module, will it be correctly managed?
Comment: `hook_update_N` is unrelated to any version string in the info file - if you're having trouble with those hooks, concentrate on that issue; adding a version, while yes of course you can do, and it won't break anything, won't affect update hooks. What it _may_ do, is give you a red/yellow item in the available updates list, as I think the updater will check d.org for versions of the module if `version` is set
Answer: If you host your module outside of drupal.org, including a private Git repository, or a local computer from which the module is copied on the site, you can set the version key in the .info.yml file for the module.
If the module updates are handled differently, the module could also implement hook_update_projects_alter() to tell the Update Manager not to check for that module updates, for example implementing the code shown in the documentation.
function mymodule_update_projects_alter(&$projects) {
  // Hide a site-specific module from the list.
  unset($projects['site_specific_module']);
}

As for the number N used in hook_update_N(), that number isn't related to the module version. It's just a progressive number, used from Drupal to verify which hook_update_N() implementation has been already run. hook_update_N() explains the convention for the four digits used for N.

1 or 2 digits for Drupal core compatibility (for example, 8 for compatibility with Drupal 8, 10 for compatibility with Drupal 10)
1 digit for your module's major release version (for example 1 for the 8.x-1.3 release)
2 digits for a counting number, starting from 01

To use an existing project as example, the pathauto.install file for the release 8.x-1.11 defines, as last update hook pathauto_update_8106(); the same file for the release 8.x-1.5 has pathauto_update_8107() as last update hook, which is the latest update hook also for the release 8.x-1.8.
Note that the digit for the major version release isn't sufficient to describe the version release (which would include also the minor version), but it's not sufficient also for a major version that is higher than 9.
Note also that Drupal core won't report any error whether (for example) a 8.x-2.3 release contains mymodule_update_8133() as update hook. What described is a convention for which only the Drupal compatibility digit is required.


How does one place a beat 'on' a given note/rest value?

Question: I am reading a book about music for digital artists, and am reading through an intro to drumming. This is the part I am confused with:
''The ride element can be placed on the quarters, eighths, or sixteenths. Placed on the
quarters, the ride can add emphasis to the primary hits, a common technique used in
dance music.  Eighths give a nice flowing sense to the drums. Sixteenths
are more intricate and give a greater sense of pace, motion, and energy''.
Credit goes to Michael Hewitt - Composition for computer musicians
Now I know what values notes can have and what they look like and all that, but what I don't get is how you can place somthing... on them? See, I thought the note values represented the beats, not the other way round.
The only thing I can think of is that he is talking about quantization. So, if the grid is quantised to represent a resolution of 16, with 4 beats representing 1 quarter (4 of which represents a bar), then the beats can be snapped, or placed, on any of the sixteenth rests (because really that's what they are before the beat is used to fill that rest), where a quantisation of 32 means beats can be placed upto a 32'nd rest.
So here, I would have a beat on every quarter, or every 4 sixteenths:

And hear I guess I have a ride on a 32'nd, coloured blue.

If this is the case, I would further presume that you can't place a beat on  say, both a sixteenth and a 32nd, but that you could place it on the 32'nd that comes before or after the 16'th. Though, placing it on the 2nd 32nd would be said to be placing it on the 16th, I think. As you can tell, am obviously an expert :D
Answer:
Now I know what values notes can have and what they look like and all that, but what I don't get is how you can place somthing... on them?

The author is saying "place a sound every X": as in every quarter, or every eight, or every sixteenth. Here are some examples of one measure in 4/4. The grid is divided in sixteenths.
Every quarter:

Placed on the quarters, the ride can add emphasis to the primary hits, a common technique used in dance music.

Every eighth:

Eighths give a nice flowing sense to the drums.

Every sixteenth:

Sixteenths are more intricate and give a greater sense of pace, motion, and energy''.

All these are common ride, cymbals, and hi hat rhythms. This is what the lesson is introducing you to. Perhaps you are over-thinking it?
Basically, the author is saying "do what they are doing on this video, but paint it on the piano roll instead of performing it".

As a side note, as Greg Jackson pointed out in the comments, in music theory beat normally refers to the basic unit of time. From your question and context we can deduce that you are using beat to refer to a sound rather than a time unit, but being aware of that distinction is important to avoid confusion from you and/or the people you are chatting with.
Comment: I'd go further and say that even if you're not working with a grid, you would use this language. "I'm going to put a kick drum on every beat, and I'm going to put a snare on the twos and fours" is something a live drummer might say (OK, I've said "put" not "place" but these are the same)
Comment: @user108262 I'm pretty sure. It's a very common lesson in DAWs, rhythm, and drum machines. "Place a ride on the quarters" means "put a ride sound on every quarter".  "Play in sixteenths" (when playing an instrument) and "put something in sixteenths" (in a piano roll) both mean the third example in the answer. What makes you think he is referring to something else?
Comment: @user108262 It isn't flexible in the sense that the author is introducing you to very specific rhythms, but it is flexible in the sense that you can do whatever you want when composing and producing. If you want to place the ride in 32nds go for it. The author is introducing you to these three basic (and important) rhythms, but there are many more possibilities.
Comment: @GregJackson You are right, it can be very confusing. Beat here is a sound, rather than a unit, but since both are closely related to the topic it can easily get in the nonsense territory. I'll change beat for sound in the answer.
Comment: I know I just asked the question, and all, but are you really sure? I really don't think that's what he means. I mean, who places a beat every sixteenth?
Comment: Mostly my lack of experience, so to me this could mean many things, my main confusion was thinking it could be flexible, and I guess it can. In other words, I didn't know it meant every single value, but looking through the examples provided by the author your certainly correct, thank you very much for clearing that up :)
Comment: @user108262 `who places a beat every sixteenth?` You can see it as hitting a ride (or something else) every sixteenth. I edited the answer and included a video as example. The instructor plays in quarters, eighths, and sixteenths. The author is telling you how to translate that performance to the piano roll.
Comment: I'm going to add that, to my ear, "place a beat every 16th" sounds incorrect - the beats in 4/4, for example, are explicitly on the quarter notes. You can play a sound every 16th, but that means you're striking the hi hat four times a beat, the beat itself isn't changing. I don't know if this is universal parlance, but it's certainly common among American musicians, and talking about a 16th note as a beat (in any time signature that isn't something over 16) may confuse things.
Comment: @GregJackson From the question and context, I assumed that by beat the asker referred to a percussion sound, so I used that same definition in the answer. I don't normally use it that way, but it's not uncommon for electronic musicians to use it that way. It doesn't mean that the time signature changes, and it's not related to the time signature at all (in this context).
Comment: @JCPedroza I understand that, but "beat" has a fairly specific meaning to musicians, especially ones trained on sheet music. it's possible that the discrepancy between a drum-beat and a proper musical "beat" caused some of the initial confusion in this case, since the latter is what most musical literature will refer to, independent of where the drum strikes fall. I'm not being pedantic, but rather pointing out a possible source of confusion.
Comment: @GregJackson note that the book quote doesn't use the word "beat", it uses the word "element". The questioner has used "beat" afterwards, but it seems from context that he means "note" or "sound" or "sample".
Answer: The beat exists without any notes being played.
Imagine the bandleader saying "and ah one, and ah two and ah one two three four" - the next "one" is the downbeat marking (nominally) the beginning of the piece. Time passes, the pulse continues, but there need not be any notes "placed" or "put" on any of those "beats." I think you need an understanding of time signatures before this question can have a meaningful answer. In Common Time, aka 4/4 There are 4 beats per measure, and the quarter-note is the primary beat. In Cut-Time (2/4) there are still four beats to the measure, if you count each beat is an eigth-note. This happens as time passes, regardless of any sound being produced by any instrument or voice. The tempo and time signature determine the "beats" regardless of anything else. See John Cage's infamous 4′33″.


problem doing this trig integral $\int \frac{x^3dx}{\sqrt{9-x^2}}$

Question: $$\int \frac{x^3dx}{\sqrt{9-x^2}}$$
$$x = 3\sin\theta$$
$$dx =3\cos\theta d\theta$$
$$\int \frac{(3\sin\theta)^33\cos\theta d\theta}{3\cos\theta }$$
$$\int 27\sin^3\theta d\theta$$
$$-27\cos\theta + 27\frac{9\cos^3}{3}$$
Replacing cosine by $\frac{\sqrt{9-x}}{3}$ does not give the correct answer what did I get wrong?
correct answer:
$$-\frac{\sqrt{9-x^2}(x^2+18)}{3}$$
Comment: I don't know about whether there's any step that is wrong, but is there a reason you used a trig substitution rather than just $u = 9-x^2$?
Comment: All right, well, your first error, then, is that $3^3 = 27 \neq 9$.
Comment: @BrianMoehring because I am practicing trig subs
Comment: @BrianMoehring still does not reach the desired form
Comment: You may want to give the answer you reached then.  If you really replaced $\cos\theta$ with $\frac{\sqrt{9-x}}{3}$, then that's another error, but I can't tell if it affected your answer or whether it's a typo.
Comment: Also:  it may look different but still be correct.  If you got an answer of $(x+4)^2$ and I said the answer is $x^2+8x+16$, we're not wrong.
Comment: $9\sqrt{9-x^2}+9(9-x)^{3/2}$
Comment: $cos\theta = \frac{\sqrt{9-x}}{3} $ seems to be ok
Comment: https://math.stackexchange.com/questions/960298/integrate-int-fracx3dx-sqrt1x2 and https://math.stackexchange.com/questions/2148572/solving-an-indefinite-integral
Comment: Typesetting tip:  Typing `$\sin\theta$`, `$\cos\theta$`, `$\tan\theta$`, `$\csc\theta$`, `$\sec\theta$`, and `$\cot\theta$` produces $\sin\theta$, $\cos\theta$, $\tan\theta$, $\csc\theta$, $\sec\theta$, and $\cot\theta$, respectively.
Answer: First and foremost, this is not an integral for which trigonometric substitution is the best way to resolve it.  We could instead just use $u = 9 - x^2$ to instead find $x^2 = 9-u$ and $x\,dx = -\frac12\,du$.
This gives
$$\int\frac{x^3}{\sqrt{9-x^2}}\,dx = \int\frac{x^2}{\sqrt{9-x^2}}\cdot x\,dx = \int\frac{9-u}{\sqrt{u}}\left(-\frac12\right) \,du = -\frac12 \int\left(9u^{-1/2} - u^{1/2}\right)\,du$$
and you should be able to finish.

That said, we certainly can use a trig substitution as you have done.
It gives $$\int\frac{x^3}{\sqrt{9-x^2}}\,dx = \int 27\sin^3\theta\,d\theta = 27\int(1-\cos^2\theta)\sin\theta\,d\theta$$
Here, we use the substitution $u = \cos\theta$ to write (I know I've already harped on it, but the fact the standard method of evaluation uses substitution again to get rid of all the trig functions is a good indication we should've used a different substitution)
$$-27\int (1-u^2)\,du = -27\cos\theta + 9\cos^3\theta$$
Substituting $\cos\theta = \frac{\sqrt{9-x^2}}{3}$:
$$-27\left(\frac{\sqrt{9-x^2}}{3}\right) + 9\left(\frac{\sqrt{9-x^2}}{3}\right)^3 = -\frac13\sqrt{9-x^2}\cdot \left(27 - (9-x^2)\right) = -\frac13\sqrt{9-x^2}(18+x^2)$$

Which errors does this show in your attempt?

Note that when integrating $27\sin^3\theta$ the coefficient of $\cos^3\theta$ is $9$.
You have at times used $\cos\theta = \frac{\sqrt{9-x}}{3}$ (the wrong one) and at times $\cos\theta = \frac{\sqrt{9-x^2}}{3}$ (the correct one).  It's not clear why you have this inconsistency.
You still seem to have a point you've written $3^3 = 9$.
Answer: Correction of OP:
$$\cos \theta =\sqrt{1-\sin ^2 \theta} =\sqrt{1-\frac{x^2}{9}} =\frac{1}{3} \sqrt{9-x^2}$$

$$
\begin{aligned}
I & =27 \int \sin ^3 \theta d \theta \\
& =-27 \int\left(1-\cos ^2 \theta\right) d(\cos \theta) \\
& =-27\left(\cos \theta-\frac{\cos ^3 \theta}{3}\right) \\
& =-9 \cos \theta\left(3-\cos ^2 \theta\right)\\&=-\frac{\sqrt{9-x^2}}{3}\left(x^2+18\right)+C
\end{aligned}
$$

Suggested solution
$$
\begin{aligned}\int \frac{x^3}{\sqrt{9-x^2}} d x
= & -\int x^2 d \sqrt{9-x^2} \\
= & -x^2 \sqrt{9-x^2}-\int \sqrt{9-x^2} d\left(9-x^2\right) \\
= & -x^2 \sqrt{9-x^2}-\frac{2\left(9-x^2\right)^{\frac{3}{2}}}{3}+C \\
= & -\frac{\sqrt{9-x^2}}{3}\left[3 x^2+2\left(9-x^2\right)\right]+C \\
= & -\frac{\sqrt{9-x^2}}{3}\left(x^2+18\right)+C
\end{aligned}
$$


Transcribing by ear, is it done with the root as reference, or the previous note?

Question: To all the people with good ears:
when you're figuring out a melody by ear, are you listening to the sequence of notes and figuring out where each note sits relative to the root of the key?
Or are you figuring out what the next note is by the interval from the last note?
Comment: You could put a poll on this, because its not like everyone transcribing use the same method
Comment: It's a bit like asking a normally-sighted person to point at the blue ball on a snooker table. not a lot of conscious thought goes into the 'how' of it.
Comment: fair enough, if someone wanted to learn how to do this would you recommend one way over the other?
Comment: Bit of a waste of time referring back to tonic for each note. I guess far more folks would use the last note as the reference point, and know what the interval is, and write accordingly. But they wouldn't necessarily go one note at a time.
Comment: The root of the chord currently played (if any) can also be a good reference.
Comment: @Tetsujin, so transcribing is an unteachable skill?
Comment: @MichaelCurtis - I think you inferred a logic leap I did not imply. However, no-one ever taught me & I've never taught anyone else… which still is neither for nor against what you inferred.
Comment: Yes, I inferred that, because I want to get to the point of answering the OP's question: how to do it.
Comment: By desesperatly trying to find a video where the bassist has been filmed.. and finding none and sit in despair.. lower frequencies are harder to locate for me, my ears are so bad that when it sounds about right it's good, so I mess different octaves, fifths and more (I was even banned from singing in pre-school for that lol).. actually theory kinda saved me
Comment: @StephenJackson , regarding this interesting question, it occurs to me there are three *different* things.  There are (A) people with completely hopeless pitch (wave!).  There are (B) people with fantastic *relative* pitch. Most (perhaps all?) musicians have fantastic relative pitch.  Totally distinct, there are a few freaks of nature who have "absolute" pitch. ie, they hear a note and can simply state "oh, that is 413.5 Hz".  I guess the answer to this interesting question would vary a lot with that situation.  (A huge point of confusion is folks use the term "perfect" pitch messily for B/C!)
Answer:
when you're figuring out a melody by ear, are you listening to the
sequence of notes and figuring out where each note sits relative to
the root of the key? Or are you figuring out what the next note is by
the interval from the last note?

All of those, and none of them.
The thing is, I don't "figure it out", and it's not a matter of reasoning or logical thinking. It happens, I see the incoming melody notes, chords and bass notes in my mind on a piano keyboard or guitar fretboard. If the melody line is too fast and unfamiliar, I don't see it, or if the harmony is completely strange i.e. something I've never played, I might only see rough guesses and movements. And even if I see the notes completely clearly, it might be wrong! I have to play it to verify my guesses.
The learning process is an action-reaction feedback loop and it goes like this:

Hear a note or chord (or whatever aspect you're trying to reproduce)
Guess something as an immediate reaction, not a logical "calculation". Even a wild random guess is ok.
Test the guess by playing it.
If it was wrong, make a correction.
Repeat

Monkey see, monkey do. Monkey don't figure out.
The important thing to realize about the process is, the guesses might be right or wrong, and the accuracy of the guesses improves over time, through practice. But it's not about logical and intellectual reasoning, it's about training and doing, practical exercises. The ability to see the notes without actually playing has come through lots of playing by ear in practice, and when I don't actually play, it's some kind of a mental simulation of playing.
If I interpret your question about tonic (which you meant by "root"?) vs. relative steps to fit this process: I "see" all aspects that I've trained myself to produce.

A tonic/key/reference point is always there and all notes are located somewhere relative to a tonic. Actually it's completely relative - I can re-calibrate the "seeing" at will to any key, because I've trained myself to play any song in any key. That's what I've had to do. For example, if I want, I can see any incoming song in F minor or Ab major, without changing the audible pitch I'm imagining or humming.
Chordal harmony inside the key. What chords would I play to reproduce this progression.
Melody notes. How would I play this melody.
Bass inversions. What would I play with bass notes to reproduce what I'm hearing.

The "next note" / "previous note" thing is an aspect as well - even if my guess is wrong about the melody's relation to the chords and tonic, the melody notes move in steps up/down the scale. Sometimes it happens, particularly if I'm "looking" at a song on the guitar (instead of piano keyboard which is the stronger instrument for me), the melody I see (=guess) on the (imaginary) fretboard is a fifth or fourth off, particularly with some fast jazzy/bluesy lines, I might confuse notes that form extended chords, for example if the melody goes G-E over an Am9 chord, I might see it as C-A. Because the Am9 is kind of Am and Em played at the same time, I imagine the wrong minor third. But if I switch my imagined instrument to piano, I might see the notes differently.
I suppose people who are good at sight reading and composing by writing music, the music staff is like an instrument they play, so they can "see" things they hear on music staves. But that's not the case for me, I need to imagine playing piano or guitar.
Answer: You have to learn motifs and intervals. (Make your self a list of the most usual like:
so-mi, so-la-so-mi, do-re-mi-do, do-re-mi-fa-so, so-do, so-do-mi, so-la-ti-do, do-do-ti-do, do-ti-la-ti-do etc. etc. and then you'll recognize them in a melody. There are lots of identical turns and formulas in folk or pop songs.
You can make (also when listening by ear) a harmonic analysis like a piano chord reduction, filtering out the triad (arpeggios)  and add the other tones as change notes, passing tones and approach notes.
And you won't ask which method we prefer. Everyone uses both and not only these two. You can listen to the base line, the melody, the cadences and sequences and the transposed motifs. All are playing a role, all of them are helpful.
So start training scales, intervals, triads and 7th chords with their resolution like: so-ti-re-fa ->mi-do, by singing, writing, playing, listening.
do-re-do-mi-do-fa ... or  do-mi-re-fa-mi-so (all combinations of intervals and sequences. That's what solfege is. Search for solfeggios and warming ups, also for piano etudes for beginners.
Answer: Many good answers here already, but I'd like to keep it simple:
Use all the clues that you can get, starting from the easiest.
If the interval from the previous note is obvious, use that.
If the interval to the root is what stands out, use that.
If you're not sure and you have an instrument with you, use that -- figure out how to play the phrase on your instrument, and then write what you play.
Comment: +1 I'd also add: if there's an obvious chord progression which the note fits, use that.  I mean, if you're trying to figure out a song and it sounds like it's going to a V chord... any long notes are *probably* going to be V, VII, or II.
Answer: As someone with absolute pitch, when I sit down and transcribe a piece or melody by ear, I determine each note individually by ear regardless of whether the piece is atonal or not or what the note intervals are.
Whoops.
For particularly hard-to-hear notes, though, I do fall back to intervals.
(As an aside, I often sing music by pitch-matching my singing to the (however flawed) recording in my head, which depends neither on keys nor intervals. Bizarrely, I am often aware of the key(s) (if any) of an excerpt I listen to for the first time before I am aware of what each individual note is.)
Answer: I don't rate my ear as good, but pretty good. (Last thing I tried to transcribe was Making Our Dreams Come True from memory. I'd say it was 85-90% right compared to the sheet music.)
I compare to the previous note. Also I make reference not to the tonic (not root) of the key, but to what I think is the surrounding chord.
That second reference to the chord is really important. In homophonic music melody is often just a series of broken chord tones with various non-chord tones added. If you can tell what the chord is and if you have a good knowledge of typical harmony changes, it can help you figure out the melody.
I think my ear improved a lot by singing along to drills on the rule of the octave (major and minor.) It got my ear tuned into the sound of fundamental diatonic harmony. Another good thing is solfege patterns like @Albrecht Hugli recommends. For me DO TI DO, DO RE MI, SOL FA MI, and DO MI SOL and the super important patterns.
Having made the point about homophonic music and diatonic harmony you should be aware that a lot of pop/rock music does not use that texture. The melody can often "contradict" the chords. When it does there is a good change the melody is following very simple scale patterns with probably the focus on the tonic or another tonally strong degree of the scale. Try testing whether the melody is using a pentatonic scale. It has a kind of natural resonance and is common.
You may find example of melody centered around stuff like DO RE MI or a pentatonic pattern while the chord progression moves through chords that "don't match the melody" for some part of the passage. In my mind it's sort of analogous to a pedal point of oblique motion. One part stays fixed on a stable point (in this case a stable portion of scale) while the other parts move through various tones/chords adding color, direction, and tension. Eventually the diverging parts will come back together. Use that knowledge to test things out when trying to transcribe.
One additional thought. When transcribing you can have passages that play note quickly. Even if the tempo is not fast notes can last only a fraction of a second. You might replay something a hundred times trying to hear one elusive, brief note! The issue isn't merely matching a pitch. If each note lasted two seconds, there probably wouldn't be a problem as long as you weren't "tone deaf." The quick change is the problem. One solution is to slow down the recording. Lots of people talk about doing that. But this is also why pattern recognition is so important. When you know common patterns you can test them and see if they match, treating a quick series of notes as single pattern unit.
Answer: If you have perfect pitch, congratulations! None of the following probably applies.
If you have good but not perfect pitch, you can probably get by...if the key and the number of voices, counterpoint, and harmony isn't that complicated. I did this in my first music theory class when we had to transcribe 2-3 moving lines, and it stunted my growth when we started getting lots of chromaticisms, secondary dominants, and hard key signatures.
For mere mortals like myself, the "correct" way according to my college professors is by training your relative pitch, or recognizing intervals between two notes. (It's been some time since I left college, so I may have forgotten some of the finer-grained details).
With good knowledge of what intervals sound like, you can do the following, given the lowest note of a chord:

Figure out all intervals above the lowest note
Figure out the lowest of the next chord in relation to the current note

This should theoretically allow you to transpose any piece of music, but it's really slow.
You can combine it with the following shortcuts to speed things up:

Use knowledge of tonality (major, minor, types of seventh, etc.) to identify the quality of the chord.
Use music theory to rule out unlikely chords in the chord progression/identify non-chord tones and chromaticisms if you are given the chord progression
Use knowledge of inversions + the location of certain intervals to quickly find the root (e.g., if you hear a 2nd in the lowest 2 notes of a 7th chord, it's probably in 3rd inversion)
Answer: When playing by ear (or writing things down), I have a lot of mental scaffoldings in my head. Like a set of automatons working in parallel, each making sense of something else:

relative intervals to the last sound
relative interval to some sound I remember / can relate (e.g. when I play a 6 note motive I hear that the last note is fifth below the first one)
possibilities of the current scale
interval relative to bass
typical harmonic behavior, like resolving dominant 3 or dominant seven (the longer one plays, the more behaviors they consider "typical")

Some of those automatons are more cerebral, and some work on the finger level (even when I am not playing an instrument and just jolting down notes, I actually move my fingers).
When I play "by ear", I see a set of "green lights" in my head: the automatons all confirm each other's choices. It's like: "OK, the next sound is a minor second below... check; it's minor seventh of a minor chord resolving to major third of a dominant... check; it is the seventh tone of the current scale... check; base jumps a perfect fourth up... check; it's the same sound we heard on the beginning of the phrase... check". Sometimes it happens that one of the machines says: "bzzzt! something's wrong!", and then a frantic voting happens, I have to take things off the auto pilot and fall back to 1 (just relative intervals).