What are good datasets to illustrate particular aspects of statistical analysis?

Question: I realize this is subjective, but I thought it would be nice to talk about our favorite datasets and what we think makes them interesting. There is a wealth of data out there, and what with all of the APIs (e.g., Datamob) along with classic datasets (e.g., R data), I think this could have some very interesting responses.
For example, I have always liked datasets like the "Boston Housing" dataset (unfortunate implications notwithstanding) and "mtcars" for their versatility. From a pedagogical standpoint, one can show the merits of a wide variety of statistical techniques using them; and Anderson/Fisher's iris dataset will always have a place in my heart.
Thoughts?
Comment: I am aware it is designed as a Q&A, but with questions like "What is your favorite statistics cartoon?" being voted up highly, I figured this wouldn't be terribly inappropriate. Especially pedagogically, if someone is trying to learn about data analysis and exploratory techniques, it might be useful to get some feedback on public datasets which offer a rich structure and have a large amount of history and research behind them.
Comment: I'm inclined to let the community decide on whether this has to be closed (as not constructive) or not, although I would add that thorough and argumentative replies might well serve as a support for future questions on particular aspects of data analysis. I'm converting this to CW in the meantime because, obviously, there's no single best answer.
Comment: This question and their answers are very useful to me. Please do not remove.
Comment: (+1) chl's edit is dead on. This question can serve as an idea shop for presentations. Going even further, the best dataset in my opinion would be one, which could be used as a common theme for assignments in the course of a lecture.
Comment: I have added a comment to the [statistics jokes thread](http://stats.stackexchange.com/questions/1337/statistics-jokes) explaining why it exists and why it does *not* serve to justify threads like this one here.  I find the present question far too ill-formed and vague to serve a useful role or garner consistently strong replies; I wish it would be modified or removed.  However, I agree with the previous comment by @chl and therefore have not voted to close, because my vote as moderator would (unfortunately) be unilaterally binding and therefore not reflect community sentiment.
Comment: FWIW, I think this question is *much* more justified than the jokes thread. If one of them should go, it should be the jokes. (I think the cartoons & quotes are potentially more useful as pedagogical aids, and would thus rank w/ this thread.)
Answer: The low birth weight study
This is one of the datasets in Hosmer and Lemeshow's textbook on Applied Logistic Regression (2000, Wiley, 2nd ed.). The goal of this prospective study was to identify risk factors associated with giving birth to a low birth weight baby (weighing less than 2,500 grams). Data were collected on 189 women, 59 of which had low birth weight babies and 130 of which had normal birth weight babies. Four variables which were thought to be of importance were age, weight of the subject at her last menstrual period, race, and the number of physician visits during the first trimester of pregnancy.
It is available in R as data(birthwt, package="MASS") or in Stata with webuse lbw. A text version appears here: lowbwt.dat (description). Of note, there are several versions of this dataset because it was extended to a case-control study (1-1 or 1-3, matched on age), as illustrated by Hosmer and Lemeshow in ALR chapter 7.
I used to teach introductory courses based on this dataset for the following reasons:

It is interesting from an historical and epidemiological perspective (data were collected in 1986); no prior background in medicine or statistics is required to understand the main ideas and what questions can be asked from that study.
Several variables of mixed types (continuous, ordinal, and nominal) are available which makes it easy to present basic association tests (t-test, ANOVA, $\chi^2$-test for two-way tables, odds-ratio, Cochrane and Armitage trend test, etc.). Morever, birth weight is available as a continuous measure as well as a binary indicator (above or below 2.5 kg): We can start building simple linear models, followed by multiple regression (with predictors of interest selected from prior exploratory analysis), and then switch to GLM (logistic regression), possibly discussing the choice of a cutoff.
It allows to discuss different modeling perspectives (explanatory or predictive approaches), and the implication of the sampling scheme when developing models (stratification/matched cases).

Other points that can be emphasized, depending on the audience and level of expertise with statistical software, or statistics in general.

As for the dataset available in R, categorical predictors are scored as integers (e.g., for mother's ethnicity we have '1' = white, '2' = black, '3' = other), notwithstanding the fact that natural ordering for some predictors (e.g., number of previous premature labors or number of physician visits) or the use of explicit labels (it is always a good idea to use 'yes'/'no' instead of 1/0 for binary variables, even if that doesn't change anything in the design matrix!) are simply absent. As such, it is easy to discuss what issues may be raised by ignoring levels or units of measurement in data analysis.
Variables of mixed types are interesting when it comes to do some exploratory analysis and discuss what kind of graphical displays are appropriate for summarizing univariate, bivariate or trivariate relationships. Likewise, producing nice summary tables, and more generally reporting, is another interesting aspect of this dataset (but the Hmisc::summary.formula command makes it so easy under R).
Hosmer and Lemeshow reported that actual data were modified to protect subject confidentiality (p. 25). It might be interesting to discuss data confidentiality issues, as was done in one of our earlier Journal Club, but see its transcript. (I must admit I never go into much details with that.)
It is easy to introduce some missing values or erroneous values (which are common issues in real life of a statistician), which lead to discuss (a) their detection through codebook (Hmisc::describe or Stata's codebook) or exploratory graphics (always plot your data first!), and (b) possible remedial (data imputation, listwise deletion or pairwise measure of association, etc.).
Comment: +1 Thank you for providing an exemplary answer that shows this thread *can* be useful and provides a standard of exposition that other replies can (and should) aim for.
Comment: This is fantastic and exactly what I was looking for with asking the question. I thank you for you valued insight.
Answer: Of course, the Anscombe 4 datasets are very good for teaching - they look very different, yet have identical simple statistical properties.
I also suggest KDD Cup datasets http://www.kdd.org/kddcup/  because they have been well studied and there are many solutions, so students can compare their results and see how they rank.
In my data mining course I provided a Microarray dataset competition which can be used by professors  http://www.kdnuggets.com/data_mining_course/
Comment: For other data sets that have been designed for a pedagogical purpose in a similar way to the Anscombe Quartet, see [this question](http://stats.stackexchange.com/questions/80196/datasets-constructed-for-a-purpose-similar-to-that-of-anscombes-quartet).
Answer: A lot of my Statistical Analysis courses at Cal Poly have used the "Iris" dataset which in already in R. It has categorical variables, and highly correlated variables.
Comment: Would you mind expanding your last points: How do this dataset help teaching statistics? (AFAICT, the iris dataset only has one categorical variable, namely iris class.)
Comment: Here is a thread concerned entirely with the [use of the Iris dataset in teaching](http://stats.stackexchange.com/questions/74776/what-aspects-of-the-iris-data-set-make-it-so-successful-as-an-example-teaching).
Answer: The Titanic dataset used by Harrell in "Regression Modeling Strategies". I use a simplified version of his analysis when explaining logistic regression, explaining survival using sex, class and age.
The Loyn dataset discussed in "Experimental Design and Data Analysis for Biologists" by Gerry Quinn and Mick Keough contains nice problems requiring transformation for multiple linear regression.


Different ways to prove similarity of the given triangles

Question:
Let $\Delta ABC$ be acute and point $D$ be foot of the altitude from the vertex $C$. Let $E\in\overline{AC}$ s.t. $DE\perp AC$. Let $F,G,H$ belong to $\overline{DC},\overline{DA}$ and $\overline{ED}$ respectively. s.t.:
  $$|DF|=\frac{1}{3}|DC|,|DG|=\frac{1}{3}|DA|,|EH|=\frac{1}{3}|ED|.$$

Prove $\Delta FGH\sim\Delta ACD$ (not necessarily in that vertex order).
My approach:
Applying the intercept theorem, we obtain the following:
Let $\overrightarrow{DJ}=\frac{2}{3}\overrightarrow{DC}$. Then:
$$AC\parallel HJ\parallel GF$$
Let $I\equiv GH\cap DE$.
$I$ is the midpoint of $\overline{HD}$.
Since $\overline{GF}\perp\overline{HD}$ , $\Delta DFH\;\&\;\Delta HGD$ and $\Delta HGI\;\&\;\Delta IGD$ are isosceles. $(\;|HF|=|DF|\;\&\;|HG|=|DG|\;)$ $\implies\Delta HGF\overset{\sim}{=}\Delta GDF$.
$$\Delta GDF\sim\Delta ACD\implies\Delta HGF\sim\Delta ACD\;\;\blacksquare$$
Picture:

Question:
Apart from methods involving vectors, are there any other non-routine that might include compositions of linear transformations or something totally different worth more focus? Thank you in advance!
Answer: As you have demonstrated, we have $|HG|=|DG|$. By Talete's theorem we have: $$\overline{DG}=\overline{GT}=\overline{TA}=\frac{1}{3}\overline{AD}$$ where $T$ is the point of intersection of the line passing throught $J$ and $H$ with $AB$. Also, we have that: $$\overline{CJ}=\overline{JF}=\overline{FD}=\frac{1}{3}\overline{CD}$$
This two results aree very important, also, as you noted before: $$\overline{HG}=\overline{GD}$$ and $$\overline{HF}=\overline{FD}$$
The sides $\overline{FH}, \overline{HG}, \overline{ED}, \overline{EC}$ are in proportion: $$\frac{\overline{FH}}{\overline{CD}}=\frac{\overline{HG}}{\overline{AD}}=\frac{1}{3}$$
Now, we have to focus on the triangles $FGD, JTD, CAD$. This triangles are similar, in fact all have in common the angle $CDA$ and, because what you have said in your post and what I have written here. So, we have:
$$\frac{\overline{FG}}{\overline{AC}}=\frac{1}{3}$$
But now we have two  triangles that have all sides in proportion, in fact:
$$\frac{\overline{HG}}{\overline{AD}}=\frac{\overline{HF}}{\overline{CD}}=\frac{\overline{FG}}{\overline{AC}}=\frac{1}{3}$$
So, the triangles $ACD$ and $FGH$ are similar.


Determine the greatest common divisor of polynomials $x^2+1$ and $x^3+1$ in $\Bbb Q[X]$.

Question: Exercise: Determine a gcd of the polynomials $x^2+1$ and $x^3+1$ in $\Bbb Q[X]$.. Write the gcd as a combination of the given polynomials.
Is it correct that I keep using long division until the result is $0$, and then the previous result would be a gcd?
<code>x^2+1 / x^3 + 1 \ x
        x^3 + x
        ________-
        1 - x

1 - x / x^2 + 1 \ -x-1
        x^2 - x
        ________-
        x + 1
        x - 1
        ________-
        2

2 / 1 - x \ -1/2x + 1/2
      - x
    ______-
    1
    1
    ______-
    0
</code>
Conclusion: A gcd is $2$?
I'm not sure what's meant with "Write the gcd as a combination of the given polynomials.", so it would be great if someone could point me in the right direction.
Answer: The Euclidean algorithm steps are
\begin{align*}
x^3+1&=x (x^2+1) + (-x+1)\\
x^2+1&=-x (-x+1)+ (x+1)\\
-x+1&=-(x+1)+2
\end{align*}
So the GCD is $1$.
We can go back up
\begin{align*}
2 &= (-x+1) +(x+1)\\
&= (-x+1) + (x^2+1)+x (-x+1)\\
&= (-x+1) (x+1)+(x^2+1)\\
&= (x^3+1 - x(x^2+1))(x+1)+(x^2+1)\\
&= (x+1) (x^3+1) + (-x^2-x+1) (x^2+1)
\end{align*}
and so $1 = \frac{1}{2} [(x+1) (x^3+1) + (-x^2-x+1) (x^2+1)]$
Comment: Maybe I'm wrong but shouldn't gcd=1?? (It has to be a monic polynomial)
Comment: Since the polynomials are members of $\Bbb Q[x]$, wouldn't $$1=\frac{1}{2}(x+1) (x^3+1) + \frac{1}{2}(-x^2-x+1) (x^2+1)$$ work aswell? I fail to see how the gcd is even defined here.
Comment: Thank you very much. Is it correct that 1 and 2 are both possible answers?
Comment: @SJ19: As a matter of convention, the greatest common divisor of polynomials is usually taken to mean the monic polynomial with the highest possible degree. So $1$ in this case.
Comment: @TonyK Alright. And how are you concluding GCD=1 from "-x+1 = -(x+1)+2"?
Comment: Well this is the euclidean algorithm : https://en.wikipedia.org/wiki/Euclidean_algorithm
Answer: $$  \left(   x^{3}  + 1 \right)  $$
$$  \left(   x^{2}  + 1 \right)  $$
$$  \left(   x^{3}  + 1 \right)  =  \left(   x^{2}  + 1 \right)  \cdot \color{magenta}{  \left(   x  \right) } +  \left(   -  x  + 1 \right)  $$
 $$  \left(   x^{2}  + 1 \right)  =  \left(   -  x  + 1 \right)  \cdot \color{magenta}{  \left(   -  x  - 1 \right) } +  \left( 2  \right)  $$
 $$  \left(   -  x  + 1 \right)  =  \left( 2  \right)  \cdot \color{magenta}{  \left(   \frac{  -  x  + 1 }{ 2 }  \right) } +  \left( 0 \right)  $$
 $$ \frac{ 0}{1} $$
 $$ \frac{ 1}{0} $$
 $$ \color{magenta}{  \left(   x  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   x  \right) }{ \left( 1  \right) } $$
 $$ \color{magenta}{  \left(   -  x  - 1 \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   -  x^{2}  -  x  + 1 \right) }{ \left(   -  x  - 1 \right) } $$
 $$ \color{magenta}{  \left(   \frac{  -  x  + 1 }{ 2 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{  x^{3}  + 1 }{ 2 }  \right) }{ \left(   \frac{  x^{2}  + 1 }{ 2 }  \right) } $$
 $$  \left(   x^{3}  + 1 \right)  \left(   \frac{  -  x  - 1 }{ 2 }  \right)  -  \left(   x^{2}  + 1 \right)  \left(   \frac{  -  x^{2}  -  x  + 1 }{ 2 }  \right)  =  \left( -1  \right)  $$
..................................
Comment: So you are saying that the gcd is -1?
Answer: Notice that $x^2+1$ is irreducible over $\mathbb{Q}$. Let $d = \gcd(x^2+1, x^3+1)$. Then $d \mid  x^2+1$ so $d$ is a nonzero constant, or $d$ is an associate of $x^2+1$.
However, $x^2+1 \not\mid x^3+1$ so $d$ must be constant. We can choose $d = 1$ since $\gcd$ is usually supposed to be monic.
Finally, notice that
$$1=\left[\frac{1}{2}(x+1) \right](x^3+1) + \left[\frac{1}{2}(-x^2-x+1)\right] (x^2+1)$$


Is positive coefficient of price correct in a multiple regression model

Question: I am currently undertaking forecasting of energy sales (kWh) for our industrial customers. From historical data gathered from 1993 to 2013, a graph of price per kwh against sales kwh shows a positive relationship. Going ahead to generate the model yielded a positive coefficient of price with energy sales. The other independent variables are GDP of the industrial sector and the lag of sales for 1, 4 and 6. What can explain the positive coefficient of price with sales? Plotting GDP of the industrial sector yields a positive relationship with sales (kWh). Can someone help? I need to understand why we have a positive slope of price with sales. The historical data clearly confirms that.
Comment: Increasing sales imply increasing demand, and increasing demand leads to increasing price
Comment: See #7 in [Kennedy's classic sign paper](http://www.stat.columbia.edu/~gelman/stuff_for_blog/oh_no_I_got_the_wrong_sign.pdf).
Comment: This looks like time series data, so you will need to think about detrending the data. If both sales and price were increasing over time, then ignoring time can produce arbitrarily wrong results.
Answer: Picking up on Dimitriy V. Masterov's comment, a demand curve sloping upwards usually means that you have simultaneous equations bias.  Here is the equation you are trying to estimate:
\begin{align}
D: Q_t &= \beta_1 + \beta_2P_t + \epsilon_t
\end{align}
As long as $Cov(P,\epsilon)=0$, you can estimate this equation using ordinary least squares regression with no problem.  In this case, you expect to get an estimate of $\beta_2$ which is negative.  However, if $Cov(P,\epsilon)>0$, then you can expect the OLS estimate of $\beta_2$ to be too high.  If that positive correlation is strong enough, then you can get a positive estimate for $\beta_2$ even when the true value of $\beta_2$ is negative.
How can $Cov(P,\epsilon)>0$ arise in practice?  There are lots of ways.  Suppose that your company prices electricity higher in time periods of high demand.  In the equation, time periods of high demand are time periods when $\epsilon$ is higher than average.  So, in this case, $P$ will be above its average when $\epsilon$ is above its average---more or less the definition of $Cov(P,\epsilon)>0$.  Another possibility is that your company prices electricity using some formula like "cost of fuel plus 5%."  Then, if the cost of fuel is high when the economy is booming and also the demand for electricity is high when the economy is booming, then you will get $Cov(P,\epsilon)>0$ through that mechanism.  So, the first thing it will be useful for you to do is to find out how your company prices electricity, find out what non-price factors affect demand for electricity from your industrial customers, and then think about how those things are correlated.
Sometimes, you can more or less fix the problem just by including control variables.  Suppose you find out that the story I told above about the overall economy booming or busting is the key driver.  Then, you may be able to fix the problem just by including GDP on the right-hand-side of the equation.
Even better, though, is to find something called an instrumental variable.  An instrumental variable would be a variable 1) which is correlated with $P$, 2) which does not belong in the equation, and 3) which is also not correlated with $\epsilon$.  In this case, you want some variable which helps to determine electricity price but which is not correlated with unobserved demand.  Usually, in electricity generation, you are going to use the price of your key fuel as an instrument.  Or, if you use several fuels, an appropriately weighted average.  The trick is that you have to include the right variables on the right-hand-side to ensure that the correlation between $\epsilon$ and the instrument is zero.  So, to defeat my story about boom times also being times when fuel stocks are expensive (this would make fuel price a bad instrument) you would need to include GDP as a right hand side variable.
What do you do with the instrumental variable?  Well, you plug it into an estimation technique called two-stage least squares.
Shorter answer:  you have endogeneity/simultaneous equations bias; use instrumental variables.


Devo controlar status de um sistema com uma única tabela ou várias?

Question: Minha pergunta é um tanto quanto conceitual e permite diversas interpretações.
Sou responsável por um sistema que usa status em diversos módulos. Status da carga, status do pedido, status do pagamento, etc. Para grupo de status há uma tabela diferente, por exemplo: StatusCarga, StatusPedido, StatusPagamento.
Entretanto, fazendo manutenção em um sistema feito por outra empresa, vi que eles têm uma única tabela de status, e todas as opções de status possíveis estão dentro desta tabela. Logo, minhas tabelas de carga, pedidos e pagamento olhariam todas para a mesma tabela Status.
Dentre estas duas formas, há uma melhor e uma pior? Há outro meio de fazer isso que eu não tenha citado aqui?
Comment: Depende muito... se todos os seus status forem apenas nomes, essa solução pode ser uma boa alternativa. Se voce possui ou possuirá no futuro campos diferentes para cada status é sugerido utilizar tabelas separadas. Mas ainda há uma terceira alternativa, criar uma tabela de status apenas com a descricao e as demais tabelas (especializadas) apontando para esta primeira com estes campos dedicados.
Comment: Bem-vindo, Anderson. Editei sua pergunta para ficar um pouco menos aberta, pois perguntas que solicitam respostas baseadas em opiniões tendem a não funcionar aqui. Elas geram muitas respostas, e nenhuma mais certa ou errada que outras. Aqui deve ser possível identificar uma resposta como sendo a correta.
Answer: Devido ao domínio dos dados de cada uma das entidades citadas na pergunta, a abordagem de uma tabela de status para cada entidade é bem mais organizada e atende melhor aos requisitos de manutenção e extensibilidade normalmente presentes em projetos de grande porte.
Caso exista apenas uma tabela para controlar status de diversas entidades, tudo pode ficar bem confuso.
Suponhamos os seguintes status para cada entidade:

Carga: separando (0), carregando (1), transportando(2) e entregue(3);
Pedido: em-andamento (0) e realizado (1);
Pagamento: pendente (0), realizado (1) e não-autorizado (2).

Os números entre parênteses são os códigos de cada status.

Note que para cada entidade existe um conjunto único de status e levando em consideração que cada uma delas existe independentemente uma da outra, um Pagamento não pode possuir o status carregando, por exemplo.
Então, uma modelagem possível seria:
Carga
  - id

StatusCarga
  - carga_id
  - codigo
  - data
  - primary_key(carga_id, codigo)

Pedido
  - id

StatusPedido
  - pedido_id
  - codigo
  - data
  - primary_key(pedido_id, codigo)

Pagamento
  - id

StatusPagamento
  - pagamento_id
  - codigo
  - data
  - primary_key(pagamento_id, codigo)

Note que além da chave estrangeira para a tabela da entidade, existe o código do status e a data. Desse modo existe um histórico preciso de quando cada um deles ocorreu. Veja também que a chave primária dessas tabelas de status é composta da chave estrangeira mais o código, desse modo uma entidade nunca o repetirá, caso esse seja um requisito.
Veja no sqlfiddle o modelo físico dessa solução.
Agora uma seleção de dados para Carga poderia ser assim:
#Selecionar todas as cargas
SELECT id, cidade, data,
   CASE WHEN StatusCarga.codigo = 0 THEN 'Separando'
        WHEN StatusCarga.codigo = 1 THEN 'Carregando'
        WHEN StatusCarga.codigo = 2 THEN 'Transportando'
        WHEN StatusCarga.codigo = 3 THEN 'Entregue'
        ELSE '<desconhecido>'
   END AS status
FROM Carga, StatusCarga
WHERE StatusCarga.carga_id = Carga.id;

Comment: Olá Fábio, muito obrigado pela resposta, muito esclarecedora. Gostei principalmente pelo campo de data que mostra quando ocorreu cada status.

Só fiquei com uma dúvida.
Digamos que eu queira retornar o status em forma escrita, numa view por exemplo.
Eu teria que fazer um CASE para cada Status?
Comment: Caro Andy. Sim, utilizar o `CASE` é uma opção. Atualizei a resposta e o sqlfiddle.


Dragdealer initialisation

Question: EDIT - I managed to work it out thanks to a friendly commenter below. It turned out to be pretty basic as I wasn't calling my function in the right place. I moved the function call to the click event that opened the group of divs where I'm using DragDealer and it now works.
I am trying to set up the Dragdealer plugin for a slider on a site i'm building
My slider button isn't moveable until I resize my browser window slightly. The slider itself is in a hidden div on page load, so i've connected the call to DragDealer to when it's parent div opens, but it's still not initialising.

Investment option

Allocation

Global Property

Drag

    <input type="text" id="input_global_property" class="investmentPercent" name="input_global_property" value="0%">

"asseTtable" is hidden until expanded by an onclick handler via jquery
function setUpSliders() {
var val_global_property = document.getElementById('input_global_property');

var sliderGlobalProperty = new Dragdealer('slider_global_property',
    {
        steps: 100,
        animationCallback: function(x, y)
    {
        val_global_property.value = (Math.round(x * 100) + '%');
    }
});

$('#input_global_property').change(function(){
    sliderGlobalProperty.setStep(stripPercentages());
        return false;
    });

}
$('#investmentOption_selfSelect').click(function(){
    setUpSliders();
});

Comment: Had to read that twice, was sure it said you were trying to set up a **drugdealer** plugin at first? Would be much cooler really!
Comment: You should show the code you have. PS. this is not a list.
Comment: @Juhana - thanks, list comment removed. I'll paste in some code now, do you have experience with this plugin in order to help debug or is that just a general SO housekeeping comment?
Comment: HTML is good, but I meant the JavaScript.
Comment: Where are you calling `setUpSliders()`?
Comment: Hi, I think I figured it out. I was opening it's parent div already somewhere else, so I added the call to setUpSliders() there and it appears to be working now. Thanks for talking me through it! I may edit the answer above and mark it as correct.
Answer: I was having the same problem with DragDealer and found this answer here via Google.
I was transitioning from one HTML page view to another using JQuery as shown, and I was calling my setUpSliders() before the fadeOut/fadeIn finished. After reading this answer, I changed my code to call setUpSliders() after the fadeIn completed. This fixed the problem. This example may help someone else.
//switch from Home page to Charts page DOM
var switchToChartsPage = function () {
    $("#HomePage").fadeOut(fadeOutTime, function () {
        $("#chartsPage").fadeIn(fadeInTime, function () { setUpSliders(); });
        //Note: delay setting up DragDealer sliders until after DOM settles
    });
    startChartPage();
}

var startChartPage = function () {
    showPanels = true; //initialization switch
      <some code removed>
    carouselPaneCount = buildCharts(); //build the charts and tables html
    //setUpSliders(); // do NOT set up the sliders here - see comment above
    $(".chartspagetitle").text(pageTitleTextLine[currentLocalStorageKey]);
}

Answer: I managed to work it out thanks to a friendly commenter @Juhana. It turned out to be pretty basic as I wasn't calling my function in the right place. I moved the function call to the click event that opened the group of divs where I'm using DragDealer and it now works.
Comment: I had a similar problem where new DragDealer(...) was not being effective, because I had the slider hidden on the page at the time. I changed my code to call the constructor at the point I first make the slider visible. Now it works fine.

Dragdealer initialisation


Is there a term for having a sequence of notes that then change key while modulating?

Question: Here's an example of what I mean.

It is a melody that is transposed down 1 whole tone every 4 measures.
I am wondering if there is a term for this transposing of a melody in music?
Answer: It's called a "melodic sequence" when a segment of melody is repeated at consistent intervals — in this case whole steps.
For more, see How to Identify & Complete Sequences.
Comment: I just put comments on your linked answer, but please note that "melodic sequence" generally refers to a repetition of a melodic motif up or down but with *changing* harmonic patterns on the repetitions.  In OP's case, the harmonies move down exactly the same along with the melody. By default "sequence" generally assumes the same harmony on each repetition, so I'd just call this a sequence or perhaps a "harmonic sequence."
Answer: What's written there is known as a motif - a short melody, which then repeats, albeit in different keys - but still the same pattern. As such, it could be labelled a sequential motif, the key differences may give it a different name, but the pattern is the important factor.


How do I know when it's time to change a tube on my amplifier?

Question: I think this would be a wonderfully instructive question to people who are new to tube amplifiers. In short, how do I know that it's time to change a tube, and what's a good strategy for figuring out which one to change (preamp vs power vs rectifier)?
Comment: I usually change them when they stop glowing.
Comment: thanks for all the great advice this helps as I am at the point of wanting to blow my Blues deluxe to bits... this being said after playing a huge gig and my amp just not sounding the way I want....this makes for a night of hard work and little to no fun within.
Comment: I think it's time to change the tubes when the amp looses its lively sound. its dementionality. bad tubes will result in a drab sounding guitar tone in other words a tele will lose its twang.
Answer: An important thing to note is the different types of valves can be changed independently of each other; eg: if you change the preamp valves you need not change the power amp valves etc.
With power amp valves you will notice very quickly when one or more have gone.  The amp will give out noticeable and unpleasant tones/white noises and will be reduced in power; the glow that a healthy valve gives off may be different in colour or gone altogether, there may even be flames in the blown valves, which is pretty hard to miss. When changing power amp valves ensure that the amp has been cut off from the power for some time before you start, valves store a lot of power and can be dangerous if removed straight away.
Preamp valves tend to last many times longer than power valves; so check the power valves first if they look ok then inspect the preamp valves closely; a blown preamp valve might also give off different noises than a power amp valve; such as excess feedback and other squeaks/screeches.   Also if a preamp valves goes you may not notice a reduction in power; which is another way to identify the type of valve which has gone.
A good rule of thumb is; if you get a drastic change in tone or hum from your amp; or it wont power on at all; its time to check the valves.  If the valves look okay check all the cables carrying signals to the amp including the effects loop; if the amp wont power up check the power cable/fuses first. then check the valves.  With no power its not possible to check the glow colour of a valve so look for valves which are opaque or have burn residue on them.
If you are unsure take it to a dealer for a service.
Comment: Pretty sure valves don't store any power, that's the function of the capacitors in the circuit.  That said, it's still a good idea to unplug the amp entirely and let it sit for a few minutes before sticking your hand in there.  Any good-sized caps should have "bleeder" resistors to dissipate their charge, but these will take awhile to bring the voltage down to safe levels.  It'll also give the tubes a chance to cool down so you don't burn yourself when unplugging them.
Comment: "noticeable and unpleasant tones", especially on low notes which cause a "blat" sound instead of kicking you in the gut the way you expect.
Answer: Two additional problems I've seen with some people's tube amps, related to tubes going bad, is their sloppy manner of treating the tubes.
Some people don't hesitate to use their fingers to pull a tube to inspect it. Finger oil, or fried-chicken grease, or dirt or whatever was on their fingers, will transfer to the glass of the tube, and begin to insulate it, reducing heat transfer. That makes the tube run a bit hotter, reducing its life. Instead, I always use a clean cloth, a couple paper towels, or something to keep oil from transferring. I've even used the tail of my T-shirt.
Another problem I saw, was our lead singer used to toss all her cables into the back of her Mesa Boogie Mk II combo. One of those cable's ends hit the tip of a pre-amp tube, on the nipple of the glass where they sealed it, and cracked it a tiny bit causing a pin-hole to open up, and vented the tube's gas. The next time she powered up the tube cooked and the amp was dead. I had to do triage on the amp after the show, and saw the little nick. She was told to put her cables somewhere else. (My personal solution is to put them in my gear trunk in a cloth bag that keeps them from getting tangled and the tips from getting damaged.)
Comment: @bleakcabal, I am an assh*le when it comes to people touching my guitars and amps; I paid good money for them, and I've usually done a lot of work on them making them how I want to feel and/or sound. It only takes a few seconds for someone to screw up the tuning, drop the guitar, break a string, change all your knobs, etc. And then there's the jerks who set beer pitchers on other people's amps... GRRRRrrrrr....
Comment: I can see saying it to wives, but cats? They'll just say "Whatever!", then claw it anyway. At least ours does.
Comment: I have found this: http://www.pa.msu.edu/sciencet/ask_st/022394.html, apparently, the fat causes a "hot spot" on the glass which can lead to it breaking.
Comment: +1 For greasy fingers; I got a pretty blank look from a guy I used to play with when I explained this one to him.
Comment: LOL... I used to play with people who never thought about eating fried chicken or BBQ ribs, or corn on the cob. Their fretboards were disgusting. Repairing/cleaning a fretboard like that starts with a liberal dose of lemon-oil, followed by gently scraping with a single-edged razor blade just to get the stuff against the fret, then finer and finer sandpaper and steel wool. They'd be amazed how pretty the neck was when the gunk was removed.
Comment: @the Tin Man: someone I once played it had the crumiest fretboard. Not only that but he must have add super-acidic sweats cause all his frets were orange and green. The strings were a greenish blue and felt oily to the touch. I was afraid to let him play my guitar for any length of time.
Comment: I threaten death and dismemberment to my wife and cat if I find my current rig damaged in any way--and it's not even anything that great :D.
Comment: Off-topic, but the finger grease and fried chicken oil issue also applies to light bulbs, especially car headlamps which stay on for long periods and can get very hot. Answer : eat pizza ?
Comment: I simply cannot accept that a thin layer of grease would actually insulate a tube, increasing its temperature. Do you have a source for this?
Comment: Vacuum tubes don't get as hot as halogens. But considering how expensive tubes are these days, while it's less likely to cause problems touching the glass with bare fingers, I'm careful to do what I can to extend their life. I've seen tubes covered with finger-prints and grime in other people's amps, enough to be very visible when working on the head. I'm very careful putting anything inside combo cabinets so it can't bounce around and hit a tube, I make sure my preamp tubes have shields/covers, and keep all the tubes as clean as possible.
Answer: Sigh, in the old days you would pull ot the tubes, put them in a suitable protective container (Standard was a woolen sock) and take them down to the local radio shop. They had a machine that would measure both cathode emmission and voltage gain.
These days you probably need to try replacing the tubes. Common failures are

Filament failure (no red glow from tube)
Vacuum failure (pink or purple neon effects inside the tube)
Emmission failure (low power output, flabby sound)
Output transformer problems, which typically manifest themselves as high distortion often coupled with red-hot tube plates (the cylinder closest to the glass).
Comment: I remember those, and used them on my old '65 Deluxe amps' tubes. (And no, I don't have them any more because I stupidly sold those. Too.) It'd be a great service to their customers if the mega-music store chains had tube testers next to their stock of replacement tubes. I'm sure they can find old testers for dirt-cheap. Slap on a coat of paint and a cute wrap and plug them in.
Answer: Further to DRL's excellent answer, valves can go "microphonic" which means they've been damaged in such a way that vibration on the valve can be heard through the amp. Given the valve's job is to power the amp and the amp's speaker is a big vibrating device (ooer), this can cause some quite horrible noises.
A test would be to switch the amp on, don't plug a guitar in, and tap the amp on the casing, near the valves. If you can hear a significant rattle through the speaker, it's a sign that the valves may be on their way out.
I say "may" because of course other things like loose connectors could cause such a noise as well.
I have seen this only once on my amp. Replacing the valve (actually I did both power valves - EL34s) cured it.
Comment: Some amps are inherently microphonic, though.
Comment: @BartekBanachewicz oh  -  Didn't know that, I thought it was always an indication of the valves being on their way out or loose connection meaning a tap causes interference. Fair point then - I guess I mean "more microphonic than usual"
Comment: I remember, as a lad of around 15, changing not the valves, but their bases, due to microphony. They had hardened up. Maybe not the wisest thing for a youngster to do, but it all worked afterwards!
Answer: You will know. It will start to sound truly terrible, or even go silent. When it does you need to isolate which one it is, which can be tricky unless you have two channels, in which case the one that moves the problem from one channel to the other when you swap it between channels is the one.
This rarely happens unless there has been physical damage, or a lightning strike. These things are really amazingly rugged given what they're made of. I have sixty-year-old valves that are still going strong, and there are plenty of guitar amplifiers that still work after a trip to the bottom of the stairs.
Comment: Some old valves can last a lot longer, there are many lengthily discussions on valve amp threads / forums. They have become quite valuable.
Answer: The amplifier is not capable of even remotely acceptable work without one of its tubes. When the tube fails, you see this beyond any doubt. Usually the filament fails, so the failed tube does not glow any longer.
While very old tube may amplify slightly worse than a new tube due lower electron emission of the aged cathode, I have never seen a recommendation to replace them periodically. A properly designed amplifier should have internals means to compensate both individual differences of various tubes and they ageing effects.
Comment: I disagree that an amplifier is incapable of working without a full set of tubes. Pulling out power stage tubes has been (is?) a common technique for power reduction. It's hardly to go unnoticed when it happens suddenly, but over a longer period of time, a tube could degrade significantly without the user noticing. As for compensation of differences, this applies to modern amps only, really. Pretty much every  "vintage" one requires a matched set and only a limited bias setting for all of them.
Comment: By pulling the tube out, you disconnect the input from the output, as there is no more tube in between. The amplifier will not work. Of course, you can pick the output from the pre-final stages instead, but this require changes in the wiring diagram.
Comment: Listen, I'm not inventing this by a long shot. The only change that might be necessary is the impedance change. [There are credible sources](http://www.premierguitar.com/articles/20713-ask-amp-man-removing-output-tubes-to-reduce-power) that talk about this *without* having to do anything you're mentioning. And please keep in mind I'm not taking sides in the "is it a good idea" debate; merely pointing out that the amp can run just fine.
Comment: The article you reference is about specific four tube design where two tubes are connected in parallel.
Answer: As long as they are working you're good. I like the sound of old tubes. More mellow.
I used to work at an AM radio station with tubes in the transmitter. The tubes were working very hard all the time. We would pull the tube out, every year. Remember, these work at max, 24hr/day, all year. Our Transmitter never went down because of tube failure. So figure it out.  That 8736 hard hours.  If you, play full blast; 4hr/ day, that's 1427hr per year. You should be good for at least 6 years.
If you play 1/2 power, then 12 years, MINIMUM!
Comment: Tubes do not wear out in the manner indicated by your calculations -- it's not like they have a fixed amount of output.


sistema é computacionalmente singular: condição recíproca número

Question: Estou tratando de séries temporais no R.
Meus Dados são Homocedásticos, não possuem autocorrelação, não tem raiz unitária no lag=0, tendencia ou sazonalidade.
Ainda sim esbarro no problema deste erro especifico:
<code>    VAR_S <- summary(VAR(Base_Dados,p = 1, type = "both"))
</code>

Error in solve.default(Sigma) :
system is computationally singular: reciprocal condition number =
          5.67068e-37
<code>VAR<- (VAR(Base_Dados, p = 1, type = "both" ) )
</code>

A principio achei que fosse colinearidade, porém a correlação dos dados não supera 0,25.
Comment: Você pode estar trabalhando com algo realmente independente, logo o vetor autorregressivo tende a um vetor nulo.
Comment: Acho que entendi, sera possível ver isso com determinantes da matriz talvez?
Answer: A matriz não pode ser inversível o determinante da matriz é zero ou aproximadamente zero.
Lidei com isso de duas maneiras distinta, mudeis os dados para um modelo parecido que funcionou más n demonstrou o resultado desejado para análise.
quanto ao modelo anterior a forma encontrada de resolução, foi re avaliar a escala das variáveis elas deixaram de estar na mesma escalada unitária mas passaram a ter aproximadamente a mesma quantidade de número inteiros por observação.
Foi um trabalho intuitivo, logo não tenho formulas para demonstrar.


Basic Question on Conditional and Unconditional Independence

Question: I am trying to get my facts straight on the following 3 scenarios:
1) I draw a random sample $y$ from $Bernoulli(p)$. Then let $X_1, X_2, ..., X_n$ be conditionally independent $N(\mu_1,\sigma_1)$ if $y = 0$ or $N(\mu_2,\sigma_2)$ if $y = 1$. Are they conditionally identically distributed, unconditionally identically distributed, or not identically distributed? Theoretically $X_1, X_2, ..., X_n$ are not unconditionally independent. However for all practical purposes this dependence will be irrelevant because I will not observe another sample $y$. Correct?
2) I draw a random sample $y_i$ from $Bernoulli(p)$. Then let $X_i$ distributed as $N(\mu_1,\sigma_1)$ if $y_i = 0$ or as $N(\mu_2,\sigma_2)$ if $y_i = 1$ for $i = 1..n$. $X_1, X_2, ..., X_n$ are unconditionally independent. They are also conditionally independent given any subset of $Y_i$. They are unconditionally identically distributed. However they are conditionally not identically distributed (or maybe they are if we are lucky?). Correct? The difference from first scenario is that $y$ is redrawn.
3) I have two urns. One urn contains $n$ numbers sampled from $N(\mu_1,\sigma_1)$ and the second urn contains $n$ numbers sampled from $N(\mu_2,\sigma_2)$. I would like to build a classifier given a number from any of the urns and determine which urn it came from. Basically I am assigning the urn as a class label to each number in the urns. Is it OK to pour the contents of both urns into a pool and treat them as independent samples to be fed to a machine learning algorithm? Are they going to be samples from unconditionally independent random variables, or conditionally independent random variables? Is this matching any of the above scenarios?
Answer: Consider the simpler example of a two-part experiment in which we first select one of two differently-biased coins (say $P(\mathrm{Heads}) = p_0$ for one coin and $P(\mathrm{Heads}) = p_1$ for the other, where $p_0\neq p_1$) and then toss the selected coin $n$ times. The choice of coin to be tossed is random: the two coins are picked with probabilities $\pi_0$ and $\pi_1 = 1-\pi_0$ respectively. We also assume that the tosses of the coin are independent sub-experiments of the main experiment, that is, the tosses are conditionally independent regardless of which coin has been selected for tossing.
If we define $X_i$ as having value $1$ or $0$ according as the $i$-th toss resulted in Heads or Tails respectively, then all the above can be summarized by saying that the $X_i$'s are conditionally independent Bernoulli random variables with parameter $p_0$ or $p_1$ depending on which coin was selected. But the $X_i$ are not unconditionally independent random variables. It is easy to calculate (via the law of total probability) that for each $i$,
$$ P\{X_i = 1\} = p_0\cdot \pi_0 + p_1\cdot (1-\pi_0),$$
that is, the $X_i$ are identically distributed random variables. But,
$$ P\{X_i = 1, X_j = 1\} = (p_0)^2\cdot \pi_0 + (p_1)^2\cdot (1-\pi_0)
\neq P\{X_i = 1\}\cdot P\{X_j = 1\}$$
and so , but the $X_i$  are not unconditionally independent random variables even though they are conditionally independent random variables under both the possible conditions. All the above is the probabilist's take on what has been described thus far.
Statisticians, on the other hand, are skeptical people who have different axes to grind. You are correct in that if the results of the $n$ tosses are the only observations that you will ever have, then whether you think of the $X_i$'s as conditionally independent or unconditionally independent is totally irrelevant. But then, the statistician who knows which coin produced the given results of the $n$ tosses but is skeptical of what he has been told are the values of $p_0$ and $p_1$ might be more interested in estimating the value of $p_0$ (or $p_1$ as the case might be) from the given results of the $n$ tosses. If the $n$ tosses resulted in $k$ Heads, then the maximum-likelihood estimate of $p_i$ would be $\frac kn$. Alternatively, the statistician could devise a confidence interval for the estimate of $p_i$.  Or, if he does not know which coin produced the given results, then he might be interested in making a decision as to which coin produced the observed results of $k$ Heads in $n$ tosses. The maximum-likelihood decision rule would choose between the two coins according as whichever of the two likelihoods $p_1^k(1-p_1)^{n-k}$ and $p_0^k(1-p_0)^{n-k}$ was larger, whereas the Neyman-Pearson decision rule would find the decision rule that had the largest power among all decision rules that achieved Type I error probability $\alpha$ or less.  In all of these methods, the fact that the experiment is really a two-part experiment which the coin to be tossed has been picked randomly with probability $\pi_i$ of selecting the coin with $P(\mathrm{Heads}) = p_i$ is ignored. All we are doing is making various inferences from the data that $n$ tosses produced $k$ Heads.
To take into account the prior probabilities $\pi_0$ and $\pi_1 = 1-\pi_0$ of the the coin selection, a Bayesian statistician would use a decision rule that minimizes the average error probability, or more generally,  results in the smallest possible average cost. It is well known that the minimum average error probability decision rule is the maximum a posteriori probability (MAP) rule: pick the coin that has the larger conditional probability given the data, and that the MAP rule reduces to comparing the likelihood ratio $\frac{f_1(x)}{f_0(x)}$ to the threshold $\frac{\pi_0}{\pi_1}$ and deciding that it is the coin with $P(\mathrm{Heads})=p_1$ if and only if
$$\frac{f_1(x)}{f_0(x)} = \frac{p_1^k(1-p_1)^{n-k}}{p_0^k(1-p_0)^{n-k}} > \frac{\pi_0}{\pi_1}.$$
In contrast, the maximum-likelihood decision rule compares the likelihood ratio to $1$. Similarly, the Bayesian statistician can make (Bayesian) estimates of $p_i$ or come up with credible intervals in which the parameter being estimated must lie with high probability and these can be different from the more common frequentist estimates found in most texts.
Answer: A) Regarding the first question, when we draw the Bernoulli a single time:
1) The variables are conditionally i.i.d by assumption.
2) They are unconditionally identically distributed.
3) They are unconditionally dependent.
Proof.
For clarity, I will concentrate on just two rv's, $X, Z$ and the Bernoulli. Using $f$ to represent either a density or a pmf/probability, we are told that
$$f(x,z\mid y) = f(x\mid y)\cdot f(z\mid y)$$
By the chain rule, the joint density of the three is
$$f(x,z,y) = f(x,z\mid y) \cdot f(y)$$
Combining
$$f(x,z,y)=f(x\mid y)\cdot f(z\mid y)\cdot f(y)$$
To obtain the unconditional joint density of $X,Z$ we integrate out $y$
$$f(x,z)=\int_{S_y}f(x\mid y)\cdot f(z\mid y)\cdot f(y) dy$$
Since $Y$ is a Bernoulli the above transforms into
$$f(x,z)=\sum_{i=0}^1f(x\mid y_i)\cdot f(z\mid y_i)\cdot \text{Prob}(y=i) dy$$
$$ = f(x\mid y=0)\cdot f(z\mid y=0)\cdot(1-p) + f(x\mid y=1)\cdot f(z\mid y=1)\cdot p$$
Using $N_1,N_2$ for the densities of two normals we get
$$f(x,z) = N_1(x)N_1(z)(1-p)+N_2(x)N_2(z)p$$
To obtain the marginal distribution of, say, $X$, we integrate out $Z$:
$$f(x) = \int _{S_z}\Big[N_1(x)N_1(z)(1-p)+N_2(x)N_2(z)p\Big]dz$$
$$\implies f(x) = (1-p)N_1(x)+pN_2(x)$$
and analogously we will get
$$f(z) = (1-p)N_1(z)+pN_2(z)$$
The last two results prove 2), and they also tell us that
$$f(x,z) \neq f(x)\cdot f(z)$$
so they prove unconditional dependence.
Regarding whether the latter "matters for all practical purposes", it depends on whether one wants to make inference or take a decision prior to draw the Bernouli or not. Obviously, if the wheels will turn only after  the Bernoulli is drawn, and if it is drawn only a single time for ever and ever, then a priori unconditional dependence does not matter.

