Azure CDN - request hostname different to origin hostname

Question: Let's say we have a custom domain name on an Azure CDN endpoint (e.g. custom domain is www-mydomain-com) that uses an Azure CDN managed certificate.
The origin for the CDN endpoint is WordPress running on an Azure App Service - origin type = Web App.
The Azure App Service native hostname is mydomain-azurewebsites-net .
It should be noted that at present the Azure App Service also has the same custom domain added (www-mydomain-com) with a valid publicly trusted certificate added.
DNS CNAME for www-mydomain-com resolves to the Azure CDN endpoint hostname (mydomain-azureedge-net).
The CDN endpoint origin is set with Origin host header blank, as per the tool tip provided by Azure portal:
"The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services, require this host header value to match the origin hostname by default."
This all works well. From logging we can confirm that a client requests www-mydomain-com and requests to origin are also to www-mydomain-com.
If we change the Origin host header to mydomain-azurewebsitesnet, then i see some odd behaviour.
Client requests www-mydomain-com - and the page loads as normal - I can confirm this is a cache miss.
Client requests to another URL - www-mydomain-com/test - this is again a cache miss, however logs show a call to origin - hostname is as expected set to mydomain-azurewebsites-net .
What is weird is that the client is then directed to mydomain-azurewebsites-net/test and NOT www-mydomain-com/test .
If a client re-requests www-mydomain-com/test - the page loads normal from cache.
It appears that the original client request is proxied to the origin using the origin host header - on a cache miss.
What I was expecting, is that requests are only ever served to clients from Azure CDN and that the CDN pulls the content from origin into cache when needed(using the set origin host headers).
What I would like to achieve is not having to add a publicly trusted cert on the App Service(just rely on the azurewebsite-net cert for the CDN to origin TLS connection).
Am I missing anything here or is this just a limitation of Azure CDN(I am not using Verizon or Akamai Azure CDN).
Comment: Why did you add a custom hostname to your appservice to begin with? Have you tried to remove that one? Then the app service should not confuse anything and just be reachable under foo.azurewebsites.net
Answer: I logged an MS ticket and during the course of that troubleshooting, I had a light bulb moment. The call to origin with the mydomain-azurewebsitesnet host header results in the backend WordPress loading the page with relative links into cache with host mydomain-azurewebsitesnet. This means that all links within the page - even when served from cache, reference the origin host. One fix is to hard code links with host www-mydomain-com - this is not ideal.
Not sure why I thought of it, but further testing revealed that Azure CDN calls to origin  using HTTPS - require the origin cert to have the host header on the cert BUT - the certificate does NOT have to be within its valid dates. I.e. you can use an expired cert with correct host name.
This allows me to achieve my original goal.
Azure CDN - leave origin host header blank - this means client host header passes through for origin requests - means my links all work correctly. The origin WebApp uses an expired cert that has the correct host listed(that matches host sent by client). Requests from CDN to origin on HTTPS still work.
This allows me to use an Azure CDN provided and managed TLS certificate(issued by DigiCert) and NOT have to worry about renewing and managing a certificate on the Azure App Service WebApp(expired cert still works).


Predict with a VECM with exogen variables

Question: After having estimated a VECM model with stationary exogen variables, I would like to compute a prediction with the predict function and the newdata argument. I'm using the Dynts library that offers the possibility to compute VECM models with exogeneous variables, but I don't see how I can use the predict function with newdata for the integrated variables AND the exogeneous ones.
The following code doesn't work. Any idea ?
library(tsDyn)
Fact1<-rnorm(100,0,10)
x<-rnorm(100,0,10)
y<-rnorm(100,0,15)
i<-1:100
Yniv2<-sapply(i,function(k) sum(x[1:k]))
Facti1<-Yniv2+y
Yniv2<-Yniv2[1:99]
plot(Yniv2,type="l")#variable macro que l'on cherche à prévoir à l'instant t
lines(Facti1,col="red")#variable macro cointégrée avec Y dont on dispose l'obs en t
lines(Fact1,col="green")#variable stationnaire qui explique également Y

exog_met1v1<-Fact1[2:99]
exog_i1<-cbind(Yniv2[1:98],Facti1[1:98])
mdl<-VECM(exog_i1, 1, r=1, include = "const", estim = "ML", LRinclude = "const", exogen = exog_met1v1)
newexogi1 <-cbind(Yniv2[1:99],Facti1[1:99])
new <- Fact1[2:100]
newdata<-cbind(newexogi1,new)
Prev_H_1<-data.frame(predict(mdl, newdata))[,1] #pbbb

First error if I want the global fit
Please provide newdata with nrow=lag+1 (note lag=p in VECM representation corresponds to p+1 in VAR rep)

Second error if I provide just the last observations
newexogi1 <-cbind(Yniv2[98:99],Facti1[98:99])
new <- Fact1[99:100]
newdata<-cbind(newexogi1,new)
Prev_H_1<-data.frame(predict(mdl, newdata))[,1] #pbbb

