Are cancer studies cases always left-censored?

Question: I'm used to traditionnal studies with plain old Cox PH models and right censoring.
But lately I was wondering about the outcome date in cancer studies. Indeed, the date we usually use as outcome is the diagnosis date, not the "real" cancer declaration date.
Cancers like solid tumors start out as few cells growing out of control and exceeding the immune system. As they grow over time, they will eventually cause symptoms that can lead to cancer diagnosis, but the primary event (as a point of no return) is the "few cells" time. Unfortunately this event is impossible to register, even by the most talented physician, so the event can have already happen unnoticed at the time of enrollment.
As a cancer can evolve for years before being diagnosable, the cancer could have appeared anywhere before the diagnosis date in case events, in the same way that it could appear anywhere after the last contact date in non-case events.
By using the date of diagnosis as a fixed endpoint, it seems to me that we are ignoring some left-censoring.
I could not find anything about this in the litterature (tried "cancer left censor" on google scholar), is my logic flawed or is my research skill weak ?
If this is a thing, which type of model can take into account such a double censoring ?

EDIT TO ACCOUNT FOR @andbel ANSWER: as several people talked about left censoring being relative to date of entry, I'll try to explain here why I don't agree. If I say anything wrong, please correct me as this may be the seed of my misunderstanding of the problem.
TL;DR: cancer appeared anytime before cancer diagnosis if event==1 (left-censoring) and anytime after censoring time if event==0 (right-censoring). I think the common (Oxford) definition about left-censoring is wrong as it is more a definiton of "left-censoring at date of entry". This is not about exposition hence no truncation. Cancer appearance is not positively bound by an interval so it is not interval-censoring.
Left censoring is strictly defined as following:

A left censoring scheme is such that the random variable of interest,
  X, is only observed if it is greater than or equal to a left censoring
  variable L, otherwise L is observed

In my textbook, they gave the example of low limit of quantification when measuring something, like viral load for HIV: the result is lower than L=20 copies/ml but you cannot know if it is 0 or 10 or 15, you only know it is not higher than 20. Hence left censoring.
When dealing with time and events, I guess it becomes a little more complicated.
In usual cases, each person have either a date of event or a date of right-censoring. I like to translate this latter as, "for anyone who did not experienced the event, it may happen at $T≥t_{rightCensoring}$". The right censoring is thus on the time of event in people who did not experienced it only, whereas there is no censoring in "event" people (the time is well known).
Here is the definition of left censoring from Oxford university, which I think everybody usualy relates:

Left censoring is when the event of interest has already occurred
  before enrolment. This is very rarely encountered.

I think this definition is about the more specific "Left censoring at enrolment point", rather than the wide definition of left censoring. Moreover, since baseline cases are usually excluded from analysis, I find this definition, along with some internet examples quite confusing. This SO example is more like what I'm thinking of.
Interval censoring is defined as:

By interval censoring, we mean that a random variable of interest is known only to lie within an interval instead of being observed exactly

This is not the case either, sine cancer appearance is not bound by an interval. Conversely, the study time is more an interval of exclusion of cancer if event==0.
Lastly, I really don't think this is left truncation. Correct me if I'm wrong, but AFAIK, left truncation is when you don't have information on exposition before a date. Oxford university define it as "Left truncation occurs when the subjects have been at risk before entering the study". If you try to measure the association between tobacco and cancer, I think it is left censored if you don't know about cancer before a date, and left truncated if you don't know about tobacco. In this question, it is not a matter of "being at risk", and we know that cancer appeared, but we don't know exactly when.
Comment: So, on Stack Exchange, the etiquette for bumping appears to be that you should make some substantive edits to the question. You can even attempt to answer your own question. You seem to have been making empty edits (i.e. you edited by adding and deleting spaces) just to bump the post. There's no clear rule against that, but it doesn't seem helpful to me, so I downvoted the post. If you can clarify the question or clarify why the answer below doesn't do it, that's more helpful. https://stats.meta.stackexchange.com/questions/735/is-there-a-polite-accepted-way-of-bumping-up-questions
Comment: @WeiwenNg I've maid a lot of edits to my posts since andbel's answer and I think I've thoroughly described in the comments and in the answer why it is not accepted (I've upvoted it nevertheless). As you said, there is no rule against bumping so downvoting my post seems quite arbitrary to me and I really don't understand how it can be a good thing for anyone. A good thing you or anyone could do though is explaining why my question is hard to answer to, so I can edit it that way. This would really help me, and help others answering my question. (Please dont take this personnaly of course)
Answer: Left censoring occurs when the outcome has already happened when you begin following the participant, so this is not generally the case. If you are thinking of a classical population-based study in which you follow individuals until the diagnosis of cancer (i.e. cancer diagnosis is the event of interest in the survival analysis), you could technically think of this as an interval censored observation: the event occurs at a specific (unknown) time between date of entry and diagnosis date.
I say technically, however, because in large cohort study this interval will likely be very long, and the real date of cancer initiation very close to the right bound (diagnosis), making methods for interval censored not really useful.
And that's why you don't find the problem described as a left/interval censoring issue. In epidemiological literature the problem you describe is referred to as latent (or incubation) period  (https://www.ncbi.nlm.nih.gov/pubmed/7304560).
Comment: Very interesting answer, thanks, I'm definitely digging into latent period. Though, I don't agree with you "interval censored" concept, since there is no reason that event (cancer apparition here) should occur after the date of enty, whereas it definitely occurs before date of diagnosis. Hence my idea of left-only censoring.
Comment: This depends on the study design and on how your time variable and event variable are defined. I'm assuming that "date of entry" corresponds to the day of a baseline clinical visit in which no cancer is diagnosed. In other studies, where you just enroll participants from home for example, you are right, the event could have already happened. From my experience the first situation is more common though.
Comment: I think maybe you misunderstood my point. Cancers like solid tumors start out as few cells growing out of control and exceeding the immune system. As they grow over time, they will eventually cause symptoms that can lead to cancer diagnosis, but the primary event (as a point of no return) is the "few cells" time. Unfortunately this event is impossible to register, even by the most talented physician, so the event can have already happen unnoticed.
Comment: Moreover, I'm actually working on a study where participants are enrolled from home. I'm editing my post to make everything clear.
Comment: If the outcome of interest were death, then sure, a cancer study can never be left censored. @DanChaltiel seems to indicate that his outcome of interest is actually developing cancer, or something like that. I'd agree, that seems like it should be treated as left or interval censored. Dan, it may help to explicitly state your outcome of interest in the question.
Comment: Actually, I may want to reconsider the comment above. It's technically true, but I can't imagine left censoring is very common. Perhaps Dan means left **truncation**, not censoring? Or perhaps something else? Either way, as @andbel correctly stated, left censoring happens if you **begin the study** and some people already had the outcome.
Comment: @WeiwenNg I added a lot more details in my question, please have a look when you have some time
Answer: The issue here is what is being modeled in cancer survival studies. You cannot correctly define censoring, truncation, or whatever without specifying the nature of the study.
Cancer survival studies have to do with determining what a clinician can tell a patient about prognosis or can best provide for therapy once a tumor has been detected clinically. In that case what you are modeling is the survival after the time of tumor detection, with the date of pathologic confirmation of a tumor typically set as the time=0 origin for each individual. The event of interest is something related to subsequent outcome (e.g., recurrence after therapy, death from cancer, death from any cause). In this type of study there is no left censoring or truncation of event times: if such an event does happen, it by definition cannot have happened before the time=0 origin as defined for that individual in the study.
As the OP rightly points out, that time of tumor detection can be long after--even decades after--the initiation of the tumor. The origins and evolution of a tumor from a single initiating cell into a clinically detectable tumor with about $10^9$ cells is a fascinating object of study. If you were trying to model survival from the time of cancer initiation to death, then some of the concerns in the OP would have to be dealt with.*
But that is not what clinical cancer studies are about. They are about survival after cancer detection. Neither the patient, family, friends, or clinicians at that point care explicitly about how long the cancer previously grew undetected. A cancer biomarker available at time=0 might in principle contain information about pre-detection tumor evolution and potentially inform prognostication. Even then, the prognosis being modeled is the clinically relevant survival after someone is known to have cancer, not from the time decades past when the tumor began.

*You would also have to deal with just what is meant as "cancer initiation": for a carcinoma do you mean the first dysplastic event, the development of carcinoma in situ, production of the first cell capable of invasiveness, or first invasion through a basement membrane?
Comment: Great answer, with very interesting thoughts, thanks ! Still, it seems to me that if the information "cancer initiation" was known, any oncologist would rather use this information than "cancer diagnosis", don't you think ? I'd think that since we cannot get this absolute `time=0`, a model that take into account some kind of `time<X` (like the limits of detections in biochemistry, `concentration<20cp/ml`) would be very powerful, so why doesn't cancer studies care ?
Comment: @DanChaltiel let's say that an oncologist knew when a tumor initiated. The survival of interest, however, would still be the survival after clinical presentation and therapy. That's all that can be influenced clinically. Information about time of tumor initiation isn't really available. Even if it were, the clinical interest would be in how that time of initiation informs a choice of therapy _now_ and prognosis _from now_, after presentation. And the time from initiation to event (recurrence or death) would just be the time from initiation to _now_ plus that from _now_ to event.


Examples of path component maps

Question:
I understand what needs to be done for the first part, i have to somehow map $1$ point onto $1$ point, in a map where there exists $2$ points... so the inverse map is injective, but how is this possible?
For the second point, i dont fully understand how i can show this, do i show $f_*$ is bijective but $f$ is not continuous?
Comment: For the second point, can you think of a path connected space which is not a point?
Answer: Let $f:\mathbb{R}^{n}\times\mathbb{R}^{m}\rightarrow \mathbb{R}^{n}$ be the projection on the first component. Then, f is not injective but induces a bijection $f_{\ast}:\pi_0(\mathbb{R}^{n+m})\rightarrow \pi_0(\mathbb{R}^{m})$, since $\pi_0(\mathbb{R}^{n+m})$ and $\pi_0(\mathbb{R}^{n})$ both are one point sets.
This also solves the second question, because $f_{\ast}$ is bijective but $f$ is not a homeomorphism.
Comment: i understand how this solves the first point, however, how have you concluded that we have one point sets in order to show the second point?
Comment: $\mathbb{R}^{n}$ is connected so the set of path components of $\mathbb{R}^{n}$ has one element only.
Answer: It is simpler than that. Take the map $f$ from $X:=\mathbb{R}$ to $Y:=\{0\}$. Then $f$ is continuous and certainly not one to one.
However $X$ and $Y$ are both path-connected so $f_*$ has all the condition needed.
Comment: From this i understand how this solves the first point, however, would this also solve the second point?
Comment: @smith $f_*$ is bijective and $f$ is not injective so yes it works for the second point too.
Comment: can you explain why $f_*$ is bijective? i can't fully see this?
Comment: @smith, $\pi_0(X)$ and $\pi_0(Y)$ are both sets with one element so $f_*$ cannot but be bijective.

Examples of path component maps


iTextSharp - Tabela dinamica

Question: Estou a tentar via C# e com o iTextSharp criar um doc pdf com a seguinte estrutura:
Tenho uma tabela com 3 Rows
Na 1ª tenho X colunas com X anos.
Na 2ª uma Row com os Meses (J, F, M...etc) por cada ano, abaixo tenho outra Row que quero afetar a propriedade da celula deBackgroundColor para qualquer coisa,
Estou a ter muitas dificultades em faze-lo, será que alguém me ajuda por aqui?
Eis parte do código, já mexi e remexi tanto que vou refazer de novo.
<code>        PdfPTable tabelaAnos = new PdfPTable(iAnos);
        for (int i = 0; i < iAnos; i++)
        {
            PdfPCell cellAnos1 = new PdfPCell();
            AnoInicio = AnoInicio + 1;
            cellAnos1 = new PdfPCell(new Phrase("Ano " + AnoInicio));
            cellAnos1.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            tabelaAnos.AddCell(cellAnos1);
        }

       for (int i = 1; i < 13; i++)
       {
           PdfPCell cell = new PdfPCell();
           cell = new PdfPCell(new Phrase("Meses com  " + i + " columns"));
           cell.Colspan = 12;
           cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
          tabelaAnos.AddCell(cell);
        }
</code>
Comment: O procedimento é criar uma tabela com anos*meses colunas e usar colspan 12 no primeiro row na coluna 1, 13, etc.
Comment: Sim já o tentei, mas na teoria é mto simples, já criei dezenas de tabelas em html e em aspnet, mas o iText não se comporta como queremos.
Comment: Hoje à noite preparo um exemplo.
Answer: Obrigado Paulo, mas entretanto resolvi a questão depois de muito penar.
Eis a solução que encontrei.
Obrigado pela sua ajuda.
<code>public static PdfPTable DRDRCriaTabelaCronogramaPDF(DataRow dr, iTextSharp.text.Font FontLinha)
       {
           PdfPTable tabelaCronograma = null;
           int NumAnos = Convert.ToInt16(dr["PeriodoAnosDiff"]);
           int AnoInt = Convert.ToInt16(dr["AnoInicio"]);

           tabelaCronograma = new PdfPTable(NumAnos * 12);
           tabelaCronograma.WidthPercentage = 100;
           PdfPCell CellMaster = new PdfPCell();
           for (int i = 0; i < NumAnos; i++)
           {
               CellMaster = new PdfPCell(new Phrase((AnoInt++).ToString(), FontLinha));
               CellMaster.HorizontalAlignment = 1;
               CellMaster.Colspan = 12;
               tabelaCronograma.AddCell(CellMaster);
           }
           CellMaster = new PdfPCell();
           int Mes = 1;
           for (int i = 0; i < NumAnos * 12; i++)
           {
               CellMaster = new PdfPCell(new Phrase((GeneralFuncs.DRDRRetornaLetraMes((Mes++).ToString())), FontLinha));
               tabelaCronograma.AddCell(CellMaster);
               if (Mes == 13)
                   Mes = 1;
           }

           Mes = 1;
           int MesInicio = Convert.ToDateTime(dr["DataInicioAcao"]).Month;
           int MesFim = Convert.ToDateTime(dr["DataFimAcao"]).Month;

           int AnoInicio = Convert.ToDateTime(dr["DataInicioAcao"]).Year;
           int AnoFim = Convert.ToDateTime(dr["DataFimAcao"]).Year;

           int AnoInicioProj = Convert.ToDateTime(dr["DataInicio"]).Year;
           int AnoFimProj = Convert.ToDateTime(dr["DataFim"]).Year;

           int IndiceMesInicio = Convert.ToInt16(dr["IndiceMesInicio"]);
           int MesesDeDuracao = Convert.ToInt16(dr["MesesDiff"]);

           for (int i = 0; i < NumAnos * 12; i++)
           {
               if (Mes >= IndiceMesInicio && Mes <= IndiceMesInicio + MesesDeDuracao - 1)
               {
                   CellMaster = new PdfPCell(new Phrase(" "));
                   CellMaster.BackgroundColor = new BaseColor(0, 150, 0);
                   tabelaCronograma.AddCell(CellMaster);
               }
               else
               {
                   CellMaster = new PdfPCell(new Phrase(" "));
                   CellMaster.BackgroundColor = new BaseColor(255, 255, 255);
                   tabelaCronograma.AddCell(CellMaster);
               }
               Mes++;
           }

           return tabelaCronograma;
       }
</code>
Answer: boa tarde aqui segue a minha tabela dinâmica com imagens.
<code>       PdfPTable table = new PdfPTable(4);

        PdfPCell cell = new PdfPCell(new Phrase(" "));
        table.AddCell(cell);

        cell = new PdfPCell(new Phrase("Produtos"));
        table.AddCell(cell);

        cell = new PdfPCell(new Phrase("Quantidade"));
        table.AddCell(cell);

        cell = new PdfPCell(new Phrase("Preco"));
        table.AddCell(cell);

        foreach (var item in detalhes_do_pedido)
        {
            Image fotos = Image.GetInstance(@"C:\imagens\" + item.Produto.ImagemUrl);
            ViewBag.foto = fotos;
            fotos.ScaleAbsolute(70, 70);
            table.AddCell(fotos);

            cell = new PdfPCell(new Phrase(item.Produto.Nome));
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(item.Quantidade.ToString()));
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(item.Produto.Preco.ToString()));
            table.AddCell(cell);
        }

        document.Add(table);