B) Regarding the second question, when we draw a Bernoulli for each variable:
Here we have two  conditioning variables, $Y_x, Y_z$. So we are looking at the joint density
$$f(x,z,y_x,y_z) = f(x,z,y_x\mid y_z) \cdot f(y_z) = f(x,z\mid y_x, y_z)\cdot f(y_x) \cdot f(y_z)$$
We also have
$$f(x,z\mid y_x, y_z) = f(x\mid y_x, y_z)\cdot f(z\mid y_x, y_z)$$
and
$$f(x\mid y_x, y_z) = f(x\mid y_x),\;\;\; f(z\mid y_x, y_z) = f(z\mid y_z)$$
This tells us what we already know, that each variable is conditioned on a different (and independent) sigma algebra. It follows that they are conditionally independent.
Are they conditionally identically distributed? In general no, because now we have the joint support of $\{Y_x, Y_z\}$ to consider, that has four possible outcomes. For two of these outcomes that reflect $y_x=y_z$ they will be identically distributed but for the other two, no. So there is a probability that they will be conditionally identically distributed, $p^2 + (1-p)^2$, if this helps somewhere, while with probability $2p(1-p)$, they won't be.
Returning to the joint density and combining,
$$f(x,z,y_x,y_z) = f(x\mid y_x)\cdot f(z\mid y_z)\cdot f(y_x)\cdot f(y_z)$$
If we follow the same steps as before, and integrate out  $y_z$ and $y_x$ we will end up with
$$f(x,z) = [(1-p)N_1(x)+pN_2(x)]\cdot [(1-p)N_1(z)+pN_2(z)]$$
which tells us that, here,  $X,Z$ are unconditionally i.i.d.