Erreur dans TVAR.gen(B = B, nthresh = 0, type = "simul", n = n, lag =    lag,  :

Matrix B badly specified: expected 5 elements ( (lagK+ n inc) (nthresh+1) ) but has 6
Comment: Please take the time to define all the variables in your code and provide some sample input to make your problem [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), otherwise it's much more difficult to help you..
Comment: Yes, this is a bug. I will try to solve it soon.
Answer: I made some modifications, (subject to future changes!), but here you go:
## install development version:
library(devtools)
install_github("MatthieuStigler/tsDyn", ref="Dev94", subdir="tsDyn")

## use these arguments:
predict(mdl, newdata=newexogi1, exoPred=new, n.ahead=2)

Comment: Thank you for your quick answer, but it still doesn't work :(. I tried on the same example I explained above and here is the returned error : `> newexogi1 <-cbind(Yniv2[99],Facti1[99])
> new <- Fact1[100]
> predict(mdl, newdata=newexogi1, exoPred=new, n.ahead=1)
Erreur dans predict.VECM(mdl, newdata = newexogi1, exoPred = new, n.ahead = 2) :
  Please provide newdata with nrow=lag`
Comment: Plus, I don't really understand why the length of the input should be of the same length of "lag", it prevents the function to return the ajustment of the models on the whole estimation period, which is often what is commented (at least in macroeconomics). Keep me in touch if you procede to further modifications please and thank you for the work
Comment: Mmh. The point is in fact that the function converts the VECM to a VAR (lag+1), and then does a prediction in terms of levels, not differences! This explains why you should provide 2 rows (levels) and not 1 (the diff).
I am not sure on the other hand to understand your second point regarding "prevent the adjustment on the model on the estimatoin period?". Do you want to generate n-ahead forecasts from multiple periods?
Comment: Ok I got it, the endogeneous newdata are longer than the exogeneous newdata. It seems to work, thank you very much !
Comment: Indeed! Exogeneous newdata should be of size n.ahead, while endogeneous data should be of size lags(+1 if vecm)! I'll document this better!
Comment: @Matifou I had a similar problem, but I tried to change ``newdata`` to 2 observations (endogenous data that would match with the VAR lag(VECM lag(1) + 1) and ``exoPred`` to 2 observations as well (to match with ``n.ahead``) as you said. But I kept receiving the same problem. Could you see the code in https://stackoverflow.com/questions/64096043/i-cant-make-a-vecm-prediction-with-tsdyn-package-number-of-test-data-rows-diff ?


Computing a prior from two components in Naive Bayes

Question: Given a model parameter $\theta$ that is composed of two distributions in a Naive Bayes classifier, how is $P(\theta)$ typically computed in practice?
More specifically, from the article of Nigam et al 2006 (pdf link), $\theta$ is two Dirichlet distributions: one for words $w_t$conditioned on classes $c_j$ denoted $\theta_{{w_t|c_j}}$ and the other for overall class probas denoted $\theta_{c_j}$.
The questions is: how to compute the term
$\log(P(\theta))$ appearing in Equation 3.8?
E.g., is there an implicit factorization assumption in this article so that we have a product $P(\theta) = P(\theta_{{w_t|c_j}}).P(\theta_{c_j})$ ?
If so, then we have
$\log(P(\theta)) = \log(P(\theta_{{w_t|c_j}})) + \log(P(\theta_{c_j}))$ which is simple to compute since each term on the right hand side is itself a log of products, i.e. sums of probabilities from Equations 3.5 and 3.6.
Conversely, if there is not a factorization assumption how is $\log(P(\theta))$ computed in this setting?
Answer: There might be an implicit assumption that $P(\theta_{w_t | c_j}) = P(\theta_{w_t | c_j} | \theta_{c_j})$. Then using the identity $P(A,B) = P(A|B)P(B)$ we have the third equality in $P(\theta) = P(\theta_{w_t | c_j}, \theta_{c_j}) = P(\theta_{w_t | c_j}|\theta_{c_j}) P(\theta_{c_j}) = P(\theta_{w_t|c_j})P(\theta_{c_j})$


Excluding certain combinations from combn function in R

Question: I am trying to exclude all combinations generated by combn function that consists of "var4" and "var5". Here below is the code that does not work at the moment:
mod_headers <- c("var1", "var2", "var3", "var4", "var5", "var6")

f <- function(){
  for(i in 1:length(mod_headers)){
    tab <- combn(mod_headers,i,function(mod_headers){
      if (combn(mod_headers,i) %in% c("var4","var5")) {return()}
    })
    for(j in 1:ncol(tab)){
      tab_new <- c(tab[,j])
      mod_tab_new <- c(tab_new, "newcol")
      print(mod_tab_new)
    }
  }
}

f()

Thanks for your help!
Comment: It's ok for either to occur by itself, you just don't want them to occur together?
Comment: yes, exactly, I do not want them to occur together. Thanks!
Answer: I'm not really sure how you want your result to be formatted, so I stopped at getting the combinations that exclude the appearance of two values together. It relies on the fact that combn returns a matrix where each column is a combination.
mod_headers <- c("var1", "var2", "var3", "var4", "var5", "var6")

combn_with_exclusion <- function(x, n, exclude){
  full <- combn(x, n)
  # remove any columns that have all elements of `exclude`
  full[, !apply(full, 2, function(y) all(exclude %in% y))]
}

combn_with_exclusion(mod_headers, 2, c("var4", "var5"))

Comment: Thanks, your script provides me with the desired outcome, however, I would not like to change the structure of my code because it is a part of more robust code (I just deleted all the parts that are not necessary here). Is there a way how to apply the FUN directly into combn function? Thanks
Comment: I think Andrew Gustar's answer may be what you want to use in place of your `f()`.
Comment: @New2coding The `FUN` in the `combn` function is applied to each individual combination, and I can't think of a way of getting it to omit the combination entirely if it meets your criteria.  An `ifelse` to replace it with `NULL`, for example, does not work.
Comment: Ok, thanks for your comment. I am trying to make this piece of code work because it is a part of my other code. The thing I am trying to do is to exclude correlated variables from GLModel by excluding names of correlated headers (original post here: https://stackoverflow.com/questions/45466513/how-to-remove-correlated-variables-from-glm-in-r)
Answer: Here is another way, generating a list of all combinations, then excluding those containing both var4 and var5...
lapply(
   lapply(1:length(mod_headers),
        function(i) combn(mod_headers, i)),
   function(x) x[,apply(x, 2, function(y) !all(c("var4", "var5") %in% y))])

[[1]]
[1] "var1" "var2" "var3" "var4" "var5" "var6"

[[2]]
     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]   [,10]  [,11]  [,12]  [,13]  [,14]
[1,] "var1" "var1" "var1" "var1" "var1" "var2" "var2" "var2" "var2" "var3" "var3" "var3" "var4" "var5"
[2,] "var2" "var3" "var4" "var5" "var6" "var3" "var4" "var5" "var6" "var4" "var5" "var6" "var6" "var6"

[[3]]
     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]   [,10]  [,11]  [,12]  [,13]  [,14]  [,15]  [,16]
[1,] "var1" "var1" "var1" "var1" "var1" "var1" "var1" "var1" "var1" "var2" "var2" "var2" "var2" "var2" "var3" "var3"
[2,] "var2" "var2" "var2" "var2" "var3" "var3" "var3" "var4" "var5" "var3" "var3" "var3" "var4" "var5" "var4" "var5"
[3,] "var3" "var4" "var5" "var6" "var4" "var5" "var6" "var6" "var6" "var4" "var5" "var6" "var6" "var6" "var6" "var6"

...etc

Answer: I've only tried this on TIO, so no benchmarking, but I'd wager to bet that this version will be quicker for large sets, if that should be of importance.
m <- c("var2", "var3", "var4", "var5", "var6")
comb <- combn(m, 3)
csums <- colSums((comb == "var4") + (comb == "var5"))
comb[, csums < 2]
#      [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]
# [1,] "var2" "var2" "var2" "var2" "var2" "var3" "var3"
# [2,] "var3" "var3" "var3" "var4" "var5" "var4" "var5"
# [3,] "var4" "var5" "var6" "var6" "var6" "var6" "var6"

Or equivalent to OP's f():
f2 <- function(m=mod_headers) {
    lapply(1:length(m), function(x) {
      comb <- combn(m, x)
      csums <- colSums((comb == "var4") + (comb == "var5"))
      comb[, csums < 2]
    })
}

Comment: This is my solution:

f <- function(){
  for(i in 1:length(mod_headers)){
      tab <- combn(mod_headers,i)
      for(j in 1:ncol(tab)){
        tab_new <- c(tab[,j])
        mod_tab_new <- c(tab_new, "newcol")
        if (all(c("var4","var5") %in% mod_tab_new)) next
        print(mod_tab_new)
    }
  }
}

f()
Answer: This is my solution:
f <- function(){
  for(i in 1:length(mod_headers)){
      tab <- combn(mod_headers,i)
      for(j in 1:ncol(tab)){
        tab_new <- c(tab[,j])
        mod_tab_new <- c(tab_new, "newcol")
        if (all(c("var4","var5") %in% mod_tab_new)) next
        print(mod_tab_new)
    }
  }
}

f()

Answer: I used this webpage to reduce a list of N-Way combination given another set of N-Way combinations. Here's a slight modification of Benjamins Code.
mod_headers <- c("var1", "var2", "var3", "var4", "var5", "var6")

combn_NWayExclusion <- function(x, n, exclude){
   full <- combn(x, n); EXC<-combn(exclude, n)
   UU<-lapply(1:ncol(EXC),function(i) !apply(full, 2, function(y) all(EXC[,i] %in% y)))
   full[,!apply(do.call(rbind,UU),2,function(u){any(u=="FALSE")})]
   }

combn_NWayExclusion(mod_headers, 2, c("var4", "var5"))


HttpClient with PostAsync code optimisation

Question: I am using below code, Code is working fine. I am new to HTTPClient so i am not sure if this code is optimised properly or what is the best way to code it. I found this example which talks about deadlock even though it is about parallel programing but i just want to make sure ifthis code can be improved/optimized for performance or error.
I connect to website with certain key parameter & get in return json data. which i i process for further action.
protected void btnClient_Click(object sender, EventArgs e)
    {
        using (var client = new HttpClient())
        {

            client.BaseAddress = new Uri("https://secure.telr.com/");
            client.DefaultRequestHeaders.ExpectContinue = false;
            var result = client.PostAsync("gateway/order.json",
                new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("ivp_method", "create"),
                new KeyValuePair<string, string>("ivp_store", "12345"),
                new KeyValuePair<string, string>("ivp_authkey", "xxx-xxxxxx"),
                new KeyValuePair<string, string>("ivp_cart", "123452"),
                new KeyValuePair<string, string>("ivp_desc", "Descripion"),
                new KeyValuePair<string, string>("ivp_test", "1"),
                new KeyValuePair<string, string>("ivp_amount", "10.00"),
                new KeyValuePair<string, string>("ivp_currency", "UAD"),
                new KeyValuePair<string, string>("return_auth", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_can", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_decl", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("ivp_framed", "1"),
            })).Result;

            var jsonData = (JObject)JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);

            dynamic jObj = JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);

            string url = jsonData["order"]["url"].ToString();
            Response.Write("
url" + url + "
");

            ltrTelr.Text = "";

        }
    }

Answer: You should avoid trying to access the Task.Result when you're not sure if/when your API is going to return data. That would block your thread because it's trying to evaluate the result.
Instead, when you're calling an async method you should use the 'await' keyword so you free up the thread, like this:
protected async Task btnClient_Click(object sender, EventArgs e)
{
    using (var client = new HttpClient())
    {

        client.BaseAddress = new Uri("https://secure.telr.com/");
        client.DefaultRequestHeaders.ExpectContinue = false;
        var result = await client.PostAsync("gateway/order.json",
            new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("ivp_method", "create"),
            new KeyValuePair<string, string>("ivp_store", "12345"),
            new KeyValuePair<string, string>("ivp_authkey", "xxx-xxxxxx"),
            new KeyValuePair<string, string>("ivp_cart", "123452"),
            new KeyValuePair<string, string>("ivp_desc", "Descripion"),
            new KeyValuePair<string, string>("ivp_test", "1"),
            new KeyValuePair<string, string>("ivp_amount", "10.00"),
            new KeyValuePair<string, string>("ivp_currency", "UAD"),
            new KeyValuePair<string, string>("return_auth", "http://localhost:1044/Test2.aspx"),
            new KeyValuePair<string, string>("return_can", "http://localhost:1044/Test2.aspx"),
            new KeyValuePair<string, string>("return_decl", "http://localhost:1044/Test2.aspx"),
            new KeyValuePair<string, string>("ivp_framed", "1"),
        }));

        var rawData = await result.Content.ReadAsStringAsync();

        var jsonData = (JObject)JsonConvert.DeserializeObject(rawData);
        dynamic jObj = JsonConvert.DeserializeObject(rawData);

        string url = jsonData["order"]["url"].ToString();
        Response.Write("
url" + url + "
");

        ltrTelr.Text = "";

    }
}

Comment: I am getting following error ` The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.`
Comment: `Task.WaitAll(Task.Run(async () =>
                {
                   ....
                   await result.Content.ReadAsStringAsync();
                }`
Comment: Oh, sorry, yeah when you use await you have to make your method async as well. The return type 'Task' is the async equivalent of void (https://msdn.microsoft.com/en-us/magazine/jj991977.aspx)


how to pass args pattern factory java

Question: i tring to implement a factory pattern in java, but i have some probleme
i have the class AbstractAction that is the abstract class for subclasses like MapMoveAction, CutAction
and the class ActionFactory that is the factory for creating instace of concrete class, the action factory class contain a static method createAction that take a string as parameter for identifying the concrect class to create
but my probleme is that each concrecte class take differente parameter when he need to be constructed :
 public class ActionFactory {

    public AbstractAction createAction(String uniqueName) {

        // TODO
    }
}

public class CutAction extends AbstractAction{

    public static final String UNIQUE_NAME = "cut";
    List<Resource> resources;

    public CutAction(List<Resource> resources) {
        this.resources = resources;
    }

    @Override
    public String getActionCommand() {
        StringBuilder command = new StringBuilder(UNIQUE_NAME);
        command.append(" ");

        for(Resource resource : resources) {
            command.append(resource.getName());
            command.append(",");
        }

        command.deleteCharAt(command.lastIndexOf(","));

        return command.toString();
    }
}

public class UseAction extends AbstractAction{

    public static final String UNIQUE_NAME = "use";

    int cell;

    public UseAction(int cell) {
        this.cell = cell;
    }

    @Override
    public String getActionCommand() {
        return UNIQUE_NAME  + " " + cell;
    }

}

Answer: The factory pattern also says to have an abstract factory with concrete factory subclasses.

The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."

Therefore, you need to make your ActionFactory abstract:
public abstract class ActionFactory {
    public abstract AbstractAction createAction();
}

Note, that the createAction method does not need a parameter anymore. Then you write concrete factories, such as
public class CutActionFactory extends ActionFactory {
    @Override
    public CutAction createAction() {
        // This factory knows how to create CutAction instances.
        return new CutAction(createResources())
    }
    private List<Resource> createResources { ... }
}

how to pass args pattern factory java


Assessing variable importance in generalized additive models (GAM)

Question: In a linear model, it's easy to assess the importance of each explanatory variable. If the assumptions of the model are met, given two explanatory variables $x_1$ and $x_2$, both with a regression coefficient significantly different from zero, $x_1$ would be more important than $x_2$ if its estimated regression coefficient $\hat\beta_1$ is bigger than the estimated regression coefficient $\hat\beta_2$ of $x_2$. In other words, $x_1$ has a stronger association with the response than $x_2$ if $\hat\beta_1>\hat\beta_2$.
I was wondering if it's possible to assess the importance of the explanatory variables in a generalized additive model as well. The output of a GAM consists in the graphs of the estimated function for each variable. For instance:

I was wondering if it is possible to assess variable importance by looking at the values of the y-axis of each of this plots. Suppose that 'year', 'age' and 'education' are all significant and that the assumptions of the model are met.
Since the codomain of $\hat f_1(year)$ is approximately $[-10,10]$ while the codomain of $\hat f_2(age)$ is about $[-40,10]$, can I conclude that 'age' is more important than 'year'?
In other words, can I conclude that 'age' has a stronger association with the response than 'year'?
Doesn't $\hat f_1(year)$ translate vertically as 'age' varies? Does this affect interpretation and the assessment of variable importance?
Comment: I haven't tested yet but I believe this could be an option: http://depts.washington.edu/oldenlab/wordpress/wp-content/uploads/2013/01/EcologicalModelling_2015.pdf you will have to program in R though. Good luck! Rafa.
Answer: Variable importance doesn't have a universally agreed-upon definition, but usually it means something like how much variance is explained by a predictor in your model. What you're describing isn't really conventional variable importance, but sensitivity to change in a covariate.
Variance explained and sensitivity are not the same thing, and can be very different. A model could be highly sensitive to change in a covariate, but if that covariate itself has low variance, it might not explain much variance in the response. You can make variance explained and sensitivity correlate better numerically by rescaling predictors to have unit variance, but the concepts remain distinct. Sensitivity can be changed simply by rescaling a variable, while variance explained is invariant to scaling in linear models.
Sensitivity isn't a single well-defined number for a GAM precisely because of the nonlinearity.
In the mgcv package, the significance of model terms can be measured through the $\chi^2$ and $p$ values reported by summary.gam and anova.gam. However, significance again is yet another somewhat different concept than importance.


Click checkbox within TR element

Question: I'd like to select the checkbox based on the user email. I try somethig like this but doesn't work: "InvalidStateError: An exception was thrown  debugger eval code:1".
$x("//span[text()='email@example.com']/parent::div/previousElementSibling::td");

What am I doing wrong? Thanks!

            <input type="checkbox" value="option1">

            My
            User

            firstname.lastname@example.com

Comment: What happend when it "doesn't work"?
Comment: I've edited my question to include the error. Thanks!
Answer: previousElementSibling is not a XPath selector but a property on a element: https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling
An almost similar selector for a XPath is the preceding-sibling selector. But that will return all the preceding siblings so you will have to maximize the result to 1 with the [1] selector:
/preceding-sibling::div[1]

And then you still need to only select the divs containing the checkbox class so you will need the [contains(@class, 'checkbox')] selector and select the input with the /input selector.
The complete selector for the checkbox then looks like this:
$x("//span[text()='firstname.lastname@example.com']/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input")

If however you are using document.evaluate instead of $x you will need to replace the text()='the text' selector with the contains(. ,'the text') selector because the text() selector does not work in the document.evaluate method.
The complete executable code snippet:

var doc = document.children[0].children[1];
var checkbox = document.evaluate(
    "//span[contains(., 'firstname.lastname@example.com')]/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input",
    doc,
    null,
    XPathResult.ANY_TYPE,
    null
).iterateNext()

console.log(checkbox)
alert(checkbox)

            <input type="checkbox" value="option1">

            My
            User

            email@example.com

Comment: Thanks for your answer! I get back a zero length array if I try the suggested solution. I also tried: $x("//span[text()='firstname.lastname@example.com']/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input").click() but then I get- TypeError: $x(...).click is not a function.
Comment: @János I've edited my answer with a working code snippet. Also, I had to replace the `text` selector with the `contains` selector to make it work in a code example because you can use $x in the developer console but not in javascript code in a website.

Click checkbox within TR element


When a text box is on focus, how can I make a listen to a down arrow press

Question:
when a text box is on focus, how can I make a listen to a down and up arrow press?
how can I get the focus on an element using codes?

Update
I want this for an auto-complete search. It's working; all I want now when the down arrow key is pressed while typing, the focus moves to the drop-down list.
Comment: What do you want on up/down keys? Select next/previous text-fields?
Comment: no I'm making an auto-complete search. it's working all I want now when the down arrow key is pressed the focus moves to the drop-down list.
Answer: You could subscribe to the onkeydown event:
<input type="text" onkeydown="myFunc(this, event)" />

and inside the function check the key code to identify which key was pressed using the code:
function myFunc(sender, e) {
    var key = e.which ? e.which : e.keyCode;
    if (key === 38) {
        // up arrow was pressed
    }
}

and here's a demo.
As far as setting the focus to a given element is concerned you could use the focus() function:
document.getElementById('id_of_element').focus();

Comment: what's the `which/keycode` for down arrow? does this work for all browsers?. thank you ^^
Comment: @SamiAl-Subhi, the code for down arrow is 40. The which/keyCode make this code cross browser as depending on the browser it is either one or the other property which will contain the key code.
Answer: I tend to use a library for this kind of stuff; John Resig's jQuery Hotkeys does the job most of the time. You can bind and unbind a hotkeys handler using the focus and blur events:

handlerFn = function() { ... };
$('input.my-text-box').focus($(document).bind('keyup', 'down', handlerFn);
$('input.my-text-box').blur($(document).unbind('keyup', handlerFn));

Answer: You can use an excelent jQuery plugin named keyz to detect which key was pressed alng with ctrl, alt, shift combinations also. I have setup a working fiddle. You can move focus from one textbox to another using arrow keys (up/down).


Difference between new KeyEventHandler(Form1_KeyDown) and Form1_KeyDown

Question: In a windows forms application you can register event handlers like this:
<code>          this.KeyDown += new KeyEventHandler(Form1_KeyDown);
</code>
and later unregister the same handler like this:
<code>          this.KeyDown -= new KeyEventHandler(Form1_KeyDown);
</code>
To me this seems odd because I would expect the -= to require the same handler that was registered originally, not a second new handler of the same signature.  But from experience I know this works.  This led me to think that this was a special case and in reality
<code>          Form1_KeyDown == new KeyEventHandler(Form1_KeyDown)
</code>
Based on that theory I have often rewritten my code to register and unregister events like this:
<code>          this.KeyDown += Form1_KeyDown;
</code>
Is this safe? Or will this have some unintended side effect I don't realize?
Answer: It is identical, the compiler knows that it must create a new instance of the KeyEventHandler delegate from the event type.  And automatically generates the code for it.  Feel free to use it, it is crystal clear to anybody that reads your code.
Even the statement with the new operator is syntax sugar, the MulticastDelegate constructor takes two arguments, not one like the statement suggests, the Target (this) and the Method.  The compiler automatically figures out the target.  Understanding that a event subscription adds a reference to your object is important, it is a common source of leaks.
The += operator is syntax sugar too, it is translated to a call to add accessor method of the event.  Similarly, the -= operator is translated to a call to the remove accessor.  Lots of plumbing that's intentionally hidden.
Last but not least, you are doing it wrong.  You should override the form's OnKeyDown() method instead.  It doesn't make sense for a class to listen to its own events, they are meant for other, unrelated code.  That was a bit unlucky.


How to create dynamic layout in Laravel with Blade?

Question: So I'm building my first blog, and I'd like to dynamically show to posts on my landing page. I want the layout to become like this (might be a little weird):
post-image   - post-preview
post-preview - post-image
post-image   - post-preview

This is what I have right now to show to blog posts:
@foreach($posts as $post)

            slug }}">
                image ) }}" class="img-responsive" style="width:100%">
                {{ $post->title }}

    @endforeach

web.php (route):
$posts = App\Post::take(3)->orderBy('created_at')->get();
return view('welcome', compact('posts'));

Now as I'd like to make the layout dynamically. I think I can do this by checking if the ID even or odd. However I have no idea on how to do this even when I've searched 50% of the web already :) .
If there is a better way on doing this just let me know! Greatly appreciated guys!
Comment: What do you mean by dynamic layout?
Comment: That's the part with the post-image and post-preview. I'd like the images to go from left to right one way or another but I can't seem to find a way to do this with.
Comment: @Sylent please check my answer: https://stackoverflow.com/a/48074956/5013099
Comment: I already have an answer now, but i'll still check it out!
Answer: Yes you can do it by checking if current post or loop iteration is odd or even. (https://laravel.com/docs/5.5/blade#the-loop-variable) For Odd loop iteration, you can write image code first and in even loop iteration you can write preview code first to achieve your desired layout. You can check the following code:
@foreach($posts as $post)

         @if( $loop->iteration % 2 == 0 )

             slug }}">
                 image ) }}" class="img-responsive" style="width:100%">

             {{ $post->title }}

         @else

             {{ $post->title }}

             slug }}">
                 image ) }}" class="img-responsive" style="width:100%">

         @endif

@endforeach

Comment: Thanks man, I didn't know laravel had a `$loop` variable but it works now! thanks man!
Answer: Ok I guess I got your question. so there is no direct solution but you can measure inside your for loop by adding extra variable such as:
<?php $inc = 0;?>
@foreach($posts as $post)

        slug }}">
            @if($inc%2 == 0)
            image ) }}" class="img-responsive" style="width:100%">
            {{ $post->title }}
            @else
            {{ $post->title }}
            image ) }}" class="img-responsive" style="width:100%">
            @endif
            <?php $inc++;?>

@endforeach

Or you can use for loop instead of foreach of loop and inside for loop you can check variable i.e. i is odd or even.


Regression with one group having just zeros as input

Question: I want to analyse the effect of the sports membership fee on the cancellation probability with a simple regression. When a person leaves a sports club (Cancel = 1), their membership fee is automatically set to 0, as they no longer have to pay. This leads to a particular situation in my dataset:
Individuals who leave/are no member (Cancel = 1) automatically have MembershipFee = 0.
Individuals who remain members (Cancel = 0) have varying values for Membership fees.
Since MembershipFee = 0 applies to all individuals who leave, this can lead to a distortion in the data, since all datapoins at Cancel = 1 are at 0.
With the panel data, I attempted to investigate the relationship between membership fee in the previous year (t-1) and membership status (Cancel) in the current year (t) but there where no big changes to see. In addition, I have about 3x more data for the people who are still members.
What is the best way to conduct a reasonable analysis? The goal is to create a simple linear probability model.
Answer: What you seem to need here is to look a the membership fees prior to the decision to leave or stay. No problem getting this for the leavers, but you need it for a group of people who stay.
One way to do this is to try to match the leavers with members who decided to stay. There are lots of ways to match people and you can find info on that in books or by browsing the matching tag here. One common method is propensity score. You would need to consider what variables you want to use for the match -- demographics, distance to club, age, sex, etc.
There are probably methods other than matching as well.
Comment: thank you very much peter!


How to interpret pairs plot in R?

Question: I am a beginner in plotting/graphing. Kindly explain how  to interpret the pairwise scatter plots generated using pairs() function in R.
The data contains 323 columns of different indicators of a disease. Although I see that many columns are mean, std, slope, min, max and so on of any one parameter. For example, for an attribute like 'walking', there are other attributes like: sum.slope.walking, meansquares.slope.walking, sd.slope.walking and so on.
Is it okay to select any one parameter in such a case (such as meansquares.slope..) ?
What are the patterns to look out for to identify relationships between attributes ?
Answer: If you have a number of different measurements in your data.frame, then pairs will show scatterplots of between all pairs of these measures.
Example data:
x <- rnorm(100)
obs <- data.frame(a = x,
                  b = rnorm(100),
                  c = x + runif(100, .5, 1),
                  d = jitter(x^2))

pairs(obs)

This is a data.frame with four different measures called a, b, c and d on 100 individuals. pairs draws this plot:

In the first line you see a scatter plot of a and b, then one of a and c and then one of a and d. In the second row b and a (symmetric to the first), b and c and b and d and so on.
pairs does not compute sums or mean squares or whatever. If you find that in your pairs plot, then that is in your dataframe.
What patterns to look for? In my example you find no pattern between a and b, a linear pattern between a and cand a curved, non-linear pattern between a and d. Look for patterns that might be of interest to your statistical questions.
Please note, that whilst asking for the interpretation of a plot is a statistical question, questions on how to use R alone are not on topic on Cross Validated. You should ask questions on R programming on Stack Overflow.
Comment: Without knowing, what kind of attributes you investigate in order to achieve what goal, we cannot answer, which aspect auf the attributes you should investigate. If you want to detect malaria form intermittend fever, you are interested in the maximum body temperature within three or four days, not in the mean temperature...
Comment: thank you. i did not mean that the 'pairs' function computes sums/mean squares.i said that the data i am using has attributes like: max_a, min_a, mean_a, slope_a, sum_a (ie, attributes that depend on each other?).In such cases, am wondering which attributes to eliminate.Is it enough to consider mean of an attribute? and so on.
Also, what are some properties inferred about the attributes from these patterns? are there any other patterns to look out for?
Comment: > .Is it enough to consider mean of an attribute?  -- Enough to achieve what?
Comment: ok. enough to identify relationships between the variables from a pairwise plot in this case.

How to interpret pairs plot in R?


Redirect all HTTP request to a local webserver using pound and dnsmasq for a wireless accesspoint

Question: I think it is possible to redirect all requests using pound and dnsmasq for an wireless access point but I must have made a mistake. Here the /etc/dhcpcd.conf
interface wlan0
static ip_address=192.168.42.1/24
static domain_name_servers=22.214.171.124
nohook wpa_supplicant

Here /etc/dnsmasq.conf
interface=wlan0      # Use the require wireless interface - usually wlan0
dhcp-range=192.168.42.2,192.168.42.20,255.255.255.0,24h
address=/#/192.168.42.1

Here is /etc/pound/pound.cfg
User            "www-data"
Group           "www-data"
#RootJail       "/chroot/pound"

## Logging: (goes to syslog by default)
##      0       no logging
##      1       normal
##      2       extended
##      3       Apache-style (common log format)
LogLevel        1

## check backend every X secs:
Alive           30

## use hardware-accelleration card supported by openssl(1):
#SSLEngine      "<hw>"

# poundctl control socket
Control "/var/run/pound/poundctl.socket"

######################################################################
## listen, redirect and ... to:

## redirect all requests on port 8080 ("ListenHTTP") to the local webserver (see "Service" below):
ListenHTTP
   Address 192.168.42.1
   Port    80
   Service
     Redirect "http://192.168.42.1:8080/roomtemp.htm"
   End
End

In my browser I can indeed access http://192.168.42.1:8080/roomtemp.htm but if I write anything else nothing is shown. My client get 192.168.42.1 as DNS server as it should. What am I doing wrong?
Answer: I forgot to enable pound and that is done in /etc/default/pound


Nylon guitar: How to mute open strings

Question: So from most videos I am seeing, it seems that classical guitar technique requires you to hold your hand away from the strings.
If I pluck an e on the 2nd fret of the D string, and then stop that e, i still get a lot of noise from my low E string, that started resonating while the higher e was playing.
To me, this sounds very muddy.
I haven't seen anybody on YouTube doing any right hand-contortions to avoid this problem, nor even mentioning it.
What am I doing wrong?
Answer: This is part of the classical technique.  The resonances of the other open strings help produce a full sound, see Carcassi's text.  It is supposed to be there.  The strings that resonate will have the plucked note as a natural harmonic so it should not be dissonant.  However you do need to gently mute when moving from one chord to another and you will get some conflicting dissonant harmonies.  Depending on the situation you can turn the meaty part of the thumb down towards the strings when switching from one chord to another, the outer part of the hand near the pinky works too.  Relaxing the left hand and flattening it over the strings is a possibility.
It takes time to develop these techniques in such a way that they are graceful and don't cause other problems like unwanted squeaks and scraping noise.
First, it sounds to me like you are not aware of proper technique.  Get the idea out of your head that the open resonances need to be stopped.  In general they should be encouraged.
Comment: This is spot-on.  I might add a note discussing the particular resonances of a given instrument -- different instruments may have different "loud" or "long" resonant pitches.  I adjusted my choice of strings (on a cello) to balance the decay of open D and open G strings.
Comment: @CarlWitthoft, this is an important point I didn't address.  We need to "adjust" our set up and technique to avoid erroneously loud or long resonances.

Nylon guitar: How to mute open strings


AngularJS Drag and Drop between lists breaks with 1.2

Question: I've been using an implementation of this Drag and Drop with AngularJS and jQuery UI:
http://www.smartjava.org/examples/dnd/double.html
With AngularJS 1.0.8 it works flawlessly. With 1.2.11, it doesn't.
When using AngularJS 1.2 and dragging an item from the left list to the right one the model for the destination list updates correctly. However the DOM doesn't update correctly. Here is the directive that's being used from the example:
app.directive('dndBetweenList', function($parse) {

  return function(scope, element, attrs) {

    // contains the args for this component
    var args = attrs.dndBetweenList.split(',');
    // contains the args for the target
    var targetArgs = $('#'+args[1]).attr('dnd-between-list').split(',');

    // variables used for dnd
    var toUpdate;
    var target;
    var startIndex = -1;

    // watch the model, so we always know what element
    // is at a specific position
    scope.$watch(args[0], function(value) {
        toUpdate = value;
    },true);

    // also watch for changes in the target list
    scope.$watch(targetArgs[0], function(value) {
        target = value;
    },true);

    // use jquery to make the element sortable (dnd). This is called
    // when the element is rendered
    $(element[0]).sortable({
        items:'li',
        start:function (event, ui) {
            // on start we define where the item is dragged from
            startIndex = ($(ui.item).index());
        },
        stop:function (event, ui) {
            var newParent = ui.item[0].parentNode.id;

            // on stop we determine the new index of the
            // item and store it there
            var newIndex = ($(ui.item).index());
            var toMove = toUpdate[startIndex];

            // we need to remove him from the configured model
            toUpdate.splice(startIndex,1);

            if (newParent == args[1]) {
                // and add it to the linked list
                target.splice(newIndex,0,toMove);
            }  else {
                toUpdate.splice(newIndex,0,toMove);
            }

            // we move items in the array, if we want
            // to trigger an update in angular use $apply()
            // since we're outside angulars lifecycle
            scope.$apply(targetArgs[0]);
            scope.$apply(args[0]);
        },
        connectWith:'#'+args[1]
    })
  }
});

Does something need to be updated for this to work properly with Angular 1.2? I feel like it has something to do with the scope.$apply but am not sure.
Answer: I see this is an older question, but I recently ran into the exact same issue with the Drag and Drop example.  I don't know what has changed between angular 1.0.8 and 1.2, but it appears to be the digest cycle that causes problems with the DOM.   scope.$apply will trigger a digest cycle, but scope.$apply in and of itself is not the issue.  Anything that causes a cycle can cause the DOM t get out of sync with the model.
I was able to find a solution to the the problem using the ui.sortable directive.  The specific branch that I used is here: https://github.com/angular-ui/ui-sortable/tree/angular1.2.  I have not tested with other branches.
You can view a working example here:
http://plnkr.co/edit/atoDX2TqZT654dEicqeS?p=preview
Using the ui-sortable solution, the 'dndBetweenList' directive gets replaced with the ui-sortable directive.  Then there are a few changes to make.
In the HTML

{{item.value}}

{{item.value}}

Note the dnd-between-list directive is no longer needed and is replaced with the ui-sortable.
In the module inject the ui-sortable, and in the controller specify that sortable options.  The sortable accepts the same options as the jquery sortable.
app.js
var app = angular.module('dnd', ['ui.sortable']);

ctrl-dnd.js
$scope.sortableOptions  = {
    connectWith: '.connector'
}

Only the additions to the controller are shown.  Note that I added a .connector class on the ul.  In the sortable I use .connector for the connectWith option.


Renewing cert on Zimbra mail server broke Outlook

Question: all.
Strange problem. We renewed our wildcard cert on the Zimbra email server over the weekend, and on Monday several users reported their Outlook no longer connected to the server (fortunately the web client still worked for them).
Looking at the Zimbra logs on the affected machines, I am seeing this:
<code>### WARNING ### Failed to obtain server cert. Error: 12019 @   Connection.cpp#1869[SaveCertAndCalcFingerprint()]
### ERROR ### Internal error loading the SSL libraries @ Connection.cpp#1961[Handle_WINHTTP_CALLBACK_STATUS_SECURE_FAILURE()]
### WARNING ### Detected asynchronous WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR -> converting to ERROR_WINHTTP_CANNOT_CONNECT @ Connection.cpp#7220[WrapWinHttpSendRequest()]
### WARNING ### Failed to authenticate @ SessionData.cpp#1993[UserSession::Auth()]
### WARNING ### Failed to determine server version, hr: 0x80040115 @ SessionData.cpp#3048[UserSession::IsServerVersionSupported()]
### ERROR ### unable to establish server connection. hr: 80040115 @ ZimbraXPLogon.cpp#855[ZimbraXPLogon::SubmitMessage()]
### ERROR ### Caught 'MailboxUnreachableException: Unable to connect.' @ ZimbraXPLogon.cpp#1288[ZimbraXPLogon::SubmitMessage()]
</code>
This only affects 6 people out of 400 atm, so it does not appear to be an issue central to the server. I re-deployed the cert ensuring that the intermediates and root CA were also included. These users are using the same version of Zimbra Connector for Outlook, and system time is correct (in case that was generating the error loading the SSL libs error).
Checking the firewall, I can see that it is not preventing connections from the users with this issue. I wonder if there is some caching that can be cleared...the previous certificate would have expired on the Monday after I deployed the renewed certs.
Has anyone seen anything similar?
Comment: Do these problematic users use different OS, did not apply updates, different version of outlook?
Comment: No, the same. I'm guessing the security level on some are higher, hence the fact that only 6 are having the problem and the rest are not. I'm not a Windows guy and these are Win10 machines.
Answer: Renewed chain cert did not include the root CA. Weird but some Win10 Outlook had no problem with that, about 6 refused to connect. I tacked on the root ca cert in the chain cert and the issue went away.


Providing a vocabulary in a custom module

Question: I am about to create a module which provides a ready-to-use term vocabulary.
What would be the clean, Drupal way to do that? Is it just a matter of a bunch of queries in hook_install(), or should I perform some additional steps? Should I take any measures in order to make the terms translatable?
I am using Drupal 7.
Answer: You should make use of the taxonomy module's functions such as taxonomy_save_vocabulary() and taxonomy_save_term() (Drupal 6), or taxonomy_vocabulary_save() and taxonomy_term_save() (Drupal 7) to populate your custom vocabulary. Creating fields should be accomplished via the Field API. There really should be no need to directly interact with the database.
Term translation is not supported out of the box in Drupal 7, but I do believe that the internationalization module provides a module that has cobbles together support for it.
Comment: That'd be `taxonomy_term_save()` and `taxonomy_vocabulary_save()` for Drupal 7
Comment: That's what I was trying to solve before your comment arrived. Thanks, Clive
Comment: My bad, should've pointed D7 first. So - tags updated. THanks guys.


Algebraic simplifying of $\frac {a + 27}{\sqrt[3]{a} + 3}$

Question: I need help in simplifying the expression:
$\cfrac {a + 27}{\sqrt[3]{a} + 3}$
I see that $27=3^3$ and $(\sqrt[3]{a})^3 = a$, but I do not know where to go then with it.
Thank you for your time.
Answer: Hint: Here's how you can factor a sum of cubes:
$$
x^3 + y^3 = (x + y)(x^2 - xy + y^2)
$$
Comment: Oh, so easy.. thank you :)
Answer: Hint: Let $a=u^3$ and then $a^\frac13 = u$


Distinct and group by at the same time in LINQ?

Question: Let say I have the following classes:
Product { ID, Name }

Meta { ID, Object, Key, Value }

Category { ID, Name }

Relation {ID, ChildID, ParentID } (Child = Product, Parent = Category)

and some sample data:
Product:
ID   Name

1    Chair
2    Table

Meta
ID   Object  Key     Value

1      1     Color   "Red"
2      1     Size    "Large"
3      2     Color   "Blue"
4      2     Size    "Small"

Category
ID   Name

1    Indoor
2    Outdoor

Relation
ID   ChildID   ParentID

1       1         1
2       1         2
3       2         1

Can we use Distinct and Group by to produce the following format (ProductDetail)
ID=1,
Name=Chair,
Parent=
{
  { ID=1, Name="Indoor" },
  { ID=2, Name="Outdoor" }
},
Properties { Color="Red", Size="Large" }

ID=2,
Name=Table,
Parent=
{
  { ID=1, Name="Indoor"}
},
Properties { Color = "Blue", Size = "Small" }

which we can get the "Color" value of the first item by using
ProductDetails[0].Properties.Color

Any helps would be appreciated!
Answer: No, you can't do this based on what you've said - because "Color" and "Size" are part of the data, rather than part of the model. They're only known at execution time, so unless you use dynamic typing, you're not going to be able to access it by Properties.Color.
You could, however, use Properties["Color"] potentially:
var query = from product in db.Products
            join meta in db.Meta
                on product.ID equals meta.Object
                into properties
            select new { Product = product,
                         Properties = properties.ToDictionary(m => m.Key,
                                                              m => m.Value) };

So for each product, you'll have a dictionary of properties. That works logically, but you may need to tweak it to get it to work in the entity framework - I don't know how well that supports ToDictionary.
EDIT: Okay, I'll leave the above up as the "ideal" solution, but if EF doesn't support ToDictionary, you'd have to do that part in-process:
var query = (from product in db.Products
             join meta in db.Meta
                 on product.ID equals meta.Object
                 into properties
             select new { product, properties })
            .AsEnumerable()
            .Select(p => new {
                    Product = p.product,
                    Properties = p.properties.ToDictionary(m => m.Key,
                                                           m => m.Value) });

Comment: Thanks for ur comment but poor EF doesn't support ToDictionary operator T T
Comment: @NVA: In that case you can probably do it using AsEnumerable... editing.
Comment: Thanks again for ur quick reply but when I want to include some extra info from another tables (edited in my post) using join, the generated SQL is too long with a bunch of SELECT ... FROM...Is there a way to clean it up?
Answer: I just came across this question while learning LINQ, but I wasn't satisfied that Jon's output matched the question (sorry Jon). The following code returns a List of anonymously-typed objects that better match the structure of your question:
var ProductDetails = (from p in Product
                      let Parents = from r in Relation
                                    where r.ChildID == p.ID
                                    join c in Category on r.ParentID equals c.ID
                                        into RelationCategory
                                    from rc in RelationCategory
                                    select new
                                    {
                                        rc.ID,
                                        rc.Name
                                    }
                      join m in Meta on p.ID equals m.Object into ProductMeta

                      select new
                      {
                          p.ID,
                          p.Name,
                          Parent = Parents.ToList(),
                          ProductMeta
                      })
                     .AsEnumerable()
                     .Select(p => new
                     {
                         p.ID,
                         p.Name,
                         p.Parent,
                         Properties = p.ProductMeta
                                       .ToDictionary(e => e.Key, e => e.Value)
                     }).ToList();

Credit goes mostly to Jon Skeet and the Visual Studio debugger ;)
I realise that you've probably moved on by now but hopefully this might help someone else looking to learn LINQ, as I was.


Why is 3-1*8+2*3 equal to 1

Question: I used PEMDAS on 3 - 1 * 8 + 2 * 3.
Steps:
1) 1 * 8 = 8
2) 2 * 3 = 6
3) 8 + 6 = 14
4) 3 - 14 = -11
Multiply all the terms, then add and finally subtract but I get -11 as the result.
But when I googled it, it said 1. Where did I go wrong?
Comment: I'm voting to close this question as off-topic because this question is not programming related and belongs on the math stack exchange site.
Comment: http://en.wikipedia.org/wiki/Order_of_operations#Mnemonics look at the part following "These mnemonics may be misleading when written this way..." and the example there.
Comment: multiplications and divisions go first and then you make the subtraction and addition. This means 3-(1*8)+(3*2)=3-8+6=1
Answer: By Following the BODMAS rule -
3 - 1 * 8 + 2 * 3
So According to BODMAS Rule-
B → Brackets first (parentheses)
O → Of (orders i.e. Powers and Square Roots, Cube Roots, etc.)
DM → Division and Multiplication (start from left to right)
AS → Addition and Subtraction (start from left to right)
So our equation ->
3 - (1 * 8) + (2 * 3)
3-8+6
-5+6
1

Answer: The order of operations is, as you said it PEMDAS (or BEDMAS whatever you like), but it is also left-to-right. And on top of that: multiplication and division are treated as the same order and so are addition and subtraction.
So your first two steps were right.
3 - (1 * 8) + (2 * 3)
3 - 8 + 6

Now here is where the left-to-right ordering takes place.
((3 - 8) + 6)
(-5 + 6)
1

To make it easier, you can remember that x - y is really just x + (-y). Then the order of subtraction and addition doesn't matter at all.
Answer: After multiply all the terms,please follow the order of operations.Right steps:
Steps: 1) 1 * 8 = 8  2) 2 * 3 = 6  3)3-8=-5   4)-5+6=1
Answer: You are not following the order of operations correctly.  You are correct in doing the multiplication first.  However, you also must always go from left to right when performing operations of the same type (addition and subtraction or multiplication and division).  By using parenthesis, we can make this clearer.
3 - (1*8) + (2*3) =>  3 - 8 + 6 => -5 + 6 => 1

Comment: So you're certain that this is off-topic?  Why answer if you're voting to close?
Comment: @Makoto - Because I had the ability to answer the question.  However, this has nothing to do with programming, so it is off topic.  It appears that at least 4 other people agree with that assessment.
Answer: Your mistake is in step 3. The - gets applied to 8 so step 3 is: -8 + 6 = -2
Comment: No, I didn't OP broke down his steps and numbered it. I was simply referring to the step where he made the mistake.

Why is 3-1*8+2*3 equal to 1


Retrieve whatsapp contacts from phonebook in android

Question: When i was looking through my contacts in phone i see whatsapp number also for those who have whatsapp account.The thing which i want to do is filter my contact list and display numbers which are synced with whatsapp.I am successfully retrieving all the contact id,number and account associated with it but not displaying whatsappaccount.Only associated google account is getting displayed.Is there any way to get whatsapp contact from local phonebook itself? I used the following code:
ContentResolver cr1 = getContentResolver();
Cursor cur = cr1.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cur.getCount() > 0)
    {
        while (cur.moveToNext())
        {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
            {
                Cursor pCur = cr1.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
                while (pCur.moveToNext())
                {
                    //phoneContactList.add(name);
                    Log.i("Contact List", name);
                    Log.i("Contact List", id);

                    getContactAccount(id,cr1);
                }
                pCur.close();
            }
        }
    }

public void getContactAccount(String id,ContentResolver contentResolver){
        Cursor cursor = null;
        try {
             cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
                     new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
                     ContactsContract.RawContacts.CONTACT_ID +"=?",
                     new String[]{String.valueOf(id)},
                     null);

            if (cursor != null && cursor.getCount() >0){
                cursor.moveToFirst();
                System.out.println("Account name is"+cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
                System.out.println("Account type is"+cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
                cursor.close();
            }
        } catch (Exception e) {
            System.out.println(""+this.getClass().getName()+","+ e.getMessage());
        } finally{
          cursor.close();
        }
    }

Comment: try this http://stackoverflow.com/questions/35448250/how-to-get-only-whatsapp-contact-from-android it read only contact who is in whatsapp account...
Answer: The MIME type for whatsapp is:  "vnd.android.cursor.item/vnd.com.whatsapp.profile"

Use the following code`:
public class MainActivity extends ActionBarActivity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment implements LoaderCallbacks<Cursor>,AdapterView.OnItemClickListener {
    /*
     * Defines an array that contains column names to move from
     * the Cursor to the ListView.
     */

    private final static String[] FROM_COLUMNS = {
            Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.HONEYCOMB ?
                            Data.DISPLAY_NAME :
                                Data.DISPLAY_NAME
    };
    /*
     * Defines an array that contains resource ids for the layout views
     * that get the Cursor column contents. The id is pre-defined in
     * the Android framework, so it is prefaced with "android.R.id"
     */
    private final static int[] TO_IDS = {
           android.R.id.text1
    };
    // Define global mutable variables
    // Define a ListView object
    ListView mContactsList;
    // Define variables for the contact the user selects
    // The contact's _ID value
    long mContactId;
    // The contact's LOOKUP_KEY
    String mContactKey;
    // A content URI for the selected contact
    Uri mContactUri;
 // The column index for the _ID column
    private static final int CONTACT_ID_INDEX = 0;
    // The column index for the LOOKUP_KEY column
    private static final int LOOKUP_KEY_INDEX = 1;
    // Defines the text expression
    private static final String mime_type ="vnd.android.cursor.item/vnd.com.whatsapp.profile";
    private static final String SELECTION =
             Data.MIMETYPE + " = '" + mime_type + "'";
    // Defines a variable for the search string
    private String mSearchString="Gourav";
    // Defines the array to hold values that replace the ?
    private String[] mSelectionArgs = { mSearchString };
    private static final String[] PROJECTION =
        {
            Contacts._ID,
            Contacts.LOOKUP_KEY,
            Data.DISPLAY_NAME,
            Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.HONEYCOMB ?
                            Data.MIMETYPE :
                                Data.MIMETYPE

        };
    // An adapter that binds the result Cursor to the ListView
    private SimpleCursorAdapter mCursorAdapter;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
         getLoaderManager().initLoader(0, null, this);
        // Gets the ListView from the View list of the parent activity
        mContactsList = (ListView) getActivity().findViewById(R.id.list);
        // Gets a CursorAdapter
        mCursorAdapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.contact_list,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
          // Get the Cursor
        Cursor cursor = (Cursor) parent.getAdapter().getItem(position);
        // Move to the selected contact
        cursor.moveToPosition(position);
        // Get the _ID value
        mContactId = cursor.getLong(CONTACT_ID_INDEX);
        // Get the selected LOOKUP KEY
        mContactKey = cursor.getString(LOOKUP_KEY_INDEX);
        // Create the contact's content Uri
        mContactUri = Contacts.getLookupUri(mContactId, mContactKey);
        /*
         * You can use mContactUri as the content URI for retrieving
         * the details for a contact.
         */
    }

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(
            int arg0, Bundle arg1) {
        // TODO Auto-generated method stub
        /*
         * Makes search string into pattern and
         * stores it in the selection array
         */
        CursorLoader cursor = null;
        mSelectionArgs[0] = "%" + mSearchString + "%";
        Log.d("ON CREATE LOADER", "ONCLREATE LOADER CALLLEd");
        try
        {
         cursor=new CursorLoader(
                getActivity(),
                Data.CONTENT_URI,
                PROJECTION,
                SELECTION,
                null,
                null
        );
        }
        catch(Exception e)
        {

            e.printStackTrace();
        }
        // Starts the query
        return cursor;
    }

    @Override
    public void onLoadFinished(
            android.support.v4.content.Loader<Cursor> arg0, Cursor cursor) {
        // TODO Auto-generated method stub
         Log.d("onLoadFinished", String.valueOf(cursor.getCount()));
           mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> arg0) {
        // TODO Auto-generated method stub
         mCursorAdapter.swapCursor(null);

    }

}

}

Answer: Use following code to get WhatsApp contacts from phonebook with associated WhatsApp number :
private void displayWhatsAppContacts() {

    final String[] projection = {
            ContactsContract.Data.CONTACT_ID,
            ContactsContract.Data.DISPLAY_NAME,
            ContactsContract.Data.MIMETYPE,
            "account_type",
            ContactsContract.Data.DATA3,
    };

    final String selection = ContactsContract.Data.MIMETYPE + " =? and account_type=?";
    final String[] selectionArgs = {
            "vnd.android.cursor.item/vnd.com.whatsapp.profile",
            "com.whatsapp"
    };

    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(
            ContactsContract.Data.CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null);

    while (c.moveToNext()) {
        String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
        String number = c.getString(c.getColumnIndex(ContactsContract.Data.DATA3));
        String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        Log.v("WhatsApp", "name " +name + " - number - "+number);

    }
    Log.v("WhatsApp", "Total WhatsApp Contacts: " + c.getCount());
    c.close();
}

Comment: I will have to check that, try to check data coming in cursor by debugging it.
Comment: How to get the contact image?


How can I set a JPanel maximum or preferred size that uses gridLayout?

Question: I had problem using a very simple frame containing two JPanel.
The problem is on the layout of the Center JPanel that contains four JButton.
How can I set a better size for buttons or directly for JPanel that uses the GridLayout. On the picture the problem:
alt http://img42.imageshack.us/img42/4601/horrible.jpg
!
Here the code: ` JFrame window = new JFrame("Horrible! LOL");
<code>    JTextField textField = new JTextField("");
    textField.setPreferredSize(new Dimension(200,20));
    JPanel textPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    textPanel.add(textField);
    window.add(textPanel, BorderLayout.NORTH);

    JButton plus = new JButton("+");
    //plus.setPreferredSize(new Dimension(50,50)); nothing would change
    JButton minus = new JButton("-");
    JButton per = new JButton("x");
    JButton divide = new JButton("/");
    JPanel prova = new JPanel(new GridLayout(2,2,10,10));
    Dimension d = new Dimension(20,20);
    prova.setMaximumSize(d); // nothing changed!

    prova.add(plus);
    prova.add(minus);
    prova.add(per);
    prova.add(divide);
    window.add(prova, BorderLayout.CENTER);

    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setSize(250,300);
    window.setResizable(false);
    window.setVisible(true);`
</code>
Which is a good solution?
Kind regards
Answer: Unfortunately gridlayout doesent respect preferred sizes. But still if you want to stick to grid layout then you can try something like this:
<code>    public static JComponent wrap(JComponent comp)
    {
        JPanel panel = new JPanel();
        panel.add(comp);
        return panel;
    }
</code>
And then instead of direclty adding in to prova add like this:
<code>            prova.add(wrap(plus));
            prova.add(wrap(minus));
            prova.add(wrap(per));
            prova.add(wrap(divide));
</code>
Tested, Works perfect!!
There are other better ways though
Comment: Thank you very much, it works but every button is kind of stick on the top edge of the grid. Is it my problem? I'll post on an answer my result, so you can judge.
Could you please show me or give me a links about better solutions. Which would be the right layout for this kind of things?
kind regards
Answer: That's what happen to me:
It's definitely attached to the upper edge of the grid.
alt text http://img96.imageshack.us/img96/9431/stillnot.jpg
Even if in this case, in the wrap method I can set the preferredSize of buttons/comp, every buttons is on its own edge. What about others solutions. How would you position buttons for a calculator?
Kind regards and thanx angain!


Xalan (XSLT) translate method translating more than it should

Question: I seem to be having an issue with Xalan's translate method.
I have the following code:
translate(translate(string(name),'<sup>',''),'</sup>','')
This is used to remove  and  from string(name). Unfortunately when I do that, it seems to remove s, u and p from the names as well.
So names like sony Braiva tm become ony bravia tm
Thanks for you help in advance :)
Comment: Good question (+1). See my answer for an explanation and for two XSLT 1.0 solutions and one XSLT 2.0 solution.
Answer: Because you said that the translate() function is successfully removing  and , I am assuming that  is not an element in the XML document, but is encoded as text.
The translate() function is defined to substitute individual characters and generally isn't suitable for string replacement when the string length is greater than 1.
It is possible to write and use a general string replacement recursive template/function in XSLT.
XSLT 2.0 programmers can use the standard XPath 2.0 function replace().
In your particular case even this this may be sufficient:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
  <xsl:variable name="vPart1" select=
   "substring-before(., '<sup>')"/>

  <xsl:value-of select="$vPart1"/>

  <xsl:variable name="vPart2" select=
   "substring-before(substring-after(., '<sup>'),
                     '</sup>'
                     )"/>

  <xsl:value-of select="$vPart2"/>

  <xsl:variable name="vPart3" select=
   "substring-after(., '</sup>')"/>

  <xsl:value-of select="$vPart3"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:
<name>
 <![CDATA[sony Braiva tm xxx]]>
</name>

the wanted result is produced:
<name>
sony Braiva tm xxx
</name>

Alternatively, here is the full-blown recursive template solution:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
  <xsl:variable name="vFirstReplacement">
      <xsl:call-template name="replace">
       <xsl:with-param name="pText" select="."/>
       <xsl:with-param name="pPattern"
         select="'<sup>'"/>
       <xsl:with-param name="pReplacement" select="''"/>
      </xsl:call-template>
  </xsl:variable>

  <xsl:call-template name="replace">
   <xsl:with-param name="pText"
        select="$vFirstReplacement"/>
   <xsl:with-param name="pPattern"
     select="'</sup>'"/>
   <xsl:with-param name="pReplacement" select="''"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="replace">
  <xsl:param name="pText"/>
  <xsl:param name="pPattern"/>
  <xsl:param name="pReplacement"/>

  <xsl:choose>
   <xsl:when test="not(contains($pText, $pPattern))">
    <xsl:value-of select="$pText"/>
   </xsl:when>
   <xsl:otherwise>
     <xsl:value-of select=
      "substring-before($pText, $pPattern)"/>

     <xsl:value-of select="$pReplacement"/>

     <xsl:call-template name="replace">
      <xsl:with-param name="pText" select=
       "substring-after($pText, $pPattern)"/>
      <xsl:with-param name="pPattern"
           select="$pPattern"/>
      <xsl:with-param name="pReplacement"
           select="$pReplacement"/>
     </xsl:call-template>
   </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on this XML document:
<name>
 <![CDATA[sony Braiva tm xxx]]>
</name>

the wanted, correct result is produced:
<name>
 sony Braiva tm xxx
</name>

Finally, here is the XSLT 2.0 solution:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
  <xsl:value-of select=
   "replace(
            replace(., '<sup>', ''),
            '</sup>',
            ''
            )
   "/>
 </xsl:template>
</xsl:stylesheet>

Comment: Thanks. This helps! Wow...seriously out of words. Thanks a lot.
Answer: tl;dr version: Don't manipulate html or xml as strings if you can possibly avoid it. Do it in XSLT.
I'm assuming that what you have is some element contains something like
<name>Sony Braiva tm</name>

So it looks like you've got a parsed XML document already in XSLT. Then, you're turning around and trying to use string manipulation to pull some tags out. That's a bad idea; see this question about matching tags. XSLT is exactly for this sort of manipulation, so use it! (If my assumption is wrong and that tm is entity-ized or in a CDATA section or whatever, that's different I guess.)
So, first. If you want to strip all tags out of name leaving just the text, you can do
<xsl:value-of select="name" />

which would give:
Sony Braiva tm

If, on the other hand, you want to strip all sup tags and their content, you would first elsewhere define a template matching sup (and do the same with anything you want to rip out, e.g. script tags, img tags, whatever):
<xsl:template match="sup" />