</code>

iTextSharp - Tabela dinamica


Will the ATP Year End No. 1 be awarded after the ATP World Tour Finals or the Davis Cup finals?

Question: Currently, in the ATP rankings, Roger Federer is, effectively, just 490 points behind Novak Djokovic with two tournaments, namely ATP Masters 1000 Paris & the ATP World Tour Finals.
Federer, to become No. 1, needs to finish ahead/beat Djokovic in both the tournaments. But if it so happens that Federer falls just short of Djokovic by say 200 points, Djokovic will be awarded the Year End World No. 1. But there is a catch here.
Federer still has to play the Davis cup final later in November & ATP ranking points are awarded to the players for winning Davis cup ties, the breakdown of which is here.
So if Federer wins 250 points through Davis cup, he will effectively overtake Djokovic & lead the rankings by 50 points. But will he be then crowned the Year End No 1 after the Davis cup finals? Or those ranking points will be considered for next year?
Comment: There are at least some sources which claim that Davis Cup may be a factor. For example, [here](http://www.rogerfedererfans.com/forum/topic/1637-important-clarification-on-whether-atp-points-of-davis-cup-final-tie-will-get-counted-in-2013-year-end-rankings-or-not/) and [here](http://ftw.usatoday.com/2014/10/roger-federer-number-one-atp-ranking-novak-djokovic-2014-no-1). I was not able to find this question  clearly specified in the ruleboo0k
Comment: [This article](http://www.atpworldtour.com/News/Tennis/2014/10/44/Paris-Monday-Djokovic.aspx) directly on ATP tour mentions that: "The 27-year-old Djokovic has a slender 490-point lead over Federer in the Emirates ATP Race To London going into Paris. There is a potential total of 2,500 points to be earned in Paris and at the Barclays ATP World Tour Finals, *with Federer also having the chance to earn possibly decisive points when he leads Switzerland in the Davis Cup final against France.* The Basel native is looking to become the oldest year-end No. 1 by some margin."
Comment: If you believe what is written here (he seems to know he's talking about) - the Davis Cup points *do* actually count towards the year end No. 1 ranking. The reason I had thought the year-end No. 1 was crowned after the World Tour Finals was because, in the past 12 years, it's been decided before the end of the year Davis Cup Final - the competition for year-end No. 1 has never been this close before. http://www.rogerfedererfans.com/forum/topic/1637-important-clarification-on-whether-atp-points-of-davis-cup-final-tie-will-get-counted-in-2013-year-end-rankings-or-not/
Comment: @Martin If it's on the ATP tour website, is it official enough? Also the link in earlier comment sounds confident of his rulebook assessment.
Comment: Well, it can probably considered official. (I would prefer seeing it mentioned somewhere in the FAQ or rulebook.) I will post this as an answer.
Answer: The article Djokovic looking over his shoulder in battle for No. 1, which is published directly on the ATP tour website, mentions that:

The 27-year-old Djokovic has a slender 490-point lead over Federer in the Emirates ATP Race To London going into Paris. There is a potential total of 2,500 points to be earned in Paris and at the Barclays ATP World Tour Finals, with Federer also having the chance to earn possibly decisive points when he leads Switzerland in the Davis Cup final against France. The Basel native is looking to become the oldest year-end No. 1 by some margin. Previously, Ivan Lendl and Andre Agassi both achieved the feat when they were 29.

To prevent link rot, I will also add a link to the version of this article on Wayback Machine.
Since I was not able to find anything about this in faq or rulebook, this article published directly on the ATP website is the closest thing to official standpoint of ATP I was able to find.
As already menioned in a comment I was able to find some other sources which say that DC finals can be a factor for Year-End No. 1. (Of course, any unofficial source can contain mistakes.) For example: 1, 2, 3,
4,
5,
6,
7,
8,
9,
10,
11. (Some of the sources I link there are internet discussions, some of them are blogs or articles. You'll have to decide for yourself to which extent you consider them reliable.)

I should clarify that I was able to find in the 2014 ATP Rulebook (internet archive) several things that are determined from the ranking after World Tour Finals (bonus pool) or even before WTF (commited players). But I did not find a mention of year-end no. 1.
I will copy here some parts from Chapter 1, which are relevant to this these topics:

I. ATP CIRCUIT REGULATIONS
...
C. Commitment Player
  A 2014 ATP commitment player is any player positioned in the Top 30 in the ATP 2013
  Rankings (singles) as of November 4, 2013.
D. Commitment
  ... 2014 Davis Cup points may be counted as one (1) of the best of six (6)
  in the Emirates ATP Rankings, however, it shall not count towards the commitment
  requirement of a commitment player. ...
...
G. ATP World Tour Masters 1000 & Barclays ATP World Tour Finals ("WTF") Bonus
  Pool
  Players in good standing shall be eligible for the bonus pool based upon the Emirates
  ATP Rankings as of the Monday following the Barclays ATP World Tour Finals in the
  current year.
Answer: Any points awarded to Federer for his Davis Cup play in November will go towards his ranking for the following year (2015). The World Tour Finals mark the end of the ATP regular season and the year-end number 1 is awarded (along with many other awards) following the end of the tournament in London. So Federer will need to secure the number one spot by the end of the World Tour Finals in order to be crowned year end No. 1. Basically, the season ends there in London, not on December 31st.
Comment: I would really appreciate a source. As Davis cup is played each year & it doesnt make sense to award ranking points for finals next year. Rather they could have scheduled the finals earlier than the ATP finals no?
Comment: I'm not able to find a source at the moment but I've been watching the men's game and follow the tournaments all year round for the past 20 years now. The year-end number one award and other awards like most improved, comeback player of the year, fan favorite, etc are all awarded right after the end of the world tour finals event. I just know that's how it's been for a long time now. Those Davis Cup points will get added to Federer's total the Monday following the DC tie, but that won't be in time to count towards the year-end number one ranking.
Comment: If you read the section "Battle for No. 1" on this page you will notice they make no mention of the Switzerland/France Davis Cup tie, only the Paris Masters and World Tour Finals. http://m.atpworldtour.com/News/Tennis/2014/10/44/Corona-ATP-Slice-27-October-2014.aspx
Comment: But Davis cup points were, very recently added to the ATP Ranking points. I guess we just have to wait for that particular scenario to arrive to find out then.
Comment: Also, I asked the question to @SteveTignor on twitter, but he hasn't replied to me yet. Any other renowned tennis writer or official or ex-players have mentioned this?
Comment: Though I don't know for certain,  my guess is that they don't wait to award the year end number one based on Davis Cup points because 1.) No points were awarded until recently and 2.) Not all of the top players are able to compete and participate in the Davis Cup final so it could be viewed as an unfair advantage. If I find any official source of info about it I will come back and post it here.
Comment: This page speaks about it as well and does not mention Davis Cup points in what makes up the year end ranking. http://www.atpworldtour.com/Rankings/Rankings-FAQ.aspx
Answer: As we can see in the ranking breakdown of Race to London, Djokovic still holds 150pts earned from DC final last year. I'm guessing that the Tour Finals mark the end of the season and DC cup final results are rewarded to the next season.
Comment: In [this discussion](http://www.menstennisforums.com/showthread.php?t=236585&page=61) it is suggested that they are counted in the race (which ends before WTF) but not in the year-end rankings. I quote: *So I am correct that the DC Final has the special disctinction of being the only event in which it is counted in the 2014 YE but also at the 2015 Race (because it happened after WTF 2014).* (Of course, it is not an official source.)
Answer: Yes. After the ATP World Tour Finals, Novak Djokovic's 150 points will be dropped and Davis Cup final points, which Roger Federer might win, will be added for Roger Federer. Race considers previous year's Davis Cup finals as well and not just the year end championship for the No.1 status. Some times ATP awards Player of the Year award which could be other than the one who holds no.1 ranking during the ATP Finals. It has happened once or twice in the past...km


What is this chord in Bach's Brandenburg Concerto No. 2?

Question: Can anyone tell me what chord Bach notated in the second half of measure 91 in the score below? I can see that the first chord in this measure is FMaj7, which is the end of a circle of fifths chord progression from the previous measure (90)...and the chord in question is used as a function for modulating to a new key of A Minor (92 and 93 consist of E7 and A Minor, 94 is in the new key of A Minor). The Chord in question seems mainly based on D and B, with viola playing a whole note of A, some F's on flute, oboe and violin, and some C's on Trumpet, but I'm not sure which notes are chromatic and what is the main chord notated here.
Comment: @Dekkadeci the top line is an F trumpet.
Comment: @AlbrechtHügli Check out the E in the fifth staff (Violin I, I believe).
Comment: Which line is the trumpet? Is it a C trumpet?
Comment: can you tell me where you can see a FMaj7 in measure 91? (Note that the e in the trumpet is actually an a)
Comment: yes, Richard, I that's right: I7
Answer: Since we're moving from a VI chord in A minor (first half of m. 91) to a V chord (first half of m. 92), standard practice suggests that the second half of m. 91 will be a chord that smoothly connects VI to V. Without even looking at a score, my guess is that the chord will be either a subdominant or supertonic of some type.
Looking at the score, the B in the bass strongly suggests a supertonic chord. Looking above it, we have B D F A, which pretty clearly lays out a Bø7 chord. With D in the bass, we're looking at Bø6/5.
The Cs in the trumpet are non-chord tones, either passing or neighbor depending on the circumstance. The same is true of the Es and Cs in the oboe.
Notice, then, that the circle-of-fifths progression that led into m. 91 continues, because F goes down a fifth to B, which goes down a fifth to E, which will ultimately go down a fifth to A.
Comment: Great answer, thanks Richard, sounds exactly right. I understand about the Bø7 chord, but would you mind explaining why the D in the bass makes it a Bø6/5? Thanks also for pointing out the circle-of-fifths continuation by the way.
Comment: Also just a little confused after thinking again about your first paragraph...because the circle-of-fifths progression actually came from the key of D minor in m.85 (so it's D minor, G min7, C, F Maj7). So I'm confused about the F Maj7 being a IV chord in A minor as it seems the change of key has not been reached yet. Also wondering why a B would be used in this circle-of-fifths progression rather than a Bb (which key would the B be diatonic to)?
Comment: @JohnMC The 6/5 is figured bass that indicates that it's a first-inversion seventh chord; I'm reading the D on beat 3 as the bass, but you could also view the B on beat 4 as the bass, putting the chord in root position. As for the Fmaj7, it's **VI** in A minor, not IV. We view this chord as being in A minor so that it's a diatonic common chord between D minor and A minor. If we wait until the next chord, the B isn't diatonic to D minor, so it can't be a common-chord modulation. The F chord moves to B, not B♭, since we're moving to A, which doesn't have a B♭!
Comment: Excellent response, I'm super clear now, many thanks Richard!
Comment: Sorry for misreading that about the VI chord by the way.
Answer: the modulation from F to am is introduced by Bm7-5 (am:IIm7b5)
(F:I => am: VI-ii-V-I46-V-I)
there is no F Maj7 in measure 91, and the f# on the last 8th note of measure 92  is the augmented 6th of the melodic monor scale.
Comment: Thanks Albrecht, and I see that f# now, thanks but do you mean the melodic minor scale? I thought the harmonic minor scale only raised the 7th?
Comment: Yes, John, of course. I'll have to correct it.


How do I mock User.Identity.GetUserId()?

Question: I am trying to unit test my code which includes the line:
UserLoginInfo userIdentity = UserManager.GetLogins(User.Identity.GetUserId()).FirstOrDefault();

I'm just stuck on one bit as I can't get:
User.Identity.GetUserId()

to return a value. I have been trying the following in the set-up of my controller:
var mock = new Mock<ControllerContext>();
mock.Setup(p => p.HttpContext.User.Identity.GetUserId()).Returns("string");

But it gives an error of "NotSupportedException was unhandled by user code". I have also tried the following:
ControllerContext controllerContext = new ControllerContext();

string username = "username";
string userid = Guid.NewGuid().ToString("N"); //could be a constant

List<Claim> claims = new List<Claim>{
    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username),
    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userid)
};
var genericIdentity = new GenericIdentity("Andrew");
genericIdentity.AddClaims(claims);
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });
controllerContext.HttpContext.User = genericPrincipal;

