Obtain the joint PDF of $\theta_{1} - \theta_{2}$ and $\theta_{1}$ where $\theta_{1}$ and $\theta_{2}$ are i.i.d $\text{Uniform}[0, 2\pi)$

Question: I have 2 i.i.d Uniform random variables $\theta_{1}$ and $\theta_{2}$ on $[0, 2\pi)$. Here the problem pushes us to consider that all operations are made modulo $2\pi$.
My question is how to obtain the joint PDF of $\theta_{1} - \theta_{2}$ and $\theta_{1}$ and then obtain the conditional PDF of $\theta_{1}$ given $\theta_{1} - \theta_{2}$??.
For the second part It can be deduced from the first by writing it as the joint PDF divided by the PDF of $\theta_{1}$. But for the first part, A common idea that I saw is to derive the $\text{CDF}(x, y) = P(\theta_{1} - \theta_{2} \le x$, $\theta_{1} \le y$) and then perform derivations respect to $x$ and $y$. Is this a right approach? If yes, how to proceed with CDF especially with our uniform distribution restrictions?
Answer: You have to take into consideration the following system
$$\begin{cases}
z=\theta_1-\theta_2\\
v=\theta_1
\end{cases}\rightarrow \begin{cases}
\theta_1=v\\
\theta_2=v-z
\end{cases}$$
The jacobian is obviously $|J|=1$ and thus
$$f_{ZV}(z,v)=\frac{1}{4\pi^2}\cdot\mathbb{1}_{(0;2\pi)}(v)\cdot\mathbb{1}_{(v-2\pi;v)}(z)$$
That is the joint distribution is defined over the following parallelogram

Knowing the joint distribution, the rest of the exercise follows as a consequence without difficulties

The fact that the uniform marginals are defined in $(0;2\pi)$ or $[0;2\pi)$ is irrelevant