And then you can apply
<xsl:apply-templates select="name" />

If you really wanted, you could even do something like this and replace that HTML with a nice unicode symbol. It might be a good idea to place this in a different mode and use that mode to eliminate all other tags.
<xsl:template match="sup" mode="mangle-name">
  <xsl:if test="'tm' = string(.)">
  ™
  </xsl:if>
</xsl:template>

<xsl:apply-templates select="name" mode="mangle-name" />

Disclaimer on all of this: It's standard XSLT (probably 1.0 even), but I've only tried it in an online Saxon parser and not in Xalan.


Two-way ANCOVA with a between-subject variable in R

Question: I have a dataset with a 2x2x2 design: Group (CTL vs. SC) x Session (Sess 1 vs. Sess 2) x Treatment (Treat vs. Placebo). The dependent variable is Response Time. I also have a variable Age. I would like to do an ANCOVA using Age as a covariate. To visualize data:
input <- mydata[,c("Group","Treatment","Session","ResponseTime","Age")]
print(head(input))

Group Treatment      Session   ResponseTime   Age
  <chr> <chr>        <chr>     <dbl>          <dbl>
1 CTL   Placebo      Sess1     0.0126         53
2 CTL   Placebo      Sess1     0.0480         30
3 CTL   Placebo      Sess1     0.0318         58
4 CTL   Placebo      Sess1     0.747          28
5 CTL   Placebo      Sess2     0.150          28
6 CTL   Placebo      Sess2     0.0149         41
...

