Vue.js - document.querySelector returns null value but the element exist

Question: I'm following Kevin Powell's tutorial on creating a responsive navbar when I encountered this problem. It seems my 'const primary_nav = document.querySelector(".primary-navigation")' returns a value of null even though the class name exists. This problem is pretty weird to me, any idea why my code returns null?

<template>

        <button @click="nav_toggle" class="mobile-nav-toggle display-none" aria-controls="primary-navigation"
            aria-expanded="false">

                Menu

        </button>

                        {{ index }}{{ navigation.name }}

</template>

Output:
Comment: I'd say `const primary_nav = document.querySelector(".primary-navigation");` is running before the template has been "mounted" - using `document.querySelector` etc in vuejs is a) an anti-pattern and b) usually never needed anyway, specially in such simple code as yours - your code could possibly work if instead of `primary_nav?...etc` you put `document.querySelector(".primary-navigation")?...etc` - but it's still not how vuejs should be used
Comment: Do not mix plain Javascript with Vue! use `ref`. `<ul ref="primaryNavigation" ... `
Comment: @JaromandaX Hi, thank you for your answer. I'm still a noobie to Vue.js and it's ecosystem.  This advice really helps me a lot in terms of using the full capability of the framework rather than relying on the functions of vanilla javascript.
Answer: I followed JaromandaX's advice and this is what I came up with. Instead of using Javascript data attribute, I found this ref() method from Vue.js documentation and used it to make a reactive variable called isMobileNavigationVisible that has a default value of false. Then I just bind it into the class and create a conditional statement where if isMobileNavigationVisible is true the mobile navigation bar will render.

<template>

        <button @click="nav_toggle" class="mobile-nav-toggle display-none" aria-controls="primary-navigation"
            aria-expanded="false">

                Menu

        </button>

                        {{ index }}{{ navigation.name }}

</template>


How to interpret regression output for a discrete target variable

Question: I have to predict amount of items which will be sold. It's a discrete variable. I've trained a regression model for prediction of this amount. Let's pretend that my model predicts that I'll sell 1.5 items. But that is impossible: I can sell only 1 or 2 items. How to interpret this output for, let's suppose, a customer? Should I round output or say like "you'll sell 1.5 items"?
Comment: You could consider using a distribution for discrete, count data, such as the poisson distribution. It sure would describe better the origin of your data, and predict only discrete values.
Answer: Your regression model is outputting the conditional mean of the sales, i.e., the average.
For instance, next Tuesday, you may sell 1 unit, the Tuesday after 2 units, the Tuesday after that again 1 unit, so on average, Tuesday sales are 1.5, and your model outputs that.
Average sales of 1.5 are consistent with a wide range of possible probability distributions:

R code:
<code>mm <- 1.5
xx <- seq(0,10)

opar <- par(mfrow=c(2,2))
    barplot(dpois(xx,mm),names.arg=xx,ylim=c(0,0.4),ylab="Probability",xlab="Sales")
    barplot(dnbinom(xx,mu=mm,size=3),names.arg=xx,ylim=c(0,0.4),ylab="Probability",xlab="Sales")
    barplot(dnbinom(xx,mu=mm,size=2),names.arg=xx,ylim=c(0,0.4),ylab="Probability",xlab="Sales")
    barplot(dnbinom(xx,mu=mm,size=1),names.arg=xx,ylim=c(0,0.4),ylab="Probability",xlab="Sales")
par(opar)
</code>


Generate dynamic LINQ expression based on array

Question: I am using LINQ exprssion to query customers and filter them by state names. I have following query which works fine till the time I have 4 items in my statesArray.
public void GetCustomersForSelectedStates(string[] statesArray)
{
    var customers = _repo.GetAllCustomers();
    var filteredCustomers = from CUST in customers
    join ST in States on CT.Tag_Id equals ST.Id
    where CUST.ID == customer.ID  && (ST.Name == statesArray[0] ||ST.Name ==statesArray[1] || ST.Name== statesArray[2]||ST.Name =statesArray[3])

    //Do something with customers

}

I want following exprssion to be created dynamically:
(ST.Name == statesArray[0] ||ST.Name ==statesArray[1] ||
 ST.Name== statesArray[2]||ST.Name =statesArray[3])

For example , create the dynamicQuery like below
var dynamicQuery = "(";
var dynamicQuery = "(";
for (int i = 0; i < statesArray.Count(); i++)
    {
        dynamicQuery += "ST.Name =="+statesArray[0];
        if(i==statesArray.Count())
        dynamicQuery+=")"
    }

and then use it something like following,
//Psuedo code
var customers = _repo.GetAllCustomers();
    var filteredCustomers = from CUST in customers
    join ST in States on CT.Tag_Id equals ST.Id
    where CUST.ID == customer.ID  && Expression(dynamicQuery)

Comment: Why not just use `statesArray.Contains(ST.NAME)` ?
Comment: @JohnWu, Thanks , this works , was making this unnecessarily complicated. But will keep the question open (to know how to generate expression dynamically)
Comment: alternatively you can use recursive method concept.
Answer: To do that via dynamic expressions basically means building a tree of:
(x.Foo == val0 || x.Foo == val1 || x.Foo == val2)

You can do that like this:
static Expression<Func<T, bool>> Where<T, TVal>(Expression<Func<T, TVal>> selector,
    IEnumerable<TVal> values)
{
    Expression result = null;
    foreach (var val in values)
    {
        var match = Expression.Equal(
            selector.Body,
            Expression.Constant(val, typeof(TVal)));

        result = result == null ? match : Expression.OrElse(result, match);
    }
    if (result == null) return x => true; // always match if no inputs

    return Expression.Lambda<Func<T, bool>>(result, selector.Parameters);
}

with example usage:
string[] names = { "a", "c" };
var predicate = Where<Customer, string>(c => c.Name, names);

You can then use this predicate in the IQueryable<T>.Where extension method.
To combine it in your case, first do your regular LINQ:
var customers = _repo.GetAllCustomers();
var filteredCustomers = from CUST in customers
join ST in States on CT.Tag_Id equals ST.Id
where CUST.ID == customer.ID;

Now as a separate step apply the extra filter:
customers = customers.Where(predicate);

What this does is accept an input lambda of the form c => c.Name, then reuses the c.Name body for each c.Name == {val}, and reuses the c parameter as the parameter for the lambda we're creating. Each value from values becomes a typed constant. The Expression.Equal gives us the == test. The OrElse is the ||, noting that if result is null, this is the first item, so we just use the match expression itself.
Answer: You can add another join
var customers = _repo.GetAllCustomers();

var filteredCustomers = from CUST in customers
    join ST in States on CT.Tag_Id equals ST.Id
    join SA in statesArray on ST.Name equals SA // No need dynamic expression now
where CUST.ID == customer.ID

//Do something with customers

Comment: I would expect this to either fail (bad), or work by performing the join in-memory locally (much worse)
Comment: @MarcGravell based on _repo.GetAllCustomers() - we are locally already. But yes, if we join to DB through EF with such join - we'll fail.
Comment: that doesn't follow; I'm guessing that the repo has something like; `public IQueryable GetAllCustomers() => db.Customers;` - it doesn't suggest we're fetching anything. Also, the question is tagged linq-to-sql, strongly suggesting this approach
Comment: @MarcGravell that's a situation where we have "it depends". If we are locally already - join will be short and simple. In some situations (with small amount of data in repo) this works fine. If we have EF (standard for .NET) - we'll fail. If we have other IQueryable - we'll be depend on provider. Your answer is much more universal and elegant, plus it correlates with a question better.


C: Condição de Parada Laço For

Question: Olá, alguém poderia me explicar por gentileza o que está acontecendo nessa condição de parada do laço for?
#include <stdio.h>

int main(void) {

    char frase[] = "Linguagem C";

    for(int i = 0; frase[i]; i++) { //frase[i]?
        printf("%c", frase[i]);
    }

    return 0;
}

A saída é: Linguagem C
Já utilizei o for várias outras vezes, mas nunca vi uma condição como essa.
Já no exemplo abaixo, é exibido além do conteúdo do vetor do tipo int:
#include <stdio.h>

int main(void) {

    int vetor[] = {34, 42, -12, 984, 86, 14};

    for(int i = 0; vetor[i]; i++) { //A condição de parada é vetor[i]
        printf("%d\t", vetor[i]);
    }

    return 0;
}

A saída é: 34      42      -12     984     86      14      1       7       136112
Acredito que os valores a partir do 14 são provavelmente "lixos na memória".
Mas por que isso acontece?
Comment: quer saber o porque dos lixos de memória?
Comment: Sim; acho que eles são valores armazenados na memória RAM por causa de outras aplicações, mas gostaria de ler a sua explicação por favor.
Answer: Em C, não há por padrão o tipo lógico/boolean, C utiliza o número 0 para falso e qualquer outro valor diferente de 0 com sendo verdadeiro. No seu primeiro caso, o vetor de char, o '\0' que é o terminador de "string" em C é definido como 0, portanto quando i=11, vetor[11] será igual a 0 e o for termina. No seu segundo exemplo, o código é mais obscuro porque pode dar resultados diferentes, mas a ideia o for irá percorrer os dados em memória até encontrar um 0.
Comment: Se a resposta te atendeu, aponte-a como resposta da questão.
Comment: Consegui entender perfeitamente, muito obrigado!
Answer: A sintaxe de um loop for tem a seguinte definição:
for( inicialização ; condição_de_saída ; incremento ) {}

O seu código é:
for( inicialização ; variável ; incremento ) {}

A definição de um loop for é flexível e permite até que as expressões sejam omitidas, mas colocar uma variável onde se espera uma expressão de condicional gera comportamento não definido. No seu caso a condicional foi definida implicitamente, mas mesmo para iterar em um char[] é errado pq basta um usuário entrar com uma sequência de caracteres que não termina em NULL para acontecer uma falha de segmentação pelo acesso de memória não autorizado.

C: Condição de Parada Laço For


Function whose graph is a cone

Question: I hope your day is going well.
Let $u : \Omega \rightarrow \mathbb{R}$ a convex function on a open convex bounded set.
I read "Let $v$ be the convex function whose graph is the cone with
vertex $(x_{0},u(x_{0}))$ and the base $\Omega$ with $v =0$ on $\partial{\Omega}$. We have $v \in \mathcal{C}^{0}(\text{adh}(\Omega),\mathbb{R})$".
I'm sorry but this function exists ? And how does he know that it is continuous. I don't say it don't exist, of course. I trust the author but may anyone give me a expression of that function ? Because it is not quite obious for me.
Maybe we can use convex conjuguate I don't know.
Thank you for your help !
Answer: An explicit expression for the function may be impossible to write down without describing the set $\Omega$ in more detail, which is why the definition of the function is given as it is.  What you know about $v$ is:

$v$ is a convex function, so given $x,y\in {\cal C}$ and $\lambda \in [0,1]$ we have $v(\lambda x + (1-\lambda )y) \leq \lambda v(x) + (1-\lambda)v(y)$.
$v=0$ on $\partial \Omega$
$v\in C^0(\mathrm{adh}(\Omega), {\mathbb R})$

and what you know about the cone ${\cal C}$ is that it has a vertex at $(x_0, u(x_0))$ and base $\Omega$.  So, if you take any point on $\Omega$ and connect it with a straight line to the vertex $x_0, u(x_0))$ then than line is part of the cone ${\cal C}$.  A straight line can be mapped to an interval (say $[0,1]$ for the sake of argument) and intervals are convex, so you know that $v$ exists at every point of the domain ${\cal C}$.
So you have enough information to know that such a function $v$ exists, and if you need to calculate explicit values you'll need to define $\Omega$ explicitly first.  If you do, then the convexity of $v$ and the boundary conditions will constrain what expression $v$ can have, but you may still need to make some choices (of constants or additional constraints) to find a single $v$.
You haven't provided any reference to where this comes from, but this way of starting things is common when the aim of the analysis is to understand what classes of functions $v$ are admissible for a given domain.  As you continue reading you may find that the author narrows down the type of function $v$ can be further.
Lastly: for this kind of thing, try sketching the domain for simple (and complicated) $\Omega$ to help build intuition.  If you let $\Omega$ be the boundary of the unit ball in ${\mathbb R}^2$ first and draw ${\cal C}$ it should be much easier to see how such a convex $v$ could be found.

Function whose graph is a cone


É possível utilizar o validador W3C para sites construídos em Angular.JS?

Question: Tenho um projeto, que foi feito em Angular.JS. Ao lançar o projeto no validador da W3C eu recebo diversos erros que eu não teria como tratar.
Por exemplo:
Erros de Atributos: ng-controller | ng-cloak | ng-model | ng-click | ng-if | ng-repeat Erro: Attribute not allowed on element.
Bad Value: Geralmente nos href's, ou src's preenchidos de uma variável do angular {{minhaVariacel}}
Existe alguma possibilidade a se tratar para que eu possa validar e obter o selo do W3C de um site com Angular.JS?
Answer: Conforme o link do Angular Guide Normalization
A normalização faz:

Remove x- e data- da frente dos elementos e atributos.
Converte o :, -, ou _ delimitado para camelCase.

Então para validar basta adicionar data- na frente dos atributos, pois os atributos com prefixo data- são validos no HTML5.
Então o próprio AngularJS irá "normalizar" para funcionar como se não houvesse data-, ficando assim:

data-ng-controller=""
data-ng-cloak=""
data-ng-model=""
data-ng-click=""
data-ng-if=""
data-ng-repeat=""

E para o src= e href= adicione data-ng- no prefixo, assim:

data-ng-src=""
data-ng-href=""

Pronto, seu site deve validar.


Collapse não escondendo

Question: Estou tentando fazer uma tabela com collapse, porém acontece que ao clicar no botão o collapse mostra, porém ao tentar esconder, ele simplismente não funciona.

Código HTML

        <input type="checkbox" name="chck" id="chck" class="filled-in chk-col-teal">
        Título

                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica,
                craft beer labore wes anderson cred nesciunt sapiente ea proident.

        <button class="btn bg-cyan waves-effect m-b-15" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
            Detalhes
        </button>

Comment: Confira aí. Faltou fechar a tag DIV
Comment: @Tony não funciona msm assim
Comment: É Bootstrap? Qual versão do Bootstrap ?
Comment: não, é o materialize
Comment: O colega Leandro postou uma resposta, usando Bootstrap, testei esta aqui e funcionou.
Comment: Qual versão do Materialize vc está usando??
Comment: estou usando a mais atual
Answer: Cara faltou fechar a tag div como disse o Tony, certifique-se que vc importou todos os arquivos necessários para o funcionamento. segue o seu código funcionando:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

  <input type="checkbox" name="chck" id="chck" class="filled-in chk-col-teal">
    Título

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

  <button class="btn bg-cyan waves-effect m-b-15" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">Detalhes</button>

Comment: eu fiz no materialize
Comment: consegue mudar?
Comment: Achei que era o bootstrap, vou ver com o Materialize
Comment: Cara pelo que percebi na documentação ele só funciona no esquema de lista, com **ul** e **li**, pelo menos os exemplos que estão lá é assim, não sei se com esse esquema de tabela funciona o collapse do Materialize.
Comment: vou tentar mudar para o bootstrap

Collapse não escondendo


Elegant way for DAO testing

Question: I want to improve my DB access code tests.
I am using GAE datastore. To test the Db classes, I used a Backdoor Servlet. Just wondering, is there more efficient and elegant way to do DAO testing?
Your views on Unit vs Integration tests for DAO?
Answer: It depends a bit on how your database is set up. Here are a couple of other options apart from what you already have:

you can write unit tests directly against your DAOs. You can mock the database calls away with mockito.
you can write unit tests that records the integration with the database and then replays it when you run the tests a second time. See the betamax library fot this.
you can run unit tests against the actual database. Now it is not unit tests anymore but a kind of integration test. In this case you will need to think about how to get a clean state in the database to start from.
you can run integration tests against the entire system and make sure that most of your database code is touched by using a code coverage tool.

I prefer to have full blown integrations tests on the whole thing including the database and any other third party integrations. And unit tests on the particulars but not necessarily involving the actual database calls. But - as always - your setup may lead you in other directions.

Elegant way for DAO testing


How to calculate this sum of series

Question: So I have something in my Notes states that:
$\sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}e^{2\pi i(2n+1)x} = 2\sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}cos(2\pi (2n+1)x)$.
I am wondering how did this work? Shouldn't it be something like
$\sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}e^{2\pi i(2n+1)x} = \sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}(cos(2\pi (2n+1)x)+isin(2\pi (2n+1)x))$?
and the range of x is $x\in [-\frac{1}{2},\frac{1}{2})$.
Comment: If you take $x=0$ then you will notice that the $2$ placed right after $=$ should not be there.
Answer: By demoivre's theorem $(\cos(x)+i\sin(x))^n=\cos(nx)+i\sin(nx)$ so we can write $e^{i2\pi(2n+1)x}=(\cos(2\pi(2n+1)x)+i\sin(2\pi(2n+1)x))$. Now as $sin(2\pi(2n+1)x)$ approaches $1/2,0$ the expression also goes to $0$ . I have done it as $|x|\leq 1$ . Thus we can ignore that sin term as it becomes negligible giving only $\cos$
Comment: Thanks. But the problem is that x is not an integer. You can see my edit
Comment: thanks for your update. I don't understand why  $e^{i2\pi(2n+1)x}=(\cos(2\pi(2n+1)x)+i\sin(2\pi(2n+1)x))^x$ ? I mean why x times the right hand side?
Comment: Sorry wrongly left it
Comment: Hope its clear now
Comment: Sorry but I still don't understand... Why $sin(2\pi (2n+1)x)$ approaches $ \frac{1}{2}$? and which expression goes to 0? Note that x is any number between $-\frac{1}{2}$ and $\frac{1}{2}$
Comment: No for those two values $1/2 ,0$ the whole $sin(2\pi(2n+1)x)$ goes to $0$
Comment: @ArchisWelankar The OP wrote an identity.
Comment: @ArchisWelankar Okay... But why should I consider when  $x=\frac{1}{2}$ or $x=0$? Bear with me I'm really not good at math
Comment: I said that as $x$ approaches smaller and smaller values the sin starts becoming negligible

How to calculate this sum of series


Intersection which is not equidimensional

Question: I would like to find an explicit example of two irreducible complex algebraic subvarieties $X,Y\subset \mathbb{C}^n$ such that the irreducible components of $X\cap Y$ are not equidimensional, i.e. there exists irreducible components $Z_1, Z_2$ of $X\cap Y$, such that $\dim Z_1 \neq \dim Z_2$.
Thanks very much!
Answer: Take the variety defined by the ideal $(xv-uy, xw-uz, yw-zv)$ in 6-space. This is a four dimensional variety.Intersect it with the linear space $x=y=0$. Then, it will have 2 components, defined by $(x,y,u,v)$ a 2-dimensional variety and $(x,y,z)$ a 3-dimensional variety.
Comment: @Quasicoherent It is the Segre of $\mathbb{P}^2\times\mathbb{P}^1$. Then you take a $\mathbb{P}^2\times\{x\}$ and $\{y\}\times\mathbb{P}^1$. These are linear subspaces under the embedding and since they meet (at $(y,x)$), they are contained in a 3-space and in fact this 3-space intersects the variety precisely in that plane and that line.
Comment: Nice example, +1.  Would you mind saying something about how you came up with it?  It looks like you took the (affine cone over the) Segre embedding of two copies of $\mathbb{P}^2$ and then projected away from some of the coordinates.  I guess by considering the dimensions, it's not a complete intersection...


Connecting a physical ethernet port to a VMware virtual switch?

Question: I hope this is the correct place for this question. I thought about posting it to Super User first, but it seems to be more relevant to this place. Anyway, here goes:
I need to connect a device plugged into a physical ethernet port of my workstation to an existing virtual switch. The physical device and a VM need to share the same network, both need to be connected to the internet via NAT and a second network adapter of my PC.
As a picture often is better than a thousand words, here is a little ASCII art drawing of what I want to achieve:
<code>                        The internets!
                              |
                             __
                            |  |   router,
                          __|__|__ firewall, etc.
                              |
           ___________________________________________________________
          |                       |        |        |        |        |
         __
        |  |                        (other machines on the physical network)
      __|__|__  my workstation
          |     (doing NAT)
     ___________
    |           |
   __          __
  |  |        |  |
__|__|__    __|__|__
physical    virtual
device      machine
</code>
I can't simply connect the physical device to a physical switch and bridge the VM into the main network because for my testing the VM needs to run a DHCP server among other things, and the admins would be coming after me with torches and pitchforks if I put a rogue DHCP server into our main network.
My problem is, I have absolutely no idea what I need to do to "plug" the physical port into the virtual switch, and I would be grateful for any input on how to do it.
If this isn't possible with VMware Player or Workstation, is there other software able to do what i want? Virtualbox, maybe?
Answer: Hmm.  I believe that your best bet may be to bridge your VM onto the private network NIC that your physical device is connected to and use NAT (Internet connection sharing in Windows, iptables in Linux) to provide internet access to the two boxes.
I'll try to elaborate.. I apologize in advance for not being very good with descriptions:

Configure the NIC in the PC for the private network. Here is where you'd want to set up the internet connection sharing if you're using windows. How that's done depends on what version of windows you're running.  If you're not running windows, there's iptables NAT in Linux.  I'm not familiar enough with OSX to know how to set up NAT.  I suspect it's similar to Linux.  Another search on here should provide information on how to do this. (EDIT: For Windows, as soon as you share the connection of your NIC in the public network to the one in the private network, the NIC in the private network is assigned a static IP address by windows which doesn't neccessarily match your private network's configuration. Just change the IP accordingly and also set your computer's IP in the private network as the preferred DNS server and you're good to go. – Tobias Gies)
Plug your physical device into a switch or directly to your PC with a crossover cable.  I would suggest using a small switch - that is just personal preference, though.  IP your physical device as appropriate on the private network with a default gateway pointing to the private network IP of your PC.
Place the network adapter of the VM in bridged mode onto the private network NIC and give your VM an IP in the private network range with a default gateway pointing to the private network IP of the PC.

In theory, if you have the NAT set up correctly, you should have a completely private network with the VM and physical device, while still providing internet access to both.  This keeps your DHCP server off of the public network, and keeps the pitchfork-laden admins away. :)
Comment: I hope it works out!
Comment: It worked exactly like you described! One thing to take note of for people who want to reproduce this: As soon as you share the connection of your NIC in the public network to the one in the private network, the NIC in the private network is assigned a static IP address by windows which doesn't neccessarily match your private network's configuration. Just change the IP accordingly and also set your computer's IP in the private network as the preferred DNS server and you're good to go.
Comment: Glad it worked! I edited the answer, adding that note for Windows hosts.
Comment: That sounds like it might just work. I'll try that and report back - it's probably going to be next week before I can get to it though. Thanks!


Solving for vector in linear algebra

Question: This is not really my field so please bear with me. In the equation:
$ (X^TX)\hat{h}_q = X^Ty_q $
I need to find the vector $\hat{h}_q$. $X$ and $y_q$ are known, and $y_q$ is the same length as $\hat{h}_q$.
$X$ is a matrix of the form:
$$X = \begin{pmatrix} 1 & 0 & 0 &0 \\ 2&1&0&0\\3&2&1&0\\4&3&2&1\\0&4&3&2\\0&0&4&3\\0&0&0&4\end{pmatrix}$$
but instead of 1 - 4 it's a vector of random numbers about 3500 long.
Comment: This is not what I would call a diagonal matrix.
Answer: $h_q = (X^TX)^{-1}X^Ty_q$. Use matlab or octave to find $X^TX$ and its inverse.
Comment: Thank you, this is helpful, but it's causing some unhappyness with Matlab. If $X$ is a 100 row by 50 col matrix, then $(X^TX)^{-1}X^T$ is a 50 row by 100 col matrix, correct? If y is then a 200-element column vector, I cannot multiply them together it seems? (at least, matlab says dimensions do not agree).
Comment: Your question has $X^Ty_q$ in it. If $X$ is $100\times50$ and $y_q$ is $200\times1$ then your question makes no sense.
Comment: @GerryMyerson Yes, I realized I have to modify $X$ depending on the length of $y_q$. Sorry for the confusion there. I have now hit a second problem though: my $X$ is 7000x10000, and trying to find the inverse of that is crashing Matlab on even the most powerful computer in our lab. Is there any way to do it in a way that won't cause that problem?
Comment: First, that's a new question, not a comment on an answer to an existing question. Second, it may be a question better suited for the programming site than this math site.

Solving for vector in linear algebra


p value vs prediction error

Question: In a lot of fields (like medicine) to check if a variable is related to an output is controlled if the p-value of that variable in a regression model is significant.
For example:
> summary(glm.D93)

Call:
glm(formula = counts ~ outcome + treatment, family = poisson())

Deviance Residuals:
       1         2         3         4         5         6         7         8         9
-0.67125   0.96272  -0.16965  -0.21999  -0.95552   1.04939   0.84715  -0.09167  -0.96656

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  3.045e+00  1.709e-01  17.815   <2e-16 ***
outcome2    -4.543e-01  2.022e-01  -2.247   0.0246 *
outcome3    -2.930e-01  1.927e-01  -1.520   0.1285
treatment2   1.189e-15  2.000e-01   0.000   1.0000
treatment3   8.438e-16  2.000e-01   0.000   1.0000
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 10.5814  on 8  degrees of freedom
Residual deviance:  5.1291  on 4  degrees of freedom
AIC: 56.761

Number of Fisher Scoring iterations: 4

>

Wouldn't be better instead of using this approach to try all the possible combinations of variables and choose the model with the lowest prediction error?
We can so assume that all the variables in such models are so relevant.
If this is not the case can you explain me why?
Comment: Our site contains extensive materials on this topic.  You might like to start at http://stats.stackexchange.com/questions/128616/whats-a-real-world-example-of-overfitting, which provides actual examples of the problems that ensue from this approach.
Comment: The answers to your question might depend on precisely what you mean by "prediction error."  How are you computing that?
Comment: My idea is to get an estimation of the prediction error with cross-validation or bootstrap
Comment: I am not sure that overfitting is relevant here. In fields like epidemiology
Comment: So you look for a definition of prediction error yourselves? The problem is that the prediction error we hope to ensure in reality can only be estimated according to a certain model and will in turn only be as good as this model matches reality. What we never know. Cross-validation or bootstrap cannot overcome this. These procedures do not validate the variable selection ifself but rather that the model construction procedure did not depend too much on the particular (training) data.
Comment: this is true. For example we can never assume that a model using variable 1,2,3 would be better than a non linear model using variables 3,4,5. But also the same problem holds for the p-value because they are used only in linear model.
Answer: You get the smallest prediction error if you include all variables. If you also include quadratic or cubic terms you will become even better. If you generate random numbers for each observation and use them as a additional independent variable, you may reduce the prediction error even further. Just try it in R with your dataset.
The regression coefficients are always chosen such that they minimize the prediction error. So the more coefficients you have (due to more independent variables), the more possibilities you have to reduce the prediction error. As you have seen with adding random numbers, these possibilities don't need to have any relation to your data, yet they yield lower errors.
There are various ways to overcome this. First of all, don't include variables in your model where you don't have any idea how they could be related to the dependent variable. It is not the availability of data that shapes the model but the insight into the fact behind them.
Secondly, consider using information criteria, like the AIC printed in your output, to find some balance between prediction error and numbers of variables. Choosing only significant variables can be dangerous, since you don't know the type-II-error (test result not significant although the variable makes a difference), so the probability of throwing away important variables can be quite hight.
There are of course many more useful ways to judge your model selection process. The best way to choose variables or model selection procedures depends on the purpose of your regression analysis.
Comment: I  do not agree the prediction error is not reduced with the inclusion of additional variables but only the training error. This is why I want to choose the model that minimize the test error
Comment: I think the term 'prediction error' is being used by the OP to mean the 'out-of-sample' prediction error.  This does not necessarily get smaller if one includes all variables: it usually reaches a minimum at some number of variables, then increases as the number of variables continue to increase.  Including all variables leads to overfitting, leading to  poor 'prediction error'.
Answer: Your question is essentially about model selection.
When you are building a statistical model, you might not want to just consider the predictive ability of your model. Conventionally, the goodness of a statistical model is evaluated by the following three attributes.

Parsimony or Interpretability, i.e., the simplicity of your model. A parsimonious model usually have better interpretations and many other advantages.

Everything should be made as simple as possible, but no simpler. – Albert Einstein

Goodness-of-fit, i.e., how good your model fits the current data at hand.
Generalizability, that is, the ability of the fitted model to describe or predict new unknown data.

Because of the above, many model selection criteria have been proposed to address the model selection problems in different aspects.
Above all, it should be pointed out that conducting variable selection solely based on the significance level (p value) of a variable can cause a lot of issues. The following is quoted from a report "Scientific method: Statistical errors" published in Nature. The paper addresses some serious problems in scientific research caused by the p-value criterion.

P values, the 'gold standard' of statistical validity, are not as reliable as many scientists assume.
  ......
  Perhaps the worst fallacy is the kind of self-deception for which psychologist Uri Simonsohn of the University of Pennsylvania and his colleagues have popularized the term P-hacking; it is also known as data-dredging, snooping, fishing, significance-chasing and double-dipping. "P-hacking," says Simonsohn, "is trying multiple things until you get the desired result" — even unconsciously. ...... "That finding seems to have been obtained through p-hacking, the authors dropped one of the conditions so that the overall p-value would be less than .05", and "She is a p-hacker, she always monitors data while it is being collected."
Comment: I am aware of the various model selection algorithms. In general in medicine is used only a small subset of variables let say 8. It is so possible to train all the possible combination of variables and to estimate their prediction perfomance. Considering linear model that seems to be the standard in medicine interpretabiliy should be fine and so variables would be chosen by prediction power.
Answer: You are absolutely right that deciding what terms in a model are relevant by looking at p-values (or AIC or BIC) - or even worse if this is done iteratively by adding and removing terms using e.g. stepwise regression - is not a really good approach for getting the best performing model by almost any standard (and certainly not for out of sample prediction). Perhaps with a single model fitted (from which non-significant terms are not removed), a huge sample size compared to the number of model terms, some sensible multiplicity adjustment and no collinearity, one might look at this as indicating for which terms the evidence is the clearest that they influence the outcome (without necessarily ruling out that other terms also play a role). That's about the most charitable interpretation and may make some sense, if you are not really that interested in prediction.
These kind of approaches seem to come from a traditional obsession with p-values and are still somewhat prevalent in some fields. However, even in medical applications universities and companies that have good statistics departments/support typically no longer do that.
As you suggest approaches like trying all models with some kind of cross-validation or bootstrapping to try to compensate for the potential overfitting is an improvement on stepwise regression. However, there are many more attractive approaches that are (rightly) gaining in popularity such as Bayesian model averaging, shrinkage priors (such as the horseshoe), LASSO (as an "older" idea), frequentist model averaging (e.g. using weights proportional to exp(-AIC/2)) and various other machine learning type of approaches (e.g. random forests). Many of these have in common that the goal is not to pick one single model, but rather to get good out-of-sample predictions taking into account the uncertainty around what the optimal model is. E.g. in model averaging approaches all models will usually contribute somewhat in real-life examples and situations where one single is clearly better than any other considered model are rare.

