Usar underline em C# seria uma boa prática?

Question: A pergunta é referente a padrão de desenvolvimento e boas práticas.
Eu venho de um mundo JavaScript e PHP, trabalho há 12 anos com desenvolvimento, e estou muito acostumado a usar underlines _ nas variáveis, como por exemplo nome_completo.
Porém estou iniciando a desenvolver em C# e não é costume fazer isso em linguagens de alto nível, na faculdade quando eu vi Java já percebia isso, é costume se escrever nomeCompleto.
Se eu continuar a utilizar underlines no desenvolvimento em C#, seria uma boa prática? Alguém utiliza este padrão também? Ou eu vou ter que ceder e mudar este comportamento?
Answer: Nem é boa e nem é má prática, é estilo.
Sem falar que boa prática costuma ser uma regra sem explicação, então a pessoa toma como algo bom sem nem saber porque e acaba virando má prática porque ela usa algo que potencialmente bom do jeito errado e se torna ruim. Se as pessoas desapegassem dessa ideia de boa prática programariam melhor.
Pode ser usado normalmente, a linguagem aceita, então não é ruim, se fosse, ela proibiria.
O padrão que se convencionou adotar em C# é não usar _ nem no início, nem no meio dos identificadores de todo tipo. Algumas pessoas violam isso, mas fica estranho para quem está acostumado com códigos nessa linguagem.
Hoje o underline tem semântica específica na linguagem (descarte de valor) usando sozinho (sem outros caracteres), então pode dificultar um pouco a leitura de alguns códigos, nada grave, mas cria alguma confusão visual.
Isso nada tem a ver com a linguagem ser de alto nível, depende de cultura criada, só isso.
Só lembrando que JS não adota esse estilo também (Google, Douglas Crockford), algumas pessoas adotam. Em PHP é inconsistente. Então provavelmente não seguia a tal da "boa prática".
Se fizer assim em C# seu código parecerá alienígena para outras pessoas, prefira o pascalCase ou CamelCase, dependendo do cenário.
Coloquei no GitHub para referência futura.
Comment: Obrigado pela opinião, realmente pareceria alienígina, concordo contigo. Em todas as empresas que eu trabalhei existe a briga "se usa ou não usa underline", é semelhante à briga "chave na mesma linha ou chave embaixo" (sou do time chave embaixo hehehe)
Comment: Não é uma opinião, é um fato, não damos opiniões aqui.
Comment: ok, obrigado pelo fato
Comment: @Maniero, mas o JS usa underline sim.
Comment: @Miriancherbo eu citei duas referências você pode citar as suas.
Comment: @Maniero, citou sim, mas não são links oficiais da linguagem ou do criadouro dela. https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Vari%C3%A1veis
Comment: @Miriancherbo Mas são guias os que as pessoas seguem. O que você citou não é um guia, e mesmo que fosse não seria oficial porque não existe um oficial. Poder usar não quer dizer que deve usar.
Answer: O que eu lhe recomendo é usar a convenção de nomes da equipa ou projeto em que você está inserido. Isso é mais importante do que "debater qual convenção de nomes é melhor usar".
Fazendo isso você garante que todos os programadores usam a mesma nomenclatura e se entendem. No final o projeto no mínimo será consistente a nível de nomes, o que acaba valendo bem mais do que parece. E também limita a margem para brigas uma vez que todos usam a mesma convenção de nomes.
Agora se você vai começar um projeto novo, sendo sozinho ou com uma equipa em que você decide a nomenclatura, pode optar por qualquer uma. Até pode ser que todos os programadores estejam mais habituados a snake case (os underscores) e que sejam mais produtivos dessa forma.
Vale salientar que a Microsoft definiu os padrões de nomenclatura que eles recomendam, como o @Maniero já mencionou, e são os que deve seguir caso não tenha uma opinião forte para optar por um deles.
Se seguir os padrões de nomenclatura definidos pela Microsoft, o seu código sai com a nomenclatura mais utilizada no mundo C# e por isso o seu código será mais natural a outros programadores C# e vice versa.


Guitar Headphone pre-amp with output jack?

Question: Ok, guys Ive tried to search the site for a similar question to no avail. Since I know little on the subject I will describe it and Im sure youl get the just.
I ocasionally play acoustic guitar in Church. All instruments go to the central mixer+amp. No special guitar amp whatsoever. Reference speakers no good. I need a mini-preamp to plug in my guitar, that works as a bluetooth emitter or has a headphone plug (to use as reference) and also has a regular output jack to go to the central mixer+amp. All Ive seen are wireless mini preamps but they dont have a regular output jack and the main mixer+amp does not have wireless reception.
Is there such a thing?? Excuse my poor techical knowledge and English.
Answer: Yes, those exist. Look for a 'guitar headphone amplifier' with a line output.  Some headphone amps don't have a line out, so make sure to check the specs.
Examples: cheap one, another
Comment: I have one of those Vox beasts, and they work well and fit your criteria, but you may find them to be noisy.
Answer: Ok, after carefully inspecting the above shown examples thats not exactly what I need. Taking some time I could find these two, just want to be sure if they work the way I want and if you can think on a cheaper alternative.
https://www.sweetwater.com/store/detail/iRigHD2--ik-multimedia-irig-hd-2-guitar-interface-for-iphone-ipad-mac-and-pc
https://www.sweetwater.com/store/detail/iRigNanoRd--ik-multimedia-irig-nano-amp-mobile-micro-guitar-amp-and-ios-interface-red
Comment: Make sure those are usable without connecting a phone or computer.
Comment: and was there anything specific you missed in my suggestions?


Heavy vs light tail distributions when modelling with outliers