Based on some code I found on stackoverflow, but this returns the same error "NotSupportedException was unhandled by user code".
Any help as to how I proceed would be appreciated. Thanks.
Comment: The standard way to achieve that is to create a new service, i.e. `IIdentity` that abstracts your code from the `GetUserId` extension method and set it as a dependency on the code that is calling your `UserManager`
Comment: Just realized my original answer only worked for derived ApiControllers. Updated my answer with an option for derived Controllers as well, plus a second approach that works for both.
Answer: You can't mock extension methods directly, so your best bet is to drill down until you hit the properties and methods upon which the extension method depends that are mockable.
In this case, IIdentity.GetuUserId() is an extension method. I'd post it, but the library is not currently open source, so you'll have to see for yourself that GetUserId() depends on ClaimsIdentity.FindFirstValue(). As it turns out, that is also an extension method, but it depends on ClaimsIdentity.FindFirst(), which is marked virtual. Now we have our seam, so we can do the following:
var claim = new Claim("test", "IdOfYourChoosing");
var mockIdentity =
    Mock.Of<ClaimsIdentity>(ci => ci.FindFirst(It.IsAny<string>()) == claim);
var controller = new MyController()
{
    User = Mock.Of<IPrincipal>(ip => ip.Identity == mockIdentity)
};

controller.User.Identity.GetUserId(); //returns "IdOfYourChoosing"

Update: I just realized that the solution I posted above only works for derived ApiControllers (as in, Web API). The MVC Controller class doesn't have a settable User property. Fortunately it's pretty easy to go in through the Controller's ControllerContext to achieve the desired effect:
var claim = new Claim("test", "IdOfYourChoosing");
var mockIdentity =
    Mock.Of<ClaimsIdentity>(ci => ci.FindFirst(It.IsAny<string>()) == claim);
var mockContext = Mock.Of<ControllerContext>(cc => cc.HttpContext.User == mockIdentity);
var controller = new MyController()
{
    ControllerContext = mockContext
};

However, if all you're going to be using the User object for is to get the user's Id, there's another approach that will work for either type of controller and requires a lot less code:
public class MyController: Controller //or ApiController
{
    public Func<string> GetUserId; //For testing

    public MyController()
    {
        GetUserId = () => User.Identity.GetUserId();
    }
    //controller actions
}

Now instead of calling User.Identity.GetUserId() when you want the user's Id, you simply call GetUserId(). When you need to mock out the user Id in tests, you simply do it like this:
controller = new MyController()
{
    GetUserId = () => "IdOfYourChoosing"
};

There are pros and cons to both approaches. The first approach is more thorough and more flexible and uses seams that are already present on the two controller types, but it's also a lot more code and doesn't read nearly as well. The second approach is much cleaner and IMO more expressive, but it is extra code to maintain, and if you don't use the Func call to get the user's Id, your tests won't work. Choose whichever one works better for your situation.
Comment: +1 Configuring the call to `ClaimsIdentity.FindFirst()` solved my problem. Here is an example in FakeItEasy syntax for anyone using that: `var fakeClaim = A.Fake(x => x.WithArgumentsForConstructor(() => new Claim(ClaimTypes.NameIdentifier, FakeEmpIDString)));` `var fakeIdentity = A.Fake();` `A.CallTo(() => fakeIdentity.FindFirst(ClaimTypes.NameIdentifier)).Returns(fakeClaim);` My setup looks a little different; can't set Controller.User property directly so I inject a ControllerContext & set its HttpContext.User property to a ClaimsPrinciple object.
Comment: Oof. The second worked flawlessly. Did this for grabbing the UserID and worked like a charm!
Comment: @joelmdev, what if the id is customized to be a long instead of string? How does your first approach work in that case?
Comment: @avidProgrammer I believe you'd just swap out `var claim = new Claim("test", "IdOfYourChoosing");` with `new Claim("test", "1234567", ClaimValueTypes.Integer64);`. I haven't tested this, but if it doesn't work it should at least put you on the right path.
Comment: Great and very simple solution :-)
Comment: `System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: mock => mock.HttpContext`
Answer: You can't set up the GetUserId method because it's an extension method. Instead you'll have to set up the name on the user's IIdentity property. GetUserId will use this to determine the UserId.
var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x => x.Name).Returns("test_name");

See this for more info: http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.111).aspx
Comment: Turns out I was actually just doing something else stupid and this wasn't my issue at all. But your answer is correct. Thanks.
Answer: This worked for me
using fakeiteasy
        var identity = new GenericIdentity("TestUsername");
        identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "UserIdIWantReturned"));

        var fakePrincipal = A.Fake<IPrincipal>();
        A.CallTo(() => fakePrincipal.Identity).Returns(identity);

        var _controller = new MyController
        {
            ControllerContext = A.Fake<ControllerContext>()
        };

        A.CallTo(() => _controller.ControllerContext.HttpContext.User).Returns(fakePrincipal);