p value vs prediction error


Connecting several points as a route on Google-maps

Question: I have a JSONarray full of coordinates like that [[lat, long],[lat,long]...] and i want to draw a line on Googlemaps-fragment which is following the route defined by the coordinates.
I just did some research, but i only found solutions using one start and one endpoint.
Answer: You can draw a Polyline:
PolylineOptions poliLine = new PolylineOptions()
                    .width(10)
                    .color(getResources().getColor(R.color.colorPrimary))
                    .zIndex(1);
poliLine.add(startPoint.getCoordinates());
for (MyPoint midPoint : points) {
    poliLine.add(midPoint.getCoordinates());
}
poliLine.add(endPoint.getCoordinates());
route = mGoogleMap.addPolyline(poliLine);

class MyPoint {

    public LatLng coordinates;

    public MyPoint(LatLng coordinates) {
        this.coordinates = coordinates;
    }

    public LatLng getCoordinates();
}

In your case, if the coordinates have an order, your coordinates.get(0) should be your startPoint, coordinates.get(coordinates.size() - 1) your endPoint and the rest should be midPoints.


Webview android 6.0 não carrega mapa com imagem

Question: Tenho uma aplicativo que recebe as configurações de js, html, css através do WebView, para criar um mapa offline.
No android 4.4 funciona corretamente. No android 6.0 não aparece nenhum conteúdo.
Realizo a chamada atraves do assets
webview.loadUrl("file:///android_asset/www/map.html");

Coloquei também as permissões no AndroidManifest.
EDIT1
O problema está ocorrendo no caminho para encontrar as imagens.
As permissões estavam certas.
webview.loadUrl("javascript:loadImg('/storage/14F0-C537/www')");

Mas o endereçamento do SdCard utilizado tem q ser alterado.
Comment: Quais permissões você colocou no AndroidManifest?
Comment: Colocamos permissoes de Internet, Acess_Fine_location, Acess_Coarse_Location, Read_External_Storage, Write_External_Storage
Answer: A partir do Android 5.0 as permissões são solicitadas sob demanda, ou seja, o desenvolvedor precisa solicitar as permissões no momento em que irá usar. Pode está acontecendo isto, vai nas configurações do aplicativo e verifica se todas as permissões foram aceitas.
Comment: Pelas configurações do aplicativo, todas as permissões foram aceitas.
A minha duvida seria, sempre q acessar o aplicativo essas permissões deveram ser refeitas?
Comment: Não, as permissões só precisam ser aceitas uma vez pelo usuário


interactive googlemap javascript api with android api

Question: i want to draw some line on google map to custom traffic flow on our custom map by javascript Api dynamically and get it with android api , i want to do this but i dont know how < is it posible ?
Comment: Why would you want your traffic flow be written in Javascript?
Answer: If you already have published your custom map with custom traffic flow in a website, you might want to consider using a webview to load your specific webpage with your map on your android application.
In your XML file:
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview_map"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>

On your Activity, you can do something like:
Webview webview = (WebView) findViewById(R.id.webview_map);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("YOUR_WEBPAGE_URL");
setContentView(webview);

Or you can use the available functions in Maps SDK for Android Here are some functions that might be able to help you in implementing your use-case:
Add a custom/styled map
Draw Polylines and Shapes on a map
Hope this helps!
Comment: there is not another way ? just web view ? no way to interactive between android api with javascript api ?
Comment: I think this is the easiest way to handle your use-case. If you are looking for a more elegant way, I think you need to programmatically implement it yourself like calling your own API in your mobile application where it gets all the updates made on your js maps. Then display it on your mobile application using Maps SDK functions.
Comment: Also, can you please add more information on your question as to what really is it that you are aiming for. Is it correct to assume that you are trying to draw on your js maps and that drawing should automatically be reflected on your map in android real-time?


show that L+ is inconsistent

Question: Let $A$ be a statement for which is not a tautology. Let $L^+$ be the formal theory obtained from $L$ by adding as new axioms all formulas obtainable from $A$ by substituting arbitrary statement forms for the statement letters in $A$, the same forms being substituted for all occurrences of a statement letter. Show that $L^+$ is inconsistent.
I have several questions:

can $A$ be an axiom by itself from given conditions ?
consider given assignment of truth values to the statement letters that gives us $A = false$. Let's replace statement letters of $false$ value with negation of a tautology, and of $true$ values with a tautology. So how can this obtained formula be an axiom that is be of $true$ value?

I cannot understand how to show that $L^+$ is inconsistent.
Comment: yes, they are as I got it from "Introduction to mathematical logic" by Mendelson, Elliott
Comment: btw do we need to consider that axioms must be of true value when it comes to inference of formulas ?
Comment: Sorry, English isn't my tongue language, it was misleading. It's about propositional-calculus
Comment: What is a statement letter? Is it a propositional variable like $P$ in $P \to Q$ or a metavariable like $\varphi$ in $\varphi \land \lnot \varphi$ or something different?
Comment: The question is tagged `first-order-logic`, but, on further reflection, I'm not sure that's right. Is the question about first-order logic or is it about different propositional logics? Can you give us some examples of possible $L$s?
Comment: Thank you. Also, [on this site](https://math.meta.stackexchange.com/questions/1617/what-is-the-site-etiquette-about-i-asking-and-ii-answering-questions-in-a-la), the consensus is that questions can be asked in any language. Someone, either the author or a community member, can then add a translation into English at the end of the post. For questions, you have a choice between using English and using other languages. For answers, I don't know what the consensus is.
Answer:
can A be an axiom by itself from given conditions ?

Yes, it will be an axiom -- because any "statement letter" is in itself a "statement form", and substituting them all with themselves is a perfectly good invocation of the procedure in the definition.
The second part of your question is in fact the solution:

consider given assignment of truth values to the statement letters that gives us $A = false$. Let's replace statement letters of $false$ value with negation of a tautology, and of $true$ values with a tautology. So how can this obtained formula be an axiom that is be of $true$ value?

Remember that "axiom" doesn't mean "necessarily true" -- it simply means "something we allow a proof to start from without further argument".
You have the right idea that $L^+$ has an axiom whose truth value is false under all truth assignments.
Depending on how you define "inconsistent", you're either done or almost done. Namely, if "inconsistent" mean that the theory has no satisfying truth assignments, then you have argued for exactly that.
On the other hand, if (as is more common) "inconsistent" means that you can derive a contradiction, then note that your variant of $A$ is always false, and therefore the negation of that formula is always true, that is, a tautology. If your proof system is complete (which I will assume you know it is), that means that you can derive that tautology. The axiom itself, by virtue of being an axiom, can of course also be derived. In total, you have derived a both a formula and its negation, and thereby proved that $L^+$ is inconsistent.
Comment: ok, according to  the conditions it's possible to construct an axiom $A$ which is always $false$ and as it is the axiom it can be derived. On the other hand I can take $\neg A$ which is tautology and as $L^+$ includes $L$ that is $L^+$ is complete it means that $\neg A$ is derivable from $L^+$. So both $A$ and $\neg A$ can be derived that is $L^+$ is inconsistent.

show that L+ is inconsistent


what is the complexity of recursive summation

Question: Can someone tell me the exact complexity of this recursion ? this is actually formula for below question ( solved in recursive brute force way )

There is n steps stairs and a person standing at the bottom want to reach at top. Person can take max k steps at a time ( i.e. he can take 1, 2 , 3,.. upto k steps).Count how many ways person can climb the stairs.

f(n,k) =
\begin{cases}
\sum_{i=1}^k f(n-i,k) \,  & \text{if $k$ > 1} \\\\
1, & \text{if $k$ = 1}
\end{cases}
Comment: This is the number of compositions of n into parts with maximum size k. A table is in https://oeis.org/A048003 , which has formulas and cross-references to special cases.
Answer: Since this problem is tagged dynamic-programming, here are my two cents on how this can be solved in $O(n)$ memory and $O(n)$ time using dynamic-programming.
The key-idea is maintaining a prefix-sum sequence (as an array in memory). It is a sequence that satisfies the property pre[i] = f[0] + f[1] + ... + f[i]. Consider the base-states: pre[i] := 0 for i < 0 and pre[0] = f[0] = 1. Now we recurse:
for i in range[1, n]:
  f[i] = pre[i - 1] - pre[(i - k) - 1]
  pre[i] = pre[i - 1] + f[i]

If you're not familiar with prefix-sums, note that I employed the fact that f[i] + f[i + 1] + ... + f[j] is the same as pre[j] - pre[i - 1].
Comment: Hey thanks, I know the DP solution of it. I am looking for complexity of recursive solution , am not able to mathematically derive it. BTW DP solution has complexity of O(nk), you are missing inner look of k ( 1,2,3,...k).
Comment: @abhi No, I did not miss anything. My answer is correct and it runs in O(n) (you would know if you even bothered to read it).
Comment: Sorry i missed.Your solution using prefix sum looks pretty good.thanks


Is it generally acceptable to expose LDAP in read only mode to the Internet?

Question: I need to support Mac clients who need to access a LDAP server to locate SMIME keys.
Since the keys are already in AD, and it's easy for me to create a RODC or read only forest where I push the certificates to, is it acceptable to expose unauthenticated LDAP and LDAPs to the internet?
One issue I can think of is an LDAP form of a directory harvest attack, where a spammer could determine which addresses are valid and which aren't.
Answer: No, it would not be generally acceptable. Not sure what you are trying to achieve but I would say  the correct way is to first establish a VPN connection and then connect to LDAP.
Answer: It depends completely on what's in the LDAP directory.
For Active Directory, absolutely not, even for an RODC - the security profile of these devices is designed for being inside your network (the RODC specifically is hardened against physical compromise, so you can keep it in a closet - a physical compromise of a normal DC would give an attacker control of the domain and all users' password hashes).
An attacker could gain a mountain of information from AD - usernames to try to authenticate with, system names, some amount of network topology.. if not enough to attack with directly (password attacks against a different public endpoint, like VPN?), certainly enough to put together a solid social engineering or spear phishing attack.
Comment: If your AD is that empty, why not just use simple LDAP?
Comment: @makerofthings7 -  I didn't even whisper the word "linux". There's plenty of LDAP server implementations for any OS you care to name. Microsoft has one, similar to AD, called AD LDS (formerly ADAM.) That would be better, in almost all cases. Exposing Active Directory to the internet, via LDAP, exposes sensitive information. It's nothing that wouldn't be available to a LAN-connected client, and if your AD truly contains nothing you don't mind exposing, then go for it. It's not generally acceptable though, which was your stated question.
Comment: Yes, ADAM seems like a fit for this.  I totally forgot about it, despite working with it for years.
Comment: In the solution I propose above, AD happens to be serving the LDAP data, and I'm leveraging its ability to replicate and do LDAP stuff.  There will be no user accounts, other than a renamed Administrator account with a 2 factor password and disabled guest account. I'm considering editing the ACLs of all containers so that enumeration by anonymous users is not possible.  Just direct queries.
Comment: @mfinni - I don't know linux, and am very comfortable with all the nuances of AD...


How to align a view's baseline to another view's top in Jetpack Compose?

Question: I have a Card view and I want to align another view (Red view in picture)'s center to top of the Card like in the picture.

How do I do it? The code for the Card is like this:
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CardDemo()
        }
    }
}