Question: I am reading this lecture notes on using the MLEs from other distributions (as Laplace) rather than a Gaussian when dealing with outliers. The lecture notes came from Oxford University: https://www.cs.ox.ac.uk/people/varun.kanade/teaching/ML-MT2016/lectures/lecture03.pdf.
Probabilistically, we may view this as follows: the Gaussian distribution has very light 'tails', i.e., there is very little probability mass a couple of standard deviations away from the mean. Thus under this model outliers are very very unlikely and so the model will not treat them as such and try to fit a model that accounts for them rather than ignoring them. Instead, we can model the noise using a distribution that has heavier tails.
My question is this:
Seeing that a Laplace distribution has a heavier tail compared to Gaussian, isn't it true though that there will be even less 'mass' on the tails of Laplace a few standard deviations from its mean? (I am just going by the logic that is presented by the paragraph above, which came from the lecture notes.)
I understand the motivation why there is a need to look for alternatives than the Gaussian when dealing with outliers, but I fail to understand how Laplace is able to solve this problem.
Comment: "Seeing that a Laplace distribution has a heavier tail compared to Gaussian, isn't it true though that there will be even less 'mass' on the tails of Laplace a few standard deviations from its mean?"  -- Can you clarify what logic you used to arrive at this? I followed the information from the linked notes but I cannot discern how you arrived at this conclusion.
Comment: The proportion beyond 3 s.d.s above the mean is much higher for the Laplace (more than 5 times as much).
Comment: [Related?](https://stats.stackexchange.com/questions/484866/masking-problem-in-outlier-detection/485741#485741)
Comment: @Glen_b In the case of the Gaussian distribution (lets say Normal(0,1)), 99.7% of the data has already been observed. This means the probability of observing beyond the positive third standard deviation would be 0.15. Now in the case of the Laplace distribution, since it has a heavier tail, then the probability of observing beyond the positive third standard deviation would be less than 0.15, isn't it? I still don't understand how Laplace is able to do the job.
Comment: That's the gist of the link I posted, that outliers pump up the variance.
Answer: Laplace is able to solve the problem because it is robust to outliers.

Check the figures above: observe how Laplace fares against outliers compared to that of Gaussian.
As explained in $\rm [I], $ heavy tails

assign higher
likelihood to outliers, without having to perturb the straight line to "explain" them.

More importantly, as noted in the lecture note linked by OP, the mle involves the minimization of absolute difference while that of Gaussian involved quadratic penalization of the outliers.

Source of Figure & Reference:
$\rm [I]$ Machine Learning: A Probabilistic Perspective, Kevin P. Murphy, MIT Press, $2012, $ fig. $2.8, $ p. $40;$ sec. $7.4, $ pp. $223-224.$
Answer: To address the issue with the tails, note that the log-density of the Laplace is linear either side of the mean, while that of the Gaussian is quadratic.
Clearly, then, as you head out into the tails, eventually the density of the Laplace must be higher than for the Gaussian. To set the mean and variance to be the same, it is relatively simple to take the standard normal, and we then set $b=\sqrt{\frac12}$ for the Laplace. Equating the log-densities we get a quadratic to solve; the Laplace density is higher from about 2.339 standard deviations either side of the mean.

This is what the document you're reading means by the Gaussian having 'less mass' on the tails.
You were comparing the entire probability beyond a specific point. In many ways that's a better way to compare tail weight of the distribution*.
For that way of comparing the two, the cdf (on the left) and survivor function (on the right) of the Laplace will be higher than those for the normal beyond about 1.68 standard deviations above the mean.

* though something else again makes a better way of comparing the way that data is weighted in the sense of a weighted mean, say -- not that it's critical for the present point


influence of the bridge on how much a guitar "chugs"

Question: Long story short, I am wondering about the influence that the bridge (considering always the same type - a Floyd Rose-like bridge) has on how much the guitar chugs.
To expand a bit more. I have recently acquired a USA BC Rich Gunslinger. At first, I noticed that the guitar was chugging less than the two other guitars I have: a Jackson DXMG (with a Jackson licensed Floyd Rose bridge) and another Jackson SL2Q MAH (with a Floyd Rose 1000 series). It is difficult to define 'chugging' in words, but this video (as well as all the video series from Ola Englund) demonstrates what I mean by 'chugging'. Chugging 'less' means that, whatever the root cause is (my theory is that the bridge has an influence), it feels that the sound is excessively palm mutted
At first I thought it could have been the pickup (Dimarzio X2N), so I swapped by a EMG81. The tone changed, of course, but not enough chug. Then I realised that the guitar was not properly setup (at all). I then took it to a guitar tech, where frets were polished, crowned, nut was shimmed etc. The setup was certainly done very well. Though I still notice that the BC Rich chugs less than the Jackson.
I am starting to thing that this might be due to the bridge. It has the original one, which appears to be good stuff (Made in Japan Takeuchi licensed Floyd Rose), although I have the impression that this bridge appears to be way too sensitive to palm muting i.e.  in order not to mute it excessively, I have to place my picking hand quite far on the back of the bridge, towards the saddles, otherwise it mutes way too much. This difference (where I place my picking hand) is noticeable compared to the bridges of my two other Jackson guitars, which supports my theory that the lack of chug (which is kinda like muting the strings excessively) can be caused by how the bridge is designed.
I really like this guitar, though it still does not have the tone as I want it to be. So I was wondering if I can expect a noticeable difference in tone if I swap the bridge (by a Gotoh, Schaller or Floyd Rose). Has anyone done that, and noticed a clear difference in how much a guitar can chug?
Comment: Would you be able to explain a little more what you mean by 'to chug' here? I'm aware of the technique of playing palm muted chords, and what that sounds like; I can imagine different types of 'chugs', but I don't really understand what would be meant by chugging *more* or *less*.
Comment: @topomorto. yes fair point, I have edited my question
Comment: You did not discuss your amplifier or effects chain. These are far more important to "chug" than any bridge. You swapped to EMG-81 (likely a good move) and claim the BC Rich "chug's" less than the jackson. You did not indicate the pickups in either jacksons.  You may be comparing apples to oranges. Pups matter.
Answer: Assuming your Pickups on the jacksons match the EMG-81 in the BC Rich, your issue is likely hand position and you've trained yourself where to place it naturally on your preexisting floyds. Learn the new placement for the new guitar. I've had this issue in the past. If not, swap it for a floyd you already like on your jacksons (e.g., the 1000 series).
Bonus: If you aren't a whammy user, dump the floyds all together. Way too much hassle - especially if you use different tunings.
Comment: Good answer, I do I think it is highly related to a combination of bridge design + hand position. I think the strings on the BCRich (Takeuchi licensed FR) are somehow more exposed, so that they are more sensitive to palm mutting, that's why I have to put them more towards the saddles, or else I mute it too much and the guitar chugs less.
Answer: Since you have already switched out pickups, it doesn't sound like they are the issue.
Going by experience, I think the bridge is the issue.  A floating bridge (like a Kahler or a Floyd Rose) will bend towards the neck to compensate for increased tension on the strings.  When you bend strings, execute dive bombs, or engage in excessive chugging, the floating bridge will compensate.  This is useful in that you are less likely to break a string and the guitar will stay in tune longer (YMMV).  A hardtail bridge does not compensate and will probably give you more "chug" since it is in a fixed position.
I have never removed a Floyd Rose bridge from a guitar, and it sounds like you have a nice USA made BC Rich, so I wouldn't recommend it. You might want to experiment where you you place your hand when palm muting near the bridge.  Or maybe buy another guitar for your arsenal, which is a "win win situation" in my book.
Comment: It may be possible to get a sound closer to a hardtail bridge by "decking" the floating tremolo so that it only bends downward, and increasing the spring tension.
Comment: @BCArg Yes, it does describe the different arrangements of tremolo bridges as I understand them.  The analysis is a bit flawed IMO, though: It creates a false dichotomy between two "theories of sustain" to the exclusion of any others.  Their empirical data *may* be correct, but I think they're blind to the assumptions they make about the mechanism behind it.  Using a human to pick the strings also introduces a lot of error.
Comment: thanks for the reply. In fact I have already played with the place of my picking hand, and it does have a massive influence. The closer I place my hand towards the saddles of the bridge, the more it chugs. Don't know if I was clear enough in my question, but I am not thinking about putting a hard tail bridge on my guitar. Idea would be to potentially swap to another floyd rose i.e. a floating tremolo from another brand
Comment: I used to have a BC Rich Bich with a Kahler bridge, unfortunately I had to sell it.  Kahler bridges are nice, I felt like I had more control over the tremelo than I did with the Floyd Rose on my Ibanez.
Comment: @theodore: like described here I guess you mean: https://www.youtube.com/watch?v=Lng0kCKW9YU&t=1s
Comment: Most guitarists seem to possess at least one  guitar less than they have already...GAS!
Comment: This answer is nonsense. I've happily chugged on hard tails, floyds and kahlers for decades.


How to calculate the percentage of values with grouping

Question: I have table:
Country:
id | name     | group| type
1  | USA      | 1    | 0
2  | Germany  | 2    | 1
3  | France   | 2    | 0
4  | China    | 1    | 1
5  | Japan    | 3    | 0
6  | Italy    | 1    | 1
7  | Mexico   | 1    | 0
8  | Columbia | 3    | 0
9  | Taiwan   | 2    | 1
...

Now I would like receive percentange of positive "type" with grouped by "group" field.
So results should looks like:
group| percentage
1    | 50%        -- 0 + 1 + 1 + 0 = 2/4 = 50%
2    | 66%        -- 1 + 0 + 1 = 2/3 = 66%
3    | 0%         -- 0 + 0 = 0/2 = 0%

How is the best way for this? Is this possible in one query? I am newbie in MySQL and I don't have any idea. I can only:
SELECT group, (????) as percentage FROM country GROUP BY group;

Comment: Possible duplicate of [Calculating percentages with GROUP BY query](https://stackoverflow.com/questions/6207224/calculating-percentages-with-group-by-query)
Answer: You want AVG
SELECT group, round(avg(type*100.0), 0) as percentage
FROM country
GROUP BY group

Fiddle
Answer: If the column type has only the values 0 and 1:
SELECT
  `group`,
  round(100.0 * sum(type) / count(*), 0) as percentage
FROM country
GROUP BY `group`;

See the demo.
Results:
| group | percentage |
| ----- | ---------- |
| 1     | 50         |
| 2     | 67         |
| 3     | 0          |


How to handle missing data in the univariate analysis

Question: Can someone please advise me on how to handle missing data in a univariate analysis (e.g. t-test, chi-squared test)?
Given that multiple imputation techniques (MICE package) are for multivariate analysis, do I simply drop or ignore missing data when it comes to the aforementioned univariate analysis? If so, will the following codes/analyses take care of the missing data for me automatically?
<code>t.test(data$Prescore, data$Postscore, paired = TRUE)
chisq.test(data$Prescore_cat,data$Postscore_cat, correct = TRUE)
</code>
Comment: This isn't actually a univariate analysis. You can use the "pre" score to predict the "post" score, and *vice versa*. The data are already in a wide format. Are you saying you're missing both pre and post values in your analysis?
Comment: What do you mean by these are not univariate analyses?  And, I only have missing pre-scoring (ie. some participants did not come back from post-tests)
Answer: Simulating the Data
First things first, you do not need to drop data. That is the whole point behind imputation...it seeks to complete your data so you don't have to sacrifice precision or power.
I'm not sure if this fits the profile of a chi-squared test, as they usually require counts of categorical variables. Additionally, the base R t-test isn't easily coded into MICE functions. However, there is an easy workaround for the t-test case by using regression instead. Since you mention MICE, I will use R below to show what I mean. First you can load the requisite libraries, create the data, and pivot it into long format:
<code>#### Load Libraries ####
library(mice)
library(tidyverse)

#### Create Data ####
pre <- c(45,50,NA,NA,40,55,60,65,45,60)
post <- c(30,20,10,NA,NA,NA,20,25,10,NA)
df <- data.frame(pre,post)
piv <- df %>%
  pivot_longer(cols = everything(),
               names_to = "Group",
               values_to = "Score")
piv
</code>
Which should look like this:
<code># A tibble: 20 × 2
   Group Score
   <chr> <dbl>
 1 pre      45
 2 post     30
 3 pre      50
 4 post     20
 5 pre      NA
 6 post     10
 7 pre      NA
 8 post     NA
 9 pre      40
10 post     NA
11 pre      55
12 post     NA
13 pre      60
14 post     20
15 pre      65
16 post     25
17 pre      45
18 post     10
19 pre      60
20 post     NA
</code>
Imputation
Then you impute the data, pool the estimates, and summarize them:
<code>#### Impute ####
imp <- mice(piv)
fit <- with(imp,
            lm(Score ~ Group))
p <- pool(fit)
summary(p)
</code>
Giving you this summary, which shows that the difference between the groups is significant (here the post test group is the reference criterion/intercept):
<code>         term estimate std.error statistic       df     p.value
1 (Intercept)     26.7  5.831524  4.578563 5.255213 0.005265395
2    Grouppre     24.6  6.913272  3.558373 9.015110 0.006118499
</code>
Answer: In general, an imputation model should be as complex or more complex than the analysis model. I.e. just because you look at one variable in the analysis does not mean you would restrict yourself to that one variable when doing imputation.
Of course, if you know nothing else but that one variable, then you cannot use anything else for imputation. However, in that case (at least in most real-life scenarios) it's entirely possible (and depending on the circumstances even likely) that your analysis will be completely invalid and give very wrong answers.


If $\lim x_n=0$ and $a>0$, then $\lim a^{x_n}=1$.

Question:
If $\lim_{n\to\infty} x_n=0$ and $a>0$, then prove that $\lim_{n\to\infty} a^{x_n}=1$.

This is a sum of Convergence of a sequence. So I am bound to use theorems related to that.
Here is my attempt :
Since $\lim_{n\to\infty} x_n=0$, there exists a natural number p such that $-\frac{1}{n}<x_n<\frac{1}{n}$ for all $n>=p$.
Let $a>1$. Then $a^{-\frac{1}{n}}<a^{x_n}<a^{\frac{1}{n}}$ for all $n\geq p$.
Let $0<a<1$. Then $a^{\frac{1}{n}}<a^{x_n}<a^{-\frac{1}{n}}$ for all $n\geq p$.
Now, $\lim_{n\to\infty} a^{\frac{1}{n}}=1$ and $\lim_{n\to\infty} a^{-\frac{1}{n}}=1$.
Therefore, by Squeeze theorem, $\lim_{n\to\infty} a^{x_n}=1$.
Is it correct? If it's not, then where is the mistake?
Please anyone help me.Thanks in advance.
Comment: For positive $a$ function $a^x=e^{x\ln(a)}$ is continuous. Are you allowed to use that?
Comment: You should really clarify what properties of exponential function you know/are allowed to use. For instance, this is immediate from the continuity, are you allowed to use it?
Comment: If $x_n\to 0$, then $a^{x_n}\to a^0=1$
Comment: can you use the epsilon delta definition of the limit to do this?  so you need to find delta > 0 such that |x| < delta implies |a^x  - 1| < epsilon .  or x < log(epsilon + 1) / log (a).  which can be found, since x is convergent
Comment: @Wojowu No. I am not allowed to say it from continuity. I have to prove it as we prove the convergence of a sequence.
Comment: The mistake is in the very first line. You cannot say $-1/n<x_n<1/n$ for big enough $n$ What you can say is that for a fixed $N$, you have $-1/N<x_n<1/N$ for big enough $n$.
Comment: Also, why are you assuming $\lim a^{1/n}=1$? I think proving this is of the same difficulty of proving $\lim a^{x_n}=1$.
Comment: @JulianMejia I have already proved that $\lim a^{1/n} =1$. So now I can use this fact.
Comment: @JulianMejia Will you please clarify why it is true only for a fixed $N$?
Comment: For instance consider $x_n=\frac{1}{\sqrt{n}}$. We have $\lim x_n=0$. But the inequality $x_n<1/n$ is never satisfied.
Comment: @JulianMejia Oh, thanks a lot.
Comment: If you already have proved that$\lim a^{1/n}=1$ I think is possible to fix your solution: You have $-1/N<x_n<1/N$ and you have that $a^{\pm1/N}$ is close to 1 when $N$ is big.
Answer: Hint:
Use the fact that if you have $f$, a continuous function, and a sequence $\{x_n\}$ which converges to $x$, then,
$$\lim_{n\to\infty} f(x_n) = f\left(\lim_{n\to\infty} x_n\right)$$
$$=f(x)$$
In particular, consider $f(x) = a^x$.
Comment: OP first says they can't use continuity, but then accepts the solution which uses continuity, interesting...


I'm looking for the sequence $\Big\{ \frac{n}{n+1}\sin{\frac{n\pi}{2}} \Big\}$ converges or diverges.

Question: I'm looking for the sequence $$\Big\{ \frac{n}{n+1}\sin{\frac{n\pi}{2}} \Big\}$$ converges or diverges.
I tried $$\lim_{n\to\infty}{\frac{n}{n+1}\sin{\frac{n\pi}{2}}}=\underbrace{\lim_{n\to\infty}\frac{n}{n+1}}_{1}\cdot \lim_{n\to\infty}\sin{\frac{n\pi}{2}}$$
As for each $n$ we have to $-1, 1$ or $0$ in response, then it means that the limit does not exist and therefore the sequence is divergent?
Note. If it becomes complicated to understand something, I apologize, that is not write English, and this hinders a lot. I'm sorry.
Comment: non-zero convergent $\times$ divergent = divergent
Comment: Correct try!${}$
Comment: The limit points of the sequence are -1,0 and 1, so it is not convergent.
Answer: Already you have noted that $$\left(\sin\dfrac{n\pi}{2}\right)=
\begin{cases}
0,  & \text{if $n$ is even} \\
1, & \text{if $n=4k+1$ for some $k\in\mathbb{Z}$}\\
-1,& \text{if $n=4k+3$ for some $k\in\mathbb{Z}$}
\end{cases}$$ is divergent.
Suppose $$\left(\dfrac{n}{n+1}\sin\dfrac{n\pi}{2}\right)$$ is convergent. Then it can show that $\left(\sin\dfrac{n\pi}{2}\right)$ is also convergent.
A contradiction!


How do I use dummy variables when there are 3 possibilities?

Question: So normally I see dummy variables used when there are 2 options (e.g. a female dummy = 1 when the person is female, 0 if male).
However, what if I want to use a dummy variable to represent e.g. company size (i.e. small, medium and large)?
Would I need 3 dummies, i.e. small, medium and large, which each equal one if the company in the dataset is that size and 0 if not?
If so, how would I interpret the coefficient after a regression has been estimated? Because if e.g. small is a dummy and it equals 0, it doesn't mean that the company is e.g. medium-sized, since it could be large-sized.
Clarification appreciated!
Answer: You could code them as 3-d vectors with a $1$ in the position corresponding to the category and $0$ in the other two positions. But...
...that's not how people tend to do it.
Usually people would make them 2-d vectors, where the first position is an indicator for being a medium company and the second position is an indicator for being a large company. Double $0$s would indicate that it is neither, which means that the category must be the remaining category: small company.
I wrote a post about how this work in ANOVA that I will link here in a moment.
https://stats.stackexchange.com/a/439818/247274


JSONParser from androidhive tutorial, NoSuchMethodError in DefaultHttpClient

Question: I'm following this tutorial, and getting this error:
Caused by: java.lang.NoSuchMethodError: No virtual method execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHttpResponse; in class Lorg/apache/http/impl/client/DefaultHttpClient; or its super classes (declaration of 'org.apache.http.impl.client.DefaultHttpClient' appears in /system/framework/ext.jar)
                at info.androidhive.materialtabs.adpater.JSONParser.makeHttpRequest(JSONParser.java:52)
                at info.androidhive.materialtabs.UserFunctions.loginUser(UserFunctions.java:37)
                at info.androidhive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:551)
                at info.androidhive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:519)