Now you can get values back from those IIdentity extention methods:
eg.
        var userid = _controller.User.Identity.GetUserId();
        var userName = _controller.User.Identity.GetUserName();

When viewing the GetUserId() method with ILSpy it shows
public static string GetUserId(this IIdentity identity)
{
  if (identity == null)
  {
    throw new ArgumentNullException("identity");
  }
  ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
  if (claimsIdentity != null)
  {
    return claimsIdentity.FindFirstValue(http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier);
  }
  return null;
}

So GetUserId needs the Claim "nameidentifier"


Inner product identity for cones

Question: Let $\emptyset \neq C\subseteq \mathbb R^n$ be a convex, open cone with the property that $\operatorname{int }C^* \neq \emptyset$, where $C^*$ denotes the dual cone defined by $$C^* = \{x \in \mathbb R^n: \langle x,y \rangle \geq 0 \quad \forall y \in C\}.$$
(always a closed and convex cone). Then we have for each $y\in C$
$$\inf_{x\in C^* \cap S^{n-1}} \langle x,y \rangle \geq c_y \lVert y \rVert$$ for some constant $c_y >0$.
I was unable to show this. I know that $C^* \cap S^{n-1}$ is compact and the inner product is continuous, so this attains a maximum. But I failed to see why it is impossible for this minimum to be $0$. Any help appreciated!
Comment: If you take $x=0$, then the inf is clearly 0.  What's to stop you from doing this?
Comment: $x = 0$ does not lie in the unit sphere.
Comment: Sorry- I was taking that to be a space of symmetric matrices...
Comment: $c_{y}$ is allowed to depend on the particular value of $y$, right?
Comment: What is $c_y$? ${}{}$
Comment: By definition, if $x \in C^*, y \in C$ then $\langle x,y \rangle \ge 0$. Choose $c_y = 0$.
Comment: Sorry if I was unclear. $c_y > 0$ should be a constant depending on $y$.
Comment: I think the key is that $C$ is a non-empty open cone.  If $C$ were a close cone, then $c_y$ would be 0 for any non-zero $y$ on the boundary.   Suppose $B(y, \epsilon)\subset C$ with $\epsilon>0$, then $\inf_{x\in C^*\cap S^{n-1}} \langle y,x\rangle \geq \epsilon$.
Comment: Sure, $C$ must be nonempty!
Comment: @irchans can you elaborate? How does this then imply the claim?
Answer: Big Hint:
I think the key is that $C$ is a non-empty open cone.
If $C$ were a close cone, then $c_y$ would be 0 for any non-zero $y$ on the boundary of $C$.   For example, suppose $C\subset R^2$ and $C=\{(x,0) | x\geq 0\}.$  Then $C^*=\{(x,y)| x\geq 0, y\in\mathbb R\}$.  Notice that
$C^*\cap S^{n-1} = \{(\sin t, \cos t) | 0\leq t\leq \pi\}$, so for any fixed $y\in C$, $y=(y_0, 0)$ and
$$
\inf_{x\in C^*\cap S^{n-1}} \langle y,x\rangle = \langle(y_0, 0),(0,1)\rangle=0.
$$
Hence $c_y$ would be 0.
On the other hand, if $C$ is a open cone and $y\in C\setminus\{0\}$, then there exist a positive number $\epsilon>0$ such that $B(y,\epsilon)\subset C$.  We know that $\langle c^*, y_b\rangle \geq 0$ for all $y_b\in B(y,\epsilon)$ and $c^* \in C^*$ by the definition of $C^*$ and the fact that $B(y,\epsilon)\subset C$. That implies that $\inf_{y_b \in B(y,\epsilon) } \langle c^*, y_b\rangle \geq 0$ for all $ c^*\in C^*$.  So now we can write that for any $c^*\in S^{n-1}\cap C^*$,
$$\langle B(y, \epsilon), c^* \rangle \geq 0,$$
$$\langle y - \epsilon c^*, c^* \rangle \geq 0,$$
$$\langle y , c^* \rangle - \epsilon||c^*||^2\geq 0,....$$
That line of reasoning should lead you to the answer.

Inner product identity for cones


Funcionamento do helper collection_select

Question: Bom dia, sou iniciante em rails e gostaria de saber qual o funcionamento do helper collection_select do rails, não consegui deduzir baseado nas explicações e no exemplos na documentação oficial.
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)

Answer: Olá, basicamente funciona da seguinte forma,
peguei da documentação oficial também https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_select
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
:post => Name do teu select, normalmente é a classe do seu model também
:author_id => Campo do seu model (na tabela de dados, que o Post está com o vinculo belongs_to :author), o que vai gerar o name do field por exemplo: post[author_id]
Author.all => É a lista com todos os autores no banco de dados, o método .all de uma classe herdada pelo ActiveRecord, vai lá no banco e busca todos os valores desta tabela
:id => Vai pegar o ID dos campos para preencher o value do select, que é o valor que irá para o controller quando submeter o formulário
:name_with_initial => Ele está pegando no model Author esta classe, que é o nome primeiro nome + o segundo nome, é o que irá aparecer em casa opção do select field
:prompt: true => Ele irá ter uma opção "vazia" no select, isso é bom, porque se não tiver, ele irá vir o primeiro valor encontrado com o Author.all e a pessoa pode selecionar "qualquer coisa" e nem se dar conta que este campo foi preenchido com o valor errado
Comment: Vê se meu pensamento está correto, o `:post` está representando a instancia que receberá o valor de `:id` no campo `:author_id`, esse `:id` é uma propriedade do modelo de Author. No HTML cada `option` possuirá a propriedade `value` com um valor de `:id` de cada valor da tabela Authors e a função `name_with_initial` retorna a primeira letra da propriedade `first_name` e o valor da propriedade `last_name` como output de cada `option` no `select`.
Comment: Se isso que eu disse estiver correto ainda me ficou a duvida, qual a necessidade do valor `post[author_id]` na propriedade `name` do `select` nesse exemplo, ele está fazendo algo?
Comment: os `params` que vão para o backend são nomeados pelo "name" do select, nesse caso.
Comment: no teu controller no caso, virá um hash + ou menos assim
`{ post: { author_id: 1 } }` sacou?
Comment: Entendi sim, obg pela ajuda!


Can someone clear up this statement on resisted motion (Dynamics)?

Question: Due to missing a lecture (for health reasons), I'm reading my lecturer's notes on the resisted motion of a particle where air resistance is proportional to the square of the particle's speed.
Here is what I gathered and understood well:

If a particle is fired vertically upwards, where the resistance is $\space mkv^2 \space$, in which $\space k \space$ is a constant and $\space v \space$ is the speed. We can express the equation of motion as:
$m \ddot{y} = -mk{v^2} -mg$
Hence:
$\ddot{y} = -k{v^2} -g$

Now here is where I get confused. The notes then proceed to say:

Had the particle been falling under gravity, the RHS would be:
$mg-mkv^2$
Taking $\space y \space$ as the distance fallen. The acceleration would be zero when:
$g=kv^2$
OR
$v=\sqrt{g \over k}$
This is the limiting speed usually written as $\space c \space$. Therefore $\space c=\sqrt{g \over k} \space$. Thus telling us that:
$k={g\over c^2}$
We can use this in the current model like so:
$\ddot y = -g - {gv^2 \over c^2} = -g\big( {c^2 + v^2\over c^2} \big)$

But why are we using it in the model?
Is that not assuming the particle is falling under gravity, when it's not? It's stated that the particle has been fired UPWARDS.
It's like we changed the rules to fit our situation. Is there something I'm not understanding?
Comment: k is the same constant whether it is going up or down.
Answer: That speed is just the "limiting speed", which everyone I've ever met refers to instead as "terminal velocity" but sure.  All that ended up happening is that your equation was re-scaled to account for terminal velocity, but everything else still works out (try it!).  It puts your equation into a form where something that is universally true for all such masses holds (namely, the terminal velocity), and I suspect it will let you work with this terminal velocity to do other things later.


How to interpret coefficients of interaction terms in logistic regression in these 2 scenarios?

Question: Let me give a simple example,
set.seed(100)
disease = sample(c(0,1),100,replace = TRUE)
snp1 = sample(c("AA","AB","BB"),100,replace = TRUE)
snp2 = sample(c("XX","XY","YY"),100,replace = TRUE)

summary(glm(disease~snp1*snp2, family = binomial))

output1
Deviance Residuals:
     Min        1Q    Median        3Q       Max
-1.55176  -0.94003  -0.00649   0.90052   1.53535

Coefficients:
                Estimate Std. Error z value Pr(>|z|)
(Intercept)   -8.109e-01  6.009e-01  -1.349   0.1772
snp1AB         5.232e-01  9.718e-01   0.538   0.5903
snp1BB         1.504e+00  8.580e-01   1.753   0.0796 .
snp2XY         4.074e-16  8.498e-01   0.000   1.0000
snp2YY         1.504e+00  9.280e-01   1.621   0.1051
snp1AB:snp2XY  1.135e+00  1.335e+00   0.850   0.3952
snp1BB:snp2XY  1.542e-01  1.254e+00   0.123   0.9022
snp1AB:snp2YY -1.216e+00  1.333e+00  -0.912   0.3616
snp1BB:snp2YY -2.785e+00  1.244e+00  -2.239   0.0252 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 138.63  on 99  degrees of freedom
Residual deviance: 127.71  on 91  degrees of freedom
AIC: 145.71

Output2
snp12 = interaction(snp1,snp2)
summary(glm(disease~snp12, family = binomial))

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-1.55176  -0.94003  -0.00649   0.90052   1.53535

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -8.109e-01  6.009e-01  -1.349   0.1772
snp12AB.XX   5.232e-01  9.718e-01   0.538   0.5903
snp12BB.XX   1.504e+00  8.580e-01   1.753   0.0796 .
snp12AA.XY  -3.990e-16  8.498e-01   0.000   1.0000
snp12AB.XY   1.658e+00  9.150e-01   1.812   0.0700 .
snp12BB.XY   1.658e+00  9.150e-01   1.812   0.0700 .
snp12AA.YY   1.504e+00  9.280e-01   1.621   0.1051
snp12AB.YY   8.109e-01  8.333e-01   0.973   0.3305
snp12BB.YY   2.231e-01  8.199e-01   0.272   0.7855
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 138.63  on 99  degrees of freedom
Residual deviance: 127.71  on 91  degrees of freedom
AIC: 145.71

Number of Fisher Scoring iterations: 4

So here I did a logistic regression for interaction between, lets say 2 mutations (each with 3 categories). Like shown above I can do it in 2 ways. My questions are,