Using example from this, I did the following:
options(contrasts = c("contr.treatment", "contr.poly"))

model.1 = lm (Value ~ Group*Session*Treatment + Age + Group:Session:Treatment,
               data = mydata)
library(car)
Anova(model.1, type="II")

I'm unclear whether I placed Group where it belongs as it is a between- not within-subject variable. I think Age is used correctly as a covariate here but could someone take a quick look at let me know whether this is correct?
Answer: The way that you have modeled your data includes no subject identifiers at all; age might be specific to an individual but it does not by itself identify one. So your model doesn't involve any within-subject analyses; it effectively assumes that each observation is independent. If you think that's the correct way to proceed, then your model is OK. (Note that your inclusion of the 3-way Group:Session:Treatment interaction in the formula wasn't needed as the specification of Group*Session*Treatment automatically generates that interaction along with all the 2-way interactions.)
If you do wish to account for differences among subjects (as is good practice if individual subjects were presented with multiple tests) then you should be including subjects as random effects. The lme4 package is a popular way to include both fixed and random effects in a model. See this page and this page for useful help on how to specify your models. With proper coding, the programs in that package can figure out the between/within groupings and analyze the data accordingly.


Is It Possible To Look at Multiple Groupings of Objects in a JSON file?

Question: So I'm looking to make a leveling system without using a database. Yes I know a database is the better way to go but the leveling system is just for my own server which doesn't have a large amount of people talking and I haven't learned how to use databases and integrate them so I want to do something smaller that I understand for now.
Right now I have it set up to hold a level and exp for anyone that sends a message. I was hoping instead of doing a bunch of "if else" statements, I could use another JSON file to store the exp required for each level. I wanted to set it up like so
{
   "level": 2,
   "expRequired": 100
},

{
   "level": 3,
   "expRequired": 300
}

Is there a way I could use this method and check through each grouping and compare it to the message author's current exp? Something like
if (memberExp[message.author.id].exp == levels.expRequired) {
   memberExp[message.author.id].level = levels.level
}

Comment: I think the issue here is that you need to expand on what the level will gate. i.e. give a more full example of how the level `enable` or `disable` a feature and what that feature is.
Answer: In your question, the levels could easily be an array (in a JSON file):
levels : [0, 100, 300, 1000, 5000]

Then you can check the exp against the lowest entry that it matches, and that will be your level
for(let i = 0; i < levels.length; i++) {
    if (memberExp[message.author.id].exp > levels[i]) {
        memberExp[message.author.id].level = i
    }
}

UPDATE
I added a level check so you can see how many levels you gained
// remember the old level
let previousLevel = memberExp[message.author.id].level

// level up according to xp
for(let i = 0; i < levels.length; i++) {
    if (memberExp[message.author.id].exp > levels[i]) {
        memberExp[message.author.id].level = i
    }
}

// check how many levels we gained
let amountGained = memberExp[message.author.id].level - previousLevel

// if we gained more than 0 we can display a message
if(amountGained > 0) {
    console.log(`Congrats! You gained ${amountGained} levels!`)
}

Comment: Dude you are seriously a life saver thank you so much for your help. That was really the hardest part of this whole thing so to see it working now makes me super happy and excited.
Comment: The only issue I have with this method is that it would start the levels off at level 0 until they hit 100 exp right? Because if they have 50 exp they're only greater than levels[0] which would make memberExp[message.author.id].level = 0 wouldn't it? I'm multi tasking hard right now so my brain isn't thinking properly so apologies if I'm not understanding correctly.
Comment: Never mind stupid me. I just have to add 1 to x to have it equal the right level. Thanks!
Comment: Exactly! It's just because arrays start counting at 0. If someone is level 0 you can display "1" in the interface.
Comment: Ok so while this works to getting the level, I want to also congratulate the person when they level up. But I can't seemt o figure out how to do that. If I put it in the for loop, it displays every level-up up to my current level. I'm not sure how I would check it outside of the for loop.
Comment: You could compare the `memberExp[message.author.id].level` before and after the `for` loop. If it's higher afterwards then the player gained a level and you can congratulate him/her!
Comment: I hate that I have to ask this but how would I do that? I've been trying to figure out for a week now and I have no clue how to get it to work. This for loop is both hurting and helping since it's not checking to see if it's at 1 specific threshold and instead it sees every level before it as well.
Comment: I added a comparison between the old and the new level!
Comment: Good luck with the game!


How to remove element from DOM tree with the event handler

Question: This is the element which I want to remove:

And its child may be have event attached.
And now I want to remove it from the DOM tree; I know I can use this:
var ele=document.getElementById("tobeRemoved");
ele.parentNode.removeChild(ele);

But how about the events? Are they cleared at the same time auto?
BTW, I prefer to a cross-browser solution.
Comment: Yes div class eventAttached will also be removed since the element is a child of tobeRemoved class
Comment: @JeffRobertDagala Yes, but they are asking if any events attached to these divs will be removed automatically
Comment: logically it will be removed since the div class eventAttached was removed. so any events attached on that class will also be removed if all class eventAttached was removed.
Comment: Attached handlers are known to clog up the garbage collector. I wouldn't worry about it unless you're developing a framework or suffering performance issues though.
Comment: yes,ianpgall is right.I wonder if the event handler can also be removed autoly.
Answer: You could try this if you know the event type:
function removeEventHandler(elem,eventType,handler) {
 if (elem.removeEventListener)
    elem.removeEventListener (eventType,handler,false);
 if (elem.detachEvent)
    elem.detachEvent ('on'+eventType,handler);
}

or jQuery's .unbind() function.
Answer: If the events are added with jQuery it will remove the events when the elements are removed.


UiPageController and NavigationBar

Question: my problem is not showing navigationBar title for first view in my controller.
For next items text is showing.
My code:
<code>ViewControllerEvent *initialViewController = [self viewControllerAtIndex:self.index];
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
[self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
</code>
And ViewController code:
<code>- (void)viewDidAppear:(BOOL)animated{
    self.navigationController.navigationBar.topItem.title = [self.event objectForKey:@"name"];
}
</code>
Answer: Try this
<code>- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.title = [self.event objectForKey:@"name"];
}
</code>

UiPageController and NavigationBar


How to make a "while" loop using input from user?

Question: Currently using 3.8.1.
I was wondering how I could make a while True: loop like in the example below, but using a number that the user inputted instead of a word (for example any number equal to or lower then 100 would print something different. I've looked on this website, but I couldn't understand the answers for questions similar to mine.
while True:
    question = input("Would you like to save?")
    if question.lower() in ('yes'):
        print("Saved!")
        print("Select another option to continue.")
        break
    if question.lower() in ('no'):
        print ("Select another option to continue.")
        break
    else:
        print("Invalid answer. Please try yes or no.")

Comment: `('yes')` is not a tuple with one element; it's just a parenthesized string expression. `... in ('yes',)` would do you want you expect, but there's no reason to use `in` with a hard-coded single-element container: just use `question.lower() == 'yes'`.
Comment: Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)
Answer: How about including less than / great than clauses in your if statements?
while True:

    # get user input:
    user_input = input("Would you like to save? ")

    # convert to int:
    number = int(user_input)

    if number <= 100:
        print("Saved!")
        print("Select another option to continue.")
        break
    elif number > 100:
        print ("Select another option to continue.")
        break
    else:
        print("Invalid answer. Please try yes or no.")

Answer: you need to extract the number from the input and then run your conditional evaluation of the inputed value.
while True:
        input_val = input("Enter a #?")
        try:
            num=int(input_val)
        except ValueError:
            print("You have entered an invalid number. please try again")
            continue

        if num == 1:
            print("bla bla")
        elif num ==2:
            print("bla bla 2")
        else:
            ...

Answer: input takes the user's input and outputs a string. To do something with numbers, check if the string is numeric, cast it to an int and do whatever you want
while True:
    answer = input("How many dogs do you have?")
    if answer.isnumeric():
        num_dogs = int(answer)
    else:
        print("Please input a valid number")

Answer: I think you maybe want a list instead of a tuple.
Could this work:
while True:
    number = input("Enter a number?")
    if int(number) in list(n for n in range(100)):
            print("lower!")
    elif int(number) in [100]:
            print ("exact")
    else:
            print("higher")


Is array.forEach(callback) with async/await inside each iteration asynchronous?

Question: I am working with react and I have the following code:
    const [avatarURLs, setAvatarURLs] = useState({});
    const [currentTutorProfile, setCurrentTutorProfile] = useState({});
    const [avatarURLsLoaded, setAvatarURLsLoaded] = useState(false); // New state

    useEffect(() => {
        const avatarObject = {};
        const fetchAvatar = async (tutorProfile) => {
            try {
                if (tutorProfile) {
                    const response = await axios.get(
                        `${process.env.REACT_APP_BASE_URL}/users/${tutorProfile.owner}/avatar`,
                        { responseType: "arraybuffer" }
                    );
                    const blob = new Blob([response.data], {
                        type: "image/png",
                    });
                    const imageUrl = URL.createObjectURL(blob);

                    avatarObject[tutorProfile.owner] = "imageUrl";
                }
            } catch (error) {
                // console.error("Error fetching user avatar:", error);
            }
        };
        tutorProfilesArray.forEach(fetchAvatar);
        console.log(avatarObject); // THIS ONE

        setAvatarURLs(avatarObject);
        setAvatarURLsLoaded(true); // Mark that avatarURLs are loaded
    }, [tutorProfilesArray]);

I have a console.log(avatarObject) // THIS ONE, line that tests the avatarObject and I get empty objects and then the objects values get filled after some time.
empty objects then filled after some time
I noticed that this behavior was only present when the api call is used with await (ex: await axios.get()). When the api call is used without the await (ex: axios.get()), the avatarObject was updated immediately. So here are what I don't understand; Since await is used, shouldn't the line be executed in a sequential (synchronous) way even the api calls are done?
This is my side project that I have been working on for months and I have been struggling to solve this issue for a week and could not figure out why and how to fix this issue. If this happens to be something you might know the solution to, I would greatly appreciate if I could hear some explanations.
Thank you
What I was trying was this: loop over an array and fetch profile picture for each element of the array and using an object store it to a react useState variable.
Problem: It did store profile pictures to the useState variable but, it was done after some time (I assume) so that when the frontend gets rendered initially, it does not see any profile pictures so it renders no profile pictures.
Comment: `array.forEach` with an asynchronous function rarely does what you actually want - unless what you want is absolutely no results from the callback function to be available at a known point in subsequent code ... i.e. yes, async functions remain asynchronous even inside a `.forEach`
Comment: "*When the api call is used without the await (ex: axios.get()), the avatarObject was updated immediately*" - well sure, but it would be updated with the wrong value, as `response` would have been a promise and `response.data` would have been undefined.
Comment: @JaromandaX I see, will keep that in mind writing JS onward, thanks!
Comment: @Bergi You are right, that explains why it "seemed" like it was updated immediately without the await. Thank you.
Answer: Yes and no. In fact, the callback inside the .forEach can be asynchronous, but the forEach statement itself can not. This means that the console.log(avatarObject); will be executed while the callbacks inside the forEach statement are still being processed. This is why at first you see an empty object, but after some time you see the object filled.
There are some ways to work around this:
1. Using Promise.all with map
The map method works like the forEach method, but the difference is that it returns a new array with the result of each callback executed, which in case of an asynchronous callback the result will be a Promise. Given that, you can use the Promise.all statement to wait for all the callbacks inside the map to be finalized before going forward. Like the following:
useEffect(() => {
  async function fetchUsersAvatarAndUpdateState() {
    const avatarObject = {};

    await Promise.all(
      tutorProfilesArray.map(async (tutorProfile) => {
        // ... code
      }),
    );
    console.log(avatarObject); // THIS ONE

    setAvatarURLs(avatarObject);
    setAvatarURLsLoaded(true); // Mark that avatarURLs are loaded
  }

  fetchUsersAvatarAndUpdateState();
}, [tutorProfilesArray]);

2. Use for await instead
The for await (...) loop is asynchronous and can be used for asynchronous iterations, like the following:
useEffect(() => {
  async function fetchUsersAvatarAndUpdateState() {
    const avatarObject = {};

    for await (const tutorProfile of tutorProfilesArray) {
      // ... code
    }
    console.log(avatarObject); // THIS ONE

    setAvatarURLs(avatarObject);
    setAvatarURLsLoaded(true); // Mark that avatarURLs are loaded
  }

  fetchUsersAvatarAndUpdateState();
}, [tutorProfilesArray]);

Note that there are some differences between those two solutions. If you want to go deeper on that, I suggest reading this thread: for await of VS Promise.all
Comment: Covered by a long standing duplicate


How to use a SqlCommand Parameter to specify the schema name for a select query

Question: The name of the Schema in our database is dynamic. Why won't the following work?
public void ReadVersion(string connString, string schemaName)
{
    string selectCommand = "SELECT major FROM [@SchemaName].[version]");
    using (SqlConnection sqlConn = new SqlConnection(connString))
    {
        using (SqlCommand cmd = new SqlCommand(selectCommand, sqlConn))
        {
            sqlConn.Open();
            cmd.Parameters.AddWithValue("@SchemaName", schemaName);
            object result = cmd.ExecuteScalar();
        }
    }
}