Here is the JSONParser class that I'm using:
public class JSONParser {
     static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
        // constructor
        public JSONParser() {
        }
        // function get json from url
        // by making HTTP POST or GET method
        public JSONObject makeHttpRequest(String url, String method,
                List<NameValuePair> params) {
            // Making HTTP request
            try {
                // check for request method
                if(method == "POST"){
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }else if(method == "GET"){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            // return JSON String
            return jObj;
        }
}

Comment: which part of code is responsible  for this error log, u can post that also
Comment: using json parse like this :
Comment: Post your code and explain your problem little bit clearly
Comment: HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();
Comment: HttpPost is deprecated one try to use HttpUrlConnection or Gson
Comment: Can u please edit and send it to me because i am not getting it
Answer: DefaultHttpClient was deprecated in api level 22, and removed in api level 23.
The documentation was even removed from the Android documentation, here is the link to where the documentation was previously, and you can see where it re-directs to:
http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html
Quote just in case the re-direct changes:

Android 6.0 release removes support for the Apache HTTP client. If
  your app is using this client and targets Android 2.3 (API level 9) or
  higher, use the HttpURLConnection class instead. This API is more
  efficient because it reduces network use through transparent
  compression and response caching, and minimizes power consumption.

I created an updated version of the JSONParser class that you're using, here it is:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}

Example AsyncTask for Post:
class PostAsync extends AsyncTask<String, String, JSONObject> {
    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://www.example.com/testPost.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("name", args[0]);
            params.put("password", args[1]);

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            if (json != null) {
                Log.d("JSON result", json.toString());

                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            Toast.makeText(MainActivity.this, json.toString(),
                    Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("Success!", message);
        }else{
            Log.d("Failure", message);
        }
    }

}

Example AsyncTask for Get:
class GetAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://www.example.com/testGet.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("name", args[0]);
            params.put("password", args[1]);

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "GET", params);

            if (json != null) {
                Log.d("JSON result", json.toString());

                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            Toast.makeText(MainActivity.this, json.toString(),
                    Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("Success!", message);
        }else{
            Log.d("Failure", message);
        }
    }

}

For more details, here's my blog post about this code:  http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html
Comment: Error:(74, 37) error: method makeHttpRequest in class JSONParser cannot be applied to given types;
required: String,String,HashMap
found: String,String,List
reason: actual argument List cannot be converted to HashMap by method invocation conversion
Comment: @chawla.19 NameValuePair was also deprecated in api level 22, and removed in api level 23.  Take a look at the example AsyncTasks, you'll need to put your parameters into a HashMap instead of using NameValuePair.
Comment: Error:(38, 27) error: cannot find symbol method keySet()
Comment: @chawla.19 keySet() is a standard method in the HashMap class.  Did you replace the full code in your JSONParser class, including the imports?
Comment: @chawla.19 not sure why you're getting a compile error there.  Just so you know, this code is fully working and tested.  I did comprehensive testing before I posted it on my blog.  Once you get it compiling correctly I'm sure it will work for you.
Comment: its showing : wrong 3rd argument type. Found:'java.util.ArrayList',required:'java.util.HashMap'
Comment: @chawla.19 You need to construct a HashMap with your parameters instead of using NameValuePairs, and give that as the third parameter for the `makeHttpRequest()` method.  Take a look at the example AsyncTasks in the answer!
Comment: when i construct a 'HashMap' , it gives keySet error as mentioned above
Comment: @chawla.19 If you correctly create a HashMap it should not give any errors.  Again, this is fully working and tested code.  Keep at it and you'll get it!
Comment: saved my day as I am also getting error at execute method after i updated API 24, now ok, many many thanks!