@Composable
fun CardDemo() {
    Column(
        modifier = Modifier.fillMaxSize().background(Color.LightGray),
        verticalArrangement = Arrangement.Center) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(15.dp),
            elevation = 10.dp,
        ) {
            Column(
                modifier = Modifier.padding(15.dp)
            ) {
                Text("Card Title")
                Text("Card Subtitle")
                Text("Card Content Line 1")
                Text("Card Content Line 2")
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ComposeDemoTheme {
        CardDemo()
    }
}

Answer: You should use Box
You need your overlay view be on top of Card otherwise it'll be cut, so place Card inside Box. Also you can use offset modifier to move your view:
Column(
    modifier = Modifier
        .fillMaxSize()
        .background(Color.LightGray),
    verticalArrangement = Arrangement.Center
) {
    Box(Modifier.padding(15.dp)) {
        val textPadding = 15.dp
        val overlayBoxHeight = 20.dp
        Card(
            elevation = 10.dp,
            modifier = Modifier
                .fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.padding(textPadding)
            ) {
                Text("Card Title")
                Text("Card Subtitle")
                Text("Card Content Line 1")
                Text("Card Content Line 2")
            }
        }
        Box(
            Modifier
                .height(overlayBoxHeight)
                .width(40.dp)
                .offset(x = textPadding, y = -overlayBoxHeight / 2)
                .background(Color.Red)
        )
    }
}

Comment: This is very close to what I need. But I want red box to be over the card centered, not inside. Like in the picture I posted.
Comment: Not sure that it resolved the question of author, but it helped me in my case, thank you.
Comment: @yigitserin, then place the box outside the card. I mean inner box inside outer box scope


Set theory, ∈-transitive

Question: The definition of ∈-transitive is where give two sets a and b, if a ∈ b, then a ⊆ b. But what are the scenarios where its not ∈-transitive or if a ∈ b then a ⊈ b?
Answer: A simple example: $\{1\}\in\{\{1\}\}$, but $\{1\}\not\subseteq\{\{1\}\}$, since $1\notin\{\{1\}\}$. The only element of $\{\{1\}\}$ is $\{1\}$, which is not equal to $1$: $1=\{0\}$.

Set theory, ∈-transitive


Encontrar posições corretas na Matriz

Question: Estou tendo dificuldades com este raciocínio. Tenho uma matriz 4x4. Devo preenchê-la com 0 e 1, desde que o número 1 apareça duas vezes em cada linha e em cada coluna, como no exemplo abaixo.
1   1   0   0
1   0   0   1
0   0   1   1
0   1   1   0

Mas a situação abaixo pode ocorrer. Aí eu teria que que mover o "1" de (2,3) para (4,2) que voltará a ficar como no exemplo acima.
1   1   0   0
1   0   1   1
0   0   1   1
0   0   1   0

Se eu somar as linhas e colunas, posso identificar qual linha e coluna está errada, mas não consigo fazer meu programa identificar a posição exata.
Eu preciso dar um retorno do tipo "mover de (2,3) para (4,2)".
Como meu programa pode encontrar as posições exatas?
Comment: Como está seu código atual? Minha sugestão - assumindo que o número de 0s e 1s está correto - é procurar pela linha e pela coluna com mais 1s, e mover essa posição para a linha e a coluna com mais 0s. Se a soma das linhas estiver correta mas a das colunas não (ou vice-versa), mova um `1` na própria linha, da coluna com mais pra coluna com menos.
Answer:
Se eu somar as linhas e colunas, posso identificar qual linha e coluna
  está errada, mas não consigo fazer meu programa identificar a posição
  exata.

R: consegue sim, a lógica é realmente somar cada linha e coluna, se a soma for maior que dois(2) você saberá qual a posição da linha,coluna com valores a mais ou seja onde tem mais 1's do que deveria, você deverá mover para a posição onde a soma for menor que dois(2) isso te diz exatamente onde está faltando número 1, seguindo seu exemplo a lógica seria a seguinte:
Para esta matriz:
1   1   0   0
1   0   1   1
0   0   1   1
0   0   1   0

Vamos começar somando todas as linhas primeiro !
Some a primeira linha da Matriz :
1   1   0   0  ==> soma == 2 (OK)

Some a segunda linha da Matriz :
1   0   1   1  ==> soma == 3 (segunda linha da matriz com problema tem número a mais) > 2

Terceira linha da Matriz :
0   0   1   1  ==> soma == 2 (OK)

Quarta linha da Matriz:
0   0   1   0  ==> soma ==  1 (quarta linha da matriz com problema tem número a menos) <2

Hora de somar as colunas:
Primeira coluna:
1
1          ==> soma == 2 (OK)
0
0

Segunda coluna:
1
0        ==> soma == 1 (problema) < 2
0
0

Terceira coluna:
0
1        ==> soma == 3 (problema) > 2
1
1

Quarta coluna:
0
1       ==> soma == 2 (OK)
1
0

Agora observe qual linha e coluna possue soma maior que dois (>2), vai ser exatamente a segunda linha e terceira coluna posição (2,3) você acaba de encontrar as posições com valores errados onde se tem mais 1's do que deveria ter, OK agora para encontrar para qual posição mover observe qual é a posição cujo valor é menor que dois (<2) você vai notar que será a quarta linha e segunda coluna (4,2), ai está uma maneira lógica de se chegar ao resultado!
Comment: Isso! Ficar mexendo com tanta matriz me confunde as vezes, mas depois dessa explicação ficou mais claro e consegui bolar um código aqui. Obrigado o/

Encontrar posições corretas na Matriz


Not taking Input from keyboard after using cin.getline() in C++

Question: In the below program, it works fine when I input string of length less than or equal to 10 but when I exceed the string length, getline works fine but the subsequent input statement won't work (not taking input)
/* used proper header */
int main ()
{
int a,b;
char s[10];
cin>>a;  //work fine
cin.ignore();
cin.getline(s,10); // work fine but if the length of string is more than 10...

cin>>b;  //...this line doesn't work
cout<<"a="<<a<<"s="<<s<<" b="<<b;
getch();
}

Comment: Isn't `ignore`ing the rest of the line enough?
Comment: You should make your variable ```s``` as a pointer to char array to be able to read variable-length strings.
Answer: Here is your solution:
#include <climits>
#include <iostream>
using namespace std;

int main() {
    int  a, b;
    char s[11]; // <-- Size should be 11, the last character will be '\0'
    cin >> a;
    cin.ignore(); // better change it to cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.getline(s, 11); // <-- this line sets failbit if the input exceeds 10 characters

    // add these lines :
    if (!cin) { // <-- checks if failbit is set
        cin.clear(); // <-- clears the set flags
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ignores the whole line
    }
    // if anything had gone bad, it has been fixed by now

    cin >> b;
    cout << "a = " << a << "\ns = " << s << "\nb = " << b;
}

A more complex but better one:
#include <climits>
#include <iostream>
using namespace std;