EDIT: If you want to integrate in V it is very useful to define joint support in a different but equivalent manner (this is why I showed you its drawing)
$$\mathbb{1}_{(-2\pi;0)}(z)\cdot\mathbb{1}_{(0;z+2\pi)}(v)+\mathbb{1}_{(0;2\pi)}(z)\cdot\mathbb{1}_{(z;2\pi)}(v)$$
Comment: For the conditional probability, we should derive that of $\theta1$ -$\theta2$ which is not obvious.
Comment: @The_NooB : Yes it is! see my edits. I did not care about $[$ or $($ in the support because irrelevant as the distribution is continuous. The resulting distribution is a triangular one


Factoring into a product with three term

Question: I want to solve the following equation:
$$144s^3-408s^2+349s-85 = 0$$
I know that the solution is:
$$(s-1)(12s-17)(12s-5)=0$$
which implies gives, $s=1$ or $s=\dfrac{17}{12} $ or $s=\dfrac{5}{12}$.
However, I don't understand how to factor the left hand side into a product of three terms.
Thanks in advance!
Comment: One can use the [Rational root theorem](https://en.wikipedia.org/wiki/Rational_root_theorem) to find one root and then perform long division
Answer: If you know that s=1 is solution, you might try to rewrite $144s^3-144s^2-264s^2+264s+85s-85=0$, then you factor with s-1


Maximum likelihood estimation of a Dirichlet distribution multivariate parameters

Question: Is it  necessary to find the 'maximum likelihood estimates' of prior dirichlet parameters after finding their initial values through the 'method of moments ' to find posterior probabilities through bayesian analysis (using dirichlet -multinomial conjugate pairs)?  If yes, I need to know an easy way to find the maximum likelihood estimates of dirichlet parameters. I did the bayesian analysis with the initial  guess made through the 'method of moments ' without finding MLE . Is it correct to do so?
Eg.  Let A,B,C be the three dependent variables with a prior probability of occurrence (Pij's). So, j = 1,2,3 for the three variables.
I have three observations of three different time periods for each variable A,B,C. So, i = 1,2,3 for the three observations.(The data given below is only an example; not original).
j=1 implies the variable A.
j=2 implies the variable B.
j=3 implies the variable C.
 Let  0.1, 0.4 , and  0.2 be the three observations (for i=1,2,3) of variable A.
 Then  0.6, 0.5, and 0.7 be the three observations of variable B.
 Then  0.3, 0.1, and 0.1 be the three observations of variable C.
I fitted this data with a dirichlet distribution.
With this prior Pij's I made the initial guess of dirichlet parameters  (alphas) by the 'method of moments' from a reference. In the reference they use this intial guess of alphas to find the 'maximum likelihood estimates' of alphas.
But I skipped the MLE method and did the bayesian analysis with a multinomial data as my likelihood function (frequency counts of each variable) and used the initial guess of alphas to estimate the posterior probability of occurrence of the three dependent variables.
Is MLE necessary for prior alphas?
Comment: Yes, I meant a trivariate distribution and the individual variables are dependent as clarified in the above answer.
I made the initial guess (prior values for the alphas) of the prior dirichlet parameters only through  the 'Method of moments' without using 'MLE' and found the posterior parameters. With these posterior parameters  I estimated the posterior mode and mean.
My doubt is actually that whether the  prior parameters found only through ' method of  moments'  without using 'MLE ' is sufficient/valid in my bayesian analysis.
Answer: You seem to be confusing many things in your question.

Is there any quick solution (either by any statistical software or
  manual workout) to find the maximum likelihood estimates of alpha of
  three independent variables of a dirichlet distribution

First of all, Dirichlet distribution is a multivariate distribution, I assume that you mean trivariate distribution in here. Obviously, the individual variables are not independent, it should be obvious at least from the fact that if $x_1,x_2,\dots,x_k$ are draws from Dirichlet distribution, then $\sum_{i=1}^k x_i = 1$, so they need to be dependent to meet the constraint.

provided that the initial values of the three parameters are found by
  the method of moments.

What do you mean by "method of moments" in here? There are many ways of computing the parameters of Dirichlet distribution (see, e.g. Minka, 2000; Huang, 2005), that in most cases maximize the likelihood numerically, and there is no simple, closed-form solution.

Or, Is the initial values sufficient to obtain posterior estimates in
  multinomial-dirichlet bayesian analysis?

To obtain posterior in Bayesian analysis you do not need to find the maximum likelihood estimates of the parameters. Maximum likelihood and Bayesian approaches are two different approaches to estimating parameters. Maximum likelihood is about finding such combination of parameters that maximize the likelihood function. In Bayesian case, you estimate the parameters in terms of the likelihood function and the priors. In Dirichlet-multinomial model (this is not the same as Dirichlet distribution), this is straightforward since Dirichlet is a conjugate prior for the multinomial distribution, and we have a closed form solution. The posterior estimate for $k$-th $\alpha$ is $\alpha_k + y_k$ where $\alpha_k$ is your prior guess for $\alpha_k$ and $y_k$ is the observed number of successes for $k$-th category in the multinomial distribution.

Huang, J. (2005). Maximum likelihood estimation of Dirichlet distribution parameters. CMU Technique Report.

Minka, T. (2000). Estimating a Dirichlet distribution. Online draft.
Comment: The prior guess for alphas is  made through the 'method of moments' by referring to the paper on ''A note on parameter estimation in the multivariate beta distribution'' by A. Narayanan, (1992). I am not using the 'method of maximum likelihood' explained in this paper for the prior guess for alphas. Is this approach   correct to find posterior estimates through bayesian method while using dirichlet - multinomial conjugate pairs?
Comment: @AnaghaRaveendran As I said in my answer, prior is *not* something that is estimated from the data. Moreover, I can't see how exactly you could estimate the prior parameters using method of moments: for this you would need to the the Dirichlet distributed data, i.e. the data *on* your parameters, while from your description it seems that you have multinomialy distributed data and assume Dirichlet distribution for the *unobserved* parameters.
Comment: I am thanking you for your reply. I estimated the prior dirichlet parameters from the prior probability data (Pij's)that I have. j=3 for the three dependent variables and i=3 for three observations of each variable. For this I choose the ' method of moments' from the reference I mentioned early. To estimate those I have'nt taken any multinomial data.
Comment: The 'MLE method ' in the aforesaid reference uses the initial parameter values obtained from 'method of moments' to find a maximum likelihood parameter values. But I did'nt use the latter method. So I need to know whether my former method alone is sufficient for the prior parameter estimation to do the bayesian analysis.
Comment: @AnaghaRaveendran then I am afraid that your description of the problem is insufficient and the question is unclear. What data do you have exactly? What do you want to estimate? How does this relate to Dirichlet-multinomial model (you either have data on multinomial counts, or on "probabilities")?
Comment: I have prior probability values of the three dependent variables  (obtained from a published data ). Then I have another sparse frequency data (counts) of the three dependent variables that I obtained from a real report. I fitted the prior data with a dirichlet distribution and the frequency counts with a multinomial distribution to estimate posterior probabilities through bayesian analysis and that's my objective.
Comment: Initially I have prior probability values but no prior parameter values (i. e. alpha values). So in order to get a prior guess of alphas I used ' method of moments' and found the three prior parameter (alphas) values. Up to this stage I am not using my multinomial data. Then to estimate posterior probabilities through bayesian analysis only  I have to use both the multinomial data and prior dirichlet data. My doubt is that whether I need use the MLE method also to obtain the initial prior guess of alphas.
Comment: @AnaghaRaveendran OK, but could you please edit your question to add those details? Perfectly: could you also add an *example* of the data you have (could be made-up) so we are clear what you are talking about? I think I now understand what do you mean and could answer that, but I'd like to be clear so not to make another guesses. Thanks.
Comment: I have edited the question with a simple example. Please go through it. Though it appears lengthy hope it   will help you to understand my doubt.


Why is the 'age squared' variable divided by 100 or 1000?

Question: I am considering the first fifteen waves of the British Household Panel Survey data. I wished to know the intuition behind using age squared/1000 as one of the variables in the published papers. How do I interpret this?
Thank you!
Comment: Hint: what happens to the estimates if age squared is used instead of age squared/1000?
Comment: To what purpose are the authors using the square of age?
Comment: @Matt The title of the present question suggests it is asking something different: that is, it appears to be unconcerned about using a quadratic term in `age`, but is wondering why that was divided by 1000.
Comment: The analysis is of life satisfaction on various factors like income, health, gender.
Why should we use age squared and also age squared/1000? General interpretation?
Comment: possible duplicate of [Why would one use age-squared as a covariate in a genetic association study?](http://stats.stackexchange.com/questions/19823/why-would-one-use-age-squared-as-a-covariate-in-a-genetic-association-study)
Comment: The text is a little less clear, but I suppose you're right.
Answer: Age squared results in often fairly large values for the variable (e.g., $60^2=3600$), with correspondingly small estimated coefficients - an increase in age squared by one really is a small change in age, so the effect of that change as measured by the coefficient should be very small.
These small coefficients may be hard to print in output, and hard to interpret (but coefficients in regressions with polynomials are always hard to interpret). The adjustment just scales up the estimated coefficients.
In general, we have the following result:
Consider transforming $X $ by some invertible $k\times k$ matrix $A$, $XA$ (e.g., change months of schooling to years and meters to centimeters when explaining wages).
Then, see what happens to the estimated coefficients:
\begin{align*}
\hat{\beta}^\circ&=\bigl(\underbrace{A'X'}_{``X'"}\underbrace{XA}_{``X"}\bigr)^{-1}\underbrace{A'X'}_{``X'"}y\\
&=A^{-1}(X'X)^{-1}(A')^{-1}A'X'y\\
&=A^{-1}(X'X)^{-1}X'y\\
&=A^{-1}\hat{\beta}
\end{align*}
That is, if
$$
A=\begin{pmatrix}
1/12&0\\
0&100
\end{pmatrix}\qquad\text{so that}\qquad A^{-1}=\begin{pmatrix}
12&0\\
0&1/100
\end{pmatrix}
$$
in the above example, the effect of a change in the regressors is, sensibly, adjusted accordingly. Another year of education yields 12 times more additional wage than another month, and another cm has only $1/100$ of the effect on wages as another meter.
Here is a little numerical example in R to illustrate the point (which I hope I could clarify is not intrinsically related to squared regressors):
X <- rnorm(20)
y <- rnorm(20)

summary(lm(y~X))$coefficients[2]
[1] -0.03610936

X <- X*10
summary(lm(y~X))$coefficients[2]
[1] -0.003610936


Printing out path from views - /drupal/ appears twice

Question: I'm using this to print out a custom link format in views. I'm using it in the unformatted views tpl.php file.
<?php print l(' a',
              $view->style_plugin->row_tokens[$id]['[path]'],
              array ('html' => TRUE)); ?>

This line calls the relevant HTML path:
$view->style_plugin->row_tokens[$id]['[path]']

For example it might contain the value: localhost/drupal/node/31.
But when I put it in the l() function I get localhost/drupal//drupal/node/31.
Anyone know how I can stop the double print out? This is driving me mad.
Comment: I see two problems there, first one is with the path format. The path should start and ends without slash, for example: `node/1`. In your case, `$view->style_plugin->row_tokens[$id]['[path]']` returns `/localhost/drupal/somepath` That's why you've got the additional slash. The second problem is with the path string, because it should be an internal path or external URL, such as "node/34" or [http://example.com/foo](https://api.drupal.org/api/drupal/includes!common.inc/function/l/7)
Comment: Cheers that cleared up the confusion. I found another thread in the end and realised that I could just build the relative path using the Node ID. Posted the answer below.
Answer: <?php print l('',
'node/' . $view->result[$id]->_field_data['nid']['entity']->vid,
array ('html' => TRUE)); ?>

Here is the final solution.
It will add the NID on the end of node/ and create the internal path "node/x". If you're using Pathauto this will still work.


How to identify slot for faulty GPU card in server using UBUNTU OS commands?

Question: I have a question. Is it possible to identify in which slot there is a broken GPU card using the UBUNTU operating system? We have a SuperMicro GPU server in which there are about 8 GPU cards for AI computing. Every now and then we go to the server room after we get information from users/department that the card is not visible in 'nvidia-smi' command. These are generally hardware failures. Then we encounter a situation where 7 cards are working properly and unfortunately we have to identify the faulty card by trial and error by pulling it from the server. This is terribly tedious and time consuming, so I am wondering if it is possible to unambiguously identify the slot where the faulty card is located.
Thank you in advance.
Comment: Are you able to determine PCI address of the faulty card?
Answer: In general, if you are able to find out which PCI bus address this card has, you can locate the precise slot it occupies. Traverse dmidecode output and find in which slot this PCI address appears.
However, this only helps if you have confidence the PCI slot numbering in DMI is predictable and corresponds to actual physical slots on the motherboard. In brand computers (HPE, Dell, etc.) this is often the case. If the motherboard is manufactured by less reputable brand, its DMI data may be not in sync. Nevertheless, this is worth trying.


Z-score distributions are not normal, explain how this still works, and how relevant this is when calculating them on a per-protein basis

Question: I did some data analysis using Z-score. For example, I have 10 proteins(N length) in my dataset. I did some prediction of each protein and that gave me residue wise score. Then we have calculated Z-score for each residue position in protein and plot Z-score distribution for 10 proteins. My observation was that Z-score distribution was skewed. Based on Z-score I did classification if Z<0 then those residue will be class1 and if Z>0 then those residue class 2. but someone asked me question 'Z-score distributions are not normal, explain how this still works, and how relevant this is when calculating them on a per-protein basis'
I gave this answer Z-score distribution is mirror of original distribution so thats why it skewed but it works.how it works that i need statistical explanation.
I am not statistical expert so can anyone help me to get right mathematical explanation of my question.
Thanks
Comment: If you used the formula $z = \frac{x - \text{mean}}{\text{SD}}$ then any values below the mean will have a negative z-score and any above the mean will have a positive z-score. As it is currently written, the question is quite unclear. When you say "explain how this still works", what does "this" mean?
Comment: how this classification still works based on +ve and -ve Z-score criteria where we have observed Z-score distribution was skewed for whole dataset? is not giving some bias result ? Although I am note sure I have used right statistical term
Comment: What is the result you are attempting to achieve? What would it mean for this result to be biased? You are correct that if the original distribution is skewed then the distribution of z-scores will be skewed too, but how does this relate to the classification problem?
Answer: You standardized the data in your data set and ensured it would have a mean of 0 and a standard deviation of 1. However, this merely shifts and shrinks/stretches your data.  The shape of your data is not going to change.  As such, standardizing won't make the data Normal and it won't remove a skew. The standardized data will be Normal only if the original data is Normally shaped and the standardized data will not be skewed only if the original data is not skewed.
Comment: I think, though it is not entirely clear, that the OP already knows this - when they saw the z-score distribution "mirrors" the original distribution, and therefore it is skewed, this is what they're getting at. But your answer doesn't address the classification issue.
Comment: Mu understanding was that OP was wondering how the distribution of $Z$-scores still skewed. OP mentioned that it mirrored the original distribution, but not *why*. I could have certainly misinterpreted the question, however!
Comment: Helpful, but the word "necessarily" should be omitted. As you say, standardization doesn't change distribution shape, so it can't even happen by accident that standardizing a distribution gets it closer to normal.
Comment: I'll edit it, Nick! I think the problem arises when I say that it would necessarily *make* the data Normal. I want to express that the standardized data need not be Normal.
Comment: Indeed, but your sentence is now correct and clearer.
Comment: Apologies if my original comment seemed unduly critical - I'm not completely sure what the original poster was asking (and hope that they clarify at some point!) but the *classification* issue, and what this meant on a "per protein basis", appeared to be important to them. I agree with Nick Cox that this answer is at least correct and clear; whether it addresses what the OP wants is hard to know until there's some clarification.
Comment: Thanks. at least from your comments it is clear I can use Z-score although it skewed .


How to prove Exponential is monotone?

Question: How can you prove that if given $x>y$ implies $e^x >e^y$ ?
Comment: What is your definition of the exponential function? the answer we will give will highly depend on your definition!
Comment: Power series definition only .
Comment: sorry x and y are real.
Answer: From the power series definition, it is clear that $e^t>1$ for $t>0$.
Take $x>y$ and let $t=x-y>0$. Then $e^{x-y}=e^t>1$, which implies $e^x=e^{x-y} e^y > e^y$.
This assumes that you have proved $e^{a+b}=e^a e^b$.
Comment: @Bob, one way is to prove that $e^x$ is the only solution of $f'(x)=f(x), f(0)=1$. It all really depends on the order you do things.
Comment: But how will you prove that $e^(a+b)=e^ae^b$.
Comment: But how can you prove that it is the unique solution and f(0)=1
Answer: Hint:
\begin{align} e^x-e^y&=\left(1+x+\frac{1}{2!}x^2+\frac{1}{3!}x^3+\ldots \right) - \left(1+y+\frac{1}{2!}y^2+\frac{1}{3!}y^3+\ldots \right) \\
&=\left(x-y\right)+\frac{1}{2!}\left(x^2-y^2\right)+\frac{1}{3!}\left(x^3-y^3\right)+\ldots  \end{align}

How to prove Exponential is monotone?


Como evitar SQL Injection em minha aplicação PHP?

Question: Explicação:
A maioria das aplicações utilizando PHP, devem receber parâmetros, por $_GET ou $_POST e estes parâmetros muitas vezes se tornam um alvo fácil para os usuários com más intenções, e isso se chama SQL Injection.
Pergunta:
Gostaria de saber como evitar que minha aplicação seja atacada via SQL Injection, como proceder?
Comment: Essa afirmação não é verdadeira: "A maioria das aplicações utilizando PHP, devem receber parâmetros, por $_GET ou $_POST e estes parâmetros muitas vezes se tornam um alvo fácil para os usuários com más intenções, e isso se chama SQL Injection.". Get ou Post podem ser utilizados como porta de entrada para uma série de coisas com problema. A injeção de SQL por acaso pode acontecer por estes meios também, mas são conceitos sem nenhuma relação direta.
Comment: http://pt.stackoverflow.com/questions/3864/como-prevenir-injecao-de-codigo-sql-no-meu-codigo-php
Comment: @Sergio vejo que a pergunta é sobre o mesmo conceito porém é limitado ao conteúdo preposto pelo OP da pergunta, não?
Answer: Você deve codificar todos os parâmetros passados para a sua aplicação antes de concatenar ao seu SQL. Todos os bancos de dados suportam de alguma forma salvar dados no banco, mesmo que seja um SQL, e para isso o valor deve estar devidamente codificado.
Métodos úteis para codificar as strings:
mysql_real_escape_string -> depois de usar este método e escapar a string, você poderá concatenar no SQL a ser executado.
Ou então use métodos que executam SQL, que levam parâmetros
Existem bibliotecas que permitem indicar um único SQL, com marcadores de parâmetro no meio do SQL, sendo que esses marcadores são substituídos de forma a evitar injeção de SQL.
Exemplo:
$con  = new mysqli("localhost", "u", "p", "test");
if (mysqli_connect_errno()) die(mysqli_connect_error());

$sql  = "INSERT INTO articles (title, body, date) VALUES (?, ?, NOW())";
$stmt = $con->prepare($sql);
$ok   = $stmt->bind_param("ss", $_POST[title], $_POST[body]);

if ($ok && $stmt->execute())
  header('Location: index.php');
else
  die('Error: '.$con->error);

Origem do exemplo no SOEN
Answer: Comentários pessoais
Vejo várias pessoas, inclusive aqui no SOPT, cometendo o erro de deixar sua aplicação vulnerável à SQL Injection, claro que por falta de informação, porém é de suma importância dizer que é essencial hoje em dia prevenir este tipo de ataque, pois é conhecido por um bocado de pessoas mal intencionadas.
Explicações:
"Como funciona o SQL Injection?"
O SQL Injection como diz no nome traduzido para "Injeção SQL", nada mais é do que um script SQL que é executado em seu banco por alguém que não tem acesso à ele, desta forma deixando seu banco totalmente vulnerável à qualquer coisa que o usuário mal intencionado queira fazer.
"Como/Porque os usuários mal intencionados conseguem fazer isso?"
O problema está em algumas aplicações PHP que utilizam parâmetros que estão presentes na URL ou até mesmo os parâmetros escondidos que você passa no cabeçalho de sua URL, para preencher dados em um script SQL.
Exemplo:
Você tem uma aplicação que precisa de um ID para realizar um SELECT, até aí tudo bem, porém vamos dizer que você tem vários links que enviam o parâmetro ID diferente:
Produto 1
Produto 2
Produto 3
Produto 4

E no produtos.php você resgata diretamente o valor e joga no SELECT (o que não deve ser feito):
$id  = $_GET['id']; //aqui ele vai pegar qualquer coisa que você passar como valor do id
$sql = "SELECT * FROM TABELA WHERE ID=".$id; //aqui ele vai inserir o valor do id

Notou o risco na segurança?? quem quiser, pode simplesmente por dedução saber que você está fazendo isto(do qual é uma coisa muito básica) e executar mais comandos no seu script como um DELETE por exemplo e acabar com o seu banco.
Resposta: "Como resolver este problema?"
Bom, há vários métodos a se fazer, depende de de cada programador, porém eu gosto de sempre manipular a variável antes, verificar o tipo correto, e até as vezes limitar o tamanho dela, para garantir que não seja um script malicioso e sim minha informação, caso contrário, não execute o sql, por exemplo:
$id = $_GET['id'];
if (is_numeric($id)) //verifica se é um numero retorna true do contrario retorna false
  $sql = "SELECT * FROM TABELA WHERE ID=".$id;

Desta forma por exemplo, só executaria o sql se $id fosse um número, então impedindo qualquer tentativa de injetar um script.
Porém há outras maneiras outras formas de realizar verificações do tipo, o objetivo apenas é: Limitar ao máximo os parâmetros que você utiliza para script's SQL, ou não utilizar parâmetros.
Comment: [*Bobby Tables*](http://xkcd.com/327/) manda lembranças ;)


Grid-based Monte Carlo simulation using mc2d

Question: I have a simple equation to calculate the "CL" from the sum of four different grids as:
CL = A + B + C + D
I am attempting to use the mc2d package to express uncertainty in the CL results based on uncertainties in each of the input grids.
The uncertainty in each input grid is expressed based on uniform distributions with uncertainty ranges of:
+/- 6 for raster A
+/- 10 for raster B
+/- 12 for raster C
+/- 5 for raster D
I would like to run a Monte Carlo simulation whereby the input grids are summed multiple times (e.g. n = 1000) based on values for each grid cell that are randomly selected from within these uncertainty ranges
The code below fails with:
Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
    cannot use this function

I am not sure how to address this error. Any suggestions would be much appreciated.
library(raster)
library(rgdal)
library(mc2d) #load package

# Input grid files
A <- raster(matrix(c(20, 35, 40, 60), nrow=2))
B <- raster(matrix(c(6, 10, 13, 14), nrow=2))
C <- raster(matrix(c(6, 8, 12, 14), nrow=2))
D <- raster(matrix(c(35, 40, 50, 60), nrow=2))

# combine the RasterLayer objects into a RasterStack
s <- stack(A, B, C, D)

# Uncertainty distance for each raster used to establish the
# min/max for the uniform distributions in the function just below
uA <- 6
uB <- 10
uC <- 12
uD <- 5

# Function for generating CL
ndunc(1000)
fun <- function(x) {
  # Convert each raster to mcnode object
  dA <- mcdata(x[1], type="0")
  dB <- mcdata(x[2], type="0")
  dC <- mcdata(x[3], type="0")
  dD <- mcdata(x[4], type="0")

  # Define uniform distirbutions for each raster
  stA <- mcstoc(runif, type="U", min=dA-uA, max=dA+uA, rtrunc=TRUE, linf=0)
  stB <- mcstoc(runif, type="U", min=dA-uB, max=dA+uB, rtrunc=TRUE, linf=0)
  stC <- mcstoc(runif, type="U", min=dA-uC, max=dA+uC, rtrunc=TRUE, linf=0)
  stD <- mcstoc(runif, type="U", min=dA-uD, max=dA+uD, rtrunc=TRUE, linf=0)

  # Apply Monte Carlo to this equation
  CL <- stA + stB + stC + stD
  # Extract the min, mean, and max CL from the 1000 iterations
  c(min(CL), mean(CL), max(CL))
}

# Need to create rasters for min(CL), mean(CL), and max(CL)
x <- calc(s, fun)
names(x) = c('min', 'mean', 'max')
plot(x)

Comment: The original question has been modified to include an answer that was provided elsewhere. The code is now working without error.
Answer: The error in the function was caused by a typo (missing equals sign) in rtrunc=TRUE


Node.js - mysql: Bad field Error

Question: I parse a big csv and insert row per row into my mysql tables.
After parsing I do a lot of calculation and transforming and save it to a new Object
  obj.push({
   "ID": value.id,
   "col1": value.calc1,
   ... });

After the Object is complete I do:
async.forEach(obj, function (Insertobj, callback) {

 var query = conn.query('INSERT INTO table SET ?', Insertobj);

  },function (err){
      if (err) {
        console.log(err);
        console.log('failed to process');
 }}

After running through the obj I get =>
Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'field list'..

But he inserts the complete Object into my table! I don't have any column called NaN or empty cols. How can I debug it? I try to set the console.log to err.sql, but he print "undefined". Using debug:true in connection didn't help me.
Answer: I think you have misunderstood how escaping mysql values works using the node js module. The error is due to you not specifying what column you want to update. In addition to this, the escaped values should be filled in using an array instead of an object. With values being in the order they are escaped in the query. Your code could look as follows:
    valuesarray.push([
       value.id,
       value.calc1
    ]);

    async.forEach(valuesarray, function ( insertarray, callback ) {

        var query = conn.query('INSERT INTO table SET ID = ?, col1 =
        ?', insertarray);

    },function (err){
        if (err) {
            console.log(err);
            console.log('failed to process');
        }
    });

Node.js - mysql: Bad field Error


Guitar Bridge saddles out of sync?

Question: I recently had a bit of trouble with a stuck string, so I unscrewed my electric guitars bridge to get rid of the string, but when i screwed it back in, it looked a bit off.

It might just be me, but can anyone tell me what's wrong and how to fix it?
Comment: They'll align back in place when you put the strings back on, just give them a hit and it'll be right.
Answer: The saddles for strings 1, 2 and 3 are definitely misaligned and are skewed off at an angle (towards the bottom of your photo). There don't seem to be any alternative holes for your string length adjusting screws, and even stripped threads wouldn't account for the issue, since the saddles are still touching. It looks to me like the bridge saddles are non-standard/retrofitted and are too wide for the bridge.
Answer: The six screws are, I guess, are what you took off - did you leave them a couple of turns loose? They're not supposed to be tight down onto the body. The vibrato only works if there's room under the heads for it to pivot. When that's done, and the new strings are on, it should straighten itself up, due to the string tension balancing the spring tension in the guitar body.
You might also like to check the intonation on the strings, as the saddles don't look as if they are in their proper relative positions - usually the B string is slightly longer than the 1st and 3rd, but here it looks too short.

Guitar Bridge saddles out of sync?


How can I bring an interface down once the amount of data transferred reaches a predefined limit?

Question: I'm using a Linux box as a router between two of its network interfaces to route local traffic to and from the internet. The internet connection in question has a defined data allowance, and exceeding this is expensive.
Ideally, I'd like to have the Linux box monitor the amount of data being transferred over the internet-facing interface (as the sum of received and transmitted data) and to bring the interface down once that limit is exceeded. I've been unable to find a ready-made tool for this purpose. How would I best go about this?
Answer: One option is to use a root cron job that runs every minute with the following script (with output appended to a logfile):
#!/bin/bash
USAGE=$(awk '/wlan0/ {print $2+$10}' /proc/net/dev)
USAGEMIB=$(echo "$USAGE" | awk '{printf "%0.1f", $1 / 1024 / 1024}')
LIMIT=500
ABOVELIMIT=$(echo "$USAGEMIB" "$LIMIT"| awk '$1 > $2 {print "1"}')
echo -e $(date)"\t"$USAGE"\t"$USAGEMIB" MiB"
if [ "$ABOVELIMIT" == "1" ]
  then
    echo "Limit reached."
    /sbin/ifdown wlan0
fi

This sums together the received and transferred bytes in the relevant entry in /proc/net/dev, prints it as bytes and MiB to stdout (redirected to a log), and if the usage exceeds the limit that is hardcoded into the file near the top brings down the connection. It's not particularly robust (in particular it doesn't have any error handling), but should serve the purpose intended.


"$nid" for individual pages not working

Question: <?php
  $nid = arg(1);
  $arg0 = arg(0);
  if(isset($nid) && is_numeric($nid) && isset($arg0) && $arg0 == 'node') {
    $node = node_load($nid);
  }
  $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
  if(isset($theme_img)) {
    // print styled image
    print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
  }
?>

I am using the above code to load styled image (from node 6) in page.tpl file. This is working fine in all the pages but when I am trying to load images from individual images by using '$nid' it is not working.
I don't understand what I made mistake in code due to which I couldn't get the value of '$nid'. Please help.
Comment: Why are expecting $nid as a global variable or if not your above code is not showing how you are using $nid.
Answer: As you are looking to edit/override node template, it is suggested to place your changes into node.tpl.php where you will get $nid as out of the box. page.tpl.php will not give you node variables by default.
If you still you want to get your code on page.tpl.php you can get $nid from url like arg(1).
Let me know if I miss anything!
Answer: If you want to use $nid variable in your page.tpl.php, you can add that variable to be available in the page.tpl.php by implementing hook_preprocess_page() in your theme's template.php. In your implementation of the hook_preprocess_page() you have to add a key 'nid' to the $variables array. Eg: $variables['nid'] = the_nid_you_want;. After you have saved the changes, clear the Drupal cache and the $nid variable will now be available in your page.tpl.php
Answer: I guess you want to replace the "6" by the current nid of the page.
If so, you could use this code to get the nid of the current page:
$nid = arg(1);
$arg0 = arg(0)
if(isset($nid) && is_numeric($nid) && isset($arg0) && $arg0 == 'node') {
  //If you're using devel
  dsm($nid);
  //If not
  drupal_set_message($nid);
}

But as stated by Jeet, if the code is specific to one content type, you should do this in a node--mycontenttype.tpl.php and not in the page.tpl.php
Comment: Thanks Matt. Due to your code I could get the node ID but getting some error on node page which doesn't have field "field_page_cover_image". Please see the updated code above.
Comment: The modified code works fine in pages which has images uploaded. It doesn't work on pages which doesn't have image field or uploaded image.

"$nid" for individual pages not working


How to make a menu that will change the language of my site

Question: I am new to web development and I want my site to have a drop-down menu that will change the language of my site.I want a solution that will not require me to create a whole new html of the new site. I also want a way to make an input field that will ask users to add a number and then it will automatically add a word after the number.
Answer: Not sure what the second part of the sentence is but a somewhat easy way of doing this is server-side scripting. For example, if you are using PHP, I would recommend you echo the a variable instead of actually typing the contents in the place it belongs. Instead, store the content in a database and then load the content from a database depending on what language is selected (store this a session variable), store it in the variable and when the variable is echoed, bam.
Answer: Perhaps this maybe of some use to you - http://code.google.com/p/jquery-translate/.
Answer: Create in PHP by using $_GET[l];
 <?php
   if($_GET[l]=='en')
   {
          echo 'Welcome';
   }
   else if($_GET[l]=='sk')
   {
          echo 'Vítajte';
   }
   else if($_GET[l]=='de')
   {
          echo 'Wilkommen';
   }
   else
   {
          echo ''; //Here set your default language. For example if is not set- automatically to english
   }
 ?>

Menu:
 <?php
   if(isset($_GET[topic]))
        {
              //This is code, if you use another $_GET[...]
              //Without this, page will crash ,while it shows another thing
         echo 'English';
         echo 'Slovensky';
         echo 'Deutsch';
              //?l=lang changes to &l=lang
        }
    else
        {
              //Link with normal ?l=lang, cause page does not use another $_GET[...]
          echo 'English';
          echo 'Slovensky';
          echo 'Deutsch';
        }
 ?>


How do I use Stan to fit a covariance matrix?

Question: I'm new to Stan (and bayesian methods in general), so this is likely very simple.
I'm trying to model some multivariate normal data. All I want to know is the covariance matrix generating the data, assuming the data is centered. I've been using this as my template: https://github.com/jrnold/pygments_bugs/blob/53eecb07aa805df7cedc365b7faab641e8fe541d/examples/stan/jaws.stan
But I can't get it to properly fit a known covariance matrix.
I'm using Matlab to simulate some data. Here's the little code snippet:
x = mvnrnd([0,0],[1,1.5;1.5,3],100);

data = struct('N',100,...
'dim',2,...
'x',x);

fit1 = stan('file','singleWishart.stan','data',data,'iter',1000,'chains',4);`

And here's the stan code:
data {
int<lower=0> N; // Sample size
int<lower=1> dim; // Number of dimensions
row_vector[dim] x[N]; // Value for each sample on each dimension
}

parameters {
cov_matrix[dim] cov1;
}

model {
vector[dim] zeros; //For now, means are zero
matrix[dim,dim] identity; //Identity for scaling matrix

zeros <- rep_vector(0, dim);
identity <- diag_matrix(rep_vector(1.0,dim));

cov1 ~ inv_wishart(dim, identity);

for (n in 1:N)
    x[N] ~ multi_normal_prec(zeros, cov1);
}

I've tried both cov1 ~ inv_wishart and cov1 ~ wishart (I'm not clear on which one I should be using - I thought wishart, but the examples I've seen seem to use inv_wishart), but neither have worked, giving me ridiculous estimates instead of the expected 1, 1.5, 1.5, 3.
Comment: You should declare and define `zeros` and `identity` in a `transformed data` block of a .stan program so that they only get allocated once at the outset rather than every time the posterior function is evaluated (which could be more than a million times with the default settings).
Answer: The primary reason that your code does not yield the expected answer is that you are using the multi_normal_prec likelihood rather than the multi_normal likelihood. The former expects a precision matrix (the inverse of a covariance matrix) as its second argument, while the latter expects a covariance matrix.
For what it is worth, you should be able to recover the matrix that generated the data if you use multi_normal_prec for the likelihood, use cov1 ~ wishart(dim, identity) for the prior, and then inspect the distribution of the inverse of cov1. But it would be more straightforward, to change the likelihood to multi_normal and leave cov1 ~ inv_wishart(dim,identity) as is.
Comment: All that said, I do not ever use the Wishart or inverse-Wishart distributions with Stan for reasons given at https://groups.google.com/d/msg/stan-users/fhghq6Rxbqs/-dG0apK0NV4J . If you must utilize the inverse-Wishart, to get decent results from Stan I would integrate it out of the posterior as described at https://en.wikipedia.org/wiki/Inverse-Wishart_distribution#Conjugate_distribution .
Comment: For the benefit of OP, I'd like to add that using a parameterization that separates the variances from correlations is superior in Stan because it allows each to move separately, which is important because Stan cares about the geometry of the posterior.


Why is it especially bad to reboot a mainframe?

Question: This is something I've heard a lot throughout my career, from practically every mainframe operator/admin I've ever worked with, and up until now, I never really questioned it, or had a reason to care one way or another.  Never reboot a mainframe, because that's particularly awful heresy, and it creates all kinds of risks and problems, plus IBM kills a puppy every time someone reboots a mainframe.  (Or something along those lines, anyway.)
Well, recently, I've been forced into a situation where I have a reason to care, and the more I think about it, the less sense it makes.  Mainframe hardware is designed to be resilient, the OS on those things is about as stable as you can get, and I'm pretty sure IBM doesn't actually have a large stockpile of puppies to murder every time an iSeries gets rebooted.
Of course, I get that server reboots in general are poor practice, or an option of last resort, or something you should only do when the on-call guy has a hot date lined up, but I'm currently jumping through all kinds of crazy hoops to avoid having to reboot an iSeries because... well, "just because," it seems.
With that in mind, can anyone with mainframe experience explain the technical reason(s) that rebooting a mainframe is especially bad compared to rebooting a *nix or Windows server?
Comment: @JamesYale I wouldn't say that it's less common to reboot *nix boxes than Windows boxes. Unless, of course, you're ignoring kernel updates.
Comment: I think you summed it up in your third paragraph. Generally if you've planned your maintenance properly you shouldn't need to reboot a box (whatever platform).

I also suspect it has something to do with the relative philosophies in administering these systems - it's more common to reboot Windows boxes, less common on *nix boxes, so when you get all the way to mainframes you're expected not to take the easy option.
Answer: I don't know if this is widely applicable, but in the 2 places I've worked that had mainframes with programmers on staff, reboots were verboten because of the amount of manual work that it took to get the applications up and running after a reboot. Things like fixing communication problems to other systems, dealing with inconsistent data on disk, etc.
In my opinion (not being a mainframe programmer) these are all indications of poorly written software. I mean, come on! Inconsistent data on disk!? It's not like I pulled your power cord. I gave you notice to cleanly shut down!
YMMV, but that was my experience.
Comment: +1 The only mainframe shops I've been in, it's this exactly. Sh*t software that doesn't shutdown cleanly and doesn't start on it's own. 100% someone else left a pile of crap in the toilet, and it wont flush...
Answer: In any situation where reboots are infrequent, reboots tend to show up all sorts of unfortunate software bugs that don't occur during normal running. Since these don't come up often, they don't get noticed and therefore don't get fixed. making reboot time a very scary thing.
The other issue is that mainframes tend to be doing a lot of different things, and so rebooting the mainframe may well take out a LOT of different systems for a while. Depending on what's on there, you could be turning your entire business off for 10 minutes while you reboot.
Answer: Well, two items.
First, remember mainframes are COMPLEX and not necessarily all software is made to stop i ncase of a reboot coming - you may run into a lot of issues with processes just interrupted in the middle of something. Manual cleanup time. Something mainframes are actively developped to avoid - with stuff like transactional memory updates (when properly programmed) and processoes that allow hot swapping a processor ;)
Second, be sure you kno wwhat you talk about when you talk of reboot. Pretty much every Mainframe runs VMS or something similar. VMS is "the" original hypervisor - like VmWare on steroits, and 50 years earlier ;) So to say.
Reboot means what? Rebooting THE MAINFRAME, or rebooting an instance of the operating system in a virtual machine? ;)
I would assume rebooting a mainframe is rarely ever necessary, mostly because (a) you ahve everything in a virtual machine anyway and (b) even most hardware failures will not require core reboot.
Comment: I'm sure if you'd tried a little harder you could have squeezed a smiley into the last paragraph, too, to keep your perfect streak going.


How to find the maximum of this oscillating function?

Question: Given $n \in\mathbb{N}$, $a_1, \dots, a_n \in\mathbb{C}$, $k \in \mathbb{R}$ and $x_1, \dots x_n \in \mathbb{R}^3$, let $\Phi : \mathbb{R}^3 \to \Bbb C$ be defined by
$$\Phi (y) := \sum_{i=1}^{n} {a_i \frac{e^{j k \| x_i - y \|_2}}{\| x_i - y \|_2}}$$
where $j := \sqrt{-1}$ is the imaginary unit. Note the singularities at $y \in \{ x_1, \dots x_n \}$.
Can somebody please point me to a more elegant method than brute forcing (just evaluating the expression at millions of points) to find $y$ for which $|\Phi|$ has the global maximum and is not near a singularity (distance > $k$)?
Comment: I understand that $\| x \|^2$ is the square of $\| x \|$, but what's the meaning of $\| x \| _2$?
Comment: $\| x - y \|_2$ is the L2-Norm (the euclidean distance between $x$ and $y$)
Comment: I wonder if there is some insight to be gained from the physics you're interested in solving here. Clearly this looks like a potential of a collection of time-harmonic charges, but I can't get my head around why you would want to maximize the potential. My intuition says away from the sources there will be one or more dominant lines along which things will add up constructively (analogous to the peaks in an antenna pattern), and then you can simply do a gradient-based optimization after restricting y to each of those lines. But I of course have not worked out the details.
Comment: Also I think your "not near a singularity" condition should be distance>1/k since k necessarily has inverse-distance as its unit, and distance > 2pi/k is maybe even better so you're at least one wavelength away from the singularity
Comment: So $\| x - y \|_2$ is the same as the "regular" $\| x - y \|$ :-)
Comment: You are right on the point. Note that im looking for the point where the sum of a given number of time-harmonic charges in space with a given amplitude and phase has its global maximum. I think (linear) gradient-based optimization doesnt work, since there are many local minima and maxima in the field since the fundamental solution of the Helmholtz-Equation is used here and theres alot of oscillation going on.
Comment: Is a result that is valid for y very far away from the charges acceptable, or are you specifically looking for the maximal potential in the near-field of the charges?
Comment: Yeah true using the wavelength 2pi/k could be a better condition. Im looking for y with a minimum distance of about a wavelength from the charge but I would be happy with any result you have obtained be it nearfield or farfield.
Answer: Follows a MATHEMATICA script which implements a maximization procedure to obtain the desired maximum. The nature of the problem, prone to many relative maxima, indicates to choose an evolutionary algorithm to perform the search. The charge points are given in X the coefficients $a_k$ are given as a[1],...,a[n], $k$ is represented by lambda. The objective function is handled as $\|\Phi(y)\|^2$ and the unknown $y$ as Y. Attached a plot showing in blue the X charge points and in red the solution for Y.
SeedRandom[2]
Clear[Phi]
n = 30;
r = 0.06;
parms = Join[Table[a[k] -> 1, {k, 1, n}], {lambda -> 5}];
X = RandomReal[2 {-1, 1}, {n, 3}];
Y = {x, y, z};
dots = Table[Sqrt[(X[[k]] - Y).(X[[k]] - Y)], {k, 1, n}];
Phi[j_] := Sum[a[k] Exp[j lambda dots[[k]]]/dots[[k]], {k, 1, n}];
objr = (Phi[I] + Phi[-I])/2 // ComplexExpand;
obji = (Phi[I] - Phi[-I])/(I 2) // ComplexExpand;
obj = objr^2 + obji^2;
restrs = Table[Sqrt[(X[[k]] - Y).(X[[k]] - Y)] - 2 Pi/lambda, {k, 1, n}];
restrs0 = Thread[restrs > 0];
case = Join[{obj}, restrs0] /. parms;
sol = Quiet@NMaximize[case, Y, Method -> "DifferentialEvolution"]

(******* To show the fitting to the restrictions *******)
restrs /. parms /. sol[[2]]
restrs0 = Thread[restrs > 0] /. parms /. sol[[2]]
(*******************************************************)

gr1 = Table[Graphics3D[{Blue, Sphere[X[[k]], r]}], {k, 1, n}];
gr2 = Graphics3D[{Red, Sphere[Y, r]} /. sol[[2]]];
Show[gr1, gr2]


How do I align a caption to be above an image?

Question: I'm trying to teach myself HTML and CSS but I can't seem to find out how to make a caption to be above an image. I'm trying to build a gif showcase of planets spinning, I have earth so far. I want to position the word "Earth" above the gif. and then so on for all the other planets. Here is my code. I am open to suggestions on improvements and criticism.

body {
  background: radial-gradient(circle at bottom, navy 0, black 100%);
  height: 100vh;
  overflow: hidden;
}

.space {
  background: rgba(128, 0, 128, 0.1) center / 200px 200px round;
  border: 1px dashed purple;
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
}

.stars1 {
  animation: space 180s ease-in-out infinite;
  background-image: radial-gradient(1px 1px at 25px 5px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 50px 25px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 125px 20px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 50px 75px, white, rgba(255, 255, 255, 0)), radial-gradient(2px 2px at 15px 125px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 110px 80px, white, rgba(255, 255, 255, 0));
}

.stars2 {
  animation: space 240s ease-in-out infinite;
  background-image: radial-gradient(1px 1px at 75px 125px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 100px 75px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 199px 100px, white, rgba(255, 255, 255, 0)), radial-gradient(2px 2px at 20px 50px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 100px 5px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 5px 5px, white, rgba(255, 255, 255, 0));
}

.stars3 {
  animation: space 300s ease-in-out infinite;
  background-image: radial-gradient(1px 1px at 10px 10px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 150px 150px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 60px 170px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 175px 180px, white, rgba(255, 255, 255, 0)), radial-gradient(2px 2px at 195px 95px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 95px 145px, white, rgba(255, 255, 255, 0));
}

@keyframes space {
  40% {
    opacity: 0.75;
  }
  50% {
    opacity: 0.25;
  }
  60% {
    opacity: 0.75;
  }
  100% {
    transform: rotate(360deg);
  }
}

@import url('https://fonts.googleapis.com/css2?family=Orbitron&display=swap');

<title>Space</title>
<link rel="stylesheet" href="Space 2.css">

Space

Earth

Earth

      ...

Comment: I gave you the answer. Please let me know, did you need this result? If you need to improve something, then tell me about it.
Comment: Thank you for your answer!. Could you explain to me the figure tag and what it does?
I'm extremely new to this.
Comment: Also I copy pasted your code and the earth stretches across the page.
Comment: 1. This tag is for displaying illustrations with a caption that defines the `figcaption` tag. In my opinion, the `figure` tag is optional. For an alternative, you can take a regular `div`, put the `img` tag and the `p` tag in it, and you will get the same result. But I will say that this is purely my opinion :) 2. What does the earth mean across the page? Do you mean full screen width?
Comment: 1. Thanks for the tip!

2.Basically the the img is stretched almost flat horizontally
Comment: I did not pay attention to the location of the picture and the tag with the description :)) Use the example @mmaismma.
Answer: One very simple way is to just place the caption div above the img tag in your HTML code. I have pointed out the change in the following code snippet with NOTICE THIS  comments.

body {
  background: radial-gradient(circle at bottom, navy 0, black 100%);
  height: 100vh;
  overflow: hidden;
}

.space {
  background: rgba(128, 0, 128, 0.1) center / 200px 200px round;
  border: 1px dashed purple;
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
}

.stars1 {
  animation: space 180s ease-in-out infinite;
  background-image: radial-gradient(1px 1px at 25px 5px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 50px 25px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 125px 20px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 50px 75px, white, rgba(255, 255, 255, 0)), radial-gradient(2px 2px at 15px 125px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 110px 80px, white, rgba(255, 255, 255, 0));
}

.stars2 {
  animation: space 240s ease-in-out infinite;
  background-image: radial-gradient(1px 1px at 75px 125px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 100px 75px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 199px 100px, white, rgba(255, 255, 255, 0)), radial-gradient(2px 2px at 20px 50px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 100px 5px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 5px 5px, white, rgba(255, 255, 255, 0));
}

.stars3 {
  animation: space 300s ease-in-out infinite;
  background-image: radial-gradient(1px 1px at 10px 10px, white, rgba(255, 255, 255, 0)), radial-gradient(1px 1px at 150px 150px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 60px 170px, white, rgba(255, 255, 255, 0)), radial-gradient(1.5px 1.5px at 175px 180px, white, rgba(255, 255, 255, 0)), radial-gradient(2px 2px at 195px 95px, white, rgba(255, 255, 255, 0)), radial-gradient(2.5px 2.5px at 95px 145px, white, rgba(255, 255, 255, 0));
}

@keyframes space {
  40% {
    opacity: 0.75;
  }
  50% {
    opacity: 0.25;
  }
  60% {
    opacity: 0.75;
  }
  100% {
    transform: rotate(360deg);
  }
}

@import url('https://fonts.googleapis.com/css2?family=Orbitron&display=swap');

<title>Space</title>
<link rel="stylesheet" href="Space 2.css">

Space

Earth

Earth

    ...


Esconder teclado ao escolher um texto no AutoComplete

Question: Estou utilizando elementos do tipo AutoComplete no projeto, para que quando o usuário digite parte do texto que busca, apresenta as opções sugeridas para o mesmo.
Para isso, estou utilizando o seguinte trecho:
private void arrayAutoComplete() {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_expandable_list_item_1, produto);
    AutoCompleteTextView textView = (AutoCompleteTextView)
            findViewById(R.id.editProduto);
    textView.setAdapter(adapter);
}

private static final String[] produto = new String[]{
        "Skol beats sensations", "Brahma", "Skol litrão", "Heinekein", "Skol 350 ml"
};

Quero saber, como faço para esconder o teclado do smartphone quando o usuário selecione um dos textos sugeridos.
Answer: Para executar uma ação ao selecionar um item, é utilizado o listener AdapterView.OnItemClickListener. Então você pode tentar algo assim:
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
});


Unable to start debugging : The value of miDebuggerPath is invalid

Question: I recently started working on vscode. I wanted to debug my C code. But the moment I am launching the debugger getting Error : Unable to start debugging. The value of miDebuggerPath is invalid.
I have my gdb installed on wsl . It's path is /usr/bin/gdb. I have copied same path to launch.json in miDebuggerPath.
Here is my launch.json :
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${workspaceFolder}/bin/main",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": true,
        "MIMode": "gdb",
        "miDebuggerPath": "/usr/bin/gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ]
    }
]

}
It should not throw the error and I should able to launch my debugger.
Comment: Is VSCode launched in WSL or in Windows?
Comment: Ever got it working?
Comment: https://code.visualstudio.com/docs/cpp/config-mingw `Missing the mingw-w64-gdb package is one cause of the "The value of miDebuggerPath is invalid." message upon attempted compilation if your PATH is correct.`
Answer: So this happened to me on WSL-Ubuntu. In my case gdb was broken because of unmet dependencies. Took a while to fix but once I reinstalled gdb properly in my WSL-Ubuntu, I finally got it working.
Installing gdb can be done on shell as
sudo apt-get install gdb

There can be multiple reasons why it could end up as broken, but once you fix gdb, vscode-debugging should be running. At the very least, you won't see that error popping.
Comment: For Arch-based Linux users:
`sudo pacman -S gdb`
https://archlinux.org/packages/extra/x86_64/gdb/
Comment: This answer worked for me. I had a new WSL installation, so before trying the suggested command, my gdb was in /usr/share/gdb and even when I put this path in my lauch.json, it still did not work. When I installed gdb as per the suggested command, everything worked as expected (and gdb was installed in /usr/bin/gdb)
Answer: I had the same problem, my solution was:
1. Change this section in launch.json
"miDebuggerPath": "/usr/bin/gdb",

for:
"miDebuggerPath": "C:/MinGW/bin/gdb.exe",

2. Do you need to install in your PC  MinGW, this is the link:
https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/
3. Next, open the MinGW then you install in the URL "C:/MinGW/bin" the gdb (select)
mingw32-gdb-bin

4. Enjoy the vs-code
Comment: IT worked for me just by changing to `C:/MinGW/bin/gdb.exe`. Ty
Comment: The description is actually saying it's under wsl, not mingw
Comment: I'm not sure if this is the best way to do it, since you are referencing a file stored on your Windows system from the linux subsystem. Ideally, those two remain as separate as possible.
Answer: it should be
"miDebuggerPath": "/usr/bin/gdbus",

Comment: Why? gdbus doesn't appear to have anything to do with gdb. Also, I get the error `Unknown command '--interpreter=mi'`
Answer: If you're running under WSL, you should check where gdb is in your current distro to set your "miDebuggerPath" using
whereis gdb

in my case it was in
/usr/bin/gdb

but it could be somewhere else, that depends on what Linux distribution are you using with WSL
Answer: I had the similar problem, running on linux.
Installing gdb fixed it.
Answer: Could you try this:
sudo apt install binfmt-support

I am using VcXsrv, and this fixed all my installation problems, including chrome and GNU C++.
Answer: i had a similar problem ,this fixed. WINDOWS 10
QUICK ANSWER : try
1)C:\your compiler\bin\gdb.exe (paste your compiler path )
or
2)C:\TDM-GCC-32\bin\gdb32.exe for 32 bit compiler .(in my case)
(i tried to use opengl GLFW glad with 32bit tdm-gcc c++ compiler , i used a repo from OpenGL C++ template by vkphillia
but when i tried to run it in vs code using "run without debugging " option ,it showed the error "Unable to start debugging : The value of miDebuggerPath is invalid",
i copied  my tdm_gcc compiler's bin path in midebugger path and it was like this ,
C:\TDM-GCC-32\bin\gdb.exe , but it did not remove the error then i checked for the gdb.exe application in my tdm gcc compiler bin where i noticed that there was no gdb.exe but a gdb32.exe file


Replacing individual Midi drum instruments with MacBook & Alesis DM Lite

Question: I am a total beginner. Had recently bought an Alesis DM Lite edrums kit. It has 10 built in drum kits and USB Midi output. It works fine with MacBook / GarageBand.
However, individual instruments inside a kit cannot be changed from the Alesis DM Lite box. For example swap the ride cymbal with cowbell / tambourine / clap / second crash.
Did not manage to do that from GarageBand either. There is MidiPipe that allow to replace midi codes and send into GarageBand , but it is very basic.
EZDrummer, Addictive Drums and the like cost at least  200 euros and are overkill with too many features.
Is there simpler & cheaper software for beginners that allows to replace individual Midi instruments , save the "settings" and output sound?
Alex
Comment: MidiPipe says it has a key mapper - do the embedded kits have any mode where you can access, say, a cowbell instead of a crash by simply changing the input note; or does each kit contain only the allocated sounds, nothing else? If the latter, then you're out of luck without going for EZDrummer etc. unless there's something in Garage Band itself; some sample playback/drummer setup - then you could re-channel the sound you want to change.
Answer: You could try the free MT PowerDrumKit2 ( http://www.powerdrumkit.com/support.htm ), SuperDrumFX ( http://www.superdrumfx.com/ ) or any other VST/AU Instrument which supports your wanted sound. Simply google for "drum sampler". You could also use standalone software (to be used outside of GarageBand).
But you have to keep in mind that you need low latency if you want to play live. If you do not use a dedicated audio interface you could run into latency problems (or sound flickering).
If you want to record your performance, you could simply record the midi data in GarageBand and route this to a virtual instrument (like PowerDrumKit2, Addictive Drums etc.) If you do this, you can also change the sound later on by switching the virtual kit.


Calculating $\tan 2\theta$ in terms of correlation coefficients and variances

Question: I know I am asking a few questions and I apologize for that. However I shall try to read the solutions and know the loopholes in my theory. Here it is:
If $u=x\cos \theta+y\sin\theta$ and $v=y \cos \theta-x\sin\theta$. The variables $u$ and $v$ are uncorrelated, then how may I prove that $$\tan 2\theta=\frac{2r_{xy}s_xs_y}{s_x^2-s_y^2}$$ where $r_{xy}$ is the correlation co-efficient between $x$ and $y$ and $s_i$ is the standard deviation of a variable $i$.
Comment: **Hint:** Algebraically manipulate $0 = \text{Cov}(u,v)$. You should expect to use the double-angle formulae $\cos(2\theta)=\cos^2(\theta)-\sin^2(\theta)$ and $\sin(2\theta) = 2\sin(\theta)\cos(\theta)$.
Comment: Great: please post your answer so future readers can learn.
Answer: Alright, I think I managed to solve it.Here is my attempt:
I shall use the notations described in my post.
Let $\mu_k$ denoted the mean of a random variable $k$.
$(u_i-\mu_x)=(x_i-\mu_x)\cos\theta+(y_i-\mu_y)\sin\theta $ and $v_i-\mu_v=(y_i-\mu_y)\cos\theta-(x_i-\mu_x)\sin\theta$.Note that $$Cov(u,v)=\frac{1}{n}\sum_{i=1}^n(u_i-\mu_u)(v_i-\mu_v)=0$$.Plugging in the values of $(u_i-\mu_u)$ and $v_i-\mu_v)$ and and expanding, we get $$\sum_{i=1}^n[(x_i-\mu_x)(y_i-\mu_y)\cos^2\theta-(x_i-\mu_x)^2\sin\theta\cos\theta+(y_i-\mu_y)^2\cos\theta\sin\theta-(x_i-\mu_x)(y_i-\mu_y)\sin^2\theta]$$.The result follows.


How to complete a scale harmonization using Quantz' Versuch

Question: In Quantz, Versuch einer Anweisung die Flöte traversiere zu spielen several harmonic/melodic skeletons are presented as the basis of melodic embellishment. Here are four which cover significant portions of a full scale (embellishment examples not included.)
Ascending...

Descending...

It occurred to me there is almost enough there to make a sort of "rule of the octave" for a treble part. With some overlapping and transposing of Quantz' examples I got this...

...the ossia staff is my bass to end with a authentic cadence.
For some reason Quantz didn't show examples descending by step to/from the tonic. Figure 5 was the only descending scale to work from...

...the small notes and ossia staff are my additions to complete a descending scale harmonization.
Do these two scale harmonizations seem ok? Obviously, I want them to fit with Quantz' early classical style.
Please share any alternatives or concerns.
Answer: A few thoughts:

I don't understand your use of 6/4 figures.  I'm assuming the penultimate bar in your first example is a simple error and is meant to be 6/4/2?  As for the second example, 6/4 chords wouldn't be idiomatic in 18th-century style in either of the places they are written in the first few bars.
The use of viio to harmonize ascending scale degree 4 is unusual.  I'm not saying it never occurs (it does!), but harmonizing 4 with any sort of dominant function tends to accent its role as seventh of that chord and push toward a downward resolution in the melody.  It's interesting that Quantz chooses that option here.  It likely has to do with the specific melodic fragment he's quoting, where F is a passing tone from E to G on a weak beat, and therefore the larger harmonic rhythm of the bar revolves around tonic.  The default intermediate option when connecting two tonic chords on strong beats (if one is trying to harmonize the weak beat) is generally viio or V(7) in this style, though that works better on 1-2-3, 3-2-1, or 5-4-3 than the ascending 3-4-5.
Also, pace Quantz, it's generally a better and more common option in this style when creating a tonic-dominant-tonic stepwise progression to use a dominant function with local scale degree 4, either vii7 or V7 in whatever inversion.  Not that I-V-I doesn't occur, but if you look at rule of the octave examples, you'll frequently see what I mean.  Take note of that for some of the other uses of V in your harmonizations, e.g., 1-2-3 or 3-2-1 with a V in the middle is very likely to have a 6/5.
One point I do take away from Zoe Sparks's answer is that I don't think Quantz was attempting to generalize to universal chord progressions for scale harmonization in the way you're doing here.  And I don't think he intended them to be chained together in this fashion.  Hence my previous issue with how to deal with ascending 4, which may depend on the particular context of a particular melody.  There are obviously other ways to harmonize ascending scale degree 4 using IV or other chords that avoid the "fa wanting to go to mi" problem.  Also, in most actual ascending melodies, the 4 would simply be treated as a passing tone, rather than assigned its own harmony.
That last point gets at the issue with harmonizing 8-7-6-5 that you bring up in the question.  It's a known problem, because just like 4 in the melody wants to go down to 3, 7 wants to go up to 8.  And the 7-8 tendency is a lot stronger with that leading tone than with 4.  Unlike descending bass patterns (which obviously are quite common idioms in 18th-century style), descending harmonized scales are much less common.  Usually, these notes are treated as passing tones.
In order to treat them as chord tones, one needs to significantly undermine the need for the leading tone to resolve upward in the melody.  Two common idiomatic methods for 18th-century style: (1) Create a series of dominant sevenths, i.e., I-V7-V7/IV-IV.  Unfortunately, that requires interpolation of a ♭7 into your scale, but it's more idiomatic.  (2) Change the function of scale degree 7 to something other than a potential leading tone.  E.g., I-V/vi-vi (though then you need a good progression for 6-5, and it's tough to create something strong there).
The difficulty we're encountering here with 8-7-6-5 is perhaps why it's pretty rare to see it occur melodically with each note harmonized in 18th-century style.  It's also perhaps one of the reason why "rule of the octave" type patterns never emerged for descending scalar melodies.  One thing you pretty much can't do in 18th-century style is have V-IV with either of them in root position (as you attempt in the second example).  The 6/4 options don't help; as I already noted, they're unidiomatic.  With the descending 8-7-6-5 in the bass, one can fall back on first inversion chords to create a V6-IV6 which is acceptable (particularly in sequential 18th-century patterns).  Obviously that can't be done with 8-7-6-5 in the melody, and iii6-ii6 is just not going to be able to create a strong progression (though it might occur as part of a long sequence).  viio6-vi6 also does occur as part of sequences, but at that point are we just going to harmonize the whole descending scale as descending sixth chords?  (That's actually a better option than most others.)

I don't know if this is helpful.  As Sanguinetti notes in his book (p. 116):

When placed in the upper voice, the scale obviously needed a
counterpoint in the bass; however, in contrast to the [Rule of the
Octave], a standard model of accompaniment never established itself.

He goes on to note small segments of the scale that did have some standardization, like 1-2-3 with the 8-7-8 bass.  But I would assume if any harmonization of the ascending/descending scale had been given in a partimento treatise as a "model," Sanguinetti would have noted it.  I think that absence is probably telling.  Even though partimento practice revolves much more around bass than melody, obviously there are plenty of melodic patterns involving suspensions, etc. that get incorporated in the tradition.  The absence of standard harmonizations for melodic scales is therefore interesting.  I would postulate it may in part be because of the issues I noted above.  The ascending version can be done, but it's a bit awkward.  The descending diatonic scale is quite difficult to create a strong progression (particularly for 8-7-6-5).  And on the rare occasions where it does occur in actual literature, the different possible solutions depend on which "rule" is broken or what specific inelegant option is chosen.
EDIT: Oops, I forgot to mention one other sequential possibility for 8-7-6-5, which would use the "descending 3rds" progression commonly associated with the Pachelbel canon (I-V-vi-iii...).  With sufficient figuration in a sequence this might work and shows up sometimes in late 18th-century music.  But it's less desirable as a simple harmonic structure because of the accented parallel octaves created with melody and bass in every other measure.
Comment: That Sanguinetti quote is _very_ helpful. I read the book several years ago, but don't own a copy. I appreciate you found a quote that sums up the problem. More or less I did come to the conclusion that the full scale harmonization just doesn't work, especially `8 7 6 5`. I keep looking out for it when reading scores, but it just doesn't come up!
Comment: Yes, the best Sanguinetti can do is find an example from Nicola Sala that shows two-voice invertible counterpoint, effectively a two-voice skeleton of a rule of the octave that's modified so the two voices can be inverted and still make some sense.  But this two-voice example is more like species counterpoint, not functional harmony.  Effectively, the two problematic bits I noted (with 4 ascending and 7 descending) are just harmonized with a series of sixths below.  So my "solution" of just using a long series of 1st inversion chords seems to be the best 18th-century option.
Comment: Among scores I already have this Solfege manual https://imslp.org/wiki/M%C3%A9todo_completo_de_solfeo_(Eslava%2C_Hilari%C3%B3n) gave a harmonized scale as the first lesson, and as you say, it's solution is mostly sixth chords. `8 7 6 5` was really nagging me. Your answer is very helpful. Thanks!
Comment: Another example of `8 7 6 5` as `I V vi iii` https://music.stackexchange.com/a/121125/23919
Answer: EDIT: Okay, sorry, I did misunderstand what this was about. I never had any exposure to "scale harmonizations", the "rule of the octave", etc. when I was a student—I learned tonal harmony in terms of chord construction and voicing, voice leading, characteristic progressions, modulation techniques, and large-scale structure. We did use figured bass, but not in that fashion, and when we talked about harmonizing melodies it was in terms of the entire edifice of tonal harmony, not something you could distill down to a characteristic set of chords over a scale. I'm not sure that that "partimenti-style" teaching approach was all that common outside of the Neopolitan tradition in the 18th century (although if you have references to the contrary I'd be curious to see them). I'm having a hard time finding much rigorous information on it outside of Robert Gjerdigen's website, so that what I'm working from.
Notably, Quantz doesn't seem to have thought in these terms either, at least not as far as he lets on in that book. I flipped through Edward Reilly's translation and read the chapter the examples you cite are from, and he doesn't seem to ever present material the way those Neopolitan theorists do. Of course, he's not writing a composition manual—those are tips for beginning flutists to start on devising melodic variations when improvising and the like:

Since...most musicians lack the necessary instruction...so many incorrect and awkward ideas appear that it would be better in many cases to play the melody as the composer has set it rather than spoil it repeatedly with such wretched variations.
To remedy this abuse somewhat, I shall give some instructions, for those who still lack the requisite knowledge, as to how variations may be made in diverse ways on plain notes in the majority of the most common intervals, without contravening the harmony of the bass.
...
I do not pretend to have created in these few examples all the variations it is possible to discover on these intervals; I present them only as an introduction for the novice.

So, if we want to tease out a Neopolitan-style rule of the octave from his examples, we're going to have to make some pretty subjective decisions. He's not trying to present harmony in a systematic fashion like that, so we have to try to read his mind a bit; as I said in my original answer, those examples don't necessarily present progressions you could extend to a general case that way. What's more, I'm not sure he even thought about music in the same fashion exactly—again, maybe, but if so he doesn't let on. So we're kind of translating between one musical language and another, even if they do have a lot in common. I'll do my best to indicate what I think is more-or-less an objective truth and what's more a matter of opinion so that you can work based on your own tastes.
Anyway, the biggest problem with lifting directly from Quantz's examples is that he elides the rules of good voice leading. This is understandable because he's just sketching out harmonic frameworks for flutists to devise variations in—the flutists are meant to work out details like that themselves (see e.g. the other part of his Tab. X). However, rules of the octave are meant to provide guidance for writing harmony, so they do worry about voice leading, as you can easily verify from the manuals Gjerdigen put up. So, despite my earlier confusion, much of what I said is still relevant, although I'll do my best this time to put it in the proper context.
A few points in particular: Quantz doesn't concern himself much with avoiding parallel 5ths and 8ves, keeping the motion of individual voices varied, or balancing parallel and contrary motion between voices. We will need to correct for all of this somehow (there are some exceptions for parallel 5ths and 8ves as far as the Neopolitan folks go, which I'll discuss). None of that is just my opinion: on top of examining the rules of the octave given in the books Gjerdigen put up, you can read Fux's Gradus ad Parnassum for a text that was popular at the time and that states them quite clearly.
Also, rules of the octave are designed around harmonizing a descending or ascending bassline, not a melody. The partimenti exercises that come after they've been learned are designed around harmonizing a melody, but rules of the octave are meant to help students make connections between basslines and the harmonies implied by them. So, instead of working from Quantz's melodies, we'll need to work from the appropriate basslines, and see if we can harmonize them in accordance with Quantz's methods.
One last point: all the Neopolitan theorists seem to give three rules of the octave per "mood", starting with the 8ve, 3rd, and 5th on top of the I chord respectively. Since you only set out to write one, I'm going to do the same, in the interest of saving myself time. More-or-less arbitrarily I'll do one starting with the 8ve on top.
Just to make sure we don't stray too far from the Neopolitan tradition, let's do a quick analysis of one of their rules of the octave—I went with one of Fenaroli's:

(listen)
I did this in a rush so if there are any careless mistakes I apologize. :P
From this (and the other Neopolitan rules of the octave you can read about on that website) we can glean the following:

Always start and end with a I chord in root position.
End with a V-I, but it's okay if it's quite weak in cadential terms—the stepwise bassline forces you to make some sacrifices (cadences are taught separately anyway in this tradition).
You can handle some of the awkwardness of the descending bassline through a brief tonicization of the dominant key starting from the third step (other Neopolitan theorists do this as well).
Occasional parallel 5ths/8ves are permitted between the bassline and the inner voices, but never sequentially. (Apparent parallel 5ths/8ves in the upper voices are generally due to the entrance of a 4th voice for the sake of 7th chords and such.)
The inner voices can be more restricted in their movement than they might be in a real piece, but they should still have pleasing contours.
The "melody" in the top voice does not need to follow the rules of good melodic writing; it can be thought of like another inner voice (all of this is meant as a study of accompaniment).
EDIT 2: In my haste, I neglected an important point, which is that the chords assigned to step 5 of the scale should be appropriate for cadential purposes. Of course, when composing an actual piece of music, you could always substitute in the appropriate harmonies when you wanted a cadence, but these "rules of the octave" seem to be meant as a starting point for teaching purposes, so it's better to keep things simple. The Neopolitan theorists seem to always put a V chord there, and furthermore a triad as opposed to a seventh chord.
Other than these guidelines, follow the rules of good voice leading and keep the harmony moving.

Okay, now let's check out Quantz:

Tab. IX Fig. 2 steps 1-2-3 is basically just a long I chord (the apparent ii in the middle is basically passing motion on the way to a first inversion I). We don't really have the space for that here so we might substitute a vii as Funaroli uses, which shares some notes with the ii but will create a greater sense of motion.
Tab. X Fig. 4 steps 3-4-5-6 is I-vii-I-ii7-V. This gives us some trouble, both because using a vii on steps 2 and 4 will get monotonous and because we should avoid returning to the I after step 3 for the same reason. The vii forces us to move to the I next for voice leading reasons, so we can solve both problems by substituting something else. V7-vi7-ii7-IV might be the closest we can get, since we need to follow this with a V-I.
Tab. XI Fig. 6 is either steps 3-4-5 or 6-7-8 depending on whether you view this as in C or in G. In C terms it's vi7-II-V; in G terms it's ii7-V-I. On the ascent it doesn't really make sense to tonicize G, but we are planning a vi7-ii7-IV-V progression which is fairly close. On the descent we will tonicize G, but we can't really use this progression, both because we'll need to already be in G by step 5 (downwards) and because we'll have a B in the bassline on step 7.
Tab. X Fig. 5 steps 6-5-4-3-2 is IV-I-vii-I-V. We would need to transpose this into G for the first two chords. Sadly we can't use a IV (in G) at this point because of the A in the bassline on step 6, and we kind of have to use a V (in G) there anyway in order to move to G. We'll also need to do something else for the vii-I-V part because we need to get back to G on step 2. We could do IV-I-V (in C terms) which isn't so far away.

Adding all this up, we get:

(listen)
EDIT 2: I realize this has a significant issue if you were to actually use this to try to compose 18th-century-style music, which is that the chord given for the 5th scale step in the ascending rule is a vi7 chord, and thus would not perform the appropriate dominant function in perfect cadences and things. However, I'm reluctant to change it, because we live in the 21st century and I love the sound of that chord very much, so I would happily use it compose with anyway, broken tonal functionality or no. But I will revise this to be more suitable for 18th-century-style composition purposes if you like.
Comment: "I don't think it really reflects how composers thought about harmony at any point in the common practice period" ...then what did they use the _rule of the octave_ for?
Comment: @MichaelCurtis Okay, I revised my answer after doing some research. Hopefully this is more useful to you.
Comment: I'm confused about what you are doing. You have a scale harmonization in the bass. The question really is how the _treble_ line `^1 ^7 ^6` might best be "harmonized" long the lines of Quantz. I suppose the common patterns were `^1 ^7 ^1` as `I V I` or `^5 ^6 ^5` as `I IV I` and if the full decent `^1 ^7 ^6 ^5` was used it would have been `I V V/V V` like the rule of the octave. If that's the case, one "harmonization" of the descending scale just isn't enough.
Comment: In other words, what I'm thinking is if `^7` decended to `^6` the typical thing would be to continue to `^5` and the harmonization would be `V V/V V`.
Comment: So, are you not actually looking for a "rule of the octave", but rather for a harmonization of a treble line? My understanding is that a rule of the octave is always a harmonization of an ascending/descending bassline, as I explain in my post—it wouldn't serve its pedagogical function otherwise. What's your larger goal—like, what do you mean to use this for?
Comment: In my question I worded it "sort of" rule of the octave. I mean to use it exactly as Quantz intended, variation of a treble line. There doesn't seem to be a problem to rearrange Quantz's examples into complete scales (the point of the model Adagio is to demonstrate their rearrangement) except he didn't show the descent ^1 ^7 ^6 ^5. I want to either fill that in with something appropriate, or a good explanation that descent wouldn't be used in the treble.
Comment: If your goal is to use this as a guide for varying a melody, I think what you have is all right. It's hard to say if Quantz would agree or not, since he meant those only as basic examples for beginning flutists, and in general recommends to follow the harmonic structure of the piece in question. For example, it would be uncommon to play I chords so often in a piece from that time, but he suggests some of those notes on the basis that they're unlikely to clash with whatever the composer is doing. If you want to use this as a composition aide, Quantz might have made different recommendations.
Comment: I guess also like, it would be helpful to know the larger angle you're coming at this from. Are you approaching this as a flutist with an interest in early music? A composer wanting to work in a style resembling Quantz's? A composer writing contemporary music looking for melodic ideas? I would say something different in each of these cases.
Comment: I know, I'm talking about the question you asked. I don't know what else to say without that information. Your original questions don't have a single right answer from my perspective—to what extent your harmonizations seem okay to me, fit Quantz's style, etc. really depends on what you're trying to do. Without more context at this point, all I can say is that if you're happy with the material you have, it's fine by definition.
Comment: Sorry, I have to downvote this. It seems you are trying to summarize from first readings of these sources, and you have a number of errors in your answer.
Comment: ...I really don't understand the way you're approaching this. Your question went unanswered for months until I was nice enough to take a crack at it. I obviously have enough technical knowledge to at least weigh in productively. I've spent over 20 hours trying to help. You seem totally disinterested in giving me any information that would help me answer your questions in the way you want. I don't understand why you even asked this at this point.
Comment: Many of my questions don't get a lot of answer. But that doesn't mean a bad answer gets accepted. I downvoted for the reasons I already gave: technical errors, lack of knowledge on the subject. I want that to be clear to anyone who reads your answer.
Comment: I have a B.A. in this field. If that's not enough expertise for you, I think you'll probably need to go pay a grad student actual money to work this hard on your behalf. You seem more interested in discrediting and antagonizing me than you do in explaining why what I've said is in error (I still have no idea, I've cited my sources) or answering the questions I asked for clarification. I don't care anymore, though. I'm glad I at least found the research I did for this interesting, because otherwise I would wholly regret that we ever crossed paths. Good luck and goodbye.
Comment: Answers are up/down voted based on the _content of the answers_ not someone's credentials.


product of two discrete sigma algebras need not be discrete

Question: I tried solving this problem but as X and Y are having discrete sigma algebra, then singletons are measurable. Henceforth, every singleton set in the product space is product of singleton sets from X and Y which means product space is also having discrete algebra. I don't know where I am going wrong.
All suggestions are invited
Comment: How do you define "having discrete sigma algebra"?  The [Wikipedia article](https://en.wikipedia.org/wiki/Sigma-algebra#Simple_set-based_examples) defines it to mean the $\sigma$-algebra on $X$ is given by the power set of $X$.  Your notion of "singletons are measurable" seems a consequence rather than a definition, because singletons are measureable in (for example) Lebesgue measure on $\mathbb{R}$.
Answer: The product $X\times Y$ needs to be countable. If so, every subset of the product is a countable union of its singletons, which are mesurable as you pointed out, and is therefore mesurable. If neither $X$ nor $Y$ are countable, that may not be true. For example, with $X=Y=\mathbb{R}$, as it was said to me in here, it is undecidable in ZFC.
Here it is shown to be true for $X=Y=[0,1]$ using the Continuum Hypothesis.


Unable to preview media items

Question: I have a node page where, in the WYSIWYG, I have embedded about 50 media items. When I edit the node, I can see this error for some of the media items.

An error occurred while trying to preview the media. Please save your work and reload this page.

In the browser console, the error is the following.

mysite.com/media/wysiwyg/preview?text=%3Cdrupal-media%20data-entity-type%3D%22media%22%20data-entity-uuid%3D%22b21db71d-3c53-4d46-afed-a3197767fac4%22%20data-href%3D%22%22%20data-size%3D%22original-size%22%3E%3C%2Fdrupal-media%3E&uuid=b21db71d-3c53-4d46-afed-a3197767fac4 429

429 is the status code.

Is there any limit for the number of the embedded media?
How do I get rid of these errors?
Answer: 429 is the HTTP status code for "Too Many Requests". Drupal would not be responsible for serving a 429; something in your server infrastructure would do that, like a load balancer or Apache/nginx. Given that, this might be out of scope for Drupal Answers.

Unable to preview media items


Continuity theorem in Itô integral explanation

Question:
What is the continuity theorem used here in the explanation of the Itô integral? I cannot seem to find anything that would be exactly useful in my measure and integration text.
Comment: Please give the source of your quoted text.
Comment: Oksendal's Stochastic Differential Equations
Answer: Since $g(\cdot, \omega)$ is continuous (and hence uniformly continuous on $[S,T]$), you can check that $\phi_n(\cdot, \omega) \to g(\cdot, \omega)$ uniformly on $[S,T]$.  Therefore $(g(\cdot, \omega) - \phi_n(\cdot, \omega))^2 \to 0$ uniformly and this gives you the convergence of the integral.
Continuity is not strictly necessary here; piecewise continuity would be enough, or something like Riemann integrability.  But you need something; if $g$ were something like the indicator of the rationals, and you unluckily chose your partition points $t_j$ to all be rational, then you would get $\phi_n = 1$ while $g=0$ almost everywhere, and the integral will not converge to 0.


Android Linkify from HTML in TextView

Question: I have HTML with standard links which correspond to commands I'd like to handle.
This is a command.

I populate a TextView with Html.fromHtml()
How can I use the Android Linkify system to convert the  links to Linkify'ed ones?
Answer: found that the WikiNotes example project from Google does exactly that. It uses the Linkify infrastructure with a Provider and MIMIE type to load the right Activity.

Android Linkify from HTML in TextView


Sobolev embedding

Question: In an exercise I am asked to prove the following statement: The embedding
$$T:W^{1,1}(\mathbb{R}^n)\rightarrow L^2(\mathbb{R}^n), u\mapsto u$$
is continuous.
Using the Gagliardo-Nierenberg inequality $\|u\|_{W^{1,1}(\mathbb{R}^n)}\geq\|u\|_{L^2(\mathbb{R}^n)}$, $u\in\mathcal{C}^1_c(\mathbb{R}^n)$, I managed to prove this result for the domain $W^{1,1}_0(\mathbb{R}^n)$ where I can approximate by test functions. Does someone know how to approach the general case? Why is the embedding well-defined?
Comment: Do you mean $W^{1,2}(\mathbb{R}^n)$? $W^{1,1}$ does not embed in $L^2$ for $n>2$.
Comment: Your Gagliardo-Nierenberg inequality is definitely in the wrong direction. Furthermore, $W_0^{1,1}(\Bbb{R}^n) = W^{1,1}(\Bbb{R}^n)$.
Comment: Yes, you're right. I've corrected this typo. Thanks!
Comment: Yes, I really mean $W^{1,1}$. It is actually an old exam that I use for revision. Ok, then there seems to be a typo on the sheet.
Answer: I am not sure you need this answer or not. But I think @PhoemueX already give you one.
In general, keep in mind that $W^{1,p}=W_0^{1,p}$. (prove it! good exercise). Then the rest is clear.

Sobolev embedding


Exported from Chrome Extension of Talend API Collection and import into Postman is not working?

Question: I have Exported  API Collection from Talend API Collection(chrome-extension://aejoelaoggembcahagimdiliamlcdmfm/index.html#requests) Chrome Extension for API Tested and try to import into Postman is not working?. Any one have idea how to make it work in postman
try to import the talend API Collection into POSTMAN tools . but its not working...
Answer: I'm guessing you exported a collection from the Talend API Tester tool, if so it's not possible to. The exports of the talend api tester only works within it share with other users or export then manually import it. You can import postman collections in it but not the other way.


How To store image view id's in array and set image resource on specific image view element

Question: imgv is a array contain id's of image view
How do I store ImageView IDs in an array and set Image resource on a specific ImageView element?
Comment: Please add your code as text, not image
Comment: Can you mention what have you tried?
Also, you can use an int array to store the id of the imageview and later retrieve the view to set the resource. But you need to be careful since the imageview might not be available any more
Answer: You can't use setImageResource on int array this method must be used on ImageView object

Sets a drawable as the content of this ImageView.

More explanation in documentation ImageView
Simply you can do something like this
<code>    int[] array = {R.drawable.imag_view_1,R.drawable.imag_view_3,R.drawable.imag_view_2};

    imageView.setImageResource(array[0]);
</code>


tcpclient receiving data incorrectly

Question: Not sure if this is the TCPClient or something else, I have used a network sniffer to check what is being sent and received from the server and the data is correct however my software is receiving the data incorrectly.
Let me explain, I transmit an enquiry byte (05) I get a acknowledgment back (06) then I transmit some data that starts with a 9B byte, once this has sent I should then receive a single 06 byte and then after that byte I should get a C5 byte, however according to my software I get another 06 byte which isn't the case according to the sniffer!
byte[] buff;
if (!this.isConnected())
    this.connect();

NetworkStream gs = _Socket.GetStream();

gs.Write(enq, 0, enq.Length);
gs.Flush();
outputByte(enq, "Trans"); //outputs ---> 05

buff = new byte[1];
gs.Read(buff, 0, buff.Length);
gs.Flush();
outputByte(buff, "Rec");// outputs <--- 06

if (buff[0] == 0x06)
{
    byte[] data = new byte[] {
                                            0x9B, 0x00,         0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x09,
        0x67, 0x11, 0x01, 0x49, 0x4D, 0x41, 0x47, 0x45,         0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,         0x01, 0x53, 0x75, 0x6D, 0x6D, 0x61, 0x72, 0x79,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,         0x00, 0x00, 0x02, 0x08, 0x00, 0x00, 0x08, 0x00,
        0x00, 0x00, 0x1F, 0x09, 0x01, 0x00, 0x04, 0x0A,         0x10, 0x00, 0x12, 0x01, 0x1F, 0x00, 0x00, 0x00,
        0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,         0x12, 0x10, 0x1E, 0x0E, 0x1E, 0x54, 0x65, 0x73,
        0x74, 0x69, 0x6E, 0x67, 0x10, 0x00, 0x12, 0x01,         0x1F, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x12, 0x10, 0x0D, 0x00,         0x00, 0x90
    };
    outputByte(data, "Trans"); /outputs --> with above byte information
    gs.Write(data, 0, data.Length);
    gs.Flush();

    buff = new byte[1];
    gs.Read(buff, 0, buff.Length);
    gs.Flush();
    // this is the first receive of 06
    outputByte(buff, "Rec");//outputs <--- 06

    if (buff[0] == 0x06)
    {
        gs.Flush();
        Console.WriteLine("fdsfsdfs");
        byte[] resp = new byte[5];
        gs.Read(resp, 0, resp.Length);
        gs.Flush();
        //this outputs <--- 06 but it should be showing <--- c5000100c4
        outputByte(buff, "Rec");
        gs.Write(ack, 0, ack.Length);
        outputByte(ack, "Trans");
        gs.Flush();
    }
}

According to the sniffer this is what should be happening
---> 05
<--- 06
---> 9b008000000080000009671101494d414745310000000000000000000000000000000153756d6d617279000000000000000000000000000000000000000000000000000002080000080000001f090100040a100012011f000000050001000000000012101e0e1e54657374696e67100012011f000000050001000000000012100d000090
<--- 06
<--- c5000100c4

And according to the software this is what is happening
---> 05
<--- 06
---> 9b008000000080000009671101494d414745310000000000000000000000000000000153756d6d617279000000000000000000000000000000000000000000000000000002080000080000001f090100040a100012011f000000050001000000000012101e0e1e54657374696e67100012011f000000050001000000000012100d000090
<--- 06
<--- 06

Any ideas? Also if you have any suggestions on how to improve the code I'll be grateful
Comment: The first thing I'd say is: can you output the results from each of the `Read` calls.
Comment: @MarcGravell that's what the outputByte function does and that's what the above shows!
Answer: Here: you are outputting the wrong buffer:
    gs.Read(resp, 0, resp.Length);
    gs.Flush();

    outputByte(buff, "Rec");  <==== should be "resp"

HOWEVER!!!
all of your Read calls are broken; they MUST handle the return value, especially when reading multiple bytes. Packet fragmentation will kill your code.
A correct "read exactly [n] bytes" method would be:
public static void ReadExact(this Stream stream, byte[] buffer,
           int offset, int count) {
    int read;
    while(count > 0 && (read = stream.Read(buffer, offset, count)) > 0) {
        count -= read;
        offset += read;
    }
    if(count != 0) throw new EndOfStreamException();
}

Then:
gs.ReadExact(resp, 0, resp.Length);

will fill it correctly, or error if not enough data is in the stream.
Comment: OMG this is why I HATE working on multiple things at once, 2 c# projects a website and 2 laptops for repair, Marc thank you so much I couldn't see that error at all, changed it and now its correct and again thanks for the ReadExact function I'll implement it ASAP, would I need something for the write as well?

tcpclient receiving data incorrectly