List all environment variables from the command line

Question: Is it possible to list all environment variables from a Windows' command prompt?
Something equivalent to PowerShell's gci env: (or ls env: or dir env:).
Comment: For a description of each, see https://ss64.com/nt/syntax-variables.html
Answer: Just do:
SET

You can also do SET prefix to see all variables with names starting with prefix.
For example, if you want to read only derbydb from the environment variables, do the following:
set derby

...and you will get the following:
DERBY_HOME=c:\Users\amro-a\Desktop\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin

Comment: @KevinMeredith: All commands in the Windows shell are case insensitive.
Comment: This prompts me for a name?
Comment: @CMCDragonkai are you using powershell?  It appears that it has hikacked set with one of its command-lets.  This is one of its less useful features!  I asked a question about disabling this [here](http://stackoverflow.com/questions/21678521/is-it-possible-to-how-do-you-stop-powershell-using-certain-cmdlets)
Comment: This is not guaranteed to work.  This requires command extensions to be enabled.  They are enabled by default on newer windows, but not older ones, and they can be turned off.
Comment: This doesn't seem to work with `cmd /c`. `/e:on` flag also doesn't help.
Comment: @John Lord: What is "command extensions"? Do you have a reference? Do you mean [PowerShell Community Extensions](https://github.com/Pscx/Pscx) (PSCX)?
Comment: i do not mean those.  I'm talking about the command prompt (cmd.exe).  Read this:  https://www.computerhope.com/forum/index.php?topic=13988.0
They can break command scripts in some cases when enabled so it's possible a user that does a lot of batch processing has them turned off by default, and they can be turned of on a single-use instance as well in the batch file.
In a specific command instance, it may be required to run this as well:  C:> cmd.exe /E:ON to turn them on.
Answer: Jon has the right answer, but to elaborate a little more with some syntactic sugar..
SET | more

enables you to see the variables one page at a time, rather than the whole lot, or
SET > output.txt

sends the output to a file output.txt which you can open in Notepad or whatever...
Comment: it's actually built in to some functions as well.  Dir for example will page with a /p.
Answer: To list all environment variables in PowerShell:
Get-ChildItem Env:

Or as suggested by user797717 to avoid output truncation:
Get-ChildItem Env: | Format-Table -Wrap -AutoSize

Source: Creating and Modifying Environment Variables (Windows PowerShell Tip of the Week)
Comment: To avoid output being truncated, I would use the following:
`Get-ChildItem Env: | Format-Table -Wrap -AutoSize`
Comment: `gci env:` instead `Get-ChildItem Env:`, easier to remember
Comment: Even if I don't use PowerShell because it doesn't work for every cmd command, this is the only solution for a pretty printing (on 2 columns) without big efforts. To achieve the same behavior in cmd, you need something like this `for /f "tokens=1,2 delims=="  ...` which becomes very complicated ...
Answer: Simply run set from cmd.

Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings.
Comment: set is run in cmd, not Powershell @JayKilleen
Comment: Doesn't seem to work these days (in 2021)

`
$ set

$ cmdlet Set-Variable at command pipeline position 1
$ Supply values for the following parameters:
$ Name[0]:
$ Set-Variable: Cannot bind argument to parameter 'Name' because it is an empty array.
`
Comment: So VERY very true @Grant! +1 But I think the MORE command option was to paginate. :D

@JayKilleen and any other people: ---> **Command Prompt CMD Answer:** `set | more` (or in shortcut: `set | more & pause`) ---> **PowerShell PS Answer:** `gci env: | Format-Table -Wrap -AutoSize` -OR- `Get-ChildItem Env: | Format-Table -Wrap -AutoSize`
Answer: Non expanded variables -
User variables -
reg query HKEY_CURRENT_USER\Environment

System variables -
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Expanded variables -
In CMD -
SET

In Powershell -
Source - https://devblogs.microsoft.com/scripting/powertip-use-windows-powershell-to-display-all-environment-variables/
dir env:

Comment: `set` by itself doesn't work with Github Actions, but the `reg query` does!
Comment: Sorry @HrishikeshKadam - it doesn't work. Command: `PS C:\Users\User> dir env` Error Message: `dir : Cannot find path 'C:\Users\User\env' because it does not exist... FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand`
Answer: You can use SET in cmd
To show the current variable, just SET is enough
To show certain variable such as 'PATH', use SET PATH.
For help, type set /?.
Comment: How is this different from existing answers?
Answer: Don't lose time. Search for it in the registry:
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

returns less than the SET command.
Comment: Why do you say "don't lose time"? Isn't writing "set" in the command prompt faster than "reg query ..."?
Comment: although that might be true, one difference is that the registry query returns unexpanded `REG_EXPAND_SZ` keys. For example `reg query "HKCU\Environment"` shows me that my `%TEMP%` variable depends on the value of `%USERPROFILE%`, so if that value changes, so would the value for `%TEMP%`. In contrast, `SET` just returns `"C:\Users\mpag\AppData\Local\Temp"`
Answer: If you want to see the environment variable you just set, you need to open a new command window.

Variables set with setx variables are available in future command windows only, not in the current command window. (Setx, Examples)


Is this a Csus4 chord?

Question: I have a book that labels C, F, Bb, and D as a Csus4 chord. I get the F is the 4th to C, but why the dominant 7th and the 9th? Are those vital to a Csus4 chord, do they add to it, or is the book just wrong?
If anyone has the book, I'm looking at page 22 in Mark Levine's The Jazz Piano Book.
Comment: Without using slash notation, this chord would be called `C9sus4` (no 5th).
Comment: I have the book in question and it is definitely a Jazz book (also a great book IMO), so all the theory doesn't necessarily apply elsewhere, such as Rock or Country.  Specific theories have specific "rules", such that Jazz and Classical theory often contradict each other or work in completely different ways, so to play or compose with the theory of either in mind is to try to replicate that genre.
Answer: No, the 7th and 9th are not vital to a sus4 chord. A "regular" sus4 would just have root, fourth, and fifth (so C, F, G, in this case). That said, jazz seems to never play simple "regular" chords without adding at least a 7th. But the chord you have listed could probably be more accurately described as a C9sus4 (without the 5th, if you want to get really technical). Alternatively, it could be described as the folowing slash-chord: B♭/C, which might make more sense.
However, this type of chord often occurs on the fifth note (dominant) of the scale (so you'd likely see this chord in the key of F). In that case, it is a particularly common type of chord to use in jazz (basically a IV chord over the 5th scale degree) so it has its own name: the jazz sus chord, or a "dominant 9sus4 chord". It's important to note, though, that "jazz sus chord" is different from a plain old "sus4" (which, as I said is just C, F, G).
I've described jazz-sus chords once before, as an example where slash-chords are useful.
Comment: Here's another answer that describes essentially the same chord (but includes the 5th): http://music.stackexchange.com/questions/20560/proper-symbol-for-this-chord-1-5-7-9-11
Answer: It is a sus4 chord I would not call it a Csus4 though. It's obviously an extension with a suspended third. I would instead call it a C9sus4 because you have everything up to the 9th (it's ok to omit the 5th) and the 3rd is suspended.
Answer: A standard triad with a bass note a tone higher than the root is often called an 11th.(Off the bass note name). Bb, D and F make up a Bb major triad, and the C is a tone above Bb. So it can be known as C11. The intro to 'Midnight at the Oasis' uses 5 of these 11th chords. Otherwise known as Bb/C, but, as the others have said, it's not a sus4 in its common form.Could be Bb add 2,or at a push add 9 though unlikely, but generally the 'sus' bit suspends the 3rd of the chord, to be replaced, usually temporarily, with either a 2 or a 4. Not in this case.
Answer: These four notes don't make a sus4 chord, and certainly not a Csus4 chord. If you leave out the D, the other notes make an Fsus4. No other sus4 chords can be made from these four notes. However, like all sus4 chords, the three notes used for Fsus4 (F, Bb, C) can also be thought of as two other suspended chords: these are Bbsus2 and an incomplete C7sus4 (it has no 5th).
Answer: Need to recognize the difference between a triad sus4 and a dominant 7th sus 4:
Csus4 = C F G
C7sus4 = C F Bb D
So in the book it's a typo, should be "C7sus4"
Comment: @MichaelMartinez - once there's a 9th in the chord, it ceases to be merely a 7th in name. It must be a 9th chord, and all ninths will have a 7th too. Except 'add 9'.So C7sus4 is CFGBb. C11 will have an E as well.
Comment: I think C7sus4 would be C F G Bb...
Comment: yes you can voice it that way. or you can drop the g and add the ninth
Comment: @mey - most times a 9th chord can be used to replace a 7th. Usually sounds richer or more sophisticated!
Comment: @Tim. you are correct. But a lot of times when a chord is written as a 7th it is implied that you can use the other tensions as you see fit. harmonically if you continue to keep the 3rd and 7th it still functions as the 7th chord. Or in this case the sus note (4th) and the 7th.

Is this a Csus4 chord?


Prevent WPF combobox clearing selection when itemssource changes

Question: I have a textbox for firstname, a textbox for lastname, and a combobox for displayname.  The displayname is editable so that the user can type in whatever they want.  However, the combobox should display a list of options.
When either textbox changes, the combobox itemssource is updated.  However, if the user previously selected a value, then the text property is blanked out.  But if the user had typed in a value, the text property remains.  How do i prevent the text value from blanking out?
Here's my code:
<Window x:Class="MainWindow"
        x:Name="MainApp"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Grid DataContext="{Binding ElementName=MainApp}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>
        <TextBox Grid.Row="0"
                 Text="{Binding FirstName}" />
        <TextBox Grid.Row="1"
                 Text="{Binding LastName}" />
        <ComboBox x:Name="MyCb" Grid.Column="1"
                  Grid.Row="2"
                  Text="{Binding TheName}"
                  ItemsSource="{Binding NameOptions}"
                  IsEditable="True" />
    </Grid>
</Window>

Imports System.ComponentModel

Class MainWindow
    Implements INotifyPropertyChanged

    Public ReadOnly Property NameOptions As List(Of String)
        Get
            Dim result As New List(Of String)
            result.Add(String.Format("{0} {1}", FirstName, LastName))
            result.Add(String.Format("{1}, {0}", FirstName, LastName))
            result.Add(String.Format("{1}, {0} MI", FirstName, LastName))
            Return result
        End Get
    End Property

    Public Property TheName As String

    Private _firstName As String
    Public Property FirstName As String
        Get
            Return _firstName
        End Get
        Set(value As String)
            _firstName = value
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("FirstName"))
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("NameOptions"))
        End Set
    End Property

    Private _lastname As String
    Public Property LastName As String
        Get
            Return _lastname
        End Get
        Set(value As String)
            _lastname = value
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("LastName"))
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("NameOptions"))
        End Set
    End Property

    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