C) Regarding the urn question:
Nothing much to contribute here, except to notice that the situation appears compatible with the following two cases, assuming that we draw from each $X$ only once per run:
1) We run scenario $A$ twice and we put the results separately in each urn.
2) We run scenario $B$ twice, then grouped the observations per resulting conditional distribution coming from both $B$-runs.
But in any case, I don't see the benefit of pooling observations from different distributions for learning purposes, that aims at a classifier that will be able to tell them apart afterwards.
Comment: @CagdasOzgenc You asked whether the urn situation is "compatible" with the previous scenarios, I tried to describe which scenarios could result in having $n$ observations in each urn, and in each urn a different distribution. As regards combining the two urns for learning, what would you learn? Say, you would try to estimate the mean, you would get the arithmetic average of the $\mu_1$ and $\mu_2$... is this useful? Is it not preferable to keep the urns separate and estimate $\mu_1$ and $\mu_2$ distinctly?
Comment: @CagdasOzgenc As I hinted, machine learning and classifiers is something I only know superficially. So I try to use logic here: "Tell me a number, and I will tell you the urn". To do that I need to know what distinguishes each number: it is the distribution from which it has come. So to me it appears that the only thing I can do is estimate the moments of the two distributions, and then ask "from which distribution is it more probable that this draw has come?" And  to do that, I certainly should not pool the two urns in order to estimate the two distributions/build the classifier. CONTD
Comment: CONTD _After_ the classifier is built, then certainly the whole point is to not know from which urn the number has come, but be able to tell by using the classifier... this is I think all the thoughts I can offer on this matter.