int main ()
{
    cin.exceptions(ios_base::failbit|ios_base::badbit); // <-- tells compiler to treat failbit and badbit as exceptions
    int a, b;
    char s[11];
    cin >> a;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    try {
        cin.getline(s, 11);
    } catch (ios_base::failure &e) {
        // cerr << e.what() << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    cin >> b;
    cout << "a = " << a << "\ns = " << s << "\nb = " << b;
}

Comment: @Hack06 I just read your comment on the question: *You should make your variable s as a pointer to...* Firstly, the approach you are suggesting using pointers is very much complex. The case is not of VLAs or dynamic arrays. You don't even know how long your string is gonna be. For that approach you'll need to keep on resizing your array, copying contents... Better way is to directly use `std::string`. Secondly, OP is explicitly using here a static array. Suggesting him to use `std::string` is surely not a solution. If he'd been using `string`, he may not have even experienced such thing. :)
Comment: Thanks for the solution, it works for me. Thanks a ton.
Answer: Simple solution , use scanf("%[^\n]",s) instead

It reads a whole line into an array until you press Enter key. You
can modify it as you want. Just replace '\n' with the character you
want to be the end of the input.

Here's how in your case :
    int main () {

        int a,b;
        char s[10];

        cin>>a;
        cin.ignore();
        scanf("%[^\n]",s);
        cin>>b;

        cout<<"a="<<a<<"s="<<s<<" b="<<b;

        return 0;

    }

Comment: Hey better give this a look : [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) and modify/delete your answer.
Comment: Thank you very much for your advice, I got to know later that using gets() function was really dangerous.  Now I have changed my approach.
Comment: Your approach still has a problem. Firstly, `s` should be of `11` characters, since it has to hold a `\0` char at the end. Secondly, you need to explicitly set `s[10] = 0` after your `scanf`, otherwise `cout << s` will simply print an array of `11`(not `10`) characters plus an extra character which may appear like a block or some special symbol (garbage value). Thirdly, no need to do a `cin.ignore()` before `scanf()`, change format string to `" %[^\n]"`. Notice the space before `%`, it'll do the work of `ignore`.
Comment: *Continuing the above comment...* Fourth, `scanf` will not work for inputs like `hello world` as `scanf` terminates scanning for a specifier as soon as it encounters a white space. I believe that's the sole logic behind using `getline`, otherwise, if he had string not having any spaces, he may have used directly `cin >> s;` :)


550 5.7.1 Unable to deliver to error for newly added emails, when sending to them from external address

Question: I recently added AD accounts and email inboxes for three new users in our org. When sending an email to them from within our organization, they arrive without issue. When sending from an external source (such as my personal Gmail account) we get a 550 5.7.1 error. No other mailboxes appear to be having this issue currently, just the ones added earlier today. Other mailboxes have the same domain name as the three having the issue. What might be causing this?
This is on Exchange 2016 and Server 2012
Comment: Do you have an interceding mail filtering service?  Like, one that performs periodic syncs of the GAL so that mail can be dropped at the connection if sent to an invalid recipient?
Comment: And frankly - if you do - it should not be returning the NDR.  It is potentially creating a lot of back-scatter, and is aiding those who perform Directory Harvest Attacks.
Answer: First Test inbound SMTP https://testconnectivity.microsoft.com/ & post the results.
Mostly occur due to the domain was changed from .com to .local
Use Command:
Get-ReceiveConnector "relay" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"
relay = name of your connector.
Check out the links for more info Link and Link1


Three Notes Per String and the 7 Modes

Question: If the third position of the three notes per string G major scale is the B Phrygian mode, then how do I play that same mode all over the fretboard of the guitar?
Comment: Do you know what makes a set of notes a mode specifically B Phrygian in this case? If not, that may be a better starting point.
Comment: You use more than three notes per string.
Comment: The 3rd 'position' of 3nps G major scale isn't B Phrygian. It's B Phrygian because it's rooted on the 3rd note of G major.
Answer: This should be a comment, but it's too complicated for just a text sentence, the fretboard picture is needed...

From the top the three-notes-per-string "boxes" are ionian (major scale), dorian, and phrygian.
The red dot represents the tonic of a major scale. In this case it's a C major scale. So, the red dot is C.
In the "ionian" box the first note, the lowest note, is the tonic, the red dot, the C.
Notice that in the "dorian" and "phrygian" boxes the lowest note of the box is not the red dot, not the tonic. If you use these boxes, and want to play in C major, you would want to make the red dot, the tonic, the main "target", not the lowest note of the box. Because you maintain C as the target, these boxes are only superficially dorian or phrygian. You wouldn't really be playing in D dorian or E phrygian, because you would keep to focus on the C to maintain C major as the key.
If you really wanted to make the so-called "phrygian" box a phrygian mode, then you need to change the tonic, you need to change the placement of the red dot. Like this...

If you take that phrygian mode and "move it all over the fretboard," like move it down to the third fret...

...you now have G phrygian. Or, if you related that back to a major scale it would be a mode (or rotation) of E flat major.
Now we can get back to your question...

If the third position of the three notes per string G major scale is the B Phrygian mode, then how do I play that same mode [B phrygian] all over the fretboard of the guitar?

Do you really mean to ask: how to play B phrygian all over the fretboard?
Do you want to play in G major or B phrygian?
Do you want to change the tonic?
Comment: Yes, that is what I mean to ask. How to play B phyrgian all over the fretboard.
Comment: The three note per string "box" patterns will be the same, but the tonic and other scale degrees will shift around. Look for a diagram like this https://discoverguitaronline.com/diagrams/17.png. Try searching 'three notes per string phrygian mode.'
Answer: You don't play the 3 notes per string scale shape all over the fretboard anyway. It has one specific place for each key.
So, using Phrygian as the example, you could leave out the first two notes from G major, and start on the 3rd. Use all the remaining notes from G major, in their 3nps positions, and there you have it. Move everything up 2 frets and it's C♯ Phrygian, etc.

Three Notes Per String and the 7 Modes


How can I fallback to one field in absence of another

Question: How can I make one field show up, unless it has no value, in which case another field is shown? I want to do this on the default node view, I already know how to accomplish it in views. I'm assuming it will mean coding something in my theme, but where best to do that is a little confusing to me.
Comment: In a node view? in a view? custom code? Please provide more data to get a good answer.
Answer: I would checkout Field formatter conditions where you can set a whole variety of conditions of one field based on if another field is empty or not. You would set these conditions in whatever display mode you are in so in the case of a node, most likely the view mode will be full or default. (e.g. admin/structure/types/manage/[MY_content_type]/display

Alternatively, you could do some custom node template theming and set conditions there such as if one field is not empty do this, else, show the other field.
<?php if (!empty($content['field_foo'])): ?>
  <?php print render($content['field_foo']); ?>
<?php else: ?>
  <?php print render($content['field_bar']); ?>
<?php endif; ?>

This assumes there is a value with field_bar so you may need to add conditions for that field too if it's empty. With per field theming, you may need to not render the general content variable as well, it just depends on the order and where things fall in the template.
Comment: Thanks that module looks promising and the code based approach is what I was looking for, though now that I see it I kick myself for not figuring it out myself.
Comment: Great, glad this helped!


lmer for simple unpooled statistics

Question: I have one vector of predictor, one vector of response, and two columns of categories, each has two possible classifications.
I tried to create an unpooled linear model using lmer, but I get conflicting results.

lmer(response ~ predictor + (1 | category1:category2), data) gives me a singular model
lmer(response ~ (predictor | category1:category2), data) gives me non-singular model

what is the difference between the two? each class should have its own slope and intercepts.
Comment: What do you mean by 'unpooled'?  Also your two models are different in that the first has a random intercept only and the second has random intercept and slope.
Comment: Unpooled as in there's no hierarchy in the categories (its gender and method of transport (public vs private).                                                                    What is the difference of #2 with lmer(response ~ predictor + (1 + predictor | category1 ) + (1 + predictor | category2)? I just want to create a linear model using lmer with 1 vector of response and 1 vector of predictor with 2 vectors of categories which has no hierarchy or orderings. Also, thank you for respondng!
Answer: "Unpooled" typically refers to a "fixed effects" model. It means that each category is given it's own unique intercept. These models are typically estimated using lm, not lmer, the latter estimating "partially pooled" or "random effects" models. In order to estimate an unpooled model on your data, I would suggest the following lm:
unpooled <- lm(response ~ predictor + category1 + category2 + category1:category2, data)
This will give you the following interpretations for each regression coefficients you see in summary(unpooled):
(Intercept)         - the adjusted response mean for individuals with 0 values on category 1 and 2
category 1          - the mean difference, relative to the (Intercept), for individuals with a 1 on category 1 and a 0 on category 2.
category 2          - the mean difference, relative to the (Intercept), for individuals with a 1 on category 2 and a 0 on category 1.
category1:category2 - the mean difference, relative to the (Intercept), for individuals with a 1 on both category 1 and category 2

By addition and subtraction of these coefficients, you can reconstruct the intercept for each of the four groups. For example the intercept for category 1 is equal to the addition of the coefficients for (Intercept) and category1.
Comment: I think what I need is cross classification model for this problem. Unpooled assuming that each of the category doesn't have any relationship with one another isn't it? However, I'd like to build a model that also take into account how these categories could affect the model despite the hierarchy/orderings doesn't matter (category 1 is not a subset of category 2, and vice versa). Thank you for the reply, I'll try your suggestion and report back

lmer for simple unpooled statistics


IIS UrlRewrite RegEx differences with .NET RegEx

Question: I have a valid RegEx pattern in .NET:
(?>.*param1=value1.*)(?<!.*param2=\d+.*) which matches if:

query string contains param1=value1
but does not contain param2= a number

It works in .NET. However IIS URLRewrite complains that it is not a valid pattern.
Can I not use zero-width negative look behind (?<!   ) expressions with IIS URLRewrite?
Note that I tried to apply this pattern both in web.config (properly changing < and > to < and > respectively, as well as in the IIS Manager - all without success.
Comment: Can't you simplify it as `^(?!.*param2=\d).*param1=value1`? Or if you need to match the whole string, add trailing `.*`: `^(?!.*param2=\d).*param1=value1.*`
Comment: @WiktorStribiżew Thanks! This works! However the question remains as to the differences. I thought that the 2 RegEx engines used are equivalent.
Comment: No, as you can see the syntaxes differ.
Answer: IIS URLRewrite default regex syntax is ECMAScript, that is not compatible with .NET regex syntax. See URL Rewrite Module Configuration Reference:

ECMAScript – Perl compatible (ECMAScript standard compliant) regular expression  syntax. This is a default option for any rule.

You cannot use a lookbehind at all, you will have to rely on lookaheads only:
^(?!.*param2=\d).*param1=value1.*

Pattern explanation:

^ - start of string
(?!.*param2=\d) - if there is param2= followed with a digit (\d) after 0+ characters other than a newline fails the match (return no match)
.*param1=value1.* - match a whole line that contains param1=value1

You can enhance this rule by adding \b around param1=value1 to only match it as a whole word.


Does each reference to a ResourceDictionary create a new instance, or do ResourceDictionaries have a caching mechanism

Question: I have some code like this
        _images = new ResourceDictionary
        {
            Source = new Uri(@"pack://application:,,,/Trilogy.T1TY2012.Transmission;component/Resources/Images.xaml")
        };

which appears several times in my application (sometimes as C# and sometimes as the equivalent XAML). Does each instance contain separate instances of each of its resources, or is there a behind the scenes caching mechanism that shares those resources across all the resource dictionaries?
I am trying to decide if I need to make efficient use of the resource dictionaries (ie: share specific instances), or whether this optimization is already handled by WPF.
Answer: If I'm understanding your question, then the answer is, they are not "cached" *between different ResourceDictionary instances: an instance of ResourceDictionary will not use any resource of the same type/key that may have been instantiated already in another ResourceDictionary.  That is to be contrasted, of course, to keys within a single ResourceDictionary; each of those entries are indeed "cached", in the sense that they are created once and shared (with an exception for value-typed resources, which are copied on each use).
So, you do have to manage the scope of your resources if they are memory intensive.  You can always put each resource into your main App.xaml dictionary, which ensures each entry will be instantiated once, and shared for all its consumers.  Note that the resources are lazy-loaded:

The items in a ResourceDictionary are not immediately processed when application code is loaded by a XAML loader. Instead, the ResourceDictionary persists as an object, and the individual values are processed only when they are specifically requested.

So you do not have to be concerned about your application loading all the resources in App.xaml on startup; it loads them only as needed.
Comment: do i understand this correctly, that in case `App.Xaml` has resource `Foo.Xaml`, and also uses `MyButton.Xaml` as a UI Element - which in turn also references resource `Foo.Xaml` as `MergedDictionary`, `Foo.xaml` is loaded only once? Or will there be two instances?
Answer: To have a dictionary which will not be instantiated for each usage
///
    /// The shared resource dictionary is a specialized resource dictionary
    /// that loads it content only once. If a second instance with the same source
    /// is created, it only merges the resources from the cache.
    ///
    public class SharedResourceDictionary : ResourceDictionary
    {
        ///
        /// Internal cache of loaded dictionaries
        ///
        public static Dictionary<Uri, ResourceDictionary> _sharedDictionaries =
            new Dictionary<Uri, ResourceDictionary>();

        ///
        /// Local member of the source uri
        ///
        private Uri _sourceUri;

        ///
        /// Gets or sets the uniform resource identifier (URI) to load resources from.
        ///
        public new Uri Source
        {
            get { return _sourceUri; }
            set
            {
                _sourceUri = value;

                if (!_sharedDictionaries.ContainsKey(value))
                {
                    // If the dictionary is not yet loaded, load it by setting
                    // the source of the base class
                    base.Source = value;

                    // add it to the cache
                    _sharedDictionaries.Add(value, this);
                }
                else
                {
                    // If the dictionary is already loaded, get it from the cache
                    MergedDictionaries.Add(_sharedDictionaries[value]);
                }
            }
        }
    }

For the resources itself u can play with the x:shared attribute


stop executing after mysqli_connect('','','')

Question: i have wriiten a a code in php...
<?php
 echo "entering db php code";
 $link=mysqli_connect ('localhost','root','MyRootPassword');
 echo "mysqli_connect is called";
 if (!$link)
 {
     echo "cannection is failed";
     exit();
 }
 echo "connection is ok";
 ?>

output is::

entering db php code

that's it.*the code stop executing after mysqli_connect() call.*
can anyone please tell me that.what is the problem in the code.
this code is absolutely doing nothing with the mysqli_connect() call and it stop executing the rest part once mysqli_connect is called
Answer: You should enable error displaying like:
ini_set('display_errors',1);
error_reporting(E_ALL | E_STRICT);

But if you never get to the second echo, that probably means that the mysqli extension is not installed and you get an undefined function error, stopping your script.
Does phpinfo(); give you a section with mysqli information?
Comment: thanks a lot...then please tell me how to establish the mysqli extension @jeroen
Comment: @Ritabrata Gautam That depends on your hosting solution, some allow for easy addition of extensions and if you manage the machine yourself, you could probably simply install it.
Comment: Strict Standards: main() [function.main]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'UTC' for '5.5/no DST' instead in C:\Program Files\Apache Group\Apache2\htdocs\include\db.inc.php on line 16

Fatal error: Call to undefined function mysqli_connect() in C:\Program Files\Apache Group\Apache2\htdocs\include\db.inc.php on line 16
Comment: @jeroen..am sorry..if you are filling disturbed....but above is the error..can u explainit for me please..everything going over my hhead
Comment: @Ritabrata Gautam exactly, you (your host...) need to add / install the `mysqli` extension or alternatively switch to `PDO` if that is installed already.
Comment: i checked my php folder..and there is nothing in the ext subfolder..that's extension_dir in php-ini file is pointing to  void as there is nothing in ext subfolder....i think i need to re-install php 5.1.x..what say?..@jeroen
Answer: $link=mysqli_connect ('localhost','root','MyRootPassword');

is missing an argument.
The correct way to call mysqli_connect is
$link = mysqli_connect('server', 'username', 'password', 'database_name');

Alternatively, you can define the following in your php.ini file
mysqli.default_host
mysqli.default_user
mysqli.default_pw
mysqli.default_db
mysqli.default_port //You should only need to change this rarely
mysqli.default_socket //You should only need to change this rarely

And call the mysqli_connect as
$link = mysqli_connect();

Comment: As far as I can see, that (and the rest...) is an optional argument.
Comment: Actually, all of them are optional, if you have them defined them in the php.ini file.
Comment: Exactly, that's what I meant with `and the rest...`.
Comment: thanks for a quick reply..but it doesn't work..i even tried with other arguments like socket and port_no. .... i think there must be some other problem...even if there was any fault with arguments it should show a error message..but the code stop executing after $link=mysqli_connect() call
Comment: Nice explanation, but I still don't see how that would cause the script to exit.
Comment: Well, you already gave the explanation on what would cause the script to exit in the middle of execution. I didn't want to say almost the same thing, except that I would change the error_reporting to E_ALL.
Comment: still am blind...dont know what wrong i have done.. :(...what should i do to establish a successfull connection..
Comment: @RitabrataGautam please see Jeroen's answer.
Comment: Fair enough, sorry to be a pain :-)
Comment: Well, you did catch the correct error. I started thinking on those lines after what I wrote initially didn't work.
Answer: i have solved it :D :)
earlier i have installed php installer version.i uninstalled it.and then unzip the php 5.2.x thread safe.now it's working after the necessary configuration ...


How to update security stamp of users in bulk? Asp.net Identity

Question: I am updating users security stamp when a user is being deactivated. I can do this for one user like this.
await UserManager.UpdateSecurityStampAsync(userId);

I want to do this form multiple users, like 500 or may bee 100.
Is there any way I can do this in bulk?
I am using entity framework.
Comment: EF is not very good with bulk updates. Are you OK with executing SQL query?
Comment: Yes, but don't know how I'll call UpdateSecurityStampAsync(Id) on each user with sql.
Answer: Security Stamp is a random string with no significant importance of the actual value, so you can just stuff new GUID there.
Best way to do it in bulk would be to execute SQL query:
update ApplicationUsers set SecurityStamp = NEWID()

You can specify where clause as needed to limit users you need to update, and most likely you'll need to change the name of the table to what you actually have in your DB.
There different ways to execute this query - you can do this with EF:
context.Database.ExecuteSqlCommand("UPDATE ApplicationUsers........");

Or you can look into already recommended EF.Extended library - bulk update is possible without dipping into SQL.
Comment: accepted you answer for hint 'security stamp is just a random string' :)
Comment: @mfahadi Glad it helped!
Answer: You can use Entity Framework Extended Library.Which is the fastest way to do the update.Extended Library batch update eliminates the need to retrieve and load an entity before modifying it.So it is very fast.Try that.
Example from their doc :
//update all tasks with status of 1 to status of 2
context.Tasks
    .Where(t => t.StatusId == 1)
    .Update(t => new Task { StatusId = 2 });

You can read more about it here : Entity Framework Extended Library
Comment: Actually I have to call this function for each user, can you tell how can I do that.

 UserManager.UpdateSecurityStampAsync(userId)


How can i get friend's friends list of facebook api in c#

Question: I want get friend's friends list of Facebook API.
I can get my friend list, but I can't get friends friends list of Facebook API with c#.
How can I do it?
Comment: This is not a good way to ask a question here. Did you try _anything_ so far to solve your problem? Show your effort first so people might show theirs. Please read [FAQ], [ask] and [help] as a start..
Comment: i so try to fined my answer , i try with fb api and another . but i cant find any way
Answer: Yes, its possible to get List of Friends of a friend but only condition is that friend should be user of that application.
Suppose there is an application "APP" used by "A" then the APP can get his friends List , now you want friends List of "B" who is friend of "A" , it will be possible only if "B" also uses the "APP"
Also try your hands on code and show us from code for the same
Answer: I'm afraid you cannot fetch that!
The Graph API don't provide any API to do so.


css / jquery animation not supported by IE9 - workaround required

Question: I have the following animation that doesn't work in IE9 as the transition property is not supported.
Unfortunately I have to get it working for IE9+.
Does anyone know any fix / workaround?
https://jsfiddle.net/jyqkr52q/1/
CSS
.egg{
    position:absolute;
    left:-120px;
    width:150px;
    height:200px;
}
.egg>div{
    position:absolute;
    width:100%;
    height:100%;
    border-radius:50%;
}
.egg>div>span{
    background-image:URL('http://leanneoleary.com/test/rollin-animation/Purple_Easter_Egg_small.png');
    position:absolute;
    left:23px;
    top:14px;
    width:150px;
    height:200px;
    text-align:center;
    line-height:45px;
    font-size:24px;
    font-weight:bold;
}

HTML

JS
var $egg = $('#egg_box > div'),
    diameter = $egg.height(),
    perimeter = Math.PI * diameter,
    n = $egg.length,
    i = 0,
    itv;

itv = setInterval(function(){
    if(i>n)clearInterval(itv);
    rotateegg( 500-(diameter*i) );
    i++;
},2000);

function rotateegg(distance){
    console.log( distance );
    var degree = distance * 360 / perimeter;
    $egg.eq(i).css({
        transition: "2s cubic-bezier(1.000, 1.450, 0.185, 0.850)",
        transform: 'translateX('+ distance +'px)'
    }).find('div').css({
        transition: "2s cubic-bezier(1.000, 1.450, 0.185, 0.850)",
        transform: 'rotate(' + degree + 'deg)'
    });
}

Comment: Check transition browser support. https://css-tricks.com/almanac/properties/t/transition/ It only support IE 10+
Comment: CSS3 is not supported in IE9.
Comment: Yes I know its not supported, I was asking if anyone knew of a workaround.
Answer: CSS3 Transition property is not supported in IE 9.0, it is supported from IE 10 onwards.so your animation is not working on IE 9.0.

But CSS3 transform property is supported from IE 9.0 onwards.
Official MDN Site
Comment: OK so what exactly would I need to change in the code to get this working using the transform property instead of the transition?
Comment: Transform and transition are completely different, there is no way you can use transition property in IE 9.0. one alternative is that you can use jquery's `fadeIn()` or `fadeOut()` effect thats the only transition there is for IE 9.0


Angular directive ng-selected doesn't update model

Question: When using the angular directive ng-selected on an option, the bound model doesn't get updated until you manually change the selection.  Is this as designed?
http://jsfiddle.net/PqHsL/1/

  <select ng-model=selectedElement>
    <option ng-repeat="color in colors" value="{{color}}" ng-selected="$last">{{color}}</option>
  </select>

  selectedElement: {{ selectedElement }}

Answer: I don't know if it is working as designed.
I get the impression that ng-selected and ng-model don't play well together.  (Note that the ng-selected API page doesn't use ng-model in the example select list.)
Here are two ways to workaround this:

set the bound model in addition to setting ng-selected.  ng-init can also be used for this:
ng-init="colors=['red', 'yellow', 'blue']; selectedElement=colors[colors.length-1]"
set the bound model, don't use ng-selected, use ng-options:
...ng-init as above...
<select ng-model=selectedElement ng-options="color for color in colors">{{color}}</select>

Fiddle.
Solution 1 has that weird "blank"/empty option, which disappears when you select something.  Solution 2 doesn't have the empty option, and is less verbose.  (So yeah, I like solution 2.)
I'm not sure what the use case is for ng-selected if we can set the model to preselect an option.  We can change the selection programatically later also -- see the ng-click in the Fiddle.
Comment: I used #2, but, yes, had to set the model explicitly first.  thx.


What is the most efficient SQL query to do the following?

Question: What is the most efficient SQL query to do the following?
Following are the two tables joined on ItemID:
Item { ItemID, OtherData }
Love { ItemID, Username }
I pass in a "someuser" as Username in the query.
Query should return ItemID, OtherData, and a boolean indicating whether there exists a Love for the ItemID.
Comment: `Like` is not advised to be table name, as it's a reserved word.
Comment: Are you looking for a query or a LINQ statement? The linq tag has me a bit confused.
Comment: Either works, but solution has been found!
Comment: What's your teacher gonna think when he/she finds this?
Comment: lol, this is not for school, but for a project I'm working on
Answer: SELECT I.ItemID, I.OtherData, CASE WHEN L.ItemID IS NULL THEN 0 ELSE 1 END AS Loved FROM Item I LEFT JOIN Love L ON I.ItemID = L.ItemID

To the op stop changing your requirements!
Comment: I'm looking for all items, and not just items with Likes
Comment: I didn't change the requirements though. I just changed the table name as suggested. But this query looks promising. Is it the most efficient though?
Comment: For something this small and trivial this is the simplest way to get what you want.
Comment: I think this is on track. Could you elaborate on your solution a little bit to help me understand what's going on exactly? As I understand it now, you're left joining all the loves to the items, and then testing if love.ItemID is there or not to set the boolean. This solution currently does not take the "someuser" username into account though.
Answer: Try something like this:
SELECT Item.*
       ,CASE WHEN t.ItemID IS NOT NULL THEN 'YES' ELSE 'NO' END AS flag
FROM Item LEFT JOIN (SELECT DISTINCT ItemID FROM Love WHERE Username = someuser) t
        ON Item.ItemId = t.ItemId

Answer: SELECT i.ItemID, i.OtherData
FROM Item as i
INNER JOIN Like as l ON i.ItemID = l.ItemID
WHERE Like.Username = {someuser}

If there is no Like for ItemID then i.ItemID will be NULL, you can test for that condition as your boolean.


Link spring boot with react

Question: I followed this tutorial for creating a web app using react and spring boot.
I followed the exact same steps, but in my react app I introduced webpack. The react app is on and running.
The pom.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0
<groupId>com.example</groupId>
<artifactId>ema</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>ema</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
<plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>

    <plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.2</version>
    </plugin>

    <plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.0.2</version>
    <executions>
    <execution>
    <id>Copy frontend production build to resources</id>
    <phase>package</phase>
    <goals>
    <goal>copy-resources</goal>
    </goals>
    <configuration>
    <outputDirectory>${basedir}/target/classes</outputDirectory>
    <resources>
    <resource>
    <directory>src/main/app/build/</directory>
    <filtering>true</filtering>
    </resource>
    </resources>
    </configuration>
    </execution>
    </executions>
    </plugin>

    </plugins>
</build>

I got to the last steps of the tutorial:
mvn clean package
java -jar target/cra-demo-0.0.1-SNAPSHOT.jar

But I see that my spring server is closig:
 :: Spring Boot ::        (v1.5.3.RELEASE)

2017-04-27 15:01:33.740  INFO 28295 --- [           main] com.example.EmaApplication               : Starting EmaApplication v0.0.1-SNAPSHOT on robucslvm03 with PID 28295 (/home/gecobici/EMA/target/ema-0.0.1-SNAPSHOT.jar started by gecobici in /home/gecobici/EMA)
2017-04-27 15:01:33.748  INFO 28295 --- [           main] com.example.EmaApplication               : No active profile set, falling back to default profiles: default
2017-04-27 15:01:33.860  INFO 28295 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@255316f2: startup date [Thu Apr 27 15:01:33 EEST 2017]; root of context hierarchy
2017-04-27 15:01:34.936  INFO 28295 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-04-27 15:01:34.958  INFO 28295 --- [           main] com.example.EmaApplication               : Started EmaApplication in 2.06 seconds (JVM running for 2.877)
2017-04-27 15:01:34.958  INFO 28295 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@255316f2: startup date [Thu Apr 27 15:01:33 EEST 2017]; root of context hierarchy
2017-04-27 15:01:34.959  INFO 28295 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

I am new to spring and react, I don't know how to get the spring server up and running and interact with my react app.
Edit:
In the pom.xml i have:
<directory>src/main/app/build/</directory>

I create production build with webpack -p but i see no build folder.
How can I do to generate production build in a build folder?
Answer: You introduced webpack witch is not bad at all, what you can do to simplify the usage of your React app with spring, is to setup Webpack Proxy to intercept all HTTP request in a specific port, this is how I do it:
'webpack-dev-server': {
      options: {
        webpack: webpackConfig,
        inline: true,
      },
      start: {
        host: '0.0.0.0',
        port: '<%= config.webpackDevServerPort %>',
        contentBase: '<%= config.dist %>',
        webpack: {
          devtool: 'inline-source-map',
          debug: true,
        },
        proxy: {
          '/myapp': {
            target: 'http://localhost:' + (grunt.option('proxy-port') || config.connectPort),
            secure: false,
          },
        },
      },
    },

one last thing in your Spring app you have to allow the following :
  /**
   * Register WebSocket publisher
   *
   * @param registry where the handler will be registered
   */
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(publisher, webSocketPath).setAllowedOrigins("*");
  }