Are both output1 and output2 same ?
If same, which one is more appropriate?
How to interpret the coefficients (and odds ratios) in each case?
Answer: 1 - Yes they are the same model parameterised differently
2 depends on which is easiest to interpret
3 - in the second case each of the eight cells is compared against the corner cell AA:XX. In the first case AB and BB are compared with AA (and similarly for XY, YY with XX) and then four extra terms tell you whether any of those cells needs an extra, so AB:XY is extra over and above what you would have expected from it being an AB and an XY. So for instance the predicted value for cell AB:XY is the intercept plus AB plus XY plus AB:XY
Comment: Edited a bit extra explanation
Comment: I didn't understand last part "then four extra ... and an XY". Can you please elaborate it ? Mainly I would like to know what each of the last four terms in output1 are compared to ? Thanks


count everything charter in string

Question: I'm sorry if this question is already asked on other threads but I just can't find my answer. I'm still a newbie at programming so please consider me :)
I need to create an application that lets the user enter a string and display the character that appears most frequently in the string.
1 Use a loop to select each character of the string
2 Inside the above loop, create a loop to compare the current character with each character in the a-z array
3 If a character matches, use the index to increment the current position in the integer array.
4 When the above loops have completed, loop through the integer array to find the highest count for a character
string = HELLLLOO
display = L
Any help would be much appreciated :)
Comment: what language are you using?
Comment: This sounds like a homework assignment. Does your teacher want pseudocode? What have you covered in class up to this point? Consider reviewing recent material for hints on how to do it.
Comment: Can you post what you've attempted so far?
Comment: I'm sorry guys if my question is unclear. I'm using C#. It is not an assignment though. It is just a weekly exercises and the numbered instructions is his tips for the exercise. I already attempted it but can't really figure it out.
Comment: I've already figured out the first part of the code. First, loop through the first character of the string, inside it another loop that compares the char with the first char in the a-z array. The part that confuses me is how to keep a count of every letter in the a-z array? And like what is mentioned above, how to use the index to increment the current position in the integer array and also in the string?
Answer: Of course, there can be more efficient or easy way. I just write a simple solution through C# without test.
<code>    string word = "HELLLOO";

    Dictionary<char, int> words = new Dictionary<char, int>();

    for(int i=0;i<word.length;i++)
    {
       if(words.ContainsKey(word[i]))
       {
          words[word[i]] = words[word[i]] + 1;
       }
       else
          words.Add(word[i],1);
    }
    char maxWord;
    int maxVal = 0;
    foreach (var item in words)
    {
      if (item.Value > maxVal)
      {
        maxVal = item.Value;
        maxWord = item.Key;
      }
    }
</code>
you can display maxWord as the most used character of a word.
Comment: Thanks Gokhan! That helped. Although there are some words I'm not associated with. Like the "Dictionary" word? In that part, you're declaring a array right? And also I haven't encountered the word ContainsKey in our class. We're using Microsoft visual studio 2010 by the way.
Comment: as I've written I used C#, I don't know language that you are using. if you use .NET framework It'll work and you can convert it easily to visual basic or any other language that part of .net framework, or C/C++ you can reach the same results through making small changes and dictionary is like associative array and it is already implemented in the framework.
Comment: Buddy you've just saved my life. :)

count everything charter in string


Array of zero length in java

Question: Below code
public class Example {
    static int[] member;
    public static void main(String[] args) {
        int[] ic = new int[0];
        if (ic == null){
            System.out.println("ic is null");
        }
        System.out.println(ic);  // [I@659e0bfd
        if(member == null){
            System.out.println("member is null");
        }
    }
}

It is obvious that elements can't be added in zero length array.
What does ic point to, if ic is not null?
As per below diagram, Is ic pointing to memory location 659e0bfd(which is empty)?
Answer:
What does ic point to, if it is not null?

It points an empty array of zero capacity. Arrays are reference types and memory space is allocated for them like any other reference type.
Comment: @overexchange The hash code which was output for the array may be related to the memory address, but it is not the memory address itself. See also http://stackoverflow.com/questions/2237720/what-is-an-objects-hash-code-if-hashcode-is-not-overridden
Comment: empty array at memory address `659e0bfd` as per above code?
Comment: @overexchange Yes `obj1 == obj2` checks if the two variables refer to the same object in memory. Java has no mechanism for getting memory address.
Answer: Imagine an array as a box. You can declare a box with some capacity, say 3
int[] x = new int[3];

and you'll get this box: [_,_,_]. You can fill it with some numbers
x[1] = 9;

to get [_,9,_]. What you did, instead, is declaring an zero capacity box
int[] x = new int[0];

to get this: []. And guess what happens if you try to add an element to it? You cannot.
So, to answer your question, what does ic point to? Your empty (and zero capacity) box.
Answer: ic refers to an empty array instance. It contains no elements (ic[i] would throw ArrayIndexOutOfBoundsException for each value of i), but it's not null.

Array of zero length in java


How to do core update with drush

Question: With which drush command can I update my Drupal 7.36 to 7.41?
I have tried so far the followings:

drush up drupal
drush pm-updatecode

But nothings has changed in either the code nor when I look at the currently pending updates.
Answer: Adi provided a good answer. So update the code with:
drush up drupal

But after that always preform database updates (if required):
drush updb

Answer: drush upc
should update all modules and core

How to do core update with drush


Evaluating a line integral over a curve

Question: I'm trying to solve the problem $\int_C x\sin(y)ds$, where C is the line segment from (0,1) to (4,4). This is my solution, which is wrong. I was hoping someone could tell me where I took a misstep.
Parametric equations: $x=4t$ and $y=1+3t$,
$\int_0^14t\sin(3t+1) \sqrt({4^2}+{3^2})dt$
$20\int_0^1t\sin(3t+1)dt$
after using integration by parts:
$20[\frac{-t}{3}\cos(1+3t)+\frac{1}{9}\sin(1+3t)]|^1_0$
which after simplifying gives:
$\frac{20}{9}[\sin(4)-3\cos(4)].$
Comment: what is the result that you are trying to get?
Comment: It looks like you just didn't plug in zero
Comment: When I plug in 0, I get 0/3 in the first term and sin(1) in the second term, which both would equal 0
Comment: you should get $-sin(1)$ together with the other two terms!
Comment: As soon as I posted that I realized what I said. Its been a long day haha. Thank you!
Answer: Notice that in the last passage you have:
$$20\left[-\frac{\cos({4})}{3}+\frac{\sin({4})-\sin({1})}{9}\right] = \frac{20}{9}\left[-3\cos({4})+\sin({4})-\sin({1})\right]$$

Evaluating a line integral over a curve


Azure VM cannot join domain controller

Question: I have setup a VM that is configured to be a Domain Controller and a second VM that I want to join to this Domain Controller. Both VM's are in the same Vnet with an Azure Private DNS Zone connected to this Vnet. Both VM's are in separate subnets and are able to ping each others private IP's and I am also able to ping the FQDN of my DC. Issue comes when I try to join the domain controller I get the following error message.
enter image description here
Issue is I am sure I have configured the A record correctly and I am able to ping the FQDN, so I am not sure why my VM cannot join the domain controller?
enter image description here
Comment: Have you configured your domain controllers to use the private DNS zone instead of windows DNS? It is not just A records that need to be created, AD needs to create a load of SRV records
Answer: You need to set DNS on the NIC or VM Level to point to the VM handling DNS request

Azure VM cannot join domain controller


Exchange 2010 Management Console missing

Question: I have installed the Exchange Management Console in Windows 10 Pro for manage a Exchange 2010 server. It connects to the server, even the Exchange Management Shell (Power Shell) connects without problem. But I'm stuck because the console tree shows only Microsoft Exchange -> Microsoft Exchange On-Premises (server.domain.com), but there are not any other nodes (Organization configuration, Server configuration, etc.)
I'm using a domain admin account, and also tried run the console 'as administrator' with the same result.
Exchange Management Console
Comment: You can add the answer and I will vote it, finally you took your time. Thank you
Comment: Yep -  https://onedrive.live.com/redir?resid=2516236AC4CD5FA3!6505&authkey=!ACFpD37m-tsbnys&v=3&ithint=photo%2cpng
Comment: What happens when you click on 'Microsoft Exchange On-Premises (server.domain.com)', any errors? Is the workstation on the same domain?
Comment: The workstation is in the same domain and the same VLAN. When I click there, the console connect with the server ("Initializing..."). Finally shows the same 'dashpanel' like the local console in the server: number of databases, servers, etc. There are links, for example: 'Manage Databases', and 'Manage Servers' but won't do nothing. The console tree won't open any other sub-node under the server.
Comment: Try deleting the following file: c:\users\\appdata\roaming\microsoft\mmc\Exchange Management Console
Comment: Also did you enable .net 3.5?
Comment: Tried delete the file: the same
.net 3.5 was enable (by default) like this https://onedrive.live.com/redir?resid=2516236AC4CD5FA3!6544&authkey=!AF_hZKAyngsYJ4U&v=3&ithint=photo%2cpng
Comment: @smwk look like EMC won't works on Win 10 (https://technet.microsoft.com/en-us/library/bb232090(v=exchg.141).aspx)
Comment: It's not supported alright but I was able to get it working on a test system. Guess you were just unlucky.
Comment: Thanks Hedmon, maybe someone else will find the answer helpful.
Comment: did you install IIS? http://www.exchangedictionary.com/solutions/install-the-exchange-2010-management-tools-on-windows-10
Answer: The Exchange 2010 Management Tools are only supported on Windows 7 or Vista. You may get lucky and have it work on Windows 10 but there is no support for this setup.

You can install the Exchange 2010 management tools on the following Windows operating systems:

Windows 7

Windows Vista with Service Pack 2 (SP2)

Windows Server 2008 SP2

Windows Server 2008 R2

Answer: Here is a great workaround to get Exchange 2010 console working on Windows 7, 8 also Windows 10.

Install Exchange 2010 SP2 Management Tools (make sure to install all the requirements first).
Copy Exchange Management Console.msc from any working computer (commonly it is in C:\Program Files\Microsoft\Exchange Server\V14\Bin).
Create a few folder on your C: drive (Something like ExchangeConsole) and paste the copied file (Exchange Management Console.msc from any working computer).
Rename the Exchange Management Console.msc file to admin.msc (inside C:\ExchangeConsole).
Create a .bat file (inside C:\ExchangeConsole).
Edit the bat file and write the following:
@echo off
set __COMPAT_LAYER=RUNASINVOKER
set COMPLUS_VERSION=v2.0.50727
admin.msc

Run the bat file every time you want to open the Exchange Console.


How to differentiate mouse selection from keyboard events in date input

Question: I am trying to differentiate between mouse and keyboard inputs in an input of type date:
template
<input type="date" (change)="onChange($event)">

controller
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  onChange(event) {
    // How to check if user used the mouse to select a date
    // or if he typed a date
    console.log(event);
  }
}