End Class

Answer: See my answer here:
How to disable ItemsSource synchronization with Text property of ComboBox
public class ComboBox : System.Windows.Controls.ComboBox
{
    private bool ignore = false;
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        if (!ignore)
        {
            base.OnSelectionChanged(e);
        }
    }

    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        ignore = true;
        try
        {
            base.OnItemsChanged(e);
        }
        finally
        {
            ignore = false;
        }
    }
}

Answer: Set MyCb.SelectedItem to null before NameOptions is updated. SelectedItem supersedes Text and when the ItemsSource is updated it will also try to update the Text supposedly connected to the SelectedItem.
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public List<String> NameOptions
    {
        get
        {
            MyCb.SelectedItem = null;   // <--- THIS is the solution. just try it!
            List<String> result = new List<String>();
            result.Add(String.Format("{0} {1}", FirstName, LastName));
            result.Add(String.Format("{1}, {0}", FirstName, LastName));
            result.Add(String.Format("{1}, {0} MI", FirstName, LastName));
            return result;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public MainWindow()
    {
        InitializeComponent();
    }

    private String _theName;
    public String TheName
    {
        get { return _theName; }
        set
        {
            _theName = value;
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs("TheName"));
            }
        }
    }

    private String _firstName;
    public String FirstName
    {
        get { return _firstName; }
        set {
            _firstName = value;
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs("NameOptions"));
                handler(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }

    private String _lastName;
    public String LastName
    {
        get { return _lastName; }
        set {
            _lastName = value;
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs("NameOptions"));
                handler(this, new PropertyChangedEventArgs("LastName"));
            }
        }
    }
}

Comment: Unless I misunderstood, this suggestion still clears the displayed value in the combobox. Thanks for trying, but it appears that my bindings are correct and this is how the combobox is designed to work.
Comment: Your code is not quite textbook-like with raising the property changed notification of the combobox's list from another property. Why do you think that this solution still clears the code? Haven't you even tied? I was able to reproduce the behavior you described and discovered that if you never select an item from the list and you enter a freestyle name in the edit field, changing first and last name didn't harm the content of the combobox's edit field. But once you select an item, it will override the edit field's content -- even when the ItemsSource is being rebuilt. Attached my C# code.
Comment: Been out for a while....I tried your suggestion before posting, and tried again just to make sure.  Still doesn't work.  Since this behavior seems to be by design I was going to mark your first answer as the answer, but I do not see it anymore.
Comment: I deleted my first answer because it was not very helpful. Strange thing, that you can't get my code to work. Maybe the behavior of the ComboBox changed durin a new version. I'm using VS 2012 Express here and it showed the problem you described along with my solution perfectly.
Comment: Bump: I'm having the same issue.


How can i stop this simple php calendar from caching the old dates?

Question: I made this simple calender for a few friends to fill in all their dates, It all works fine when you update the dates but then when you go back to the calendar it shows all the old dates selected. You have to manually refresh the page to get the updated dates it's really frustrating.
You can demo it here: http://olli460.com/poker/index.php
If you click "Add/Edit Dates" then click on "oliver" and select a few random dates. When you go back to the calendar it's still showing all the old dates until you press F5.
This is my index.php
<?php
date_default_timezone_set('Europe/London');
//error_reporting(E_ALL);
$pageWeb = $_REQUEST['page'];
$pageWeb = filter_var($pageWeb, FILTER_SANITIZE_STRING);
if(empty($pageWeb)) {
  $pageWeb = "main";
}

$mysqli = mysqli_connect("localhost","xxxxx","xxxxxx","xxxxxx") or die("Error " . mysqli_error($link));
?>

<!DOCTYPE html>

  <title>Poker Calendar</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="mobile-web-app-capable" content="yes">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" />

<link rel="shortcut icon" sizes="192x192" href="if_icon-82_667352.png">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <link href="css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Arvo:400,700' rel='stylesheet' type='text/css'>

 <link rel="stylesheet" type="text/css" href="theme.css">
  <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Cache-Control" content="no-cache" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />

          Poker Calendar
          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

          </button>

            <li <?php if(empty($pageWeb)) { echo "class=\"active\""; } ?>>  Calendar

            <li <?php if(empty($pageWeb) OR $pageWeb == "add-dates") { echo "class=\"active\""; } ?>>  Add/Edit Dates

            <li <?php if(empty($pageWeb) OR $pageWeb == "add-player") { echo "class=\"active\""; } ?>>  Add Player

                <?php
                  if(isSet($pageWeb)){
                  if (!(strpos($pageWeb, "http") === false)){
                   echo "not allowed";
                  }else{
                    include("$pageWeb.php");
                  }

                  } else {
                    include("main.php");
                  }
              ?>

After they enter the dates i'm using this to redirect back to the main page, is this the issue?

Comment: Just tried that, same error dates dont actually show until i press F5
Comment: it's an add OR edit facility.. if the dates are not cached, how can they be edited? I don't see why that's an error?
Comment: Theres no errors, It's just displaying the old dates for some reason i dont understand why.
Comment: it showed the edited dates when I edited them?
Answer: if you want to fix that script, tell the browser not to cache the page:
<?php
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
?>

and why load data from mySQL? maybe use the Google Client Library (GitHub) instead?
Comment: this seems a little overly complex i only want a basic calendar for a couple of friends. I've done a similar script before and that worked fine i cant understand why this one is caching like it is
Comment: @Exoon it it rather overly complex not to use a library - while your question is lacking half of the scripts. guess I know what the issue is, because my browser told me "from disk".


Check url is a file or directory

Question: Hi there.
I have a URL list. I do not know how to check is this address to a file or directory.
examples:
url = "http://example.com/path/to/file.html"

if '.' in url.split('/')[-1]:
    return True

but if url is
url = "http://example.com/path/domains/domain.com"

domain.com is a directory not a file. How to detect it?
Checking the file extension is not good, maybe some headers? But I want to do as little as possible internet transfer usage.
Edit:
I need to download a large number of links and map their path to the location in my operating system. eg
example.com/path/to/file.html
~/Downloads/example.com/path/to/
and here download file.html.
eg:
example.com/directory/
create ~/Downlods/example.com/directory/
next url: example.com/directory/dir2
create ~/Downloads/example.com/directory/dir2
next url: example.com/directory/file.html
Download file.html in too ~/Downloads/example.com/directory/
not too create file.html directory

Comment: Really, you can't unless it has a slash at the end.
Comment: all page is in one site? check somethings unique in directory page and crawl pages, and now you can check... but i think best way add extension
Comment: @TylerCrompton Even then it's not a sure-fire thing. A URL is something the server handles, and while some servers map URLs to their filesystem, it's becoming increasingly common not to (mod_rewrite and pals make it very easy not to). You can make any URL point to anything you want on your server.
Comment: @Lattyware, trust me, I know. Though not always, rewrites usually go from a file to a file or from a directory to a directory.
Answer: In short, you can't. Accessing the URL http://example.com/path/domains/domain.com would send a 302 redirect (if I remember correctly) to http://example.com/path/domains/domain.com/ by default. There are no headers in the response that indicates if a URL points to a directory. May I ask why you need to know this? I suppose you can add a slash to a URL and see what happens from there. That might get you the results you are looking for.
Comment: Unless it's not backed by the filesystem at all. In which case this whole exercise is pointless.
Comment: Exactly. I'll go so far to say that it's pointless either way.
Comment: I need to download a large number of links and map their path to the location in my operating system
Comment: Look into `wget`. That can download recursively and it creates a file structure on your OS based on the URLs. `curl` may also do it but I don't use it that often.
Comment: @TylerCrompton i know this post is old but the salsh idea was perfect. fixed my problem. thanks
Answer: On HTTP servers, there is no such "file" or "directory" things. You just send an URI to the server which identify a specific resource that depends of the server's configuration.
By default, most of the HTTP servers use the files and directories of your system, but it can be configured (URL Rewriting, ...).

Check url is a file or directory


How to make every cell in a column display the instances of a string from that cell's respective row without hardcoding the row number