if you don't setAllowedOrigins("*"); rest calls from outside spring server will not be intercepted, this is just for dev and have to be disabled when the app goes to production.
Comment: How can i genreate production build in a build folder using webpack?
Comment: I added proxy settings in webpack config and the same behaviour
Comment: webpack will just bandel your app and then you have to use maven to package the front and the back in one single jar to be executed

Link spring boot with react


UINavigationController not displaying

Question: I am new to IOS dev so I'm sure the answer is simple but my ignorance makes it hard to find the answers online. I'm trying to use a UINavigationController to switch between views. Thus far I have been succesfully displaying the first view with the following code.
FLInitialMapViewController *control = [[FLInitialMapViewController alloc] init];
self.window.rootViewController = control;

I then wrote the code to add the navigation controller but when I run it I see mostly a black screen with a gray bar at the top of it. Here's the code
FLInitialMapViewController *control = [[FLInitialMapViewController alloc] init];
_navController = [[UINavigationController alloc] initWithRootViewController:control];
self.window.rootViewController = _navController;

Here is the complete code for AppDelegate.m in 'didFinishLaunchingWithOptions':
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

FLInitialMapViewController *control = [[FLInitialMapViewController alloc] init];

self.navController = [[UINavigationController alloc] initWithRootViewController: control];
[self.navController setNavigationBarHidden:YES];