File Copy failing to create files with same name

Question: I am copying files from one location to another. I encountered an issue where sometimes a file with the same name would try to save and it would break the program. So I added the logic below to add a number to the filename before copying it:
                int counter = 0;
                try
                {
                    File.Copy(FileToCopy, FileToSave);

                }
                catch (Exception)
                {
                    string CurrentFileName = FileToSave.Split('\\', '\\')[4];
                    string CurretFilePrefix = CurrentFileName.Split('.')[0];
                    string CurrentFileSuffix = CurrentFileName.Split('.')[1];
                    string UpdatedFileName = CurretFilePrefix + "_" + counter + "." + CurrentFileSuffix;
                    File.Copy(FileToCopy, UpdatedFileName);
                    counter++;
                }

However, this is now causing a crash saying the file already exists:

When I check the file does not exist:

Why am I getting this exception? How do I save copies of these files?
Comment: Shouldn't that counter variable be in a loop with what you are trying to accomplish?
Comment: You are getting the exception because the file DOES exist but you are looking in the wrong place. You stripped off the directory in the process of creating the new file name.
Comment: @LarsTech I didn't want to post the entire program, it is in a foreach.
Comment: @Ian Mercer You found the issue. Please put as an answer.
Comment: A `for each` of what?  That doesn't make any sense.  Your posted code can only handle a blank or a 0.  The Path class is your friend, you should be using it a lot in your code.
Comment: Does the problem go away if you do a Clean before a Build?
Answer: A good approach to this problem would include (i) a loop; (ii) use of Path expressions; (iii) avoidance of try-catch when you can test if the file exists; (iv) use of a specific Exception for the extremely unlikely case that two threads or processes are trying to do this same copy at the same time and each get past the File.Exists check; (v) avoidance of while-true-forever loops as even the best code can contain mistakes that could cause a spin-wait forever in production code on a server and it's better to instead have an exception that tells you when something has gone wrong.
        int counter = 0;
        string proposedDest = dest;
        while(counter < 5000)
        {
            if (!File.Exists(proposedDest))
            {
                try
                {
                    File.Copy(fileToCopy, proposedDest);
                    break;
                }
                catch (IOException ex) when ((uint)ex.HResult == 0x80070050)
                {
                }
            }
            counter++;
            proposedDest = Path.Combine(Path.GetDirectoryName(dest),
                Path.GetFileNameWithoutExtension(dest) +
                "_" + counter + Path.GetExtension(dest));
        }
        ;
        if (counter == 5000)
           throw new Exception($"Could not copy file {fileToCopy} too many retries");