simplest stackblitz: https://stackblitz.com/edit/angular-zz2nbl
Is it possible? Do I need to subscribe to multiple, diffrent events?
Comment: Let me try in the demo :)
Comment: the problem is, that the (click) event is not behaving the way you would expect for the date input. An event gets fired when the user clicks on the down-arrow for example, but not when he selects a date. @Vega
Comment: The type is always `change` if I subscribe to `(change)` @Vega
Comment: If you combine it with the presence of (input) and (click), you can distinguish from where the event came ?
Comment: Something like this, although I feel you are looking for something a bit more complex : https://stackblitz.com/edit/angular-ovijfe
Comment: Thank you @Vega. I like simple over complex ;) The problem still is, that when we use the `(click)` event, we do not get an event when the user actually clicks on a date :( (the event gets triggered when the user clicks on the down-arrow to open the date-view)
Answer: Firs of all here are the definitions of click and change events as per MDN
Click Event

An element receives a click event when a pointing device button (such
  as a mouse's primary mouse button) is both pressed and released while
  the pointer is located inside the element.

Change Event

The change event is fired for <input>, <select>, and <textarea>
  elements when an alteration to the element's value is committed by the
  user. Unlike the input event, the change event is not necessarily
  fired for each alteration to an element's value.

Now if you see the click event is available to all elements but change is available to only input , select and textarea. Also is clear from the definition the latter is fired when the value of the element is changed/altered.
So in order to capture both the events Yes you will have to capture both separately like below.
<input type="date" #input [ngModel]="myInput" (change)="onChange($event)" (click)="onClick($event)" (keydown)="onKeydown($event)" >

export class AppComponent {
  isKeyboardChange: boolean;
  isDatepickerChange: boolean;

  onChange(event) {
    // How to check if user used the mouse to select a date
    // or if he typed a date
    console.log(event.type);
    if (this.isKeyboardChange) {
      console.log("Was changes using Keyboard");
    }

    if (this.isDatepickerChange) {
      console.log("Was changes using date picker");
    }
  }

  onClick(event) {
    this.isKeyboardChange = false;
    this.isDatepickerChange = true;
  }

  onKeydown(event) {
    this.isDatepickerChange = false;
    this.isKeyboardChange = true;
  }
}

Also with the above code you will see. When the user click on the input be it the date or the arrow, the logged value on the console will bee click and when he selects a different value from the current one the value logged will be change.
Also if you use tab to move between input elements click event wont trigger in that case focus will be fired.
Javascript Events: this is a list of events available to all the HTML Elements. This does not include the change event as its only applicable to input, select and textarea.
So the short answer to your question will be that every type of event you want to capture you will have to have a corresponding eventListener/eventHandler.
UPDATE: And in this case you might want to use keydown event which fires whenever a keyboard key is pressed down. So in this case when the user changes the value using a keyboard a keydown event will be fired just before change event and whenever a key is pressed down while the focus is on the input else if user uses the datepicker click will be fired just before change. Also when the user selects the date no click will be fired it will only fire when user clicks on the textbox to open the picker. So using these you will be able to figure out how the value was changed.
UPDATE2: edited to use keydown event instead of keypress as keypress does not captures the arrow keys and the input type date can be changed using arrow keys as well.
UPDATE3:
Browser Compatibility:

Chrome: OK
Firefox: OK
Safari: Does not support date picker
IE: Does not support date picker
Edge: Supports only date picker. But arrow keys are allowed to change the date when datepicker is open (this specific case need to be handled separately as user is actually using datepicker but arrow keys may give a false impression)

Below is a small demo for the same (not in angular) but will behave exactly how it will in angular. The principles are exactly same. Have updated the stackblitz demo and it logs the way user used to change the value i.e. keyboard or datepicker.
Stackblitz Demo

function onChange(event) {
  console.log(event.type)
}

function onClick(event) {
  console.log(event.type)
}

function onFocus(event) {
  console.log(event.type)
}

function onKeypress(event) {
  console.log(event.type)
}
<input type="date" onclick="onClick(event)" onchange="onChange(event)" onfocus="onFocus(event)" onkeypress="onKeypress(event)" onkeydown="onKeypress(event)">

Hope this helps :)
Comment: Hi @Manish. Thank you for the detailed answer. I am aware of the diffrent event types. The problem I am trying to solve it to know, wether the change to the date value was made by a click or by keyboard input. I don't think your example can demonstrate that?
Comment: Hi again! Could you link to the updated stackblitz? I think the one I've created is still unchanged?
Comment: Hey @Manish. I don't think your updated example solves my problem. In the resulting change event I still can't decide wether the user used the mouse or keyboard to initiate the change. Have a look at `sportzpikachu`s answer. He has it working the way I need it. But there I am not sure if the event order is always the same.
Comment: @Riscie thats correct the order wont be same as per the other answer. But with the update i have made the order will be always the same i.e keypress first and then change and click first and then change. Let me do one thing update the stackblitz accordingly
Comment: @Riscie update the answer and a working demo on stackblitz. Hope this solves your problem :)
Comment: Thanks again for your effort! This is now the same answer as sportzpikachus gave ;) I am still not sure wether the event order is the same in all browsers, right?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/207412/discussion-between-manish-and-riscie).
Comment: Thanks for clarifying and testing in diffrent browsers. Will accept this answer after the bounty-block-time.
Answer: Try using onMouseDown and onKeyDown. mouseLast would be a boolean whether or not the last event was mouseDown.
template
<input type="date" (change)="onChange($event)" (keydown)="onKey()" (mousedown)="onMouse()">
controller
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  onMouse() {
    this.mouseLast = true;
  }
  onKey() {
    this.mouseLast = false;
  }
  onChange(event) {
    if (this.mouseLast == undefined || this.mouseLast == null) {
        return;
    }
    console.log(this.mouseLast);
  }
}

Comment: Thank you for the answer. I was thinking about this solution. Can we actually be sure, that the `mousedown` and `keydown` event always fire before the `change` event? If this is the case and there is some documentation for this, I would look at this as a valid answer.
Comment: I did some research. It seems like the event order is not defined by the js standard. Browsers are free to implement them they want. However I see that it would always make sense to fire `mousedown` and `keydown` before `change`, so I am not sure wether the answer is correct in all browsers...
(reference: https://stackoverflow.com/questions/282245/dom-event-precedence)
Comment: Hey, @Riscie, sorry I couldn't get back to you earlier, but as you said, the `mousedown` and `keydown` events may not fire before the `change` event. So you could perhaps add a `if` statement to check whether or not `mouseLast` is declared? Hopefully that helps you! I've edited my answer to reflect these changes.


I broke aptitude

Question: I tried ro remove some unused packages in debian with aptitude.
Apparently I left some conflicting packages and now aptitude refuses to run (same as apt-get)
I get this error
apt-get: symbol lookup error: /usr/lib/libstdc++.so.6: undefined symbol: _ZNSt7num_getIcSt19istreambuf_iteratorIcSt11char_traitsIcEEE2idE, version GLIBCXX_3.4

The obvious thing for me would be to install aptitude again. But this is an egg and chicken problem...
What should I do? dpkg works.
Comment: What command did you run to remove "unused packages"?
Comment: I fooled around with aptitude itself. I think I created the havoc trying to remove X11 and gcc (I don't use those, it's a webserver).
Comment: LOL, had to give you a point for the title "I broke aptitude"
Answer: You could try to install it using the .deb file from packages.debian.org.
(scroll to the bottom of the page and select the appropriate architecture)
Comment: lucky me wget still works :-)
I had to download several packages but now everything looks ok.
Thanks
Answer: To fix this issue, I would immediately UNDO what you've just done; take a look at /var/log/dpkg.log for a history of what you removed, and reinstall those packages using dpkg and their respective .deb files from http://packages.debian.org.
If you still want to find out what package (specifically) caused this failure, use the same list of packages above, and uninstall them one at a time until you run into the error.

I broke aptitude


How to show price range

Question: I got Drupal 8 / Commerce 2 installation, and trying to create product category pages, showing product image, title and price range (min & max price)
I've created product category page with Views. Category is defined as Taxonomy reference field in product.
Views has "Contextual filter", where category name is taken from url e.g. /product/[category].
Product catalog page works fine, showing fields defined in (custom) Summary view mode. It shows title and the first product variation image and price.
Only thing missing is the price range info
I've tried to do some experiments by

overwriting commerce-product.html.twig in custom theme
writing hook__preprocess_commerce_product in custom module