self.window.rootViewController = self.navController;

[self.window makeKeyAndVisible];
return YES;

Interestingly, the gray bar near the top is slightly translucent and I can see some of my UI elements underneath it.
EDIT: I removed the top bar and now I see the following!

This is what should be seen.
Comment: Are you setting the `UINavigationController` in the `AppDelegate.m`? Assuming that you started with an `Empty Application`. Please share a screenshot.
Comment: This code is in AppDelegate.m. Isn't the code above setting the navcontroller?
Answer: I have added navigation bar setup for your convenience. Try this in your AppDelegate.m under didFinishLaunchingWithOptions: method -
FLInitialMapViewController * control = [FLInitialMapViewController new];

UINavigationController *myNav = [[UINavigationController alloc] initWithRootViewController: control];
self.window.rootViewController = myNav;

// Setup navigation bar programmatically
UINavigationBar *navigationBar = myNav.navigationBar;
navigationBar.barTintColor = [UIColor orangeColor];
navigationBar.barStyle = UIBarStyleBlackOpaque;

// Boiler plate code from AppDelegate
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

Comment: No changes. Is it possible that my controller is not adding elements to the view correctly? Because it appears that my elements are being displayed but underneath the navigation controller.
Comment: Do you want the code for the controller? Because that codes pretty long and I don't know what else would be relevant.
Comment: Not from the controller. But, from your `AppDelegate.h` and `AppDelegate.m`. Just update the question with complete code. I hope you started with an 'Empty Application' (which we had in Xcode 5.1).
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/63568/discussion-between-raurora-and-nate).

UINavigationController not displaying


call stored procedure from java springboot program pool empty error

Question: I have a springboot application which calls a stored procedure quite frequently which performs some inserts and update to some of tables. I can see that functionally this code works but after a while I can more number of connections are open and any new request to run any query is not being satisified and getting below error
<code>'Timeout: Pool empty. Unable to fetch a connection in 30 seconds, none available[size:100; busy:100; idle:0; lastwait:30000].","logger_name":"org.hibernate.engine.jdbc.spi.SqlExceptionHelper"'
</code>
Below is code which invokes the stored procedure,  I tried changing to a different implementation using entity manager as well but same result
Will appreciate any thoughts on the issue , also let me know if anything is not mentioned.
<code>@Transactional
private Status bulkSaveOrderInterfaceStatus(String procName,String orderIds,
  interfaceType, String errorMsg, String status) {

    String outPutPram;
    try(Session session = (Session) em.getDelegate()) {
        SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) session.getSessionFactory();
        Session ses = sessionFactory.openSession();
        ses.beginTransaction();
        ProcedureCall storedProcedure =  ses.createStoredProcedureCall(procName);
        storedProcedure.registerParameter(SqlConstants.BULK_INS_PROCEDURE_ORDERID_INPUTPARM, String.class, ParameterMode.IN).bindValue(orderIds);
        storedProcedure.registerParameter(SqlConstants.BULK_INS_PROCEDURE_INTERFACETYPE_INPUTPARM,String.class, ParameterMode.IN).bindValue(interfaceType);
        storedProcedure.registerParameter(SqlConstants.BULK_INS_PROCEDURE_ERRORMSG_INPUTPARM,String.class, ParameterMode.IN).bindValue(errorMsg);
        storedProcedure.registerParameter(SqlConstants.BULK_INS_PROCEDURE_STATUS_INPUTPARM,String.class, ParameterMode.IN).bindValue(status);
        storedProcedure.registerParameter(SqlConstants.PROCEDURE_OUTPUT_MESSAGE, String.class, ParameterMode.OUT);
        outPutPram = (String) storedProcedure.getOutputs().getOutputParameterValue(SqlConstants.PROCEDURE_OUTPUT_MESSAGE);
        ses.getTransaction().commit();
        if (outPutPram.equals(SqlConstants.PROCEDURE_STATUS_SUCCESS)) {
            return Status.SUCCESS;
        } else {
            return Status.ERROR;
        }

    } catch (Exception e) {
        return Status.ERROR;
    }

}
</code>
Comment: Can you please share your data-source property file or Hibernate property file.
Answer: I think you should close session and it is better to do it in finally or use try with resource statement.
<code> finally {
     ses.close();
  }
</code>
Comment: that 's right ;) i didn't notice he use try and resource statement.
Comment: sorry i missed here. I even tried using it in a finally block but still same issue
Comment: Do you close ses reference in finally ?