[A better approach would also not use hard coded constants littered through the code ;)]
Answer: As CurrentFileName is relative, you are trying to save the file in the location of your executable. Check that directory if your file exists.
Also, there are much better ways to find if the file exists, and also to get the filename and extension of a given file.
i.e. you should use the File.Exists method to determine if the file exists, instead of using exceptions for flow control
if (File.Exists(FileToSave))
{
   FileToSave = GetNewFileName(FileToSave)
}
try
{
  File.Copy(FileToCopy, FileToSave);
}
catch (Exception)
{
  //something went really wrong
}

You should also use the Path methods for getting parts of the name, instead of "knowing" to get the fifth part of the filename (Path.GetExtension, Path.GetFileNameWithoutExtension)
private string GetNewFileName(string oldFileName){
   var counter = 0;
   var extension = Path.GetExtension(oldFileName);
   var directory = Path.GetDirectoryName(oldFileName);
   var fileName = Path.GetFileNameWithoutExtension(oldFileName);

   var newFileName = Path.Combine(directory,
      string.Format("{1}_{2}{3}", filename, counter, extension);

   while (File.Exists(newFileName)){
      counter++;
      newFileName = Path.Combine(directory,
        string.Format("{1}_{2}{3}", filename, counter, extension);
   }

   return newFileName;
}

Comment: BTW you should use `Path.Combine` not `string.format` to combine path elements otherwise this code will not work correctly on other OS platforms.
Comment: The folder is generated before trying to save the file. That isn't whats causing the exception.
Comment: The path in the exception message doesn't say "C:\ScrumWorks..." so that's not where it's trying to save to.
Comment: It doesn't matter if the folder exists, as you are not saving in that folder. You've stripped the path of of `CurrentFileName`, so by default, it goes to the path of your .exe file.
Answer: use this instead:
string CurrentFileName = System.IO.Path.GetFileName(FileToSave);
string CurretFilePrefix = System.IO.Path.GetFileNameWithoutExtension(FileToSave);
string CurrentFileSuffix = System.IO.Path.GetExtension(FileToSave);
string UpdatedFileName = CurretFilePrefix + "_" + counter + "." + CurrentFileSuffix;

Then you have
File.Copy(FileToCopy, UpdatedFileName);

Are you sure this shouldn't be
File.Copy(FileToSave, UpdatedFileName); // FileToSave instead of FileToCopy

Comment: I am still getting the same exception.
Comment: Maybe it's because it already exists from other tries at running your code?
Comment: This code is still stripping the directory path from `FileToSave`.
Comment: @IanMercer, that is true. But I don't know the intention of the OP.


Is high falsetto range means high chest range?

Question: I'm a male singer.  I've been studying voice and doing exercises for almost 1 month. My overall range is F2-D6. My problem is: I can only go up to F4 with my chest voice. For other notes, I have no choice but to use my falsetto. I have 2 questions;

I see other male singers who has same falsetto range with me (around C6-D6) and has very high chest voice range (around G5). Does the fact that our falsetto range is same mean our chest voice range is also same? (In other words, do I have potential to sing the high notes?)

Does falsetto range have connection with chest voice range? (In other words, Does high chest voice range means high falsetto range or does high falsetto range means high chest voice range?)

Thank you in advance!
Answer: To answer your questions, no, there is no precise relationship between each person's normal (*) and falsetto ranges. They both depend on several factors: anatomy, technique, state of mind, etc., and what each person can achieve with or without falsetto is highly variable. So it's not very useful (to say the least) to compare your range with other singers, except to try to understand what technique they use to achieve certain results.
If you practice correctly you'll improve both your normal and falsetto ranges, as the most important factors to good singing, like breathing, posture, abdominal support, relaxation, and others, will help with both modes of singing.
BTW, a 2 octave range is quite good to begin with, and F2 to F4 is almost the minimum required for a choir baritone, so not so bad at all. You should work on your high AND low registers, not just the high register and with practise you may extend them both, though more one way or the other it's impossible to predict.
(*) I prefer not to use the term "chest voice" as, though historical, it is not very correct. All the main resonance parts of the whole body contribute, in different degrees, to the production of vocal sound, be it "normal" register or falsetto. Falsetto is not the result of resonance existing only in the head, but it's a different mode of vibration of the vocal folds.
Comment: @Tetsujin The "normal" voice can also more technically be referred to as the "modal" voice  (which, of course, means "normal")
Comment: Anecdotally… I have no distinct falsetto range at all. If I can hit a note I can hit it in both full voice & falsetto. I have no range above that at all.
Comment: @JudyN. - sorry, I'm completely untrained - been singing 50 years & still don't know what any of it is actually called;) Thank you.
Comment: @Tetsujin sorry I don't know why my reply tagged you! It was just a general comment on the answer
Comment: @JudyN. Tagged ya back! ;) No worries at all. :)


How can I search for symlinks that point to other symlinks?