When the command is executed, the parameter value is not substituted. Is this a limitation of the SqlCommand Parameters?
Answer: You can't do the following in plain SQL (so ignoring all of the ADO.Net overheads):
DECLARE @SchemaName sysname
SET @SchemaName = 'dbo'
SELECT major FROM @SchemaName.[version]

And the reason is simple. What SQL wants after FROM is a name. What you're trying to give it is a string. SQL Server doesn't randomly start peering inside of strings to see if they resemble some other construct.
To your sanitation query, assuming that you're keeping the schema names sane, just use a simple regex on the schema name before you trust it (e.g. ^[A-Z][A-Z0-9]+$ should be enough for most uses). Make sure you use a whitelist (allowed characters) rather than a blacklist.
Comment: Thanks Damien - my SQL understanding has grown. I now see that I can make our code a lot more elegant by giving the DB users (which query the schema at runtime) a DEFAULT_SCHEMA - because we create a matching unique DB user for each schema.
Comment: Hi - I hope I dont necro this thread, but is it viable to just check @SchemaName against sys.schemas to validate it ?
Answer:
Is this a limitation of the SqlCommand Parameters?

Yes, it is a limitation. In ADO.NET you cannot use parameters for the schema (things like table and column names). Your best bet is to use string concatenation and obviously as a result your own filtering for injection.
Comment: @GarethOwen, you may want to create a test that passed schema name is valid. For example the length and should not contain [,],",'.
Comment: I think that this is not a limitation of SqlCommandParameter. They were not designed for such use in the first place.
Comment: Thanks Darin. I wanted to use parameters so that I don't have to worry about SQL injection. This public method is in a library to be used by other internal projects. Any advice on how to 'filter for injection'?


