$\lim_{x\to 1} \sqrt{x^2 + 8} = 3$ -- Proof Via Epsilon-Delta Definition of a Limit

Question: This problem was originally asked here: $\lim_{x\to 1} \sqrt{x^2 + 8} = 3$ prove this using epsilon delta. It got closed and is no longer accepting answers.

Prove this using epsilon-delta
$$\lim_{x\to 1} \sqrt{x^2 + 8} = 3$$

Definitions: $\lim_{x\to c}f(x)=L⟺∀ϵ>0,∃δ>0$ s.t. $0<|x−c|<δ⟶|f(x)−L|<ϵ.)$ as defined by Gregory Hartman et al. by the Virginia Military Institute in LibreTexts Mathematics$_1$

Context For Why This Question Is Important: Epsilon-Delta proofs of limits form the foundations of rigorous calculus as we know it. The rigor and importance of these fundamental limits should be demonstrated to students. By giving me guidance on how to correctly evaluate this limit, users provide me (and future readers of this post) with a token of knowledge.

Additional Context For the Problem: I have searched for the answer, and found this video on YouTube$_2$. https://www.youtube.com/watch?v=yC8Y50H6kw8. However, the person does not provide an example where the inequality is not easily factorable.

Given $\epsilon>0$
Choose $\delta$ such that:

Suppose $0<|x-1|<\delta$
$$|\sqrt{x^2+8}-4|<\epsilon$$
$$|\frac{x^2-8}{\sqrt{x^2+8}+4}|<\epsilon$$
The denominator is always going to be positive, so we can take it out of the absolute value brackets.
$$\frac{|{x^2-8}|}{{\sqrt{x^2+8}+4}}<\epsilon$$
[...]

Here's why I believe that this problem is interesting. Usually, epsilon-delta proofs have the convenience of being easily factorized. This one is easily solved by substituting $x=1$, but that does not respect the official definition of a limit.

Here, $\epsilon=0.00001$. I know that the function's domain is the entire real numbers (the range is the nonnegative numbers) because the $x^2$ in the radicand forces the entire radicand to be positive. The square root of any positive number is well-defined in the real numbers (see below for reference).

How does one express $x^2-8$ in terms of $x-1$? Are there any other methods on how I should proceed?

Notes and Thanks:
Firstly, I would like to thank Gary for responding by telling me how I should improve this question (i.e. Show my thought process and provide context). I would also like to thank DESMOS for providing the software to produce a graphic of the function.

Citation:

Hartman, Gregory, et al. "1.2: Epsilon-Delta Definition of a Limit." Mathematics LibreTexts, December 21, 2020. https://math.libretexts.org/Bookshelves/Calculus/Calculus_3e_(Apex)/01%3A_Limits/1.02%3A_Epsilon-Delta_Definition_of_a_Limit. Context on the Epsilon-Delta Definition of a Limit.

"Limits with Epsilon-Delta Definition! (Linear, Square Root, and Quadratic Examples)." YouTube, January 16, 2022. https://www.youtube.com/watch?v=yC8Y50H6kw8.

References:

Libretexts. "3.3: Domain and Range." Mathematics LibreTexts, October 6, 2021. https://math.libretexts.org/Bookshelves/Algebra/College_Algebra_1e_(OpenStax)/03%3A_Functions/3.03%3A_Domain_and_Range#:~:text=Another%20way%20to%20identify%20the,shown%20on%20the%20y%2Daxis.
Comment: The issue is that you have a $4$ instead of $3$. Then $$|\sqrt{x^2+8}-3|=\frac{|x^2-1|}{\sqrt{x^2+8}+3}=|x-1|\frac{|x+1|}{\sqrt{x^2+8}+3}$$ Then you can factor $\delta$
Comment: @LucienJaccon Note that $$
\left| {\sqrt {x^2  + 8}  - 3} \right| = \frac{{\left| {x^2  - 1} \right|}}{{\sqrt {x^2  + 8}  + 3}} = \frac{{\left| {x + 1} \right|}}{{\sqrt {x^2  + 8}  + 3}}\left| {x - 1} \right| \le \frac{{\left| x \right| + 1}}{{\left| x \right| + 3}}\left| {x - 1} \right| \le \left| {x - 1} \right|.
$$ Thus, $\delta:=\varepsilon$ works.
Comment: Thank you. Very helpful.
Answer: Given $\epsilon>0$, instead of providing some $\delta$ out of the blue and check it "works", like textbooks too often do, we shall look for the "best" $\delta$ (i.e. the largest one which "works"). We will thus experience concretely the fact that the smaller we take $\epsilon$, the smaller $\delta$ has to be chosen.
Let us take advantage of the monotonicity of $x\mapsto\sqrt{x^2+8}$ for $x\ge0$. Assuming $|h|\le\delta\le1$, in order to get $|\sqrt{(1+h)^2+8}-3|\le\epsilon$, we just need
$$3-\epsilon\le\sqrt{(1-\delta)^2+8}\quad\text{and}\quad\sqrt{(1+\delta)^2+8}\le3+\epsilon,$$
i.e., assuming moreover $3-\epsilon\ge0$:
$$(3-\epsilon)^2-8\le(1-\delta)^2\quad\text{and}\quad(1+\delta)^2\le(3+\epsilon)^2-8,$$
i.e., if we even have $3-\epsilon\ge\sqrt8$:
$$\delta\le\delta_0(\epsilon):=1-\sqrt{(3-\epsilon)^2-8}\quad\text{and}\quad\delta\le\delta_1(\epsilon):=\sqrt{(3+\epsilon)^2-8}-1.$$
Note that $\delta_0(\epsilon)$ and $\delta_1(\epsilon)$ are $>0$, and tend to $0$ when $\epsilon$ does.
The claim $\lim_{x\to 1} \sqrt{x^2 + 8} = 3$ is thus proved, and for every $\epsilon>0$ less than $3-\sqrt8$, the "best" $\delta$ is
$$\delta(\epsilon):=\min\left(\delta_0(\epsilon),\delta_1(\epsilon)\right).$$
(We could prove that this $\min$ is $\delta_1(\epsilon)$, and that this $\delta_1(\epsilon)$ is still the "best" $\delta$ for every $\epsilon\ge3-\sqrt8$, but we don't care.)
Answer: Prove $\lim_{x\to 1} \sqrt{x^2+8}=3$
We need to find a delta given an epsilon, so we try to find $0<\delta<1$.
$1-\delta < x < 1+\delta$
$1+\delta^2-2\delta < x^2<1+2\delta +\delta^2$
$9+\delta^2-2\delta<x^2+8<9+2\delta+\delta^2$
So $|(x^2+8)-9|<3\delta$
So  if $\delta=\min(1,\epsilon/3)$, we have proven $\lim_{x\to 1} x^2+8=9$
$|(x^2+8)-9|=|x^2-1|$
$|a^2-b^2|<3\delta\implies |a-b|<\frac{3\delta}{|a+b|}$
If $a=1$ and $b=1+\delta$, then max $|a+b|=3$.
This suggests $\delta=\epsilon$ will give us the full limit for our original expression.
Let's see.
$|(x^2+8)-9|=|x^2-1|<3\epsilon$
$|x-1|<\epsilon\iff 1-\epsilon< x<1+\epsilon\implies 2-\epsilon<x+1<2+\epsilon$
$\frac{3\epsilon}{2+\epsilon}<\frac{3\epsilon}{x+1}<\frac{3\epsilon}{2-\epsilon}=(3/2)\epsilon(1+\epsilon/2+\epsilon^2/4+\epsilon^3/8+..)<(3/2)(2\epsilon)$
Where for the last inequality, I've replaced all higher powers of $\epsilon$ with $\epsilon$ itself and added up a geometric series.
This tells us the corresponding square root expression holds if $\delta=\min(\epsilon/3,1)$.


Problemas ao trabalhar com datas no banco de dados usando um maskedtextbox no formato dd/MM/yyyy

Question: Estou usando um MaskedTextBox na cultura pt-BR pra forçar o usuário a preencher a data no formato correto (dd/MM/yyyy). Retiro a string do MaskedTextBox  para inserir  no banco de dados e  registrar uma informação  contendo a data desta informação. Meu intuito é que o usuário possa além de registrar algumas informações, possa também realizar uma pesquisa por período de tempo filtrando as datas através de dois MounthCalendar.
O problema é que aparentemente as informações estão sendo registradas no formato MM/dd/yyyy e quando realizo a pesquisa por período, o banco de dados retorna as datas com os meses invertidos com as datas.
Por exemplo, se eu registro um evento chamado de "Calibração" com a data 02/03/2016 (02 de março de 2016) , no banco de dados o registro fica como 03 de fevereiro de 2016. E se eu fizer uma pesquisa no período de 01 de março de 2016 a 31 de março de 2016, o evento de "Calibração" não aparece nos resultados. Mas, se fizer a pesquisa no período entre 01 e 29 de fevereiro de 2016 o evento aparece como se estivesse registrado no dia 03 de fevereiro.
Não sei se estou enganado, mas creio que o problema esteja acontecendo na hora de inserir no banco de dados, estou tentando converter a string que é digitada no MaskedTextBox para o formato MM/dd/yyyy mas não estou conseguindo.
Já tentei usar o DateTime.ParseExact mas surge o erro : "Cadeia de caracteres não foi reconhecida como DateTime válido."
string dataDoFat = mskData.Text;
System.Globalization.DateTimeStyles none = new System.Globalization.DateTimeStyles();
IFormatProvider format = new System.Globalization.CultureInfo("en-US", true);
DateTime dtime = DateTime.ParseExact(dataDoFat, "MM/dd/yyyy",format);

O código que uso para inserir os registros no banco de dados é este:
            Conexao ca = new Conexao();
            string sql = "";
            sql += " Insert Into SisIndice (FAT, nSerie, idDefeito, DataFat) ";
            sql += " Values ( ";
            sql += " " + txtFat.Text + ", ";
            sql += " '" + txtnSerie.Text + "', ";
            sql += " " + cboDefeito.SelectedValue + ", ";
            sql += " #" + mskData.Text  + "# ";
            sql += " ) ";
            ca.Conectar();
            OleDbCommand cd = new OleDbCommand(sql, ca.cx);
            try
            {
                cd.ExecuteNonQuery();
                MessageBox.Show("Ocorrência registrada.");
            }
            catch (OleDbException x)
            {
                MessageBox.Show("Erro: " + x.Message);
            }
            ca.Desconectar();
            LimparCampos();

E o que uso para ler os registros do banco de dados no período de tempo escolhido pelo usuário é este:
        string DataInicio = mcInicio.SelectionStart.Date.ToString("MM/dd/yyyy");
        string DataFim = mcFim.SelectionStart.Date.ToString("MM/dd/yyyy");

        Conexao ca = new Conexao();
        string sql = "";
        sql += " Select ";
        sql += " s.idProduto, s.FAT, s.nSerie, d.Defeito, s.DataFat ";
        sql += " From ";
        sql += " (SisIndice s INNER JOIN ";
        sql += " Defeitos d ON s.idDefeito = d.idDefeito) ";
        sql += " WHERE(((s.DataFat) BETWEEN ";
        sql += " #" + DataInicio + "# ";
        sql += " and ";
        sql += " #" + DataFim + "#)) ";
        ca.Conectar();
        OleDbDataAdapter da = new OleDbDataAdapter(sql, ca.cx);
        DataSet ds = new DataSet();
        da.Fill(ds, "SisIndice");

        dgvTestGraf.DataSource = ds.Tables["SisIndice"];
        ca.Desconectar();

Realmente a solução é converter o formato da data inserida no banco de dados? Qual é a melhor maneira para se fazer isso?
Desde já agradeço!
Answer: Leandro,
Provavelmente ele está invertendo o dia e mês na hora de inserir.
A melhor maneira de se trabalhar com data é enviar o parâmetro no seu command.
Command.Parameters.Add(new System.Data.OleDb.OleDbParameter("nome","valor"));

Usando dessa forma, o próprio OleDb fará a conversão para o formato correto.
Além do código ficar mais seguro evitando SQL Injection.
Comment: Muito obrigado, Marcelo!!!


Labeling boxplots in R

Question: I need to build a boxplot without any axes and add it to the current plot (ROC curve), but I need to add more text information to the boxplot: the labels for min and max. Current line of code is below (current graph also).
Thanks a lot for assistance.
boxplot(data, horizontal = TRUE, range = 0, axes=FALSE, col = "grey", add = TRUE)

The other solution is add the line from 0 to 1 (instead of x-axis), but I want it to go through the central line...for example like this graphic
Answer: I think you will find this produces something like your hand-drawn diagram.
data    <- c(0.4, 0.7, 0.75, 0.82, 0.9)
endaxis <- c(0, 1)  # endpoints of axis
datamm  <- c(min(data), max(data))
boxplot(data, horizontal = TRUE, range = 0, ylim = endaxis,
                    axes = FALSE, col = "grey", add = FALSE)
arrows(endaxis, 1,  datamm, 1,  code = 1, angle = 90, length = 0.1)
valuelabels <- c(endaxis[1], round(fivenum(data)[2], digits = 2) ,
                 round(fivenum(data)[4], digits = 2), endaxis[2]  )
text(x = valuelabels, y = c(1.05, 1.25, 1.25, 1.05), labels = valuelabels)

There are probably better ways of doing it.
You may need to adapt it to fit your ROC plot, including changing add = FALSE
Comment: Well, your response seems more close to what was asked by the OP (so I've +1). However, I feel like this isn't a boxplot anymore, or at least it loose its interest in spotting possible outlying value. Of note, you can customize a little bit more the boxplot (see the `pars` arguments to reduce its aspect ratio (`boxwex`) and the size of the whiskers (`staplewex`)).
Answer: Try something like this for a standalone version:
bxp <- boxplot(rnorm(100), horizontal=TRUE, axes=FALSE)
mtext(c("Min","Max"), side=3, at=bxp$stats[c(1,5)], line=-3)

Note that you can get some information when calling boxplot, in particular the "five numbers".
If you want it to be superimposed onto another graphic, use add=T but replace mtext by text; you will need to set a $y$ value (which depend on the way you plot the other graphic).
A more complete example was given by John Maindonald (code should be on his website):
Answer: Fully customizable ggplot2 boxplot...
#bootstrap
data <- data.frame(value=rnorm(100,mean = 0.5, sd = 0.2),group=0)
#processing
metaData <- ddply(data,~group,summarise,
            mean=mean(data$value),
   sd=sd(data$value),
            min=min(data$value),
   max=max(data$value),
            median=median(data$value),
   Q1=0,Q3=0
   )
bps <- boxplot.stats(data$value,coef=1.5)
metaData$min <- bps$stats[1] #lower wisker
metaData$max <- bps$stats[5] #upper wisker
metaData$Q1 <- bps$stats[2] # 1st Quartile
metaData$Q3 <- bps$stats[4] # 3rd Quartile

#adding outliers
out <- data.frame() #initialising storage for outliers
if(length(bps$out) > 0){
 for(n in 1:length(bps$out)){
  pt <-data.frame(value=bps$out[n],group=0)
  out<-rbind(out,pt)
 }
}
#adding labels
labels <-data.frame(value=metaData$max, label="Upper bound")
labels <-rbind(labels,data.frame(value=metaData$min, label="Lower bound"))
labels <-rbind(labels,data.frame(value=metaData$median, label="Median"))
labels <-rbind(labels,data.frame(value=metaData$Q1, label="First quartile"))
labels <-rbind(labels,data.frame(value=metaData$Q3, label="Third quartile"))

#drawing
library(ggplot2)
p <- ggplot(metaData,aes(x=group,y=mean))
p <- p + geom_segment(aes(x=c(0.1,0,0.1),y=c(0,0,1),xend=c(0,0,-0.1),yend=c(0,1,1)))
p <- p + geom_text(aes(y=c(0,1),label=c(0,1),x=0.2))
p <- p + geom_errorbar(aes(ymin=min,ymax=max),linetype = 1,width = 0.5) #main range
p <- p + geom_linerange(aes(ymin=min,ymax=max),linetype = 1,width = 0, color="white")# white line range
p <- p + geom_linerange(aes(ymin=min,ymax=max),linetype = 2)    #main range dotted
p <- p + geom_crossbar(aes(y=median,,ymin=Q1,ymax=Q3),linetype = 1,fill='white') #box
if(length(out) >0) p <- p + geom_point(data=out,aes(x=group,y=value),shape=4) # drawning outliers if any
p <- p + scale_x_discrete(breaks=c(0))
p <- p + scale_y_continuous(name= "Value")
p <- p + geom_text(data=labels,aes(x=0.5,y=value,label=round(value,2)),colour="black",angle=0,hjust=0.5, vjust=0.5,size=3)

p <- p + opts(panel.background = theme_rect(fill = "white",colour = NA))
p <- p + opts(panel.grid.minor = theme_blank(), panel.grid.major = theme_blank())
p <- p + opts(axis.title.x=theme_blank())
p <- p + opts(axis.text.x = theme_blank())
p <- p + opts(axis.title.y=theme_blank())
p <- p + opts(axis.text.y = theme_blank())

p + coord_flip()

Result:

...code maybe a bit ugly but works the right way.
Answer: Here is mine implementation of your solutions. I've decided not to map the mean value, there is not to much space left. Also the line from 0 to 1 seems odd.
Thank's a lot everyone.
data <- read.table("roc_average.txt")
bxp <- boxplot(data, horizontal = TRUE, range = 0, axes = FALSE, col = "grey", add = TRUE, at = 0.2, varwidth=FALSE, boxwex=0.3)
valuelabels <- c(round(fivenum(data)[2], digits = 2), round(fivenum(data)[4], digits = 2))
text(x = valuelabels, y = c(0.35, 0.35), labels = valuelabels, font = 2)
mtext(c(min(round(data, digits = 2)),max(round(data, digits = 2))), side=1, at=bxp$stats[c(1,5)], line=-3, font = 2)

Comment: The boxplot is supposed to summarize the AUC? If so, why is the min value = 0.5?
Comment: yep, seems strange, because several ROC should be below 0.5. Digging up what's wrong...
Comment: That is the point I have inverted the ROC AUC for values below 0.5, so the graphics should be remade. Thanks a lot!
Comment: +1 for coming back, I'm waiting for your update. If you're working with different classifiers, you might have a look at [ROCR](http://rocr.bioinf.mpi-sb.mpg.de/).
Comment: I did ROC curve with ROCR

Labeling boxplots in R


The difference of $\sum_{i=1}^{n}X_{i}$ and $\sum_{i=1}^{n}X_{(i)}$

Question: Here is a exercise from *Mathematical Statistics. Jun Shao. Second edition. EX2.20
Let $X_1,..., X_n$ be $i.i.d.$ random variables having the exponential distribution $E(a,\theta)$, $a\in R$, and $\theta > 0$.
$$
      f(x,a,\theta)=\frac{1}{\theta}e^{-(x-a)/\theta}I(x>a)
$$
$$
      F(x)=1-e^{-(x-a)/\theta}
$$
Show that the smallest order statistic, $X_{(1)}$, has the exponential distribution $E(a,\theta/n)$ and that $2\sum\limits_{i=1}^{n}(X_{i}-X_{(1)})/\theta$ has the chi-square distribution $\chi^2_{2n-2}$.
What I know is:
The p.d.f. of $X_{(1)}$ is:
$$
     f(x)=\frac{n!}{(n-1)!}\left[\frac{1}{\theta}e^{-(x-a)/\theta}\right]\left[e^{-(x-a)/\theta}\right]^{n-1}=\frac{1}{\theta/n}\exp\left\{-\frac{x-a}{\theta/n}\right\}\sim E(a,\theta/n)
$$
I don't know how to caculate the p.d.f. of $2\sum\limits_{i=1}^{n}(X_{i}-X_{(1)})/\theta$ ;
But I know how to caculate the p.d.f. of $2\sum\limits_{i=1}^{n}(X_{(i)}-X_{(1)})/\theta$ .
My question is that can we assume $\sum\limits_{i=1}^{n}X_{i}$ and $\sum\limits_{i=1}^{n}X_{(i)}$ are the same?
If we can not, can you give one example to explain? and how to solve the question above.
Comment: Original problem discussed at https://stats.stackexchange.com/q/272385/119261.
Comment: > *I don't know how to caculate the p.d.f. of* $$2\sum\limits_{i=1}^{n}(X_{i}-X_{(1)})/\theta$$

*> But I know how to caculate the p.d.f. of* $$2\sum\limits_{i=1}^{n}(X_{(i)}-X_{(1)})/\theta$$This is exactly the trick, use the [memoryless](https://en.m.wikipedia.org/wiki/Memorylessness) property of the exponential distribution, well done.
Comment: > *But I know how to caculate the p.d.f. of* $$2\sum\limits_{i=1}^{n}(X_{(i)}-X_{(1)})/\theta$$ Here you actually use the same principle as the one that you are asking for. The sum of ordered exponentially distributed variables $(X_{(i)}-X_{(1)})$ is similar to the sum of unordered exponentially distributed variables.
Comment: If you shuffle a deck of cards, the sum of the numbered cards is the same every time. It's also the same if you sort the cards.
Answer: Hint:  If the data is $X_1, X_2, \dotsc, X_n$ and its order statistics is
$X_{(1)} \le X_{(2)} \le \dotsm \le X_{(n)}$, can you explain that the order stats is simply some permutation of the data $X_i$ in its original order, that the two collections are equal as sets, so the sum must be the same?
$1 +2+3$ is the same as $1+3+2$.
Comment: But whatever is the data, the same argument can be made. There is no possibility of an outcome where the result does not hold.
Comment: I think I know what confused me. For $X_{i}$ and $X_{(i)}$, they have different distribution. But for $\sum X_{i}$ and $\sum X_{(i)}$, they have the same distribution. And $X_{i}$ are i.i.d. but $X_{(i)}$ are not independent.
Comment: When we observe the data, we can know the  $\sum X_{i}$ is equal to the $\sum X_{(i)}$. But $X_{i}$ and $X_{(i)}$ are random variables, I am still a little confused.


Don't render html.tpl.php for a specific path

Question: Is it possible to load page content without rendering html.tpl.php? I mean on default Drupal has the follwoing:
Html.tpl.php --> Page.tpl.php -->...(etc.)
my goal is to remove Html.tpl.php for a custom path (site://ajax-unesco)
so:
page--ajax-unesco.tpl.php --> ... (etc.)
Comment: is ajax-unesco content type ?
Comment: keying in on the ajax portion of your path, if you are wanting Drupal to just output the $content of a page instead of all the various wrappings, in that menu callback, PRINT what you want instead of RETURNing it.
Comment: It`s a view, i wanna get its contents by ajax call without additional data (like html.tpl contents).
Comment: @Jimajamma i didn't get it, currently i have a view with page display and a template file called "page--ajax-unesco.tpl.php (my view name) i'm rendering with the following code:
Comment: have you tried creating html--ajax-unesco.tpl.php in templates file ? you can create and keep it blank and test.
Comment: @sandeshyadav i tested it right now, but no results.
Comment: did you clear the cache ? And sorry dont put it blank.    put

in it.
Answer: You could do something like this:
<code>/**
 * Implements hook_menu
 */
function MY_MODULE_menu(){
  $items = array();
  $items['clean/view'] = array(
    'page callback'    => 'MY_MODULE_clean_view',
    'page arguments'   => array(2, 3),
    'access arguments' => array('access content'),
    'type'             => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Menu callback for clean/view
 * Output view without wrapper page markup
 */
function MY_MODULE_clean_view($name, $display = 'default'){
  // Note views_embed_view performs views access check
  print views_embed_view($name, $display);
  drupal_exit();
}
</code>
You can then use the dynamic path <code>/clean/view/view_name/display_id</code> to render the View without the wrapper markup.


Relations between matrix norm and determinant

Question: I was wondering whether there is a way to obtain the determinant of a matrix out of its norm (when the matrix is regular otherwise it is not true). If $A$ is a square matrix of dimension $n\geq 1$, and $\det A\neq 0$, do we have something like?
$$|Ax|_2 \leq \|A\|_{\text{op}} |x|_2 \leq C_n |\det A| \ |x|_2 \leq \cdots$$
or similar? Or maybe a similar estimate for different norms for $A$ and $x$ if needed since many matrix norms are related to eigen- or singular values which are related to the determinant.
Thanks a lot! :)
Answer: Consider the matrices of the form $\left(\begin{smallmatrix}1&x\\0&1\end{smallmatrix}\right)$, with $x\in(0,+\infty)$. All of them have determinant equal to $1$, but their norms are arbitrarily large. Does this answer your question?
Comment: But anyway there is a bound for the determinant: https://en.wikipedia.org/wiki/Hadamard%27s_inequality
So we have something like $|\det A|\lesssim \|A\|^n$ for a $n\times n$-Matrix.
Comment: @Martingalo Sure. Take $\left(\begin{smallmatrix}\sqrt{x^2+1}&x\\x&\sqrt{x^2+1}\end{smallmatrix}\right)$. Its determinant is $1$, but its norm is arbitrarily large.
Comment: Funily enough if $A$ is invertible and its determinant positive we may find some estimate for its inverse because:
$$\|A^{-1}\| = \frac{1}{\det A} \|Adj(A^\ast)\|$$ but of course the constant is another matrix.
Comment: In some sense yes. So the question should be reformulated. For instance. $|Ax|_2\leq \|A\|_{op}|x|_2\leq C_{n,A} |\det A| \ |x|_2$ (i.e. the constant depends on the values of $A$?)
Answer: I don't see any way to obtain an upper bound of $\|Ax\|$ using the determinant, because the norm of a matrix can remain unchanged when the determinant approaches zero. E.g. when $x=(1,0,\ldots,0)$ and $A=\operatorname{diag}(1,t,\ldots,t)$, we have $\|Ax\|_2=1$ but $\det A\to0$ as $t\to0$.
Answer: I'm not sure how to prove it, but you might find this exact formula for the norm from Hubbard & Hubbard's Vector Calculus interesting:

If A is a real 2x2 matrix, then
$$||A|| = \left(\frac{|A|^2+\sqrt{|A|^4-4(\det A)^2}}{2}\right)^{1/2}$$
where |A| is the Frobenius norm of $A$.

José Carlos Santos's answer shows that the determinant alone does not carry enough information to determine the norm. For the matrix $\begin{pmatrix} 1 & x \\ 0 & 1 \end{pmatrix}$ that he considered in his example, we see that as $x \to \infty$, while $\det A \to 1$, the above formula is still able to work because $|A| \to \infty$.
Comment: Could you please give a page reference? I am trying to find it but I can not. Here is the [link](https://notendur.hi.is/mbh6/html/_downloads/Vector%20Calculus%20-%20Hubbard.pdf) I have found.
Comment: Ok, it is exercise 2.8.8.


Why not go for a field goal attempt instead of a punt in some situations?

Question: I have noticed that in American football the ball seems to travel farther when launched from a tee on the ground, or from the fingers of a holder on the ground, than when launched from a punt.
What are the rules for if a field goal is not successful but the ball lands inside the field of play?  Then why don't teams use a field goal kicker to launch punts in that way?
Comment: @posdef FYI, when I first read the question, I thought the OP was asking why punters do not punt like how a kicker kicks a FG (OP says ball travels further when kicked from the ground). Now, it reads like "Why not attempt a FG instead of punting?" The answer does remain the same, however, outside of mentioning that the [longest FG ever made in the NFL is 64 yards](http://espn.go.com/nfl/story/_/id/10104268/matt-prater-denver-broncos-sets-nfl-mark-64-yard-field-goal) and [69 yards in NCAA football](https://en.wikipedia.org/wiki/Field_goal_%28American_and_Canadian_football%29#College_football).
Comment: @edmastermind29 that's what I thought as well, then the second paragraph changed my mind. Besides this way the question makes more sense; "_why dont punters punt like a FG_" has one answer really, "_'cus that's not how a punt works, what you are asking is a FG attempt_".

Regardless, if I have misunderstood the question altogether, it's always possible to roll back. :)
Answer: This is covered in Rule 11, Section 4, Article 2 when "the ball has not been touched by the receivers beyond the line [of scrimmage] in the field of play."
If a field goal attempt is missed, which would be the case if the ball lands inside the field of play (the kick falls short of the goalpost, for example) on a field goal attempt, the opposing team will take possession of the ball at the spot of the kick.
 Note: If the spot of the kick is within the opposing team's 20-yard line (the kick is mishit, for example), then the opposing team will take possession of the ball at the opposing team's 20-yard line.

Rule 11, Section 4, Article 2 (page 58) in the 2012 NFL Rule Book states:

Missed Field Goals.
If there is a missed field-goal attempt, and the ball has not been
  touched by the receivers beyond the line in the field of play, the
  following shall apply:

(a) If the spot of the kick was inside the receivers' 20-yard line,
  it is the receivers' ball at the 20-yard line or
(b) If the spot of the kick was from the receivers' 20-yard line or
  beyond the receivers' 20-yard line, it is the receivers' ball at the
  spot of the kick.

Note: These options apply only if the ball has been beyond the line.
Answer: The strategic answer to the main question is: Field Position
Please see this article: https://www.football.com/en-us/charting-the-importance-of-field-position/
Basically, as you get farther away from the goal posts, the chances of successfully making the kick get lower and lower. As you can see in the linked article, as you get better and better starting field position, the chances of you scoring get higher and higher. Also a key factor here is that on a field goal, if you miss the field goal and the other team does not decide to return it, the other team gets the ball (their starting field position) on your previous line of scrimmage.
So putting all of those things together, it is a much smarter strategic move to give up on the chance for 3 points, given the possible negatives, but instead use a punt to "pin your opponent deep" and give them very bad starting field position (optimally at their own 10 yard line or less.) Their odds of scoring are lower, and your odds of getting good starting field position are better, making it easier for your offense to score.
As to the sub-question as to why not punt the ball using the same kicking technique as a field goal: because then it wouldn't be a punt. A punt has different rules and circumstances than a field goal kick, and each is outlined in the rules if that sort of thing interests you: http://football.calsci.com/TheRules6.html
In layman's terms: a punt occurs when an offensive player kicks the ball while possessing it behind the line of scrimmage without it touching the ground. Most often this occurs with a punter and on 4th down, but it can be done by anyone and sometimes you'll see this happen with the Quarterback in shotgun formation.
Answer: The answer to this gets trickier in high school.  A missed field goal is treated as a punt.
In my senior year in high school, I began punting, but was already an accomplished placekicker.  I averaged 30 yards from scrimmage on my punts.  As a placekicker, I would kick the ball from 50 to 55 yards, and sometimes 60 yards, on the fly from the point of the kick, which meant that I could placekick the ball 43 to 53 yards from the scrimmage line (because a placekick is teed up 7 yards behind the line of scrimmage).  And that doesn't count any potential roll if it is not caught.
With the ball on the 48, we tried a 65-yard field goal, and the ball landed 2 yards in front of the goal posts.  The other team got the ball on the 20, so we had a 28 yard net gain, about the same if I had punted, plus we had the possible advantage that we would have gotten 3 points if it had gone another 4 or 5 yards.    Had the ball been it been on the 20, it would have carried from our own 13-yard line all the way to the 20 - 55 yards, assuming it was caught.
Covering a field goal attempt is harder from field goal formation.  My solution would be to simply kick the ball out of bounds every time we weren't in field goal range.  We still would have netted 40 yards a kick, and no returns, because it's far easier to placekick accurately out of bounds than to punt to a location.
With the ball on the 2, there is no need for punter to be backed up against the end line.  The tee would be placed 5 yards deep in the end zone, and the kicker would have plenty of room.
I'm not sure why high school teams with good kickers don't do this.


How do I add multiple links in each table row form table?

Question: I am new to drupal 8. I have created a form listing in admin.Now i want to add three or more links for operation(Edit/Delete/Suspend) in single TD columns. Can anyone let me know how to do this? I tried by concatenation two links but did not work. I am creating links as below.

$query = \Drupal::database()->select('vacations', 'v');
    $query->fields('v');
    $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
    $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
    //$results = $query->execute()->fetchAll();
    $results = $pager->execute();
    // Initialize an empty array
    $output = array();
// Next, loop through the $results array
    foreach ($results as $key => $result) {
      $approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
      $reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
      $newLink = $approve_link; // this works
      //$newLink = $approve_link . "|" . $reject_link; //this does not work it shows plain html in table columns
      $output[$result->id] = [
        //'id' => $result->id,
        'employee_name' => $result->employee_name,
        'employee_email' => $result->employee_email,
        'vacation_start_date' => $result->vacation_start_date,
        'vacation_end_date' => $result->vacation_end_date,
        'leave_days' => $result->leave_days,
        'status' => $result->status,
        'operations' => $newLink,
      ];
    }
    $form['table'] = [
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $output,
      '#empty' => t('No users found'),
    ];

I am using Drupal 8.
Comment: Welcome to Drupal Answers! So far you are just stating facts which aren't totally clear. You need to show all the code you are using; that is only a minimal part. We cannot say what you are doing wrong without seeing the code. Then, we aren't a _write the code for me_ service, so a request like _this is all my code; fill the holes with the missing code_ is not acceptable.
Comment: I only want to show to links "Approve | Reject". Approve and reject both will be href links. Below is the full function for your reference.
Comment: The above $output array is in for each loop after querying the DB. Two links one for approve and second for reject is required. Every admin listing has these links. But I am not able to show them in a single column. Remember I am using Drupal 8.
Comment: I have updated the question and put my full code.Please check reply.
Answer: After a long research i was able to acheive this as follows:

$approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
$reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
$mainLink = t('@linkApprove | @linkReject', array('@linkApprove' => $approve_link, '@linkReject' => $reject_link));

and then use $mainLink in foreach loop.
Thanks for all your help.


How to avoid double sharps in LilyPond

Question: I have this code:
\new StaffGroup <<
  \override StaffGroup.SystemStartBracket.stencil = ##f
  \new Staff \with {
  } \relative {
    g'8 ais8 dis2
  }
>>

This produces following

I want exact same melody to be played by Alto Sax. So I did this:
\new StaffGroup <<
  \override StaffGroup.SystemStartBracket.stencil = ##f
  \new Staff \with {
  } \transpose c a, {
    \relative {
    g'8 ais8 dis2
  }
}
>>

But lilypond produces this:

I would prefer to have just E G C in the output instead
of the double sharps.
Answer: Frankly, I cannot imagine a melody where your original notation makes any sense.  Once the pitches and accidentals make sense regarding the scale degrees of the notenames and intervals within the current key signature (it doesn't help that you don't even include and thus transpose one), players will prefer the correctly transposed accidentals because they put the notes better into melodic context.
This probably does not apply to strict dodecaphonic/serial music, but then sax would be an unusual instrumentation for that purpose.
Answer: The simplest solution would be to change the notes from G A# D# to G Bb Eb. Then the transposition will become E G C.
However, if this is not possible, you could use the "smart transpose" code snippet included in the LilyPond documentation. See 1.1.2 Changing multiple pitches: Transpose. Its purpose is to

enforce enharmonic modifications for notes in order to have the minimum number of accidentals.
Answer: In general, a good practice is to figure out what key your song (or part of your song) is in, and then whenever you need an accidental, use the one that belongs to that key.
For example, the key of B♭ major contains the following notes: B♭, C, D, E♭, F, G, A, B♭. If you had written your score using notes from B♭ major, this problem wouldn't have happened.
There is no key that contains both G and A♯, and that's a good indication that you usually don't want to use the notes G and A♯ nearby each other. That partly explains why this problem happened in the first place: you provided unusual input, so you got unusual output.
(Of course, you should usually use a key signature, and that will make your scores easier to read by eliminating most of the accidentals. If I remember correctly, Lilypond still makes you type the accidentals even if you have a key signature, and so it's still important—but also easy—to know what key you're in and stick mainly to notes from that key.)
Comment: I am more of a programmer and less of a musician :-)
Comment: Yes, in lilypond you have to type the accidentals. Not being a trained musician, I just use sharps for all black keys :-(

How to avoid double sharps in LilyPond


Sending outgoing mail from multiple e-mail accounts (of different domains hosted on the same server) using sSMTP

Question: I'm hosting multiple domains in my public html folder of an ubuntu-nginx vps server. And I currently have my 'ssmtp.conf' file set up successfully to send outgoing mail(contact, registration, verification, forgot password etc using php 'mail()') from one of those domains, say, example1.com.
Would there be any way to make some modifications on the 'ssmtp.conf' file such that mail can be sent from the e-mail accounts pertaining to the other domains as well?(email@example.com or firstname.lastname@example.com, for instance).
Thanks in advance.
My current ssmtp.conf file looks like this:
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
email@example.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.example1.com:25

# Where will the mail seem to come from?
rewriteDomain=example1.com

# The full hostname
hostname=example1.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES

email@example.com
firstname.lastname@example.com

Answer: You should use a SMTP library like SwiftMailer in PHP to send mails via SMTP to the mail server instead of mail() function. This way you can use arbitrary From addresses in e-mails.


Como verificar dia da semana sendo 1,3,5

Question: Galera,
Tenho um campo em minha tabela que guardo o dia do mês, exemplo
Mas nesse mesmo campo estou gravando a informação assim:
1,2,3,5,22
Hoje é dia 22 DAY( NOW( ) ) = 22
Veja que no meu campo o dia está 1,3,5 como hoje é 22 deveria trazer o registro.
Como posso verificar meu campo no mysql? Split? Se sim como posso usar?
Answer: Use o like
SELECT * FROM tabela WHERE campo LIKE "%5%"

Comment: Me desculpe, só dei o exemplo do dia da SEMANA, mas preciso do dia do  MÊS também. Então o like não resolve.
Comment: Então sua pergunta está muito confusa. Pq do jeito que está, o like funcionaria. Explique melhor.


symbol at particular location in line chart with core plot

Question: I want to draw line chart using core plot
i have x-axis with time (1,2,3,...13,14...00)
and y-axis with numbers(0-50-100-150-200-....500)
now at each coordinate(x,y) i want to put symbol like circle with color
for example
at x-axis - time 4'o clock and
y-axis - number 65
at x-axis - time 13'o clock and
y-axis - number 25
at x-axis - time 14'o clock and
y-axis - number 15
at x-axis - time 23'o clock and
y-axis - number 5
so at each (x,y) want to put symbol and then draw line using these symbol
thank you very much
Answer: Read about CPPlotSymbol..You can adjust CPPlotSymbol size as you like.
A small example..
<code>CPScatterPlot *dataPlot; (dataPlot obtained elsewhere)

// Add points to this plot
CPPlotSymbol *circlePlotSymbol = [CPPlotSymbol ellipsePlotSymbol];
circlePlotSymbol.fill = [CPFill fillWithColor:dataPlot.dataLineStyle.lineColor];
circlePlotSymbol.size = CGSizeMake(6, 6);

dataPlot.plotSymbol = circlePlotSymbol;
</code>
Comment: thanks for advice but i am asking for a symbol on particular location


Autenticação padrão do Asp.net MVC

Question: Estou iniciando estudos sobre o asp.net MVC, e queria saber onde é que o visual studio cria o banco e tabelas quando se escolhe o projeto padrão MVC.
Ao que parece ele já cria todo o suporte para registro e login. Onde ficam essas tabelas ? Posso migrar isso para um banco mysql, por exemplo?
Answer: Onde ficam essas tabelas?
No diretório App_Data fica um banco provisório no formato LocalDb, mas esse arquivo fica escondido. No Solution Explorer, clique no botão Show All Files para vê-lo:

Posso migrar isso para um banco mysql, por exemplo?
Pode. Primeiro você precisa configurar o Entity Framework para MySQL, e depois executar o comando Update-Database para popular seu banco. Esta resposta ensina como fazer isso para SQL Server, mas serve também para o MySQL.
Comment: Valeu Cigano, funcionou beleza no vs2013. Agora estou testando o vNext e esse diretório App_Data nem existe mais.
Comment: @paulo Ah, sim. A aplicação que eu colei de exemplo ainda é MVC5.
Comment: Acabei descobrindo que o banco de dados ele cria em c:\Usuarios\seuusuario
Comment: @paulo É normal variar. Tudo depende de como o projeto é iniciado.

Autenticação padrão do Asp.net MVC


smallest element -> highest percentage

Question: I have a set of numbers $Q = \lbrace q_1, ..., q_n \rbrace$ and want to assign weights $w_i$ to each element $q_i$ such that the weights add up to one. However, I'd like to assign the highest weight to the smallest element in the set.
I came up with this solution:
\begin{align}
w_i &= \frac{1 - \frac{q_i}{\sum_{q \in Q} q}}{n - 1}
    = \frac{(\sum_{q \in Q} q) - q_i}{(n - 1) \cdot \sum_{q\in Q} q}
\end{align}
The rationale is that I first calculate the inverted percentage of element $q_i$ and divide it by $n - 1$ to normalize the weight.
What do you think about this solution? Do you think, it's practicable or are there better approaches?
Thank you for your help.
Comment: If $Q$ is sorted, can't we have $w_i = \frac{q_{n-i+1}}{\sum_{i}^n q_i}$?
Comment: There are infinitely many ways to do that. How do you decide which is better? What you suggest would work, but so would $w_i=\frac {q_{n+1-i}}{\sum_{q\in Q}q} $.
Comment: @user8734617 I wanted to confirm that is solution is ok because I was a bit sceptical about it (because you can interpret it as the average of all elements except for $q_i$ divided by the sum of all elements, so, it's somehow the normalized mean of all elements except $q_i$). Moreover, I was looking for a more concise, maybe a bit more intelligent alternative.
Comment: My hint here is identical to @TiwaAina 's answer, but you had different concerns about the two. I didn't want to post mine as an answer because I was not sure what you have been looking for. How do you measure whether the solution is more or less intelligent, for instance? As for your concern about Tiwa Aina's solution, of course $w_i $ depends not only on $q_i $ but on all $q $'s, but so does *your* solution.
Comment: Yes, you're right. I think I didn't really understood the main idea behind @TiwaAina 's answer. - Of course, I have no measurement for "intelligent" solution because it's somehow a matter of opinion. However, I do not want to put to much weight on the question how to evaluate the quality of an answer and just focus on the set of possible solutions. Feel free to post your solution, too.
Answer: Assuming all $q_i \ne 0$, you could try
$$ w_i = \frac{1/q_i}{\sum_{j=1}^n 1/q_j} $$
Comment: Thanks for your answer, introduction601. This looks very good. My use case does not explicitly states that $q_i \neq 0$, but in practice, this may hold.
Answer: If $Q$ is sorted, you could use $$w_i = \frac{q_{n-i+1}}{\sum_{i}^n q_i}$$
There are tons of weighting methods that would fit your criteria, but I imagine that this is the simplest.
Comment: Thanks for your answer, Tiwa. Actually, $Q$ is not sorted and can contain arbitrary numbers $q_i \in \mathbb{R}_{\geq 0}$. I'd like to avoid sorting because the complexity of my algorithm would become at least $\mathcal{O}(n\cdot \log n)$.

However, I do not really understand the rationale of this equation. Can you please explain it shortly? As far as I can see, $w_i$ depends in this equation on number $q_{n-i+1}$. But I wanted to make it depending on the number $q_i$, i.e., $w_i = f(q_i)$

smallest element -> highest percentage


Problema com json no angularjs

Question: Estou a desenvolver uma aplicação móvel e estou a resgatar da base de dados uma lista de dados.
O que acontece e que entre cada dado fica sempre uma , "virgula" e não sei como retirar.
Deixo abaixo um print do acontece:

Controller
.controller('ListaEstabelecimentos', function($scope, $http, $stateParams) {
    $http.get("https://www.sabeonde.pt/api/api_estabelecimentos.php?categoria_slug="+$stateParams.catSlug).success(function (data) {
        $scope.estabelecimentos = data;
    });
})

Onde Mostro os dados

Retorno
<?php

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST');
    header("Content-type: application/json");

    require_once("../funcoes/funcoes.php");

    $result_cat_locais = $conexao->prepare("SELECT * FROM categorias_estabelecimentos WHERE categoria_slug = :categoria_slug ");
    $result_cat_locais->bindValue(':categoria_slug', $_GET['categoria_slug'], PDO::PARAM_STR);
    $result_cat_locais->execute();
    $rows_locais = $result_cat_locais->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows_locais as $row_cat_locais) {

    $result_local = $conexao->prepare("SELECT * FROM estabelecimentos WHERE id = :row_cat_locais AND activo = :activo ORDER BY RAND()");
    $result_local->bindParam(':row_cat_locais', $row_cat_locais['estabelecimento_id'], PDO::PARAM_INT);
    $result_local->bindValue(':activo', 1, PDO::PARAM_INT);
    $result_local->execute();
    $row_local = $result_local->fetch(PDO::FETCH_ASSOC);

    $result_anexo_local = $conexao->prepare("SELECT * FROM estabelecimentos_anexos WHERE id_mae = :row_local AND seccao = :seccao ");
    $result_anexo_local->bindParam(':row_local', $row_local['id'], PDO::PARAM_INT);
    $result_anexo_local->bindValue(':seccao', 'thumbnail', PDO::PARAM_STR);
    $result_anexo_local->execute();
    $row_anexo_local = $result_anexo_local->fetch(PDO::FETCH_ASSOC);

    $result_count_posts = $conexao->prepare("SELECT COUNT(*) AS id_post FROM posts WHERE estabelecimento_id = :estabelecimento_id");
    $result_count_posts->bindParam(':estabelecimento_id', $row_local['id'], PDO::PARAM_INT);
    $result_count_posts->execute();
    $bar_posts = $result_count_posts->fetch(PDO::FETCH_ASSOC);

    $result_count_fotos = $conexao->prepare("SELECT COUNT(*) AS id FROM estabelecimentos_anexos WHERE id_mae = :row_local AND seccao = :seccao ");
    $result_count_fotos->bindParam(':row_local', $row_local['id'], PDO::PARAM_INT);
    $result_count_fotos->bindValue(':seccao', 'fotos', PDO::PARAM_STR);
    $result_count_fotos->execute();
    $bar_fotos = $result_count_fotos->fetch(PDO::FETCH_ASSOC);

    $query = $conexao->prepare("SELECT ROUND((SUM(pontos) / COUNT(*)), 1) FROM avaliacoes WHERE estabelecimento_id = :estabelecimento_id");
    $query->bindValue(':estabelecimento_id', $row_cat_locais['estabelecimento_id'], PDO::PARAM_INT);
    $query->execute();
    $row_avaliacao = (double) $query->fetchColumn();
    $row_avaliacao = $row_avaliacao > 0 ? number_format($row_avaliacao, 1, '.', '') : $row_avaliacao;

    $cor_rating = round($row_avaliacao);

    $return[] = '

'.$row_local['titulo'].'

'.$row_avaliacao.'

 Opiniões '.$bar_posts['id_post'].'

 Fotos '.$bar_fotos['id'].'

    ';
    }
    echo json_encode($return);
?>

Comment: Adicione na sua pergunta o código que usas para resgatar os dados.
Comment: Já adicionei o codigo
Comment: "Concelho" na verdade é com "s". Coloque o HTML retornado pela chamada Ajax: aparentemente, esta vírgula esta vindo no HTML retornado pela API.
Comment: Mas tive a ver na api e nao tem nenhuma virgula
Comment: @CésarSousa coloque o retorno por favor, porque dependendo de como for o retorno você terá que fazer algum tipo de escape antes de retornar o json.
Comment: sim já coloquei o retorno
Answer: Seu retorno está sendo um array de HTMLs, por isso a virgula, tente fazer um retorno com um único HTML, ou seja, o seu retorno deve ser uma string. Não sei como concatena string em php mas seu retorno deve ricar algo como isso que vou passar abaixo:
$return += '

'.$row_local['titulo'].'

'.$row_avaliacao.'

 Opiniões '.$bar_posts['id_post'].'

 Fotos '.$bar_fotos['id'].'

';

Comment: E isso mesmo funcionou certinho. Obrigado

Problema com json no angularjs


How to know now when multiple server call methods with nested loops have all finished

Question: I have multiple methods, each with nested loops and facebook requests.  There is an array of X id's and each method loops through each id, makes a request for that id then does stuff with the result data.
I need to be notified when each method has completed... ie, when the method has finished looping through all the id's in the array, making the facebook request for each, received the results and finished its tasks with the resulting data.  I can't seem to figure out how to make this happen.  here are examples of the methods:
- (void)runLoopForFacebookFriendsContent1 {

    for (NSString *fbIdStr in self.fbIdsArr){
        FBRequest *fbRequest = [FBRequest requestWithGraphPath:graphPathString parameters:nil HTTPMethod:@"GET"];
        [fbRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            if (error) {
                //show alert
            } else {
                //Do stuff with the resulting data
            }
        }];
    }
}

- (void)runLoopForFacebookFriendsContent2 {

    for (NSString *fbIdStr in self.fbIdsArr){
        FBRequest *fbRequest2 = [FBRequest requestWithGraphPath:graphPathStringNumber2 parameters:nil HTTPMethod:@"GET"];
        [fbRequest2 startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            if (error) {
                //show alert
            } else {
                for (PF_FBGraphObject *obj in [result objectForKey:@"data"]){
                    NSLog(@"facebook result:  %@",result);
                        NSMutableDictionary *dict          = [[NSMutableDictionary alloc]init];
                        [dict setValue:@"type2" forKey:@"ContentType"];
                        [dict setValue:obj forKey:@"data"];
                        [self.theFacebookDataArray addObject:dict];
                }
            }
        }];
    }
}

I call these methods in viewWillAppear.  is there a way to setup some sort of completion handler to put the call for these methods inside?  and then post an NSNotification when they are all done?
Comment: question down-voted without a comment or explanation??? that's helpful...
Answer: One option is to take a look at the ReactiveCocoa framework. I find it helps tremendously with this kind of pattern, after you get past a bit of a learning curve.
The following is an example directly from the linked file:
// Perform 2 network operations and log a message to the console when they are
// both completed.
//
// +merge: takes an array of signals and returns a new RACSignal that passes
// through the values of all of the signals and completes when all of the
// signals complete.
//
// -subscribeCompleted: will execute the block when the signal completes.
[[RACSignal
    merge:@[ [client fetchUserRepos], [client fetchOrgRepos] ]]
    subscribeCompleted:^{
        NSLog(@"They're both done!");
    }];

You could adapt this to the Facebook SDK fairly easily.
Comment: thanks for the response, Ill check out Reactive.  The problem isn't really with facebook & know when the server calls are done... I think it's more about knowing when all the nested loops are done iterating.  but I'll look into this to see if there is some way to setup a notification system for nested loop completion.
Answer: This behavior is expected since you are calling dispatch_group_enter and then instantly calling dispatch_group_leave which means the group has nothing to wait for.
You should call dispatch_group_enter before every block and call dispatch_group_leave at the end of every block.
Check the accepted answer here:
Wait until multiple networking requests have all executed - including their completion blocks
Update:
For the given example, you can call dispatch_group_enter before every call to startWithCompletionHandler:, and call dispatch_group_leave at the end of the completion block:
for (...) {
    FBRequest *fbRequest = ...;
    dispatch_group_enter(group);
    [fbRequest startWithCompletionHandler:^(...) {
        ...
        dispatch_group_leave(group);
    }
}

Comment: this is exactly the problem though... I don't know where to call dispatch_group_leave. The code above was just to show the idea I had been trying... not the only thing i've tried. I've placed dispatch_group_leave everywhere I can think of, with no success.  If I just put it as the last line of each method, doesn't work & notify happens before server calls are done. And I cant put it in a completion block for the server calls, cuz the server call is happening in a loop through different id's, so group_leave there would bump on 1st iteration.
Comment: where or how, with the above code, could I place dispatch_group_leave in order to have it leave after the entire method is done?  meaning after each iteration of each nested loop?  Is it possible to put the call to the method (from viewdidappear) inside a block?   something like 'blah_blah_completion(block^{ [self runLoopMethod1]; });'   ???
Comment: I'v added more details, check the answer again.
Comment: I see what your saying, and i've played around with it, but I can't seem to get it to do what I need to do.  I need to know or be notified when the entire method is finished... ie, when the entire series of nested for loops have completed.  I'll try to update the question to be shorter and more clear
Answer: Didn't want to have to answer my own question... don't really like doing that, and was hoping for a more elegant solution... but it doesnt seem to be coming and someone even downvoted the question.  So i'm just going to post my solution and close the question out. If you end up with a similar problem and are reading this, I dealt with it by:
creating 2 int's for each method.  One int is immediately set with the count of the array being iterated through.  at the end of each iteration, I am posting an NSNotification.  In the NSNotification handler method, i am ++ incrementing the second int & each time running an if condition, checking to see if they match.
It's a pain to keep track of all these when there are many methods like this happening... So if anyone ever finds a better solution, I'd love to hear it.  Thanks to everyone who answered and tried to be helpful, I appreciate it!


External JSON to create/update node

Question: I have external REST service with some info about products. This comes from some software of the company.
How I can use this JSON I got to create nodes and fill in the fields in nodes?
Also, I need to detect when something is changed and to update field in existing node.
I'm on Drupal 8 and I'm getting JSON with POST method (I need to send 'id' parameter in order to get product for exact client).
Any ideas?
Comment: Could you post some code with what you're trying to do? Also, is it necessary to post the request or can you make a GET request? The call for the data would be handy to see too.
Answer: The Feeds Module does this great for D7, offering cron imports and ability to update existing nodes/etc. Looks like they have a D8 branch, but I haven't tested. Might be helpful to look at for you.

External JSON to create/update node


Easy way to find the key in a map given a binding, Ocaml

Question: I am not very familiar with Map module in Ocaml.
I have a simple map m: string Map.Make(Int).t from int to string, and I know that every binding (:string) is unique. I would like to write a funciton find_from_string_to_int: string -> string Map.Make(Int).t -> int, could anyone help? Thank you very much!
Answer: If this is an infrequent operation, the easiest way is to fold over all the (key,value) bindings of the map SMap.fold:
# module SMap = Map.Make(String);;
# let reverse v t =
  SMap.fold (fun k v' acc -> if v = v' then Some k else acc) t None;;
val reverse : 'a -> 'a SMap.t -> SMap.key option = <fun>

If this is a common operation, what you're looking for is a bidirectional map (a map that can be queried in both "directions"). The easiest way is to carry around a pair of maps: int IMap.t * string SMap.t (accesses in both direction are logarithmic, while the reverse above is linear in the size of the map). You could also implement a dedicated data structure, but that's probably not worth the added complexity.
PS: reverse could be optimized to quit the iteration early if the value is found, but if it's an uncommon operation it's not really important anyway.


Is the derived category of a full subcategory full?

Question: Certainly not, but I cannot find a good counterexample. I tried to do something like $\mathbf Z\text{-Mod}\subseteq \mathbf Z[x]\text{-Mod}$, but without success. Does anyone have a short counterexample?
Comment: Find a subcategory which is not closed under extensions.
Comment: Find now a nonzero morphism from $Z$ to $Z[1]$ in the derived category of $R$-modules.
Comment: @MarianoSuárez-Álvarez Let $R=\mathbf Z[x]/(x^2)$. Then $\mathbf Z\xrightarrow{x} R \to \mathbf Z$ is a nontrivial extension in $R$-Mod which splits in $\mathbf Z$-Mod. Does this help me in some way?
Comment: (and replace $Z$ by a field, to make things easier)
Comment: @MarianoSuárez-Álvarez I see, so $\begin{matrix} k \\ \downarrow \\R & \rightarrow & k\end{matrix}$ is an example of such a morphism $k\to k[1]$ (with $k$ instead of $\mathbf Z$). Thank you for your advice!
Comment: Please write a complete answer with the details.
Answer: Thanks to the comments by @MarianoSuárez-Álvarez, I can formulate the following answers:
Consider a field $k$ and the ring $k[x]$. Of course, $\hom_{D(k)}(k, k[i])=\begin{cases}k & \text{if i=0,}\\0& \text{o/w}\end{cases}$ in the derived category $D(k)$. Now in the category $k[x]\text{-Mod}$, there is a nontrivial extension $0\to k\xrightarrow{x} k[x]/(x^2) \to k\to 0$, where we consider $k$ a $k[x]$-module by $k=k[x]/(x^2)$. This extension yields a map
$$\begin{matrix}k\\\simeq\:\downarrow\phantom{\simeq} \\k[x]/(x^2) &\rightarrow& k\\&&\downarrow\\&&k\end{matrix}$$
which is a nontrivial map $k\to k[1]$ in $D(k[x])$.


$\sec\theta$ never equals $\tan\theta$. Or does it?!?

Question: Wolfram-alpha is disagreeing with me. I am wondering why: which of us is wrong?
I was writing a question to demonstrate why domains of functions matter. The question is:

Does there exist an angle $\theta$ such that $\sec\theta=\tan\theta$?

Then you get $\sin\theta=1$ and $\cos\theta\neq0$ (knowing to retain this inequality is the point of the question). These angles $\theta$ coincide (so $\theta=n\pi+\pi/2$ and also $\theta\neq n\pi+\pi/2$). We conclude that no such angle $\theta$ exists, so $\sec\theta\neq\tan\theta$ for all $\theta$.

However, WolframAlpha disagrees. Apparently, $\theta=2n\pi+\pi/2$ works (but not, for example, $3\pi+\pi/2$). What is going on here?

Am I wrong?
Does WolframAlpha use an odd definition for $\sec$?
Do I use an odd definition for $\sec$? (I use $\sec=1/\cos$, which I believe is standard. I have never heard of any other definition.)
None of the above.
Answer: I think the other answers indicating that this is an error made by WolframAlpha are perfectly reasonable and I upvoted them all.  I also think it's a good idea to push the feedback button as @AlexR suggests. However, we can place the query in a broader context that makes WolframAlpha's response reasonable and shows us how to fix it at the same time.  I want to emphasize that I am not saying that I agree with WA's output; I'm simply trying to demonstrate how it might be reasonable from one point of view.
To see this, try entering just tan(pi/2) or sec(pi/2) into WolframAlpha. and you'll see that you get the same result, namely $\hat{\infty}$ or complex infinity.  A reasonable interpretation is that WA is working on the Riemann Sphere and, indeed, Mathematica does exactly that in this context. This suggests that we  might get different results from the following queries:
solve tan(x)=sec(x)

vs
solve tan(x)=sec(x) over the reals

I invite you to try that.  Note that all these WolframAlpha inputs correspond to Mathematica commands like the following:
In[1]:= Tan[Pi/2]
(* Out[1]= ComplexInfinity *)

In[2]:= Sec[Pi/2]
(* Out[2]= ComplexInfinity *)

In[3]:= Reduce[Tan[x] == Sec[x], x]
(* Out[3]= Element[C[1], Integers] && x == Pi/2 + 2 Pi C[1] *)

In[4]:= Reduce[Tan[x] == Sec[x], x, Reals]
(* Out[4]= False *)

Comment: Thank you - this is precisely the answer I was hoping for. And you are right - adding "over the reals" does mean that it [outputs no solutions](http://www.wolframalpha.com/input/?i=sec%28x%29%3Dtan%28x%29+over+the+reals). Again, thanks.
Answer: Suppose that
$$\sec\theta = \tan\theta$$
then it follows, from the Pythagorean identity that
$$\sec^2\theta=\tan^2\theta+1$$
$$\tan^2\theta=\tan^2\theta+1$$
$$0=1$$
which is a contradiction, therefore my original supposition (that $\sec\theta=\tan\theta$) was false.
Answer: $$\frac1{\cos\theta}=\frac{\sin\theta}{\cos\theta}\iff\begin{cases}\sin\theta=1\\{}\\and\\{}\\\cos\theta\neq0\end{cases}$$
and since the lower case always happens when the upper one happens, there is no solution.
If WA tells otherwise then it is, again, wrong.
Comment: @user1729 Unfortunately, W|A is proprietary and therefore you'll probably never know *why* it erred.
Comment: Thanks - this means that I am not going mad. However, my question really is *why* is it wrong? Is there something I am missing?
Comment: @user1729 "why is it wrong".... **what** ?
Comment: @user1729 W|A is wrong. Why? Programming error. What to do? Give them feedback so they fix it :)
Comment: No, I mean *why did it make the mistake*. I know it made a mistake, and perhaps we will never know, but...maybe (for example) it was assuming $\theta$ was complex and this tripped it up...
Comment: WA is wrong in quite a few things, and many times I and others have discovered mistakes there, but I don't have a record of them. Of course, I've no the slightest idea why that happens.
Comment: My guess is that W|A looks at series expansions and somehow forgets about divergence.
Answer: Note that the solution W|A claims is $\frac12 (4\pi n + \pi) = \frac\pi2 + 2\pi n$ but $\tan\theta$ is never defined for $\theta = \frac\pi2 + 2\pi n$, thus you have found an error in W|A, wich you should report to them using their feedback form.
Answer: Why not?
$\sec \theta = \tan \theta \leftrightarrow \dfrac{1}{cos \theta}=\dfrac{\sin \theta}{\cos \theta} $. We should conver this into $\cos \theta$.
$\dfrac{1}{cos \theta}=\dfrac{\pm \sqrt{1-cos^2 \theta}}{\cos \theta}$. Now, we can cut $\cos \theta$ from both sides when $\cos \theta\ne0$. But at last we gets $\cos \theta = 0$.. so, it is a contradiction.
In the WA, by watching graph, we can imagine if it intersects then it will only once, whence in solution, it tells the graph interects many times. This is not semms right.


Pygame Buttons, First button working, second button not working

Question: I have recently been working on a game using python and pygame and have started on buttons for various things. An issue that I have been running into is when I create a button class and create two objects of that class for each button, both of them will turn darker when hovered over by the mouse as expected, but only the first one to process will detect when the player clicks it. I started a new python file with the same button class and mostly the same code and it still has the same issue. I have tried processing the buttons separately and changing various other things but the only way I can get the second button to work is by processing it first, but then the first button won't work. Here is that simplified code.
import pygame

class Button:
    def __init__(self, x, y, width, height, color, hover_color, click_func):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = color
        self.hover_color = hover_color
        self.display_color = self.color
        self.click_func = click_func

    def process(self):
        events = pygame.event.get()
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.display_color = self.hover_color
            for event in events:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.click_func()

        else:
            self.display_color = self.color

def press_func1():
    print('press func 1')

def press_func2():
    print('press func 2')

WIN = pygame.display.set_mode((500, 500))

buttons = [
    Button(200, 100, 100, 50, (255, 0, 0), (150, 0, 0), press_func1),
    Button(200, 300, 100, 50, (0, 255, 0), (0, 150, 0), press_func2)
]

running = True
fps = pygame.time.Clock()
while running:
    fps.tick(60)

    WIN.fill((255, 255, 255))

    [button.process() for button in buttons]
    [pygame.draw.rect(WIN, button.display_color, button.rect) for button in buttons]

    pygame.display.update()

If you know what the problem is, I would love to hear it.
Answer: pygame.event.get() get all the events and remove them from the queue. See the documentation:

This will get all the messages and remove them from the queue. [...]

If pygame.event.get() is called multiple times per frame, the events are only retuned once, but never all calls will return all all events. As a result, some events appear to be missed.
Get the list of events once per frame and pass the list of events to Button.process:
import pygame

class Button:
    def __init__(self, x, y, width, height, color, hover_color, click_func):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = color
        self.hover_color = hover_color
        self.display_color = self.color
        self.click_func = click_func

    def process(self, events):
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.display_color = self.hover_color
            for event in events:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.click_func()

        else:
            self.display_color = self.color

def press_func1():
    print('press func 1')

def press_func2():
    print('press func 2')

WIN = pygame.display.set_mode((500, 500))

buttons = [
    Button(200, 100, 100, 50, (255, 0, 0), (150, 0, 0), press_func1),
    Button(200, 300, 100, 50, (0, 255, 0), (0, 150, 0), press_func2)
]

running = True
fps = pygame.time.Clock()
while running:
    fps.tick(60)

    WIN.fill((255, 255, 255))

    events = pygame.event.get()
    [button.process(events) for button in buttons]
    [pygame.draw.rect(WIN, button.display_color, button.rect) for button in buttons]

    pygame.display.update()


Double Angle identity???

Question: The question asks to fully solve for $$\left(\sin{\pi \over 8}+\cos{\pi \over 8}\right)^2$$
My question is, is this a double angle formula? And if so, how would I go about to solve it?
I interpreted it this way; $$\left(\sin{\pi \over 8}+\cos{\pi \over 8}\right)^2$$
$$=2\sin{\pi \over 4}+\left(1-2\sin{\pi \over 4}\right)$$
Have I done this right so far? I feel I have not.
Answer: Yes, you can use double angle identity to simplify as follows $$\left(\sin\frac{\pi}{8}+\cos\frac{\pi}{8}\right)^2=\sin^2\frac{\pi}{8}+\cos^2\frac{\pi}{8}+2\sin\frac{\pi}{8}\cos\frac{\pi}{8}$$
$$=\left(\sin^2\frac{\pi}{8}+\cos^2\frac{\pi}{8}\right)+2\sin\frac{\pi}{8}\cos\frac{\pi}{8}$$
$$=1+2\sin\frac{\pi}{8}\cos\frac{\pi}{8}$$
using double angle identity, $2\sin A\cos A=\sin 2A$
$$=1+\sin2\left(\frac{\pi}{8}\right)$$
$$=1+\sin\frac{\pi}{4}$$
$$=1+\frac{1}{\sqrt 2}=\color{red}{\frac{2+\sqrt 2}{2}}$$
Comment: @DunjaElez Why is it incorrect? It seems to be correct to me.
Comment: that narrowed it down, thank you!
Comment: although your final answer is incorrect
Answer: It is related to a double-angle identity.  The relevant identities you need are:
$$\sin^2\theta + \cos^2\theta = 1$$
and
$$\sin 2\theta = 2\sin\theta\cos\theta$$
You will also need to expand your binomial, using the basic algebraic identity
$$(A+B)^2 = A^2 + 2AB + B^2$$.
So, start by expanding the binomial; then use the two trig identities to simplify.
Comment: By far the cleanest answer for this particular question.  No need to look at the initial values at all!
Answer: HINT:
Use the identity $\sin x+\cos x=\sqrt{2}\sin(x+\pi/4)$ with $x=\pi/8$
Answer: We have identity here to directly solve. Its $\left(\sin(x)+\cos(x)\right)^2=1+\sin(2x)$ thus here $\theta =\frac{π}{8}$ so $2\theta=\frac{π}{4}$ hence answer is $$1+\sin\left(\frac{π}{4}\right)=1+\frac{1}{\sqrt{2}}=\frac{\sqrt{2}+1}{\sqrt{2}}$$ hope it's clear.
Answer: Notice, $$\left(\sin\frac{\pi}{8}+\cos\frac{\pi}{8}\right)^2$$
$$=2\left(\frac{1}{\sqrt2}\sin\frac{\pi}{8}+\frac{1}{\sqrt2}\cos\frac{\pi}{8}\right)^2$$
$$=2\left(\sin\frac{\pi}{8}\cos\frac{\pi}{4}+\cos\frac{\pi}{8}\sin\frac{\pi}{4}\right)^2$$
Using trig identity $\sin A\cos B+\cos A\sin B=\sin(A+B)$ $$=2\sin^2\left(\frac{\pi}{8}+\frac{\pi}{4}\right)$$
$$=2\sin^2\left(\frac{3\pi}{8}\right)$$
Comment: How is this different from mine??
Answer: In general, you can write expressions of the form $a\sin \theta + b\cos\theta$ in the form $c\sin(\theta + \psi)$ for suitable choices of $c$ and $\psi$. To see this, look at the double-angle formula for sine; you obtain
$$a\sin\theta + b\cos\theta = (c\cos \psi)\sin\theta + (c\sin\psi)\cos\theta$$
Comparing coefficients gives $a=c\cos\psi$ and $b=c\sin\psi$.
Dividing the second equation by the first gives $\tan\psi = \frac{b}{a}$; and squaring both equations and adding them together gives
$$a^2+b^2 = c^2(\cos^2\psi+\sin^2\psi) = c^2$$
So you can work out the values of $c$ and $\psi$ from here.
Here, $a=b=1$, so we get
$$\tan\psi = 1 \quad \text{and} \quad c^2=1^2+1^2=2$$
so $\psi = \frac{\pi}{4}$ and $c = \sqrt{2}$ will work. Hence
$$\boxed{\sin \frac{\pi}{8} + \cos \frac{\pi}{8} = \sqrt{2}\sin\left(\frac{\pi}{8} + \frac{\pi}{4}\right)}$$
You can probably take it from here.
Comment: The last equation is my "HINT." ;-))
Answer: We can solve an equation, but not a number, so I interpret "solve" as "compute". Then: $$(sin{\pi \over 8}+cos{\pi \over 8})^2=\sin^2(\frac{\pi}{8})+\cos^2(\frac{\pi}{8})+2\sin(\frac{\pi}{8})\cos(\frac{\pi}{8})=1+\sin(\frac{\pi}{4})=1+\frac{\sqrt{2}}{2}$$
using the Double Angle indentity $\sin(2\theta)=2\sin(\theta)\cos(\theta)$.
If the intended question was to compute $\sin(\frac{\pi}{8})+\cos(\frac{\pi}{8})$, then $\sin(\frac{\pi}{8})+\cos(\frac{\pi}{8})=\sqrt{1+\frac{\sqrt{2}}{2}}$, since $\frac{\pi}{8}$ is in the first quadrant, which means that $\sin(\frac{\pi}{8})$ and $\cos(\frac{\pi}{8})$ are both positive.

Double Angle identity???


I got a question about trig on the unit circle

Question: The unit circle is defined to be $x^2 + y^2 = 1$. Makes sense. Its an equation of a circle. Now from here if we think about cosine as the $x$ value and sine as the $y$ value then we get a trig identity most of use know. There was something about this that always bothered me. And maybe this sounds crazy, but why can we use trigonometric functions to define a point on the unit circle?
$$\cos x  = \frac{ \text{adj} }{ \text{hyp} } \quad \text{and} \quad \sin x  = \frac{ \text{opp} }{ \text{hyp} }$$
So I can see why $\cos(x)$ would be defined in terms of an $x$ value since the adjacent side is the leg of the triangle that is on the $x$ axis but where is the hypotenuse going at in this argument? Same for sine.
Sorry I over think things but I like to really know what something is saying.
Comment: The triangle's vertices are at (0,0), (x,0), and (x,y). The hypotenuse is from (0,0) to (x,y), which is just the radius of the circle (i.e. 1). ($\theta$ is measured from the $x$-axis to the point.)
Answer: If we see $( \cos \theta, \sin \theta)$ as a point in $\mathbb{R}^{2}$, then we know that the distance from $(0, 0)$ to $( \sin \theta, \cos \theta)$ is (according to the Pythagorean Theorem)
\begin{align*}
\sqrt{(\cos \theta - 0)^{2} + (\sin \theta - 0)^{2}} & = \sqrt{(\cos \theta)^{2} + (\sin \theta)^{2}} \\
& = \sqrt{1} \\
& = 1
\end{align*}
Of course, the definition of a circle with center $(h, k)$ and radius $r$ is the set of points which are a distance $r$ from the center $(h, k)$. We see that every point $(\cos \theta, \sin \theta)$ is a distance $1$ from a center $(0, 0)$. That is to say, $(h, k) = (0, 0)$ and $r = 1$.
Answer: Another way to say this is that the map $\theta \mapsto (\cos \theta, \sin \theta)$ parameterizes the unit circle. (The fact that the image of this map is contained in the unit circle is exactly a consequence of the identity you mention.)
Geometrically, the point corresponding to $\theta$ is the intersection of the unit circle with the ray that makes a (signed) angle $\theta$ with the positive $x$-axis, so that the hypotenuse is the line segment with endpoints this intersection and the origin. (As usual in the setting, we allow adj and opp to take on negative values according the quadrant in which the indicated ray sits.)
Answer: Please see this reference :
in this please read section 4.14.. This is a very good source of basic trigonometry.
http://gujarat-education.gov.in/textbook/Images/11sem1/maths11-eng/chap4.pdf


Rationalizing this chord progression (I7-iii-IV)

Question: Trying to expand my harmonic palette here, and came across this song.

Chorus of Stevie Wonder's "Don't You Worry 'Bout a Thing" (in E♭ minor, but temporary shift to relative major, G♭):
<code>G♭       G♭7     B♭m7    C♭maj7
A♭add2   D♭9sus  G♭maj7  B♭(ALT)
</code>
I'm pretty sure I understand the rest of the song's harmony: stepping into the relative major, then we end up on the IV chord, then II-V-I, and V-i back to the relative minor for the verse. The way we got to the IV chord, though, is a mystery to me. I'm confused about the particular sequence [G♭7, B♭m, C♭], however. I can see the I7 (G♭7) chord moving to the IV chord (C♭), but the iii chord in-between is stumping me.
I'm picking up that the iii-IV move sounds nice, so from that angle I can see why the iii goes to IV, but the I7 going to the iii sounds kind of strange.
I'm currently thinking of the chords as a I7-IV movement with a passing chord in-between, but that seems strange to me, because the harmonic rhythm has this chord land on a strong part of the phrase.
I guess my other possibility would be a deceptive resolution to the iii chord, followed by some sort of delayed resolution to the IV, where I feel the song is pulling towards...
What would you guys do to analyse this progression?
(For starters, have I misheard the chords? Is there a better justification for the chords?)

(And please, let's stay away from "if it sounds good, it is good". You and I both know that; if I were looking for that kind of answer, I wouldn't need this site to tell me about it.)
Comment: Analyzing Stevie Wonder; I admire your ambition. Here's Adam Neely discussing Stevie Wonder's choice of chords in Sir Duke, and whether they are always functional, or used more for their color: https://www.youtube.com/watch?v=NckkwiYrjTw&t=49
Comment: @user45266 Calling it "I7-iii-IV" already oversimplifies it. IMO you shouldn't look at it as unambiguous building blocks where every moment in the harmony only has exactly one simple "correct" role. Like a lot of jazzy things, it's toying around with your perception of "where is the tonic now and where is the harmony leaning now". It's a game of illusions. You have to understand that there are multiple simultaneous plausible interpretations. Chord progressions and chord symbols are a "for dummies" simplification that cannot convey everything. You have to read between the lines.
Comment: @YourUncleBob - thanks for that link, often 'wondered' about Sir Duke's chord sequence. The ensemble part is pure major blues, but the verse...And doesn't Adam Neely know his stuff!
Comment: @YourUncleBob I remember when I saw that video, actually! :) That Fm7 chord works so nicely going to E...
Comment: Has nobody considered the possibility that Stevie Wonder wrote those chords simply because he liked the progression?
Answer: Here's my take by listening to what the clip sounds like. I just assume you transcribed them correctly enough, except for the G♭7, which I think is better explained as F♭/G♭ or D♭m7/G♭.

G♭ : tonic
G♭7 : Instead of "G♭7" it sounds more like F♭/G♭ (or E/Gb or whatever), giving a mixolydian/bluesy feel, implying that it might be going to go to B (or C♭) next, or just toying around with indefinitely held tension like you do in blues. To expand on the idea of the first two chords here, play G♭ - D♭m7 - G♭ - D♭m7 - ... You're supposed to think that the tonic might actually be C♭.
B♭m7 : This has two feelings and interpretations at the same time. (1) If you believed the "C♭ is tonic" suggestion, then this feels like the start of a B♭m7 - E♭7 - A♭m progression. Think Beatles's Yesterday as "C♭ - B♭m7 - E♭7 - A♭m". (2) But if you didn't fully believe the "C♭ is tonic" suggestion, then it means we abandon the "G♭ - D♭m7" mixolydian/bluesy idea and switch to G♭'s relative minor side E♭m. But not really as strongly as possible ... The stronger version would be to use a proper dominant B♭7. (in which case for interpretation 1 it would mean a secondary dominant, going for B♭7 - E♭7 - A♭m)
C♭maj7 : another change of mood. After the B♭m this feels like a clarification that the "C♭ is tonic" interpretation was wrong, and now we're at G♭'s subdominant i.e. IV chord.
A♭add2 : it's just a tweaked II chord. A plain A♭7 would sound like a too obvious secondary dominant going for A♭7 - D♭7 - G♭.
D♭9sus : dominant chord, with some added stuff to make it a bit more ambivalent.
G♭maj7 : tonic. We're home.
B♭(ALT) : it's a tweaked B♭7, a dominant for E♭m, meaning a switch to the dark side.
Answer: The progression III - IV is as logical and useful as any other combination of related chords in a key. And especially as III and I7 have 3 common tones it III can - as you mean be considere as a substitution of the tonic, aswell as the VII can be  functionally used as a dominant7 without a root tone.
Any  degree can be followed by any other and these progressions and combinations existed before the theory of functions.


Does $element['#title'] need to be escaped with check_plain()?

Question: I see (with grep) that the value of $element['#title'] in a render element is sometimes sanitized with check_plain(), and sometimes printed unfiltered.
Which one is correct? Is the value considered safe to print? Or does it depend on the theme hook?
Examples from core:
modules/field/field.form.inc
314:        'data' => '' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "",

(notice the "!" in the placeholder, this means that format_string() will not escape the placeholder value)
modules/field/field.module
1052:  $variables['label'] = $variables['label_hidden'] ? NULL : check_plain($element['#title']);

This question applies in both ways:

When setting $element['#title'] in a render element.
When printing the value of $element['#title'].
When printing a $variables['title'] value that was extracted from a render element property.

Note: Very often the $element['#title'] property comes directly from a t() call.
Answer: It's user input and should be considered unsafe; you should always sanitise it.
For the specific example you've given where it isn't, the title is already sanitised before it's passed to the theme function containing the t() call. This happens in field_multiple_value_form()
$title = check_plain($instance['label']);

...

$element = array(
  ...
  '#title' => $multiple ? '' : $title,
  ...
);

As an aside, if you ever did need to preserve HTML in the title for whatever reason, you could consider using filter_xss() instead.
Comment: Hmm, having re-read I think maybe i am contradicting myself here after all. You're absolutely right, if it was the same `#title` it wouldn't need to be escaped again. Will try to have a deeper look a bit later
Comment: You are contradicting yourself, sort of. In the given example, `$title` is raw user input, but `$element['#title']` is not. So it seems it depends on the render element type.
Comment: Also the distinction is not necessarily about html vs plain text, but about trusted vs non-trusted.
Comment: Sure, I was just referring to the fact that `check_plain` removes HTML and not using it preserves it. If you're asking whether `#title` in _any_ render array, ever, can be trusted then yes the answer is definitely "it depends", because render array properties are arbitrary, and what a `#title` is to a form element isn't necessarily the same thing as it is to a different type of element. I assumed you were asking about the field module specifically because of the examples. It's been a long child-filled day so I might also be missing something about what you're asking ;)
Answer: The correct way is to check with check_plain() to prevent cross site scripting attacks in the first example from modules/field/field.form.inc $element['#title'] passed as arg to t function.
if you look at t function source code it call format_string function it check plain $args[$key] = check_plain($value);.
Comment: Actually no, in the first example the placeholder is "!title" with "!", which means no escaping will happen in format_string().


Test doesn't show up

Question: I have created a test orb.test for my module and placed it within the module directory. Installed the Simple Test module. When I visit the /admin/config/development/testing my test orb.test its not listed. Here is the code for my test
class OrbTestCase extends DrupalWebTestCase {
  protected $privileged_user;

public static function getInfo() {
  return array(
    'name' => 'Orb Test Case',
    'description' => 'Ensure that Online Booking functions properly',
    'group' => 'Examples',
  );
}

public function setUp() {
    parent::setUp('orb');
    $this->privileged_user = $this->drupalCreateUser(array('allow online  reservations'));
    $this->drupalLogin($this->privileged_user);
}

public function testorbroomavailability() {
  $this->drupalGet('orb');
  $this->assertText('Room Status');
}
}

Have I missed something here?
EDIT 5th August 2014:
My tests written and placed in of my modules do not show up in the list of tests (admin/config/development/testing)
Comment: Yes U have. I use the devel module to install and reinstall the module.
Comment: How is your test file named? Where is it exactly placed?
Comment: "Have I missed something here?" Well there is a lot of stuff you do *not* tell us.  Without knowing *exactly* what you've done, it is impossible to tell what you've missed.
Comment: @tunic mymodule.test placed in the module folder.
Comment: I think Free Radical's answer is absolutekly right, some of the points he talks must be failing in your setup.
Comment: Can you edit in your full directory listing for that module (ls -R) and your .info?  And can you double confirm that you are uploading to the proper place and have cleared caches?
Comment: Under what *group* on `/admin/config/development/testing` are you looking for the Orb Test case (for reference, see screendump in my answer below)?
Answer: Your test class look OK.
There is no need to install or enable the Simple test module if you're using Drupal 7.  Instead, you should enable the core Testing module.  (Don't know if installing Simple test will make a difference, but it were not present when I went through the routine described below.)
Provided it exists inside your module's directory, you're using Drupal 7, have enabled the core Testing module, cleared the cache, and made sure to declare your test file with the correct name in your module's .info-file, nothing should stop it from appearing in the list included in the "Examples" group when you visit /admin/config/development/testing.
Here is how it looks on my site (after I've gone through the steps outlined above):
Comment: My module.info file was missing this line "testing_api = 2.x" and hence was not not showing up.
Comment: Nope. Done all that you have mentioned. Doesn't show the test group :-(
Comment: There is no "test" group.  You're placing it in the "Examples" group. Have you looked there?
Comment: my issue seems stranger the fiction! I have removed the examples module from my laptop, cleared caches but it still appears in the list of tests. So it seems like a cache issue. For some reason it doesn't seem to be updating the list. I am using drupal 7.22 At one point I had a doubt if I was copying the module to the correct VHOST directory, which I definitely was. Very strange behaviour.

Test doesn't show up


IDE para desenvolvimento de games

Question: Gostaria de saber quais as engines que possuem IDE própria e se essa IDE possui sistema interno de versionamento, também gostaria de saber para quais plataformas elas compilam...
Comment: Cara, uma IDE excelente para desenvolvimento de Jogos, é a Unity 3D, segue o link para você conhecer melhor: https://unity3d.com, ela compila para diversas platagormas e você desenvolve códigos em Javascript e, ou C#, é simples de utilizar e o proprio site do unity tem diversos tutoriais para iniciantes.
Answer: Uma gratuita e boa é o Unity 3D, ele compila para praticamente todas platoformas e sim, possui versionamento.
É possivel programar os código em C# ou javascript
além disso o help deles é muito bom, com ele você já consegue entender bastante das funcionalidades.
Na internet existe bastante material também.
Agora se você quer algo menos robusto e mais fácil tem outras ferramentas como Construct 2, Stencyl que
nem exige programação, é possível fazer muitas coisas com drag and drop

IDE para desenvolvimento de games


NoActionBar configuration still showing the action bar on Android

Question: I implemented the following code in my styles.xml file and passed it to my AndroidManifest but I can still see the action bar on an Android 13 Pixel 5 device. I have checked to see if I also have a styles-night.xml file, which I do not. As it is not my primary choice to call the getActionBar().hide() method in my Java code, is there a way to fix this?

<code><resources>
    <style name="Theme.Application" parent="Theme.Material3.DayNight.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
</resources>
</code>
Answer: I can't see your screen action bar. It looks like what you expect When you remove android default action bar  you change end of .Light.DarkActionBar to Light.NoActionBar in theme and theme(night) xml file
Now i see your status bar in this screen
Comment: Thank you, but doesn't the color change at the top imply that the ActionBar is still there? In any case, is there a way to hide the light purple color in the styles.xml?
Comment: You said about statusBarColor color you might change it any time. When you want to change top type of screen let change statusBarColor item color in res>values>themes>themes.xml and themes.xml(night) files
Comment: Thank you for the help! Changing android:statusBarColor in the themes.xml worked for me. I thought that the issue was about the action bar, turns out I just forgot to change the color.
Comment: I am very happy to help for this problem. You said about statusBarColor in your head question. You may confused to understand statusBarColor and ActionBar. I think you learn full information these components on internet


How to translate percentage decline into a regression slope?

Question: I want to model a negative relationship of count/binary data over 10 years with a known value for the decline rate (in percentage). However, I have problems in calculating the correct slope value for the trend.
Let´s say, I know that the starting value for the response is 50 (intercept value) and that the slope should be a decline of 5% per year.
The slope of the regression line shows the amount of change in the response per 1 unit X. So, in the Gaussian case, I would calculate the 5% of 50 (which is 2.5) and set the slope = 2.5. But this is not true for the poisson or binomial case as we are dealing with log-differences (poisson case).
My question thus is: "How do I translate my percentage decline rate into a slope value for a poisson or binomial model?"
So far I tried this...
    #### POISSON EXAMPLE

## load libraries and source sim.glmm.r from github
library(lme4)
library(visreg)
source("https://raw.githubusercontent.com/pcdjohnson/sim.glmm/master/sim.glmm.R")

## create a data frame with known sampling design
mydata<-expand.grid(SAMPLE=1:20,SUBSAMPLE=1:10, year=1:10)
mydata$SAMPLE<-factor(mydata$SAMPLE)
mydata$SUBSAMPLE<-factor(mydata$SUBSAMPLE)

## create my slope value
myIntercept <- 50
AnnualPercentageDecline <- 0.05 #(=5%)
mySLOPE <- myIntercept * AnnualPercentageDecline

## simulate data with sim.glmm - here, "year" requires the declining slope
sim.data <- sim.glmm(design.data = mydata,
              fixed.eff = list(intercept = log(50), year = -(mySLOPE)),
              rand.V = c(SAMPLE = 5, SUBSAMPLE = 1),
              distribution = 'poisson')

## perform the glmer model
mydata.temp<-(glmer(response~ year +(1+year|SAMPLE)+
(1+year|SUBSAMPLE),family="poisson",data=sim.data))

## visualize output
par(mfrow=c(1,3))
visreg(mydata.temp, scale="linear")
par(mfrow=c(1,1))

## END

Comment: 5% per year is not 50% over 10 years unless change is linear. For anything ecological or environmental, exponential decline is much more likely. I think you're conflating distribution family with link function here. Binomial distribution does not imply log link! It's also unclear how far your question is about (1) statistical ideas or (2) how to do this in your adopted software. (2) is off-topic here. I suggest rewriting your question to focus on what you are asking statistically.
Answer: Linear decline of 2.5 units/year in your Gaussian example is not the same as a decline of 5% per year (as Nick Cox points out). If the response is reduced by 5% each year, then it's being multiplied by 0.95 each year. E.g.:
Linear decline: year1 = 50 - 2.5 * 0 = 50; year10 = 50 - 2.5 * 9 = 27.5
Exponential decline: year1 = 50 * 0.95^0 = 50; year10 = 50 * 0.95^9 = 31.5
NB the intercept in this example isn't the same as the response in year 1 unless year 1 has the value 0, not 1 as in your code.
Do you definitely want to model linear decline and not exponential decline? I don't know a simple way of modelling linear decline in counts. To simulate exponential decline in the Poisson example (which is much easier due to the log link) change
fixed.eff = list(intercept = log(50), year = -(mySLOPE))
to
fixed.eff = list(intercept = log(50), year = log(0.95))
and
mydata<-expand.grid(SAMPLE=1:20,SUBSAMPLE=1:10, year=1:10)
to
mydata<-expand.grid(SAMPLE=1:20,SUBSAMPLE=1:10, year=0:9)
Also,
(1+year|SAMPLE)+(1+year|SUBSAMPLE)
fits random slopes and intercepts, whereas only random intercepts have been simulated in the data. This might be what you want, but to fit the intercepts-only model, change to
(1|SAMPLE)+(1|SUBSAMPLE)
The same applies to a binomial model with a logit link provided you want to model a 5% annual decline in the odds.


Returning to a previous work directory (shell terminal)

Question: I know about cd -
and pushd commands.
what i am looking for is something could be described as the following:
1- save what pwd command return to you in some kind of variable (say X)
2- go to whatever other directories you want to visit
3- once done , cd X (go back to the original working directory)
Thanks Community for your help and for the amazing tips i find here :)
Cheers,
Udai
Comment: "I know about forks, but I need something where I can 1) stab it into a piece of food, 2) bring to mouth, and then 3) take it off with my lips so I can eat it." Dude, `pushd`/`popd` do exactly what you're describing. If not, you have to describe what they're not doing that you need.
Comment: the thing that pushd queue get crowded pretty fast for me and i get lost where is my working directory, i guess i am not used to the pushd command pretty well
and btw :looooool .. hilarious comment
Answer: Amadan is correct, however if you're really dead-set on it, you can do
alias back='cd '`pwd`

Then do your browsing, then type back to come back to the directory you ran alias in.
Edit: Slightly more sophisticated idea: add
alias save=`alias back="cd $PWD"`

to your ~/.bashrc. Then, you can type save in a directory, browse, then back will bring you back to the original directory.
Answer: You can do it easily exactly as you say, with variables. Bonus, you can access your files from elsewhere:
GOLDMINE=`pwd`
cd /tmp/casino
play
echo "oops, forgot my wallet"
cat $GOLDMINE/wallet
cd /tmp/bedroom
play harder
echo "gotta go back to work"
cd $GOLDMINE

(well, actually I'd probably use something short like $D, but you get the gist)


General combinatorics formula

Question: HD = Hamming distance; this question is an extension to this.
For an example 4-bit string, I want to be able to express ALL binary bit strings in a set that are a multiple of certain HD (in this example say 2) from each other in the set.
For 4 bit strings, the correct set would be {0000,1100,0110,0011,1001,0101,1010,1111}
My understanding of the combinatorics formula is 4C0+4C2+4C4=8 elements as above.
But when I follow the same formula for 4-bit strings, HD=3, it comes to 4C0+4C3 = 5 elements which are wrong: {0000,0111,1011,1101,1110}. As you can see only 0000 is an HD=3 away from other elements.
I want this set {0000,1110} as they are uniquely an HD=3 away from each other.
Is there any way to generalize this number of combinations in the set through combinatorics/any formula for n bit strings?
EDIT:
All these are correct for HD=3: {0000,0111} or {0000,1011} etc. as long as all the elements are an HD=3n ( n >= 1,2...) away from each other.
For say 6 bits, these would be the correct set for HD=3:  { 000000, 000111, 111000, 111111 } because the number of elements = 6C0+ 2 (I don't know how to express this with combinatorics)  + 6C6
Comment: "all binary bit strings in a set that is a multiple of certain HD from each other in the set" doesn't seem to make sense – is there a typo?
Comment: In the given example, for the **correct set** of HD=2, all the bit strings present are an HD of multiple of 2n away from each other where n>=0,1,2 .... hence "a multiple of certain HD from......". I feel it's right. But can't generalize when HD=3.
Comment: "I want this set {0000,1110} as they are uniquely an HD=3 away from each other."  Why is it this one and not {0000,0111}, for example?
Comment: All these are correct for HD=3: {0000,0111} or {0000,1011} etc. as long as all the elements are an HD=3n ( n >= 0,1,2...) away from each other.

For say 6 bits, these would be the correct set for HD=3:  { 000000, **000111**, **111000**, 111111 } because the number of elements = 6C0+ **(I don't know how to express this with combinatorics) 2**  + 6C6
Comment: @zzzzzazaza: Indeed, "the bit strings are" a multiple of a distance of each other, but that sentence says "bit strings in a set that is a multiple of certain HD from each other" – it seems that perhaps you mean "are" where it says "is"?
Comment: @joriki Yes Sorry I thought you were focussing on the "multiple". I corrected it. Thanks.
Comment: There is a linkage between XOR and even/odd because the XOR of two numbers with an even number of bits has an even number of bits, as does the XOR of two numbers with an odd numbers of bits.  When you look for a HD of $3$ you lose this linkage because you can XOR two numbers at a distance of $3$ from a given number and get one at a distance of $1$.  If you start with $000000$ and note that $000111$ and $011100$ are both at distance $3$, their XOR is $000100$.
Comment: @RossMillikan "If you start with 000000 and note that 000111 and 011100 are both at distance 3, their XOR is 000100"--------but I am trying to find a set so that all the HDs between them are a certain distance apart; why am I comparing HD with just 000000?
Comment: @joriki Do you think it is possible to generalize it?
Comment: I used 000000 as a convenient starting point.  You can use any bit string you want and XOR it with all the elements in the set.  000000 is handy to help see what is going on in terms of how many 1 bits each word has.
Comment: @RossMillikan I need those XOR values between all the elements in the set to be **exactly** HD=3n  (n>=1,2....) so 011100 won't be in the set. The correct set would be { 000000, 000111, 111000, 111111 }. Maybe I am missing the point you are making.
Comment: @zzzzzazaza: I'm not sure why you're pinging me about that – you already asked that in the question, and as you know, I read the question. If I have something to say about it, I will.
Comment: Sorry about that.
Answer: If you have $n$ bits and want distance $3$, you need $n$ to be a multiple of $3$.  You just divide the bits into blocks of $3$ bits and turn on or off each block.  You will get $2^{n/3}$ words, each with a multiple of $3$ bits turned on, and each a Hamming Distance a multiple of $3$ from each other.  For example, with $n=9$ we might have the words
$000000000\\
111000000,000111000,000000111\\
111111000,111000111,000111111\\
111111111$
Comment: Will this 2^(n/3) formula for the number of codewords hold true for all odd numbers of **HD**s(3,5,7.....)? Or for just HD=3?
Comment: It would be $2^{n/k}$ where $k$ is the HD.  You just have all the binary numbers from $0$ through $2^{n/k}$, then replicate each bit $k$ times.
Comment: Thank you. And for n bit strings' even numbers of **HD**s do you think my formula is correct?

For 4-bit strings, HD=2, 4C0+4C2+4C4
For 5-bit strings, HD=2, 5C0+5C2+5C4
For 6-bit strings, HD=4, 6C0+6C4
For 8-bit strings, HD=4, 8C0+8C4+8C8
Comment: No.  For six bit strings, $6C4$ accepts $111100$ and $111001$ which are only at a distance of $2$ from each other.  HD=2 is special because of its relationship with XOR.  For larger numbers you just need to replicate the bits as I said above.
Comment: So basically you are saying that only for HD=2, the summation of [n C (0,2,4....)] will work, and other than that when HD>=3 doesn't matter if it's odd or even I have to replicate the bits?
Comment: That is correct.
Comment: When n is not a multiple of k it seems this formula doesn't work.
Comment: You can just ignore the last bits, so you round $n/k$ down and leave the remainder always $0$

General combinatorics formula