Question: I have morass of chained symlinks like this scattered around:
A (symlink) -> B (symlink) -> C (file)
Some may even involve longer chains, I'm not sure yet.
When manually examining a single file it's easy to see what's going on but I'm looking for an automated way to find these and (preferably) clean them up.
In the example above I would want the B->C symlink to stay in place but the A->B symlink would become A->C
Identifying them if the main goal; the quantity might end up being sufficiently low that fixing them manually wouldn't be a big deal.  But finding them all manually isn't feasible.
I'm aware of the "symlinks" utility and it is useful in many scenarios such as finding dangling symlinks, but it doesn't seem to have the ability to detect "chains" like this
I'm aware of "find -type l" as well as the -L option for find but they don't seem to work together as "find -L -type l" always returns an empty response.
I make use of "find -type l -exec ls -l {} +" (which works better than find's -ls option) and tried to use it to obtain a list of symlink destinations which I could then check to see if they're symlinks or not, however, all the symlinks are relative rather than absolute so the output is a bit messy
for example I get outputs like this:
lrwxrwxrwx 1 username 50 Nov  5 01:00  ./a/b/c/d -> ../../e/f/g/h

From that I have to think a bit to figure out that the actual symlink destination is ./a/e/f/g/h (and I can then check to see if it's a symlink or not), not really ideal for automation
If the symlinks were (temporarily) absolute rather than relative this would be easier but the "symlinks" utility can only convert absolute -> relative; as far as I can tell it can't convert relative -> absolute.
Answer: Following the entire link chain
realpath
realpath(1) gets you the absolute destination of a link. But it only gives you the final destination, so if you have a link chain, it will only show you the path of the last real file/folder that the chain eventually points to.
So in your case, if ../../e/f/g/h is real file or folder, you will see the absolute path. But if one of the components is also a symlink, it will keep recursively until it resolves all the symlinks in the way.
readlink
You could also use the readlink(1) command with the -f or -e flags, which will give you similar result to realpath.
  -f, --canonicalize            canonicalize by following every symlink in
                                every component of the given name recursively;
                                all but the last component must exist
  -e, --canonicalize-existing   canonicalize by following every symlink in
                                every component of the given name recursively,
                                all components must exist

Avoid following the entire link chain
If I understand correctly, you don't want to follow the chain to the last component, but to only get the absolute path of the actual link. It's a little ugly, but you can do something such as:
LINK=./a/b/c/d
/usr/bin/realpath --no-symlinks "$(dirname ${LINK})/$(readlink ${LINK})"

Explanation:
$ dirname $LINK # dirname ./a/b/c/d
./a/b/c

$ readlink $LINK # readlink ./a/b/c/d
../../e/f/g/h

$ echo "$(dirname ${LINK})/$(readlink ${LINK})"
./a/b/c/../../e/f/g/h

$ /usr/bin/realpath --no-symlinks "$(dirname ${LINK})/$(readlink ${LINK})"
/home/a/e/f/g/h

If you only want to see the link relative to your CWD, you can add the --relative-to argument:
$ /usr/bin/realpath --no-symlinks --relative-to ./ "$(dirname ${LINK})/$(readlink ${LINK})"
a/e/f/g/h

Using find
You can get the argument for the realpath command I've shown before by using the find command:
$ find ./ -type l -printf "%h/%l\n"
./a/b/c/../../e/f/g/h

From man find:
%h     Leading directories of file's name (all but the last element).   If
       the  file  name  contains  no  slashes  (since it is in the current
       directory) the %h specifier expands to ".".

%l     Object of symbolic link (empty string if file is not a symbolic link).

Then you could combine it with the realpath command from above.
$ find ./ -type l -printf "%h/%l\n" | xargs /usr/bin/realpath -s
/home/a/e/f/g/h

If you only want to see the link relative to your CWD:
$ find ./ -type l -printf "%h/%l\n" | xargs /usr/bin/realpath -s --relative-to ./
a/e/f/g/h

Comment: Interesting... the fact that it follows the chain to the end isn't ideal but I might be able to cross-reference the realpath output with the target information on "ls -l" to see if they match
Comment: I've edited my answer and added another option, the last one might be what you're looking for.
Comment: @Displayname71, I have added some more options to my answer, hope one of them will fit your needs


Find the remainder of $(2x^3-7x^2-19x+8)/(x^2-4x+5)$ without using division

Question: I have the following problem:

Find the remainder of $f(x)=2x^3-7x^2-19x+8$ is divided by $x^2-4x-5.$

An classmate said to equate coefficients, but I do not know what they referred to.
I have no idea how to proceed with this problem. Whether it's a hint or a full solution, any help would be appreciated.
Comment: I guess there are several such problems on this site itself. Here is one: http://math.stackexchange.com/q/873755/321264.
Answer: We have $f(x)=q(x)g(x)+r(x)$ with $\deg r<\deg g$. Hence $\deg(r)\le 1$.
Now the hint: $$f(5)=q(5)g(5)+r(5)\text{ and }f(-1)=q(-1)g(-1)+r(-1).$$
Comment: 5 and -1 chosen because they are the roots of $x^2 -4x -5$, in case that wasn't obvious.
Answer: Hint
Find $a,b,c,d$ s.t.
$$2x^3-7x^2-19x+8=(ax+b)(x^2-4x-5)+cx+d.$$
You immediately remark that $a=2$. I let you continue.


Why a component inherited from TCustomFrame looks different from TFrame?

Question: I wrote a TCustomFrame's child class which has been exactly copied from TFrame (Forms.pas unit):
  TMyFrame = class(TCustomFrame)
  private
    { Private declarations }
  public
    { Public declarations }
  published
    property Align;
    property Anchors;
    property AutoScroll;
    property AutoSize;
    property BiDiMode;
    property Constraints;
    property DockSite;
    property DragCursor;
    property DragKind;
    property DragMode;
    property Enabled;
    property Color nodefault;
    property Ctl3D;
    property Font;
    property Padding;
    property ParentBackground default True;
    property ParentBiDiMode;
    property ParentColor;
    property ParentCtl3D;
    property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property ShowHint;
    property TabOrder;
    property TabStop;
    property Visible;
    property OnAlignInsertBefore;
    property OnAlignPosition;
    property OnCanResize;
    property OnClick;
    property OnConstrainedResize;
    property OnContextPopup;
    property OnDblClick;
    property OnDockDrop;
    property OnDockOver;
    property OnDragDrop;
    property OnDragOver;
    property OnEndDock;
    property OnEndDrag;
    property OnEnter;
    property OnExit;
    property OnGetSiteInfo;
    property OnMouseActivate;
    property OnMouseDown;
    property OnMouseEnter;
    property OnMouseLeave;
    property OnMouseMove;
    property OnMouseUp;
    property OnMouseWheel;
    property OnMouseWheelDown;
    property OnMouseWheelUp;
    property OnResize;
    property OnStartDock;
    property OnStartDrag;
    property OnUnDock;
  end;

As described here, I've initially defined a TFrame's child class, then I've switched to TCustomFrame and removed the TabOrder property from the DFM in order to be able to open the file in the IDE and recompile the package.
object MyFrame: TMyFrame
  Left = 0
  Top = 0
  Width = 296
  Height = 31
  TabOrder = 0 //this line has been deleted
end

Everything seemed to be ok but after opening and saving the source file, there were several new properties in the DFM and a titlebar appears:
object MyFrame: TMyFrame
  Left = 0
  Top = 0
  ClientHeight = 0
  ClientWidth = 280
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = True
  PixelsPerInch = 96
  TextHeight = 13
end

Why is this happened and how should I do it for avoiding these problems?
Comment: I also do not understand why this question is downwoted. It has a good problem description and formatted pretty well.
Comment: I can guess that you might be getting down-votes because instead of working with Delphi's framework, you're fighting it. And basically you seem to have started what's likely to become a never-ending chain of: Got the previous problem fixed, now here's the next ...
Comment: Me neither. Probably the downvoters have a good reason...
Comment: What if you change the `object MyFrame: TMyFrame` in your DFM to `inherited MyFrame: TMyFrame`?
Comment: @GünthertheBeautiful: I tried to do that but after replacing `object MyFrame: TMyFrame` with `inherited MyFrame: TMyFrame` I get an error `Error creating form: Ancestor for 'TCustomFrame' not found.` on opening the source file using the IDE.
Answer: I believe all you need to do is register your frame class as a custom module.
In your package's register procedure, add something like this :
procedure Register;
begin
[...]
  RegisterCustomModule(TMyFrame, TCustomMyFrameModule)
end;

And TCustomMyFrameModule is defined as
TCustomMyFrameModule = class(TCustomModule)
  function Nestable: Boolean; override;
end;

function TCustomMyFrameModule.Nestable: Boolean;
begin
  Result := True;
end;

EDIT:
For it to work, you need to register a custom module for the parent class of the class your are editing in the IDE.
TFrame1 = class(TMyFrame)
end;
RegisterCustomModule(TMyFrame, TCustomMyFrameModule)

If you want to edit your TMyFrame in the IDE, you will need to register a custom module for TCustomFrame.
TMyFrame = class(TCustomFrame)
end;
RegisterCustomModule(TCustomFrame, TCustomMyFrameModule)

Comment: I've copied your code in my design-time package, built it and restarted the IDE but nothing seems to be changed (The titlebar is still there and the dfm file still contains automatically added properties). Could you please clarify if there's something missing in what I did?
Comment: hmmm.... Reading your question more carefully, I guess you'd need to `RegisterCustomModule(TCustomFrame, TCustomMyFrameModule)` for it to work. Though I'm not sure it's the best way to go about it. I'd personally would make 2 classes, 1 extending TCustomFrame (TMyFrame) and then 1 for designing the frame in a descendant class (`TWhatever = class(TMyFrame)`). Though I guess it would require the 2 frames to be in different packages.
Comment: It seems that it works now! Could you please explain me why you override the `Nestable` function? What does it do? I didn't found any useful [documentation](http://docwiki.embarcadero.com/Libraries/Seattle/en/DesignEditors.TCustomModule.Nestable) about that.
Comment: It seems to be how the IDE determine if you can drop a component inside another one (http://www.delphigroups.info/2/2/757465.html), and then some. I've found this solution a long time ago, I don't really remember how I stumbled upon it.


A question regarding Cauchy's convergence test

Question: The convergence test is this statement:
$ \forall \epsilon>0,\exists N>0:n>N,\forall p\in \mathbb N \implies |a_{n+p}-a_n|<\epsilon\iff \{a_n\}$ has a finite limit
This is the wrong version of it.
$ \forall \epsilon>0,\forall p\in \mathbb N, \exists N>0:n>N \implies |a_{n+p}-a_n|<\epsilon\iff \{a_n\}$ has a finite limit
Can this "wrong" statement prove $|\sqrt {n+p}-\sqrt{n}|<\epsilon$ when n is large enough?
My idea is that if using this wrong statement during the prove, things will be
$\displaystyle |\sqrt {n+p}-\sqrt{n}|=|\frac{p}{\sqrt {n+p}+\sqrt{n}}|=\frac{p}{\sqrt {n+p}+\sqrt{n}}$. Then based on the wrong statement, "for all $p\in \mathbb N$, there exists a N",I can regard $p$ as a constant at this time. Thus when n is sufficiently large, $\displaystyle \frac{p}{\sqrt {n+p}+\sqrt{n}}<\epsilon\implies |\sqrt {n+p}-\sqrt{n}|<\epsilon\implies \{\sqrt n\}$ has a finite limit. By using the wrong statement, the result can be this.
However, if using the right statement for the convergence test and going back to this step in the proof
$ \displaystyle \frac{p}{\sqrt {n+p}+\sqrt{n}}$. Then at this time, since in the right statement, $N$ is only depend on $\epsilon$, $p$ at this time is not a constant. Thus,I can't say when n is sufficiently large, $ \displaystyle \frac{p}{\sqrt {n+p}+\sqrt{n}}$ can smaller than $\epsilon,\forall \epsilon>0$, and the result will be $\{\sqrt{n}\}$ is not convergent to a finite number which is correct.
Comment: Second statement is same with $\forall p, \lim(\sqrt{n+p}-\sqrt{n})=0$ i.e. "non uniform" convergence for each $p$.
Comment: I have not learned uniform convergence this part yet, sorry
Answer: There's only one question in the Question, so I address it...
$ \underline{\forall \epsilon>0,\forall p\in \mathbb N}, \exists N>0:n>N \implies |a_{n+p}-a_n|<\epsilon\iff \{a_n\} \text{ has a finite limit}$
Let $\varepsilon$ and $p$ be given.  Example: $\varepsilon = 1/10$ and $p = 23$.  We now ask, does there exist a positive $N$ such that  $|\sqrt{n+p} - \sqrt{n}| < \varepsilon$ is true for all $n > N$?
Example: Since $n+23 > n > 0$, we start with the simplification $|\sqrt{n+23} - \sqrt{n}| = \sqrt{n+23} - \sqrt{n}$ to see if we obtain an inequality of the form "$n > {}$ some constant" (or a solution that is a union of intervals, at least one of which is of that form)...
\begin{align*}
\sqrt{n+23} - \sqrt{n} &< \frac{1}{10}  \\
|n+23| - 2 \sqrt{n+23}\sqrt{n} + |n| &< \frac{1}{100}  \\
n + \frac{23}{2} - \sqrt{n^2+23n} &< \frac{1}{200}  \\
- \sqrt{n^2+23n} &< \frac{1}{200}  - n - \frac{23}{2} \\
\sqrt{n^2+23n} &> n + \frac{2299}{200}  \\
n^2+23n &> n^2 + \frac{2299n}{100} + \frac{5\,285\,401}{40\,000}  \\
23n -  \frac{2299n}{100} &> \frac{5\,285\,401}{40\,000}  \\
n &> \frac{5\,285\,401}{400}  \\
n &> 13\,213.5025  \text{.}
\end{align*}
So, if we set $N = 13\,213$ (or any larger number), then $n > N$ implies $|\sqrt{n+23} - \sqrt{n}| < 1/10$.
So let's repeat those manipulations for the general case.
Since $n+p \geq n > 0$, we start with the simplification $|\sqrt{n+p} - \sqrt{n}| = \sqrt{n+p} - \sqrt{n}$...
\begin{align*}
\sqrt{n+p} - \sqrt{n} &< \varepsilon  \\
|n+p| - 2 \sqrt{n+p}\sqrt{n} + |n| &< \varepsilon^2  \\
n + \frac{p}{2} - \sqrt{n^2+pn} &< \frac{1}{2}\varepsilon^2  \\
- \sqrt{n^2+pn} &< \frac{1}{2}\varepsilon^2  - n - \frac{p}{2} \\
\sqrt{n^2+pn} &> n + \frac{p-\varepsilon^2}{2}  \\
n^2+pn &> n^2 + (p-\varepsilon^2)n + \frac{(p-\varepsilon^2)^2}{4}  \\
pn -  (p-\varepsilon^2)n &> \frac{(p-\varepsilon^2)^2}{4}  \\
\varepsilon^2n &> \frac{(p-\varepsilon^2)^2}{4}  \\
n &> \frac{(p-\varepsilon^2)^2}{4\varepsilon^2}  \text{.}
\end{align*}
So, if we set $N = \max\left\{1,\frac{(p-\varepsilon^2)^2}{4\varepsilon^2}\right\}$ (or any larger number), then $n > N$ implies $|\sqrt{n+p} - \sqrt{n}| < \varepsilon$.
Since a suitable choice of $N$ exists, the left-hand side of the biimplication in the wrong statement is true for $a_n = \sqrt{n}$.  That is, with that choice of $a_n$,
$$ \forall \epsilon>0,\forall p\in \mathbb N, \exists N>0:n>N \implies |a_{n+p}-a_n|<\epsilon $$
is true; and if we accept the biimplication, we conclude (wrongly) $\{\sqrt{n}\}_{n \in \Bbb{N}}$ has a finite limit.
Comment: @Yink : Yes.  An object of existential quantification can depend on all the variables introduced externally to its quantified context.  For $N$ in the correct statement, $N$ can only depend on $\varepsilon$.  For $N$ in the wrong statement, $N$ can depend on both $\varepsilon$ and $p$ (since both are quantified in a scope that encloses $N$'s scope).
Comment: Thus, if using the wrong statement, the choice of N can depend on p, so there can be an answer of choosing N with the appearance of the letter p. However, in the right statement, the choice of N is independent of p, so the answer of suitable N can't have anything with the letter p. With this restriction, we can't have "n>" this expression if using the right one. Is this correct?


como eu posso substituir todos todos os valores negativos de um array no javaScript por 0. EX [-1,2,-3,4] [0,2,0,4]

Question: so consegui fazer isso
var numeros = [2, -3, 5, 6, 8];
function sopositivo(n) {
  let index = 0;
  let novo = [];
  for (let i = 0, l = n.length; i < l; i++) {
     if (n[i] < 0) {
      index = numeros.indexOf[i];
     } if (index !== -1) {
        novo = numeros[index] = 0;
      }
  return novo;
  }
}

console.log(sopositivo(numeros));

Answer: O método map() retorna um novo array (sem modificar o array já existente) rodando a função callback passada nele para cada item do array.
a função callback que usei tem um if ternário validando se o número é menor que 0.
var numeros = [2, -3, 5, 6, 8];
var arrayPositivos = numeros.map((item) => (item < 0) ? 0 : item);
console.log(numeros);
console.log(arrayPositivos);

Para mais detalhes consulte: Array.prototype.map()
Comment: obrigado!! vou pesquisar mais a respeito do assunto
Answer: Isso você resolve dessa forma
        // Entrada
        let numeros = [1, 2, 0, -1]

        for(let i = 0; i < numeros.length; i++){
            if(numeros[i] < 0){
                numeros[i] = 0
            }
        }

        // Saida [1, 2, 0, 0]

Comment: obrigado pela ajuda1


How to get the Published or Archived revision of a node

Question: I'm trying to compare some field values from the edit form of a node to the published/archived field values. However I'm running to an issue where when im trying to load the Node object using
Drupal::entityTypeManager()->getStorage('node')->load($nid)
It's returning the last saved draft revision. How do i get the Node object of the published/archived revision?
P.S. Content Moderation is turned on, and content type is assigned to a workflow.
Answer: You can do this with a direct database query in your function, then load the specific revision.
$connection = \Drupal::database();
$query = $connection->query("SELECT vid FROM {node_field_data} WHERE nid = :nid",
    [':nid' => $node_nid,]);
$node_revision_id = $query->fetchField();

$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

Untested code, but this should put you on the right track.  Might also be worth confirming in your SQL query that "WHERE status = 1" to confirm that the node is still published.
Comment: Thanks. But this didn't work. It gave me the same node as ```Drupal::entityTypeManager()->getStorage('node')->load($nid)``` which is the draft revision and not the currently published revision.
Comment: Actually disregard my comment above this works. However, the condition to check status/moderation state is important because, a node might not have a published/archived version yet.


Executar Selenium webdriver navegador oculto em Python

Question: Estou começando a programar com python3, mas estou com uma dificuldade, no qual não sei como deixar oculta a janela do navegador (firefox) oculta enquanto o código é executado.
Segue abaixo a parte que estou com dificuldade.
from selenium import webdriver

driver = webdriver.Firefox(executable_path=r"C:\Users\Eduardo\Desktop\geckodriver.exe")

driver.get("URL")

Comment: Habilite o modo headless no webdriver: https://www.selenium.dev/selenium/docs/api/rb/Selenium/WebDriver/Firefox/Options.html#headless!-instance_method
Answer: Você precisa adicionar o parâmetro headless como True.
Tente isto:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options,
executable_path=r"C:\Users\Eduardo\Desktop\geckodriver.exe")
driver.get("http://google.com/")
print("Modo Headless inicializado")
driver.quit()


Ranking System (ELO)

Question: I want to create a ranking system for a sports game, where more that 2 "teams/players" participate in each match. This means NOT chess, or soccer, or boxing. It could be bowling or long jump etc. For example let's say it's running 100m.
One way of doing so is that every player gets 3 points for 1st place, 2 points for 2nd place and 1 point for 3rd place. But I don't want the ranking to be accumulative. I want to gain and lose points, so that your score represent your current form.
So I thought of the ELO rating system. Assuming that every player has an ELO before the match, these are some variations i have thought so far:
1) calculate an expected time for each player. then, according to his time he either gains or loses ELO points
2) assume that every player is having a mini-match with every other player. Then we just look if a player has won or lost a mini-match, regardless of his time.
Then I though of some modifications to second case:
2a) mini-match not with every other player, but only with N number of players each time. These players will be the players whose ELO is closer to yours.
2b) discard matches where less than M players participate.