VBA - Word 2007 - Subscript out of range (error 9)

Question: I don't know what's causing this.
I've created a template with a lot of macro code in it. And I've used the Custom UI EDitor for Office 2007 applications to create a custom Tab in the Ribbon interface. In this tab I've got this button which is supposed to open a userform. The XML code for the button is this:
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
    <ribbon startFromScratch="false">
        <tabs>
            <tab id="CustomForm" label="CustomForm">
                <group id="customuserdata" label="Custom Userdata">
                    <button id="openForm" label="Open userform" imageMso="OpenForm" size="large" onAction="openForm" />
                </group>
            </tab>
        </tabs>
    </ribbon>
</customUI>

And in the same Template I've got a Public Sub named openForm and it this I just run myForm.Show. It's in this sub that the error occurs "Run-Time error '9'. SubScript out of range". What could cause this?
The exact code of the Sub I'm trying to call is this:
Public Sub openForm(control As IRibbonControl)
    FormAltData.Show ' This is where the debugger stops at'
End Sub

Answer: The error was caused by an Array I believe. I tried to access an array before it was even declared ^^ My bad :)


Is Microsoft's KMS functionally the same as Amazon's KMS?

Question: As I understand it: Microsoft's KMS is used to temporarily enable Windows \ Office, whereas Amazon's KMS is for cryptographic key management.

Are both KMS services fundamentally the same: if so in what sense?
Is there some unifying explanation for model for Key Management that explains the two KMS versions?
Answer: They are entirely different. Where Microsoft KMS provides activation service (as you noted), AWS KMS is an encryption service to securely store key materials and encrypt/decrypt data.