Question: I have an attendance list with a list of names in the first column, and dates in the first row, with an "x" marking the dates someone attended.  I'd like to make one of the columns display the total number of times an "x" appears in that row, without needing to change the row number in each cell(I'd like to reference the current row as a variable I guess).
The following works:
=COUNTIF(E2:Z2, "x")
but I'd like something more like this:
=COUNTIF(ROW()2:ROW()2, "x")
I would also like a similar way to reference the current column dynamically.  I'm OK with needing to paste the same equation in each cell of the row/column if necessary, but if there's a way to highlight an entire row and do something like "for each cell in this row, get the current column and count the instances of "x" that would be most ideal.
I have almost no experience with excel, but I'm a developer as a profession so this stuff at least makes sense to me.  Any help would be appreciated
Thanks in advance for any responses!
Answer: This formula counts "x" in the entire second row:
<code>=COUNTIF(2:2,"x")
</code>
To count the "x" in column B the formula would be
<code>=COUNTIF(B:B,"x")
</code>
When you copy it, the row/column values will adjust.


Full screen background not working on ipad

Question: Would you know why, on my website full screen background doesn't work on ipad? Many thanks
I tried this:
#presentation {
    height: 1300px;
    background: #afc9ff;
    background: url(../images/bg-24.jpg) no-repeat center fixed;
    -webkit-background-size: 100%;
    -moz-background-size: 100%;
    -o-background-size: 100%;
    background-size: 100%;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

}

and this
#activity {
    height: 1300px;
    background: #8aba56;
    padding-top: 150px;
    background: url(../images/bg-22.jpg) no-repeat center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -ms-background-size: cover;
    -o-background-size: cover;
}

Answer: please try this:
#activity {
    height: 1300px;
    background: #8aba56;
    padding-top: 150px;
    background: url(../images/bg-22.jpg) no-repeat center fixed;
    -webkit-background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    background-size: 100% 100%;
    -ms-background-size: 100% 100%;
    -o-background-size: 100% 100%;
}

Comment: Thanks for the suggestion. Unfortunately that doesn't work (I tried for the "activity" DIV, second menu item). Have updated the link in my post accordingly if you want to have a look. Many thanks
Answer: Try
#presentation {
 background-attachment: fixed;
background-color: #AFC9FF;
background-image: url(../images/bg-24.jpg)
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
height: 1300px;
-webkit-background-size: 100%;
-moz-background-size: 100%;
-o-background-size: 100%;

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}

good luck...
Answer: in body add

next to
and add CSS
#fixedbg{
    background:url(../img/sec2.jpg) no-repeat center center;
    height:100%;
    position:fixed !important;
    width:100%;
    z-index:0;
    top:0;
}

Best of luck....


Is an Immersion which is also a homeomorphism always a diffeomorphism?

Question: In my differential geometry script we defined a Immersion the following way:
Let $f \colon U \rightarrow \mathbb{R}^3$ be such that $\forall x \in U: f^{\prime}(x)$ is injective, where $U \subset \mathbb{R}^2$ is open. Then $f$ is called an immersion.
My question is, whether an injective immersion which is also a homeomorphism onto its image has got a differentiable inverse $f^{-1} \colon \operatorname{im}(f) \rightarrow U$.
I would suggest that the answer is no, but it is a blind guess and all the theorems I know only work for $\operatorname{dim}(U)=3$, but I am interested in $\operatorname{dim}(U)=2$.
If necessary one can assume that $f \in C^{\infty}$, but I am mostly excited about results for $C^1$ or just differentiable.
Comment: $f$ cannot literally be a homeomorphism, since $\mathbb{R}^3 \setminus \{0\}$ has trivial fundamental group but $U \setminus \{x\}$ (for any $x \in U$) does not. Do you mean "homeomorphism onto its image"?
Comment: Oh yes, I will change my question, thanks for pointing out.
Comment: Ok, thanks! And what are you assuming about the differentiability of $f$? Of course $f$ must be differentiable for this question to make sense, but are you assuming anything more (e.g. $C^1$ or $C^\infty$)?
Comment: I'd imagine this is true by the inverse function theorem. $f$ is local immersion, hence locally its image is an embedded submanifold $S$. The injectivity of $f'$ should eventually imply the necessary hypotheses for the inverse function theorem.
Comment: I have thought about that, but my versions of the inverse function theorem only work if domain and range have the same dimension as I mentioned in the question.
Comment: You bet.........................
Answer: The answer is yes, once you add the phrase "onto its image" everywhere and assume enough regularity. More precisely:

Theorem.
Let $M,N$ be smooth manifolds (of dimensions $m,n$ repsectively), $f:M\to N$ a smooth map. If

$f$ is an immersion (meaning for each $x\in M$, the tangent mapping $T_xf:T_xM\to T_{f(x)}N$ is injective)
$f$ is a homeomorphism of $M$ onto $f(M)$, equipped with the subspace topology from $N$,

then $f(M)$ is an embedded submanifold of $N$, and the restricted mapping (on the target) $f:M\to f(M)$ is a diffeomorphism.

First, some remarks.
Notice that I'm not saying $f:M\to N$ is a diffeomorphism; this would be absurd (consider $M=\Bbb{R},N=\Bbb{R}^2$, $f(t)=(t,0)$). Also, the theorem above and proof below holds if we replace "smooth" by $C^1$ everywhere. The idea of the proof is pretty easy once you know the basic consequences of the inverse/implicit function theorems (particularly the local canonical form for immersions). The annoying part is making sure all the open sets are small enough so that things match up.
Regarding terminology, a mapping $f$ which satisfies the hypotheses of the theorem (an immersion which is a homeomorphism onto its image) is known as an embedding. So, the theorem can be stated as "the image of an embedding is an embedded submanifold" (where 'embedded submanifold' means it satisfies the 'local slice-chart' condition).

TL;DR of Proof
The crux of the proof is the first statement, that $f(M)$ is an embedded submanifold of $N$ (of the same dimension as $M$). Once you do this, it is basic stuff that $f:M\to N$ being smooth implies $f:M\to f(M)$ is smooth, so being an immersion and bijective easily prove that the latter is a diffeomorphism (usual inverse function theorem argument).

Proof of the Theorem.
To show $f(M)$ is an embedded submanifold, we need to show the existence of a "slice chart" around any point. So, take an arbitrary point $f(x)\in f(M)$. Since $f$ is an immersion, we can:

find a chart $(U,\phi)$ of $M$ around $x$ with $\phi(x)=0\in\Bbb{R}^m$,
find a chart $(V_0,\psi)$ of $N$ around $f(x)$ such that $\psi(f(x))=0\in\Bbb{R}^m$
$f$ maps $U$ into $V_0$ (we can always arrange this WLOG by replacing $U$ with $U\cap f^{-1}(V_0)$ if necessary) and the local representative $F:=\psi\circ f\circ \phi^{-1}:\phi(U)\to \psi(V_0)$ is given by $F(\xi^1,\dots, \xi^m)=(\xi^1\dots, \xi^m,0,\dots 0)$.

i.e the local form of $f$ is (the restriction of) the canonical injection of a lower dimensional vector space into a higher dimensional one (this stuff with inverse function theorem and charts is the non-linear analogue of basic linear algebra results regarding row-reduction of matrices corresponding to injective linear transformations). Now, we shall have to choose small enough open sets.

First of all, since $f:M\to f(M)$ is a homeomorphism, it is an open mapping, so $U$ being open in $M$ implies $f(U)$ is open in $f(M)$; by definition this means there exists some open $V_1\subset N$ such that $f(U)=V_1\cap f(M)$.
Next, let us define $V_2:=\psi^{-1}\left(\psi(V_0)\times \left(\phi(U)\times \Bbb{R}^{n-m}\right)\right)\subset V_0$.
Finally, define $V:= V_0\cap V_1\cap V_2=V_1\cap V_2$ (since $V_2$ is already contained in $V_0$). In particular $V$ is open in $N$ since it is the intersection of three open sets in $N$.

Then, we have $f(U)\subset V_0$ (by definition), and next by definition we have $f(U)=V_1\cap f(M)$, and we also have $\psi(f(U))=F(\phi(U))=\phi(U)\times \{0_{\Bbb{R}^{n-m}}\}$ (see the explicit formula for $F$), so that $f(U)\subset V_2$. These three statements imply that $f(U)= V\cap f(M)$, and a little more set-theoretic unwinding of these definitions shows that
\begin{align}
\psi(V\cap f(M))=\psi(V)\cap \left(\Bbb{R}^{m}\times\{0_{\Bbb{R}^{n-m}}\}\right).
\end{align}
So, what I have shown is that for each point in $f(M)$, there is a chart (namely the restricted $(V,\psi|_V)$ above) such that $\psi(V\cap f(M))=\psi(V)\times (\Bbb{R}^m\times \{0\})$ looks like a flattened $m$-dimensional piece sitting inside of $\Bbb{R}^n$. This is precisely the slice-chart we're looking for so the definition of $f(M)$ being an ($m$-dimensional) embedded submanifold of $N$ is satisfied.
It is now clear that $f:M\to f(M)$ is a diffeomorphism, because $f:M\to f(M)$ is a bijective mapping between two smooth manifolds of the same dimension ($m$) and has injective derivative, so by the inverse function theorem is a local diffeomorphism. Coupled with bijectivity, this implies $f$ and $f^{-1}$ are smooth.
Alternatively, we can avoid usage of the inverse function theorem as in the previous paragraph to finish things off. We already used it once to obtain the charts $(U,\phi), (V,\psi)$ above. With these charts, the local representative of $f$ is $F: (\xi^1,\dots,\xi^m)\mapsto (\xi^1,\dots, \xi^m,0,\dots, 0)$. Now recall that a chart for the submanifold is obtained by ignoring the last few zero coordinates, so $(V\cap f(M), \tilde{\psi})$ is a chart for $f(M)$, and now the local representation is just $\tilde{F}:(\xi^1\dots, \xi^m)\mapsto (\xi^1,\dots, \xi^m)$, i.e it locally looks like the identity mapping (which is actually exactly what the inverse function theorem told us in the previous paragraph). So, $f:M\to f(M)$ is a local diffeomorphism, and due to bijectivity, it follows $f:M\to f(M)$ and $f^{-1}:f(M)\to M$ are both smooth functions (since smoothness is a local property). Hence $f:M\to f(M)$ is a diffeomorphism.
Comment: Thank you for your effort, I haven't yet read everything but it sounds good! Amazing to hear.
Comment: @PMG sure. note that I added a TLDR of the proof which should hopefully also address your concern about inverse function theorem when dimensions don't match up.
Comment: In our lecture we only had the inverse function theorem for mappings$f \colon U \rightarrow V$, with $U,V \subset \mathbb{R}^n$, how can we use this here?
Comment: Once you compose with the chart maps, you can apply the IFT to the local representative $F$