..but with no luck. Debugging is hard because, for some reason kint() / dpm() calls fail or just take tooo long and give execution time out...
So the question is: how and where to check product variations lowest & highest prices plus pass them to product template?
Any hints or ideas are greatly appreciated.
EDIT:
I got it done by adding the following preprocess  hook to my custom module
<code>function CUSTOMMODULE_preprocess_commerce_product(&$variables) {

  $product = $variables['elements']['#commerce_product'];

  foreach( $product->variations as $variation) {
    $prices[] = $variation->entity->getPrice()->getNumber();
  }

  $min_price = min($prices);
  $max_price = max($prices);

  if ($min_price != $max_price) {
    $variables['min_price'] = $min_price;
    $variables['max_price'] = $max_price;
  }

  $variables['currency'] = $variation->entity->getPrice()->getCurrencyCode();
}
</code>
... And then in commerce-product--teaser.html.twig
<code>{% if min_price is defined and max_price is defined %}
  {{ min_price |number_format(2, '.', ',') }} -
  {{ max_price |number_format(2, '.', ',') }} {{ currency }}
{% else %}
  {{ product.price }}
{% endif %}
</code>
Answer: I don't think the min max would be readily available in the template and you'll have to add it in.
You could use hook_preprocess_commerce_product($variables) and within $variables it will contain the product entity and also all of its variations. You would just need to loop through the variations to work out the min and max price and then add the new value into $variables e.g.
<code>$variables['min_max_price'] = $myvalue;
</code>
Then in your template commerce-product.html.twig do:
<code>{{ min_max_price }}
</code>
and that should come out with your $myvalue value
Comment: thank you so much!! This lead me to the right track, and I managed to get this done with preprocess hook. Now just need to get it work with taxes etc. and find another way of debugging...since for some reason kint is not working very well with my installation :(

How to show price range


NAudio Play Silence without speakers

Question: I know that I can play silence audio like that
<code>var silence = new SilenceProvider(sourceStream?.WaveFormat).ToSampleProvider();
wo = new WaveOutEvent();
wo.Init(silence);
wo.Play();
</code>
but How can I play silence when no speakers are attached to the computer?

I want to capture realtime WASAPI audio but the callback don't get called up when nothing is playing, so I need to play silence
Answer: You can only play silence if your computer actually has an audio output device. If it doesn't then you'd need to find another workaround for the WASAPI audio (such as timestamping the captured audio to account for periods of silence).

NAudio Play Silence without speakers


Sanitizing Query Results Data

Question: In my customized module, I have queried a database value, Jocelyn D. Napiñas. It contains ñ that causes my code to break. Is there any way I can display it? I tried the following code.
$data;  //Contains `Jocelyn D. Napiñas`

drupal_convert_to_utf8($data, 'us_ascii'); //Returns false

check_plain($data); //Returns ''

How will I display it as Jocelyn D. Napiñas?
Answer: According to drupal_convert_to_utf8 it required Requires the iconv, GNU recode or mbstring PHP extension to work,  make sure mbstring Php extension installed(Go to /admin/reports/status and take a look at your unicode library) if not installed install it and try again
 drupal_convert_to_utf8($data , 'us-ascii');

if not worked  according to mb convert encoding you can let Php detect encdoing with AUTO, so  use
drupal_convert_to_utf8($data, 'auto');

Also  I can suggest another solution for you
iconv(mb_detect_encoding($data, mb_detect_order(), true), "UTF-8", $data);

Comment: @Qerjiuthn you are welcome, I getting happy when my solution save another guy time. we are here to help each other,
Answer: Try us-ascii instead of us_ascii. That's how it's written in unicode.inc

Sanitizing Query Results Data


Opening a workbook with VBA/macro is making it read only?

Question: I would like my code to open a workbook (always the same one), detect the first free row, write to just two cells in that row, and then save/close the workbook. This seems like a simple problem, but the macro seems to be opening a copy of the file, and then locking it for editing.
Can you see any errors in my open code? I know that the file opens and that the row search works, but then it 1. never writes to the cells, and 2. locks the file.
Function WriteToMaster(Num, Path) As Boolean

'Declare variables
Dim xlApp As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim infoLoc As Long

Set xlApp = New Excel.Application

'Specifies where the Master Move Key is stored
Set wb = xlApp.Workbooks.Open("DOC LOCATION")
Set ws = wb.Worksheets("Sheet1")

'Loop through cells, looking for an empty one, and set that to the loan number
infoLoc = firstBlankRow(ws)
MsgBox "First blank row is " & infoLoc & ". Num is " & Num

ws.Cells(infoLoc, 1).Value = Num
ws.Cells(infoLoc, 2).Value = Path

'Save, close, and quit
wb.Save
wb.Close
xlApp.Quit

'Resets the variables
Set ws = Nothing
Set wb = Nothing
Set xlApp = Nothing

'pieces of function from http://p2p.wrox.com/vb-how/30-read-write-excel-file-using-vb6.html
End Function

Thank you again, stackoverflow <3
Comment: does the workbook open as readonly when you do it manually?
Comment: do you get any error messages?
Comment: For future reference, the function [firstBlankRow comes from this question](http://stackoverflow.com/questions/12497804/finding-first-blank-row-then-writing-to-it/)
Comment: @SeanCheshire No it doesn't throw any errors, and I can make it write correctly to the current wkbk, which makes me think it's an error with the new workbook portion (and not the writing portion).
Comment: @ScottHoltzman Not that I can tell.
Answer: Do you need to open a new excel app just to open a workbook?
Can't you just do something like this:
Sub Macro1()

Dim wkb As Workbook
Workbooks.Open Filename:="\User Documents$\bob\My Documents\workbook_open_example.xlsx"
Set wkb = Workbooks("workbook_open_example.xlsx")

End Sub

Comment: Thank you so much. This solved half of my problem, and I think the other half was caused by a corrupted file of some sort...I restarted my computer and replaced my master file, and now the macro works as intended. I really appreciate it!


What Kind of Right-Hand Picking Technique is Being Used in This Lick?

Question: I'm having the toughest time learning this lick because I don't know if inside picking is being used or a double down stroke. This conundrum seems to be present in guitar riffs that use hammer on/pull offs instead of picking again. For example:

He picks the B string using a down stroke
Does he use another down stroke when going to the G string,
or does he pick the G string from the inside using an up
stroke?

I've slowed the video down but still can't get his picking pattern. I want to learn this common lick the right way, if I practice incorrectly I would be wasting my time. Please help!
Comment: It seems quite clear from the video. However, what makes you think this is the only way to do it? The learning process, without a teacher, is often hit and miss, but is made better with experimentation, rather than learning stuff parrot-fashion. This is not a rant, nor criticism; purely words of wisdom through (sometimes bitter) experience!
Comment: @Tim "it seems quite clear from the video"? So then, care to explain how he's picking?
Answer: The basic ingredient of the lick is this:

B -15-12----12--------
G -------14----14-12--
   D (p) D  U  D (p)

where D stands for "downstroke", (p) for "pull-off", and U for "upstroke".
The reason why this works well is that your right hand keeps moving in a regular pattern. The pull-offs give your hand the time to move back up, and so your right-hand movement remains constant. If you picked each note (i.e., no pull-offs) then you would get downstrokes and upstrokes at exactly the same notes as with that pattern (the pull-offs replace the upstrokes).
However, this is not the only reasonably way to play that lick, and if you find a way that works and that sounds good, it can't be wrong. It's especially important to get the timing right. Try and practice all possibilities that seem reasonable to you. It's only after having put in some practice time that you'll be able to judge which way works best for you.
Comment: thank you for your reply. So you're saying that repeating the downstroke twice (as in your great diagram) is better than doing an inside pick in order to "alternate" (an upstroke instead of a downstroke)?
Comment: @reddish: Well, it is one way that works well for many people. You can do it differently, but then you'll have a more irregular hand movement. It's very subjective and you simply have to try all options before you can decide what works best for you.
Answer: Seems like the right way is never to repeat the same stroke. In other words, if there is an upstroke, then a downstroke should follow, never two continuous downstrokes or upstroke as this would defeat the purpose of "alternate" picking. Strokes should only be repeated when doing sweeps or economy picking.
Found this guys with great info:
Comment: That's not what the guy in the other video is doing (see my answer). Also, this definition of "alternate picking" makes most sense if you pick *every* note. If you use legate (hammer-ons and pull-offs) things can be different.


JasperServer: how to change "Jaspersoft: Login" page name to our "Organization: Login" page

Question: How to change "Jaspersoft: Login" page name to our "Organization: Login" page, when we login on JasperServer default page name is Jaspersoft: Login? You can see in browser after login.
Comment: You can customize `WEB-INF\jsp\modules\login\login.jsp`
Comment: Can you tell me the exact location where i have to change "Jaspersoft: Login" to "Organization: Login" because i have tried to customize login.jsp but couldn't find how to change.
Answer: You can find in WEB-INF\jsp\decoratos\decorators.jsp
Here you will find Japsersoft default message you can edit that tile or you can edit in pro_nav_messages.properties found in bundles and print their and reflect this in your decorator.jsp
E.g.


Regression Interpretation

Question: i have a regression where dependent variable is a share variable that ranges between 0 and 100%.
And independent variables are % variables, like let's say % of people in a specific age group. Suppose, the regression equation is like Y=0.5X1,+0.3X2+intercept...
I want to know how to interpret. Can i say, for a 1% change in X1 (which is a percentage variable), the Y goes up by 0.3%? (keeping all other variables constant).Likewise, can we say, if i change X2 by 1%, Y goes up by 0.2%? (keeping X1 constant)
Also, how to quantify this part - keep all other variables constant. Should i keep the others at average?.Basically, i want to know mathematically, what number should i report for a 1% increase in X1 and 1% increase in X2?
Please let me know, thank you
Answer: Ok for simplicity, let's ignore the fact that your independent and dependent variable are percentages
$$y= intercept+ 0.5 x_1 + 0.3 x_2$$
Typically the interpretation is,

for every 1 unit increase in $x_1$, $y$ increases by 0.5
for every 1 unit increase in $x_2$, $y$ increases by 0.3

Now, let's add make all your variables percentages. The problem with this is that your model can predict outside of the range of what is possible. For example, if $intercept=0.7$ and $x_1=0.5$ and $x_2=0.5$ then $y=0.7+0.25+0.15=1.1>1$.
In effect, the percentage data is not a problem for independent(since these are already given to you) variables but it is a problem for dependent variables. Therefore, you need a mapping from $(0,1)$ to the ${\rm I\!R}$. The log transformation is a typical one (also known as logistic regression).
$$log(\frac{y}{1-y})= intercept+ \alpha x_1 + \beta x_2$$
So you should fit your model to estimate $\alpha$ and $\beta$ this way. The interpretation then becomes

for every $0.1$ increase in $x_1$, the log odds of $y$ increases by $0.1 \alpha$
for every $0.1$ increase in $x_2$, the log odds of $y$ increases by $0.1 \beta$

Regression Interpretation


What is the criterion value on sequential feature selection for binary classification?

Question: I have a set of data represented by 16 features and a binary classification (true, false). I want to determine which features are important using forward and backward sequential feature selection, i.e. can the results improve by leaving out features (backwards) or by adding features (forward). For validation I use a 10-fold cross validation.
The Matlab help page on SequentialFS states that I should use the misclassification rate for that.
It also states:

sequentialfs divides the sum of the values returned by fun across all test sets by the total number of test observations. Accordingly, fun should not divide its output value by the number of test observations.

Therefore i have a function (for Linear Discriminant analysis as an example) as follows:
function misclass = PartLDA(XT,yT,Xt,yt)
    lda = fitcdiscr(XT,yT);          %poerform LDA
    ldaClass = resubPredict(lda);    %prediction
    misclass=sum(ldaClass ~= yT);    %calculate missclassification rate
end

I call the function form a different function as follows:
X = SampleList;       %this are the 16 features
y = SampleClass;      %and the classification (true / false)

c = cvpartition(y,'k',10);  %create 10-fold cross validation
opts = statset('display','iter'); %show iterations

direction='forward' %or 'backward'

[fs,history] = sequentialfs(@PartLDA,X,y,'cv',c,'options',opts,'direction',direction)

As an example of running the code, i get the following output
SequentialFS using LDA on sample Sample5
Start forward sequential feature selection:
Initial columns included:  none
Columns that can not be included:  none
Step 1, added column 12, criterion value 1.65698
Step 2, added column 1, criterion value 1.23336
Step 3, added column 15, criterion value 1.07029
Step 4, added column 11, criterion value 0.997188
Step 5, added column 16, criterion value 0.922212

My question is: What does the criterion value actually mean? It is quite clear that a smaller number seems to be the result of a smaller misclassification rate, however I am confused why the criterion value can be bigger than 1? Is that feasible? Because of the description of the sequentialfs quoted above, shouldn't the criterion value always be smaller than 1? Or do I have to divide the misclassification variable by the number of samples?
Comment: I have the same question. Another question that I have is that are these features listed in decreasing order of their importance? Like more important features appear first int the list, other appear later?
Answer: The criterion value is the output of your function PartLDA - in your case its the misclassification rate but it can also be any other measure that you are trying to minimise, e.g. RMSE in a linear regression model.
In your case it is the number of misclassified samples divided by number of folds. Given that you are running 10-fold CV this appears to be an estimate of misclassification rate expressed as a percentage.


How can I solve this difference equation, if $p=q$?

Question: I'm trying to solve the difference equation
$$
pE_{k+1} - E_{k} + qE_{k-1} = -1
$$
given the boundary conditions $E_{0} = 0, \; E_{a} = 0$, if $p=q=\frac{1}{2}$
To attempt this, I first found and solved the characteristic polynomial, as follows:
$$
p \lambda^{2} - \lambda + q = 0 \\
\iff (p \lambda - q)(\lambda - 1) \\
\iff \lambda_{1} = \frac{q}{p}, \; \lambda_{2} = 1
$$
But since we know that $p=q$, we know that $\lambda_{1} = \lambda_{2} = 1$. Thus, the general solution to the homogeneous difference equation would be
$$
E_{k} = Ak + B
$$
I have then found that
$$
E_{k} = \frac{k}{p-q}
$$
is a particular integral for this equation, so we no that the solution to the inhomogeneous equation would be
$$
E_{k} = Ak + B + \frac{k}{p-q}
$$
Finally, the boundary conditions $E_{0} = 0, \; E_{a} = 0$ can be used to find the constants $A$ and $B$, as follows:
$$
E_{0} = A(0) + B + \frac{0}{p-q} = B = 0
$$
and
$$
E_{a} = A(a) + \frac{a}{p-q} = 0 \Rightarrow A = -\frac{1}{p-q}
$$
Thus, our exact solution would be
$$
E_{k} = Ak + B + \frac{k}{p-q} = -\frac{k}{p-q} + \frac{k}{p-q} = 0
$$
Why has my final solution come out as $E_{k}=0$?
Comment: Mean exit time of simple random walk from interval (0,a)... This could be mentioned.
Comment: How your particular integral is $E_K=\frac{k}{p-q}$ as $p=q$ ?
Comment: Particular Solution = General Solution + Particular Integral
Comment: I mean the particular integral
Comment: Using a trial PI of the form $ck$ for some constant $c$ and subbing it into the original difference equation to find the value of the constant $c$ in terms of $p$ and $q$.
Comment: Sorry, I should have said that $p=q=0.5$.
Comment: Did you understand how the difference equation is solved ? $E_k$=\frac{k}{p-q}$ is not a particular integral. It is even not defined, because of the denominator.
Answer: Because the RHS is $-1.1^k$, this means that you should search for particular integral of the form $ck^2$, where the square is because $\lambda =1$ is a double root of the characteristic equation.
Then, plugging it in the difference equation:
$$\frac{1}{2}c(k+1)^2-ck^2+\frac{1}{2}(k-1)^2=-1$$
$$c=-1$$.
So your general solution is $E_k=Ak+B-k^2$. From the initial conditions $E_0=E_a=0$:
$$0=B$$
$$0=Aa+B-a^2\Rightarrow Aa-a^2=0\Rightarrow a(A-a)=0 \Rightarrow A=a\Rightarrow E_k=ak-k^2$$
Comment: $E_a=0$ gives $A=a$ and $E_k=k(a-k)$.
Comment: @LutzL I thought, it is not $a$ but $1$, i.e $E_0=E_1=0$ as initial conditions. I will correct it.


Table, TR each 2 loop, PHP, HTML again

Question: I've has help with the problem: Table, TR each 2 loop, PHP, HTML
But it still doesn't work, so I post my loop structure, because if I add:
        if($i % 2 == 0) {
            echo '

';
        }

It doesn't even close & re open the table row (tr).
Here is my loop structure:
    $similar .= '
';
    $similar .= '
';
    while ($row = $db->fetch_array($query)) {
        $similar .= '

                    Pojedynek #' . $i . ':

' . $wT . '

' . $oT . '

                    ' . $wContent . '

przeciwko

                    ' . $oContent . '

            ';
        if($i % 2 == 0) {
            echo '

';
        }
        $i++;
    }
    $similar .= '

';

Comment: just tested that weirdly enough, not initialising `$i` produces a notice but `$i++` dutifully produces 1 so it's not that
Comment: yeah, I've added $i = 0 before the 'while' loop.
Answer: You need to put $i = 0 outside the loop, not initialising it means it will be initialised with zero every time your loop goes round and your if statement will either always fire or never fire
Comment: I did, just forget to paste it.

Table, TR each 2 loop, PHP, HTML again


A tough logic puzzle

Question: I took a course on logic a few semesters ago so am having trouble remembering certian concepts. I came across another problem in one of my classes yesterday and am not sure how to solve it exactly. Could I use resolution to solve the following
A, B, C, D, and E all live in a house together.

If A is at home then so is B
Either D or E, or both are at home
Either B or C, but not both are home
D and C are either both at home or both not at home
If E is at home then A and D are also at home

The question asks, who's at home and who isn't?
If I remember correctly, resolution is used when we want to determine if an argument is valid. If the conjunction of the premises and negated conclusion leads to a contradiction (an empty set), then the argument is valid. However, this isn't that type of question. I tried using it and ended up with the following clauses
$$D \vee \neg E$$
$$B \vee D$$
This can't be resolved further. So either I made a mistake or we can't use resolution here. How else could this problem be solved?
Thanks for the help
EDIT
Here's what my resolution looked like
I converted the statements into clauses
$$\neg A \vee B$$
$$D \vee E$$
$$B \vee C$$
$$\neg B \vee \neg C$$
$$\neg D \vee C$$
$$\neg C \vee D$$
$$\neg E \vee A$$
$$\neg E \vee D$$
Comment: Logically, of course! :-P
Comment: Well, seeing how only C and D are home, this turns out to be a fairly poor deal for the other three roommates.
Comment: How did you reach that conclusion?
Answer: Either $E$ or $\neg E$. If $E$ then $A\land D$, hence $B\land C$, a contradiction. On the other hand $\neg E$ implies $D$, then $C$, then $\neg B$, then $\neg A$. Since this truth assignment for $A,B,C,D,E$ is compatible with the givens it follows that only $C$ and $D$ are at home.
Comment: I've fixed your answer because clearly you want to have $C \land D \land \neg A \land \neg B \land \neg E$, not just "$C \land D$".
Comment: @user21820: Thank you. Its clearer now.
Comment: You're welcome! =)
Answer: You must have made an oversight.  We can show D is home.  If E is home, by 5 so is D.  If E is not home, by 2 D is.  Then 4 tells us C is home.  3 tells us B is not.  1 tells us A is not.  Then 5 tells us E is not.
A mechanical approach would be a truth table, though it has $32$ lines.  Make one and see which of your clues come out true for each line.  There should be only one line where they all come out true.  If there is more than one, you can cite that to show the puzzle is flawed.
Edit:  it appears you missed the inference that $(D \vee \lnot E) \wedge (D \vee E)\implies D\vee (E \wedge \lnot E) \implies D$
Comment: This question asks to use resolution.
Comment: @DougSpoonwood, the OP's specific question is "How else could this problem be solved?"  This answer shows how else.
Answer: I use Polish notation.  The clauses now read as follows:

ANab
Ade
Abc
ANbNc
ANdc
ANcd
ANea
ANed

To prove any member of {a, Na, b, Nb, c, Nc, d, Nd, e, Ne} we can assume it's complement C.  Then if we deduce a contradiction by resolution, the complement of C will have gotten proved.
To show that we can't deduce any member of the above set with 8 members requires more work.  We can basically show that we can only deduce a certain number of formulas by resolution and then indicate that such a set of formulas doesn't have any instance of $\alpha$ and N$\alpha$.  Consequently, that formula can't get deduced.
For an example of the latter, let's assume that Na holds.
Assumption 9 Na

Only 7 has 'a' as one of it's disjuncts, and thus we can only deduce 'Ne' so far.
9, 7      10 Ne

Now only 2 has 'e' as one of it's disjuncts, and thus the only new formula we can deduce is 'd'.
10, 2     11 d

Only 5 has 'Nd' as one of it's disjuncts, and thus the only new formula we can deduce is 'c'.
11, 5     12 c

Now both 4 and 6 have 'Nc' as one of their disjuncts.  But 12, 6 yields 'd' which we have in our set of derived formulas so far.  But, we can derive 'Nb' as a new formula.
12, 4     13 Nb

Now, 1, and 3 have 'b' as one of their disjuncts.  But, 13, 1 as well as 13, 3 yield a formula already in our set of derived formulas.  Thus, given Na, we can only derive formulas in the set {Na, Ne, d, c, Nb}.  We don't have a literal and it's complement there, and thus we can't deduce a contradiction.  Therefore, 'a' is not provable here.
Here's an example of proving one of the eight formulas.
assumption 14 a
1, 14      15 b
4, 15      16 Nc
5, 16      17 Nd
17, 2      18 e
17, 8      19 Ne
18, 19     20 {}

Thus, since 'a' leads to a contradiction, 'Na' holds true.  And we have a bonus of sorts.  Since 'Na' holds true, the above disproof of 'a' as true tells us all five formulas which hold here.
In other words, A is not at home, E is not at home, d is at home, c is at home, and B is not at home.
Answer: You have 5 variables to start with, however,

3. Either B or C, but not both are home
4. D and C are either both at home or both not at home

These allow you to assume $B = \lnot C$ and $D = C$, so you can reduce the problem to 3 variables, $A, C, E$.

1. If A is at home then so is B
2. Either D or E, or both are at home
5. If E is at home then A and D are also at home

$$(A \implies B) \land (D \lor E) \land (E \implies (A \land D))$$
Becomes
$$(A \implies \lnot C) \land (C \lor E) \land (E \implies (A \land C))$$
Now there are only 8 cases left over.  For this formula it is easier to exclude cases 1 clause at a time:
$(A \implies \lnot C)$ excludes $\{T, T, T\}$ and $\{T, T, F\}$.
$(C \lor E)$ excludes $\{T, F, F\}$ and $\{F, F, F\}$.
$E \implies (A \land C)$ excludes $\{T, F, T\}$ and $\{F, T, T\}$ and $\{F, F, T\}$.
That excludes 7 cases, the only remaining case is $\{F, T, F\}$, so

$$A = \text{False}, B = \lnot C, C = \text{True}, D = C, E = \text{False}$$

However, this was a special case of proposition that can be reduced from 5 variables to 3 variables.  In general, there is no known technique for checking propositions faster than just checking every single case.
Comment: Haha you're wrong about your last claim; look up SAT solvers, which can find a satisfying assignment asymptotically faster than checking all cases (https://en.wikipedia.org/wiki/Boolean_satisfiability_problem#Algorithms_for_solving_SAT). If P = NP then there would even be a polynomial time algorithm, though most if not all complexity theorists believe that P != NP.
Comment: Read the first sentence of your link: "only algorithms with exponential worst-case complexity are known for it."
Comment: You're making a common error. $f \in 2^{O(g)}$ does not mean $f \in O(2^g)$.....
Comment: Next time don't be so quick to assume that someone else is wrong unless you really know what you're talking about. =)

A tough logic puzzle


Fastapi and Pydantic: How to nest objects?

Question: Let's say I have an object "user" and an object "article".
It is defined (in a simplified version here) in Pydantic as:
class User(BaseModel):
    id: int
    name: str

    class Config:
        orm_mode = True

and
class Article(BaseModel):
    id: int
    text: text
    author_id: int

    class Config:
        orm_mode = True

Now, I want the following to fall out of fastAPI:
{article: {"id": 1, ""text":"article text", "authorId": 1}, author: {"id":1, "name": "Bob"}}

How do I do this with pydantic? Do I create an extra class with nested dicts? Is there another way? What is the elegant way to do so?
Answer: Create a schema that describes the response you want:
class ArticleResponse(BaseModel):
    article: Article
    author: User

You then configure this as the response model for your view with response_class=ArticleResponse in your view decorator:
@router.get("/{article_id}", response_class=ArticleResponse)
def ..:
    return ArticleResponse(article=article, author=article.author)