Do you find any flaws to my thoughts?
Do you have something else to propose?

Edit: Any abstract ideas are fine to be proposed. I need as many different ideas possible. I will be able to figure out then which to implement.
Comment: Online gaming may have tackled this problem already for you. Microsoft use a system called TrueSkill for xBox Live, which you can read about at http://research.microsoft.com/pubs/67956/NIPS2006_0688.pdf. DotA2, et al use a different system called Match Making Ranking, or MMR. The details of this were hard for me to find by googling, but emailing someone at Valve occasionally produces good results.
Comment: By the way, why is ELO all in caps? It is named after Dr Arpad Elo, who was (is?)  a a human, not an acronym.
Comment: I don't see how you can reasonably choose an ordering on which match gets applied first.
Comment: @JessicaK If I understand your worry: you just calculate all N minimatches with the ELO you had before the match, and then update your ELO
Comment: I feel like this could have an odd effect on rating inflation. Suppose you are running a 64k "Speed-Walking World Championship" with 200 participants. If you consider just the first place winner and suppose his ELO is roughly the mean of the 200 participants ELO ratings, this single tournament win is going to make his ELO astronomical and not a good basis for comparing skill level.
Comment: i am just comparing with N players. let's say N=5. so i will compare with 5 out of 200. these are the 5 competitors who have similar ELO to me before the run. You can also assume that after every match I divide the elo_won or elo_lost with the number of mini-matches (5 for our case).
Comment: @IgorRivin From wikipedia: It is in caps so as to distinguish it from the name of Dr Arpad.
Answer: Some ideas:

Take a discounted average of past finish times. That is, suppose there is a race each month $m$, and some associated finish time $t_{im}$ for runner $i$, then the discounted average is $$DA_i=\frac{\sum_{m=0} \delta^m t_{im}}{\sum_{m=0} \delta^m},$$
where $m=0$ is the current month and then we count backwards. $0<\delta<1$ is the discount factor. In effect, a time $t$ gets less weight the farther in the past it is - this reflects current shape. (This can also be viewed as the predicted running time for a new race.)
Use a multinomial logit model. Logit models are very popular in empirical applications. They help you predict the probabilities that some runner wins a match given some characteristics, like number of contenders.
Use forecasts from betting or prediction markets. If you try to classify actual 100m runners, then the public has an often very accurate forecast of who is going to win, which you can find out by looking at betting odds or prediction market prices. In these markets, people stake money on their beliefs, so only people who are reasonably sure that they are right actually bet, which makes these forecasts pretty accurate (there is a lot of empirical research on this). Of course, this doesn't work for runners which are not featured on tv.

Ranking System (ELO)


Alterar gráficos dos betas de uma regressão

Question: estou qurendo modificar o gráfico dos betas dessa regressão que rodei:
x

c(-0.0179316822180174, -0.00641604898349779, 0.0118829440361971,
-0.00821159118344772, -0.0171607214317729, 0.0162441460856755,
0.00963105000906578, 0.00394937550015284, -0.0373589167442337,
-0.00470636563065663, 0.0236590046189202, 0.0063475614358427,
-0.0070059434857957, -0.0169201469608903, 0.00155616011324267,
0.0249988251813635, -0.0229110197078823, 0.0196769910169684,
-0.0232707200733515, -0.0147603533337192, 0.0146431308369133,
0.014497826586643, -0.00797107471083758, 0.0127135417735376,
0.0251444784676054, -0.00765473955145302, 0.00261176732854917,
0.00422561863994186, 0.0169941535677274, -0.0273569406032738,
0.00744049850761097, -0.0239050021435552, 0.00364945909804465,
0.0298095264998562, -0.0118560732543823, -0.00568936398070341,
0.0263777219741199, -0.01045817176334, 0.0193070220281141, 0.0458305554890071,
-0.0127560808477733, 0.0107511726413252, 0.0289323343688418,
-0.0160308496643017, 0.0180222017522788, 0.0240456896851978,
-0.0523667660813357, 0.0221451602414924, 0.0129487350977803,
0.0143767869461501, -0.00637530773247202, 0.00715694081686963,
0.010049767615021, -0.0132797307956235, -0.0175982918196536,
-0.0131551067453106, 0.0105408021133636, 0.0195710544478027,
-0.0203275721747587, 0.0293425895382764, -0.000777621507193182,
-0.00675534408376044, -0.0231203355600037, -0.0040448935503764,
-0.0409024741790648, -0.0245661039171186, 0.00984019692277266,
-0.0164702632938923, 0.00516051244449134, 0.00544526835976067,
-0.0340426755099334, -0.0207890109659793, 0.0426363179214442,
-0.00351865802118057, -0.0110782883419167, -0.024773727630523,
-0.00716884307950422, 0.0262043639376453, 0.0161207659146274,
-0.0491302988818763, -0.0211728961394305, -0.0133934386752423,
-0.0400734284906117, -0.0166611855989933, -0.0193531306066065,
0.00971419325460077, 0.0357254985156947, -0.0333207907402884,
0.0109406291684547, -0.00272395613977894, 0.0107796305168576,
-0.00588183923966368, -0.012491285708382, -0.0423110888432794,
-0.00438693819528468, 0.0177541412380439, -0.020772938896655,
0.0189228345365723, -0.0106763932048778, 0.0468064583053511)