Ao clicar em Selecionar Todos, todos os checkboxs fiquem marcados

Question: Tenho o seguinte formulário onde o usuário pode marcar todos os clientes de uma só vez:

Quando clico em Selecionar Todos, ele funciona corretamente, mas quando desmarco uma das opções, o checkbox Selecionar Todos continua marcado e quando desmarco o Selecionar Todos e volto a selecioná-lo, o checkbox que desmarquei anteriormente não desmarca, fica selecionado.

Segue abaixo o código. Ele está dentro de um método em PHP:
...
$listar = "

               <input type=\"checkbox\" id=\"marcarTodos\" onclick=\"marcarDesmarcar();\">

SELECIONAR TODOS

";
$listar .= "

             Cliente
             Compras

";
$c = 1;
while($jmListar = mysqli_fetch_object($sqlListar)){
   $listar .= "
";
   $listar .= "<input type='hidden' name='Clientes[]' value='".$jmListar->IdCadastros."'> ".$jmListar->NomeUsuarios."	";
   $listar .= "

                      <input type=\"checkbox\" class='marcar' name='Comprou[]' value='S' id=\"checkbox\">

Sim

               	";
   $listar .= "
";
$c++;
}
$listar .= "
";
$listar .= "
";
}
....

JQuery
function marcarDesmarcar()
{
  if($("#marcarTodos").prop("checked"))
  {
    $(":checkbox[name='Comprou']").attr("checked","checked");
  } else {
    $(":checkbox[name='Comprou']").removeAttr("checked");
  }
}

Enfim, uma bagunça só. Como faço para que ao clicar em Selecionar Todos, ele marcar todos os checkboxs, mas quando desmarcar um deles o checkbox Selecionar Todos fique desmarcado também?
Answer: Você pode fazer desta forma, terá controle total sobre os checkboxes. Quando algum for desmarcado, o "SELECIONAR TODOS" será desmarcado e vice-versa:

function marcarDesmarcar()
{
   $(":checkbox[name*='Comprou']").prop("checked", $("#marcarTodos").is(":checked") ? true : false );
}

$(":checkbox[name*='Comprou']").click(function(){

   var mTodos = $("#marcarTodos");

   if(mTodos.is(":checked") && !$(this).is(":checked")){
      mTodos.prop("checked", false );
   }else{
      var cbs = $(":checkbox[name*='Comprou']");
      var allchkd = true;

      for(var x=0; x<cbs.length; x++){
         if(!$(cbs[x]).is(":checked")){
            allchkd = false;
            break;
         }
      }

      if(allchkd) mTodos.prop("checked", true );
   }
});

      <input onclick="marcarDesmarcar()" id="marcarTodos" type="checkbox"> Selecionar todos

      <input name="Comprou[]" type="checkbox">

      <input name="Comprou[]" type="checkbox">

Comment: Obrigado dvd. Funcionou perfeitamente!
Answer: Apenas corrigi seu código:
$(":checkbox[name='Comprou']").prop("checked",true);

Estava .prop("checked","checked");. Espero ajudar:

function marcarDesmarcar()
{
  if($("#marcarTodos").prop("checked"))
  {
    $(":checkbox[name='Comprou']").prop("checked",true);
  } else {
    $(":checkbox[name='Comprou']").removeAttr("checked");
  }
}

<input type="checkbox" id="marcarTodos" onclick="marcarDesmarcar()">
Marcar/Desmarcar Todos

<input type="checkbox" name="Comprou">
Item 1

<input type="checkbox" name="Comprou">
Item 2
Comment: Olá Taylor. A solução do dvd serviu dentro do que eu esperava. Obrigado mesmo assim.


Reporting $R^2$

Question: Following my question here, when is it appropriate (or inappropriate) to report r squared for a bivariate linear correlation.
As explained in the earlier question, r = 0.74 which results in r squared of 55%.
The size of r is an excellent outcome but when r squared is taken into account (especially when 45% of the variance in the dependent variable remains unexplained), it sort of dilutes the message.
As pointed out in the answer to the earlier question, I do understand that it is not readily possible for a single factor to explain all the variation.
I think all statistical textbooks that I have consulted (unless I am consulting the wrong books!) state that r squared is a better way of understanding r (or the effect size).
I do understand though that r of at least 0.71 is needed to get r squared of 50%.
Questions

Is reporting both r and r squared a good practice (in social science research)?
When can I not report r squared?

I have asked Q2 in order to to avoid a situation like the above, where my non statistical target audience may focus more on 45% of the unexplained variance, rather than on the 55% of the explained variance.
Comment: Is it ever a good idea to report something when you have it? I realize there are different conventions for different sciences, but reporting $R^2$ is normal in economics. BTW, $R^2=.55$ is pretty good for a bivariate, non-time-series regression. Your biggest issue with a bivariate regression will be [omitted-variable bias](http://en.wikipedia.org/wiki/Omitted-variable_bias).
Answer: You don't need to report both, either is fine.
Reporting R^2 does not "dilute" the meaning of R.  That's like saying reporting your speed in kilometers per hour dilutes the meaning of speed in mile per hour.
In social science research, an R^2 of .45 is suspiciously HIGH.
Comment: Well, the sign of $r$ tells you the direction of the relationship, while $R^2$ does not.
Comment: @macro Good point.
Answer: I don't really feel like this question has an answer.  It's sort of asking 'how do I pick a value for alpha in a hypothesis test?'  I could explain to you what alpha is, but there's no rule or formula for picking an appropriate value.  In terms of scientific research, you don't only report things when you want to, though.
Knowing that two variables have no relation is sometimes just as important as knowing that they do have a strong relationship. For example, if you designed an experiment, you may be interested in showing that two variables which are commonly assumed to be causal are in fact not related when viewed outside of an observational study.

Reporting $R^2$


Calculando data e hora

Question: Estou utilizando a estrutura tm do header time.h da seguinte forma:
<code>#include <stdio.h>
#include <time.h>

int main()
{
    struct tm dt_current, dt_begin;

    dt_current.tm_year = 2018;
    dt_current.tm_mon = 11;
    dt_current.tm_mday = 13;

    dt_current.tm_hour = 9;
    dt_current.tm_min = 45;
    dt_current.tm_sec = 0;

    printf("Data %d/%d/%d\n", dt_current.tm_mday, dt_current.tm_mon, dt_current.tm_year);
    printf("Hora %d:%d\n", dt_current.tm_hour, dt_current.tm_min);
    printf("-----------------\n");
    printf("10 dias atras\n");

    dt_begin = dt_current;
    dt_begin.tm_mday = dt_begin.tm_mday - 30;
    printf("Data %d/%d/%d\n", dt_begin.tm_mday, dt_begin.tm_mon, dt_begin.tm_year);
    printf("Hora %d:%d\n", dt_begin.tm_hour, dt_begin.tm_min);

    return 0;
}
</code>
Tem alguma função que eu possa retirar n dias da data (dt_current) ou preciso fazer o tratamento manualmente?
Comment: Tem que fazer manualmente. Só isso que queria saber?
Comment: Pensei em um jeito mais fácil, transformar datetime em dias e subtrair n dias, depois transformar novamente em datetime, tem alguma função que já faz isso ou na unha também?
Comment: Não existe tipo `datetime` tudo que ser na mão.
Answer: Com a estrutura tm da lib time.h você pode atribuir data do sistema ou uma manualmente, o ponto é que uma vez que você faz alguma operação com sua data é necessário valida-la e isso é feito com o comando mktime.
<code>struct tm dt_current;

dt_current.tm_year = 2018;
dt_current.tm_mon = 11;
dt_current.tm_mday = 13;
dt_current.tm_hour = 9;
dt_current.tm_min = 45;
dt_current.tm_sec = 0;

dt_current.tm_mday = dt_current.tm_mday - 30; // Voltar 30 dias

printf("%d/%d/%d\n", dt_current.tm_mday, dt_current.tm_mon, dt_current.tm_year);
// Saida: 17/11/2018 -> ESTA ERRADO

mktime(&dt_current); //Recalcular a data
printf("%d/%d/%d\n", dt_current.tm_mday, dt_current.tm_mon, dt_current.tm_year);
// Saida: 14/10/2018
</code>
O mesmo pode ser feito com as horas.

Calculando data e hora


Selecting First Name of Billing Address in Rules with Data Selector?

Question: How do I use data selector for Billing Address > First Name in Rules for Commerce?
I want to use the order owner's first name in automatically generated emails.
For example:

Hey Scott,
Thanks for your order...
Answer: The solution likely depends on the billing customer profile's address field using a split first and last name field instead of the combined "full name" field. I've noticed on my Commerce site that there appears to be a bug in Address Field (hope to fix soon) that prevents a full name field from being split up into first and last name fields or vise versa.
Assuming your customers are entering first and last name separately, then all you have to do is drill down from the order through the profile to the first name on the address field. To do this using a Rules data selector, you'd first need to add two "Entity has field" conditions - one to ensure the commerce-order entity has the commerce_customer_billing field and a second to ensure the commerce-order:commerce-customer-billing entity has the commerce_customer_address field. IF those are in place, using the data selector you can drill down to the following token:
commerce-order:commerce-customer-billing:commerce-customer-address:first-name
The problem comes when you actually want to embed this value in the body of an e-mail. Right now, as far as I can tell, there is no chain of tokens (replacement patterns in Rules UI parlance) that will drill down to the first name using that same pattern. Looking in the code for addressfield.module, I don't see any token related code. This may just need to be opened as a feature request for the Token module.
Comment: Actually, yes, Address Field has core token support nowadays. : )
Comment: Is there any update on this answer?
Answer: Found the solution. My rule was already sending an email but I could not see any token for the customer first and last name.