y

   c(0.000576738240914476, 0.000538252649209758, 0.000328347920403316,
0.000551536204488168, 0.000621483730588512, 0.00091495119712004,
0.00109651825560558, 0.00123180669729761, 0.00129148926642808,
0.00129037681820299, 0.00134693760472337, 0.00156192230364605,
0.00142144112291509, 0.00154651078830825, -0.000167473330263679,
0.00195431640270072, 0.00145027931070263, 0.00364735971060892,
-0.00096570131327478, 0.00926719634555029, -0.00233090423778703,
0.00169002340998969, -0.0018999947889875, -0.00321632100485059,
0.000738983028809759, 0.000560542619919058, 0.000774568378244744,
-0.000434821126273743, 0.000881431501733143, -0.00244624308218078,
0, 0.0125279278690494, 0.00185927179999512, -3.28186278559794e-05,
-0.00589444451637772, -0.00014506419115895, 0.000891099594783507,
-0.00695464873509455, 0.000574144381182862, -0.000156492073995818,
-0.00239438631071848, -0.00471931618926341, -0.00481921408324487,
-0.00081512646250681, -0.000502817266098854, -0.0011187389928583,
-0.00434727701657506, -0.000627596326747082, 0.00055506055967075,
0.000490259703263163, 0.000440631958631366, -0.00332497619117139,
-0.000767416119292985, 0.00109638345042196, 0.00172299673107124,
0.00179699775909237, 0.00167405836622925, 0.000276277238694167,
0.00419818885099232, 0.00675923261514455, 0.0016239844842349,
0.000268701255320192, 0.00176419582798132, 0.00206722933963693,
0.000731336330279664, 0.00182748588872217, -0.00411706814274904,
0.00176192435305844, 0.0146897325351242, 0.00640952859808785,
0.00216051625545427, 0.00587491055544875, -4.93125015511575e-05,
-0.000330825886204311, 0.0100184061569999, 0.00681726701302382,
0.00189868295029555, 0.00187938991649916, -0.0039783258159809,
0.00203838232559217, 0.00295293766227511, -5.09100165567711e-05,
0.00223329417681417, 0.00784583472285028, 0.00229086844066151,
0.00257624622374575, 0.0088559303832999, 0.000833133961172683,
0.00274639936803289, 0.00589460164436073, 0.00276022547587274,
0.00550758009795338, 0.00796644625557363, 0.0022694837516456,
0.0114793057877365, 0.00134302892350002, 0.00333286567514701,
0.00721456781660945, 0.00512657322727417, 0.00154581658468977
)

fit1 <- rq(y ~ x, tau=seq(0.05, 0.95, by = 0.05))

summary<-summary(fit1,se="iid")

plot(summary,parm=2,ylab="beta",xlab = "tau", cex = 1, pch = 20)

No plot tenho várias bolinhas representando os betas estimados.
Como faço para mudar essas bolinhas, fazendo com que para determinados betas (eu vejo isso utilizando o comando summary) sejam asteriscos e outros triângulos?
Answer: Basta alterar o argumento pch do teu plot. Por exemplo,
plot(fit1.summary, parm=2, ylab="beta", cex=1, xlab = "tau", pch = c(rep(c(2, 8), 7), 2))

Apenas ajuste o vetor com os valores do pch para que cada beta seja representado com o símbolo correto.
Answer: Atribua um vetor ao parâmetro pch:
library(quantreg)

## Ajuste da regressão quantílica
seqt <- seq(0.1, 0.9, by = 0.05)
fit1 <- rq(dist ~ speed, tau = seqt, data = cars)
resu <- summary(fit1,se="iid")

## Um 'plotting character' (pch) para cada theta
plot(resu, parm = 1, ylab = "beta", xlab = "tau",
     cex = 1, pch = seq_along(seqt))

## Um 'plotting character' (pch) distinto para os thetas em que
## a estatística t do intercepto é maior de |1.96|
ind <-  sapply(resu, function(x)
    abs(x$coef["(Intercept)", "t value"]) < 1.96)
plot(resu, parm = 1, ylab = "beta", xlab = "tau",
     cex = 1, pch = ifelse(ind, 8, 19))

Answer: Aqui vai uma tentaiva de copiar este gráfico:
fit1 <- rq(y ~ x, tau=seq(0.05, 0.95, by = 0.05))

library(ggplot2)
library(dplyr)
library(broom)

broom::tidy(fit1) %>%
  filter(term == "x") %>%
  mutate(shape = ifelse(row_number() %in% c(1, 5, 7), "a", "b")) %>%
  ggplot(aes(x = tau, y = estimate)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2) +
  geom_point(aes(shape = shape)) +
  geom_hline(aes(yintercept = mean(estimate)), colour = "red") +
  geom_hline(aes(yintercept = quantile(estimate, probs = 0.05)), colour = "red", linetype = "dashed") +
  geom_hline(aes(yintercept = quantile(estimate, probs = 0.95)), colour = "red", linetype = "dashed")

Aqui o gráfico original. Note que as linhas vermelhas não são iguais... não sei muito bem o que elas representam, mas você pode tentar ajustar. NO código isso está bem simples de modificar.


How can we find this limit $\lim_{n\to\infty \\x\to\infty}f^n(x)$?

Question: Let $f:\mathbb{R}\rightarrow \mathbb{R}$ , $f(x)=\frac{ax+b}{cx+d}$ and $a,b,c,d>0$ then  $f^1(x)=f(x), f^2(x)=f(f(x)), f^3(x)=f(f(f(x)))$ and $f^n(x)={f(f(f\cdots f(x)\cdots )))}$, where $ f^n(x)$ is the $ n $ composition of the function $f(x).$

It's required finding this limit:
$$\lim_{n\to\infty \\x\to\infty}f^n(x)$$

It is possible to find $f^n(x)$ for finite number $n$. For example, I found $f^2(x) = \frac{a^2 x + a b + b c x + b d}{a c x + b c + c d x + d^2}$. I can't do more than that. What is the math level of this problem? In fact, I wanted to solve. But I could not.
Thank you very much!
Comment: Perhaps the matrix formulation helps. See https://en.wikipedia.org/wiki/Möbius_transformation#Projective_matrix_representations
Answer: One approach is using linear algebra: For a matrix $ M = \begin{pmatrix}\alpha&\beta\\\gamma&\delta\end{pmatrix}$, put  $f_M(x)=\frac{\alpha x+\beta}{\gamma x+\delta}$. Then direct computation shows that
$f_M(f_N) = f_{MN}$.
In your case, $f = f_A$, and $f^n=f_{A^n}$, with $A=\begin{pmatrix}a&b\\c&d\end{pmatrix}$. From this follows the answers to your question in the text is:
1. The level of math is linear algebra (where you learn how to compute powers of matrices, e.g., by eigenvalues or jordan form) and calculus 1 (where you learn to compute the resulting limit).
And the answer to the question in the title is: Yes with some work.
Comment: (+1) Is it possible to add more details to your answer?..
Comment: @Elementary what kind of details? On the composition? On powers if matrices?
Comment: Can you look
 https://math.stackexchange.com/q/3101388/548054
Comment: Your say that , is answer equal to $1$? This is wrong.
Answer: You could define the limits by recursion. If $p_n = \lim_{x\rightarrow \infty} f^n(x)$, then
$$ p_{n+1}=\frac{a \cdot p_n+b}{c\cdot p_n+d}$$
And $p_0=a/c$
There should exist some results on this kind of sequences.


DNN7 module cannot debug due to break point not hit

Question: When i using the Default DNN7 create modules (DotNetNuke Compiled Module), i want try to debug on Page_load
<code>CustomModuleController objCustomModules = new CustomModuleController();
</code>
and make and breakpoint on the line, or anyline on Page_load, it given the error.
The breakpoint will not currently be hit. No symbols have been loaded for this document.
Answer: I would recommend that you check out the templates at http://christoctemplate.codeplex.com the templates in the visual studio starter kit frankly don't work.
That being said, if you want to make sure that the current template will work, check the following

What is the build location of the DLL (right click on the project, choose properties, check the build tab)
Do you have debugging enabled in the web.config file?
Are you building in DEBUG or RELEASE mode?
Answer: What if you want to develop dynamic modules (non-compiled), in separate project, other than the website proj?
The Christoc Templates are all compiled, right?


If $g(x) = \sum_{k=0}^{\infty} a_k \cdot \frac{x^k}{k!}$ is 0 at integer values, does it mean that all $a_k = 0$?

Question: For a sequence of real numbers $\left(a_k\right)_{k \in \mathbb{N}}$, does the fact that
$$
g(x) = \sum_{k=0}^{\infty} a_k \cdot \frac{x^k}{k!} = 0,  \forall x \in \{1, 2, 3, ... \}
$$
imply that $a_k = 0, \forall k \in \{0, 1, 2, 3, ... \}$?
In the case where the property is true $\forall x \in \left(0, \infty \right)$, one can use differentiation and Taylor expansion (as was done in this answer) to conclude that $a_k = 0, \forall k = \{0, 1, 2, ... \}$.
I don't think the same approach works in the case where the values taken by $x$ are discrete.
I think it's enough to show that the infinite matrix
\begin{pmatrix}
1^0 & 1^1 & 1^2 & ... \\
2^0 & 2^1 & 2^2 & ... \\
3^0 & 3^1 & 3^2 & ... \\
. & . & . \\
. & . & . \\
. & . & . \\
\end{pmatrix}
has a determinant of $0$, but I'm not sure where to start. I don't think an approach related to generating functions will work either, since only the values at positive integer $x$ are known.
Can anyone give me a hint on how to proceed with this?
Comment: No, consider $
\sin (\pi x) = \sum\limits_{k = 1}^\infty  {( - 1)^{k - 1} \pi ^{2k - 1} \frac{{x^{2k - 1} }}{{(2k - 1)!}}}
$. The odd index $a_k$'s are non-zero.
Comment: @Gary You could consider posting that as an answer as well. Your call, of course. Not easy to phrase it as "a hint" :-)
Answer: No, consider
$$
\sin (\pi x) = \sum\limits_{k = 1}^\infty  {( - 1)^{k - 1} \pi ^{2k - 1} \frac{{x^{2k - 1} }}{{(2k - 1)!}}} .
$$
In this example, with your notation,
$$
a_{2k - 1}  = ( - 1)^{k - 1} \pi ^{2k - 1} \neq 0,\quad a_{2k}  = 0,
$$
yet the power series vanishes at integer values of $x$.
Comment: This is exactly what I was looking for! I had a hunch that circular functions might work, but I couldn't arrive at anything concrete. Thank you for the answer!