Add a condition "Entity has field" > commerce_customer_billing
Add an action "Fetch entity by id":
Entity type  > Value: Commerce Customer Profile
Identifier > Data selector: commerce-order:commerce-customer-billing:profile-id
Provided variables
Variable label: Customer Billing Profile
Variable name: customer_billing_profile
Add an action "Send email"
(if you installed Mime Mail module for sending email within Rules you can choose "Send HTML e-mail" like I did)
Use those tokens for first name and last name:
[customer-billing-profile:commerce-customer-address:first_name]
[customer-billing-profile:commerce-customer-address:last_name]

Note that it's taking the first and last name from the order itself NOT in the address book or profile. So if a user change its name in his address book it won't update in the order. I tried it.
I was inspired by a rule set found here:
https://gist.github.com/ogredude/3956560
Comment: I think this should be the accepted answer :)


How to force detach EBS from EC2 instance?

Question: I can't restart my EC2 instance, and there are important data in both the EC2 instance and external EBS volume.
Now I want to mount the EBS in my new temporarily created EC2 instance, and fix that old EC2 instance later. I  detached the EBS volume in the AWS Console, but the EBS state is still remains in `i-6da1cf05:/dev/sdf (detaching)' state and can't be attached to the new EC2 instance.
What can I do now?
Answer: Add --force option to ec2-detach-volume utility:
<code>sudo apt-get install ec2-api-tools
ec2-detach-volume [LOGIN-OPTIONS] --force VOL-ID
</code>
Comment: Keep in mind that there's a potential for data loss when you do this. Read more about --force here: http://docs.amazonwebservices.com/AWSEC2/2010-08-31/CommandLineReference/index.html?ApiReference-cmd-DetachVolume.html
Comment: Console allows this now too.


Intepreters and static type checking

Question: After reading this post:
How does an interpreter/compiler work
I have this question:
In a programming language that has only interpreter (for example Basic) (as shown in the photo in the second answer  in the above link) is it possible to have static type checking??.
 As far as I know the interpreter run each single line-command every time we execute the program. So how could be possible to do check the types statically before we run the program??
Comment: As an example: Haskell is a well-known statically typed PL. You can run a Haskell program via the interpreter `runhaskell hello.hs`. Haskell does check the types first — compile time is just before run time.
Comment: Doesn't "interpreter" mean "no types" by definition?
Comment: It depends on your definition of "statically typed". If you mean "known at compile time", then no, interpreted only languages cannot have statically typed variables simply because there is no "compile time" step. If you mean "variable is locked to a type" then yes, an interpreted language can have statically typed variables. I've seen both definitions, which is why I bring it up. Usually the term is referring to the first definition.
Comment: But the whole issue is blurry because many interpreted languages also have a compile step, it just happens at runtime. So the case in which you're asking should be made explicitly clear, otherwise the only answer that can be given is "it depends".
Comment: @  Lasse V. Karlsen ,I mean "known at compile time" ,thanks for the answer ,I just want to make sure if i had thought this right thanks!!!!
Comment: A language is a language, it is neither interpreted nor compiled. *The interpreter* for that language or *the compiler* for that language is what determines how it runs. The same language can be run through an interpreter *or* compiled by a compiler. Many languages have multiple compiled/interpreted implementations. The same language can also be *statically analysed*, with the static analyser trying to infer as much type information as it can without actually executing the code.
Comment: @ deceze ,Yes but with interpreter everything is decided in running time ,so how could we talk about static typing language???
Comment: That is not the deciding factor. Imagine a *type annotated* language, e.g. `Foo foo = new Foo()`… An interpreter could heed those type hints *at runtime* and throw errors when they don't match. Conversely, you can perfectly have *non-type annotated* languages which are compiled: `let foo = new Foo()`. The compiler is able to *infer* the type here pretty obviously. And so can a static analyser.
Answer: It is common to say that a statically typed programming language is type checked "at compile time", so it might be easy to say "interpreters don't have a compile time1 and therefore can't be statically typed", but really "static" doesn't necessarily mean "at compile time", it means "before run time" or "without running the code".
So a statically typed language is one where a type error anywhere in the program will cause the program not to run. Whereas in a dynamically typed language a type error will only abort execution when and if control flow reaches the ill-typed statement.
So given this definition can a statically typed language be implemented using an interpreter? Sure. Just let the interpreter find type errors in the program (using the same algorithms a compiler would use) before it starts executing anything and voilà you have static type checking.
The reason you might not want to do that is that it increases startup time as it introduces an additional step before the code starts executing. And depending on the complexity of your type system, type checking may actually consume a lot of time. So that can be quite annoying for an interpreter, but it's definitely possible.

1 This is only true for very simple interpreters though. Most real-world interpreters involve some code generation, be it bytecode or JITed machine code.
Answer: A language is a language, it is neither interpreted nor compiled, until it is. Meaning, the same language can be interpreted on the fly or it can be compiled into a binary. In fact, an interpreter does compile the code on the fly into byte code.
The main difference between compiled and interpreted languages is that an interpreted program needs a separate runtime, while a compiled program can typically run by itself or with minimal bootstrap help from the operating system. A compiler will typically also spend more time on the compilation step than an interpreter, where it can do more in-depth error checking and code optimisations. An interpreter doesn't do this only because it is a slow process, not because it's fundamentally impossible.
Type hints/inference is a completely separate problem. Many languages which are primarily compiled use type hints extensively, because the compiler has the time to use that information. Mainly interpreted languages often forgo type hints, because the additional type checking costs time at runtime, and the design goal for the language is a fast development cycle to begin with, which includes less typing. That doesn't mean those languages are "type free" by any means, every single value still has a type, and that type is known. In fact, even many compiled languages these days forgo explicit type annotation when it is unnecessary for brevity. For example:
Foo foo = new Foo();

let foo = new Foo();

The Foo type hint here is rather superfluous; of course the compiler can infer that foo is of type Foo here, just looking at the right hand side of the assignment. The same goes for any other type, including numbers, strings and so on. A compiler or static type analyser can trace what values are being assigned to variables or returned from functions and infer a lot about types without a single explicit annotation.
Having said this, in unannotated languages which heavily depend on runtime information, in some situations it's not possible to know what type a variable will be until runtime. In that case a static type analyser or compiler cannot help in advance and cannot catch errors resulting from incompatible types at compile time. For example, TypeScript is a bolt-on solution for static typing for Javascript, and it walks that line. Everything you do annotate in TypeScript is rigorously type checked; anything you do not annotate or leave as any cannot be type checked and may blow up in your face at runtime.
Type systems in statically typed languages and dynamically typed languages serve different purposes (note statically vs. dynamically typed, not "compiled" vs. "interpreted"). Static typing serves mainly to catch errors at compile time and give a compiler more information to produce better code; dynamic typing serves to define program behaviour, i.e. how values of two types should behave when operated upon, which includes throwing an error on incompatible types. Such incompatible type errors can still be predicted by a static analyser, even if not in all situations.
Comment: deceze, I agree that the characteristics of a language depends on the designing process of the language ,but I can't when it comes to check the types which I believe the type checking is independent (as you also mention) from the language ,the I think we couldn't statically check the types with only interpreter??
Comment: I'm not sure I understand what you're asking, but… If you assign a number to a variable, it's clear that the variable will hold a value of type number. If then the code goes on to only do numeric operations on that value, it's very clear and easy to trace that this value will continue to be a number. That's what a static analyser can do perfectly fine. There are situations in code where the analyser will cease to be able to infer the type in advance, e.g. `foo = rand(0, 1) ? 42 : 'bar'`. In that case it can either raise a warning about type safety, or give up predictability features.

Intepreters and static type checking


on click popup load another popup and close other popup

Question: I'm having a requirement where I have to show popup on the click link. and then after that pop up open need to show related content on that pop-up. this part is working. by doing this

Click

so when I click related content I again need to show a popup and close the old one.
this case not working
I know there is CloseModalDialogCommand but how to use in this case as I have

Click

this link for related content also
Answer: As per my understanding you want to open a new modal from an existing open modal. I have checked the same case in latest drupal 8.7.5 and it works without a problem. You don't have to add any additional script to do this. I would recommend you to debug it and check the exact problem that is preventing popup to open and close existing one. You can follow the below steps to debug it-

Create any of 2 dummy articles like below and link one with another one.

First Article:-
Title - Dummy Article 1
Body - Click Article 2
Text Format - Full HTML
URL - node/1

Second Article:-
Title - Dummy Article 2
Body - Click Article 1
Text Format - Full HTML
URL - node/2

Open/View any of the above created article to check if the problem is with the modal or related with any other issue. Check browser console if in case modal doesn't open.