Checkbox Condicional

Question: Preciso realizar uma validação ao selecionar algumas opções no seguinte checkbox:

A regra é a seguinte:
Se o IMPEDITIVO estiver selecionado com "S", o EXECUTADO deve estar "N". Porém ambos podem estar como N mas nunca podem ser ambos S.
Ou seja, ao selecionar um, o outro deve ser descelecionado, porém a página (que é uma página de edição) será sempre carregada com uma das opções selecionadas.
O que estou tentando fazer até o momento é isso:
  comparaImpeditivoExecutado1(ocorrenciaSolicitacaoVO) {
if(ocorrenciaSolicitacaoVO.statusImpeditivo){
  ocorrenciaSolicitacaoVO.statusExecutado = false;
}
else {
  ocorrenciaSolicitacaoVO.statusExecutado = true;
}

}
Mas aparentemente não está resolvendo.
Comment: Você precisa passar por parâmetro quem está alterando no momento, assim você verifica o status do outro, por exemplo: `if(this) other = false;`
Answer: Você pode usar a tag input com o type="radio" e name="radio".

    <input class="checkClass" type="radio" name="radio" id="checkbox1">
    checkbox 1
    <input class="checkClass" type="radio" name="radio" id="checkbox2">
    checkbox 2

Answer: Transformei os valores em boolean e no component manipulo eles da seguinte maneira:
checkboxExecutado(ocorrenciaSolicitacaoVO) {
ocorrenciaSolicitacaoVO.statusExecutado = !ocorrenciaSolicitacaoVO.statusExecutado;
ocorrenciaSolicitacaoVO.statusImpeditivo = false;

}
checkboxImpeditivo(ocorrenciaSolicitacaoVO) {
ocorrenciaSolicitacaoVO.statusImpeditivo = !ocorrenciaSolicitacaoVO.statusImpeditivo;
ocorrenciaSolicitacaoVO.statusExecutado = false;
}
Me atendeu.

Checkbox Condicional


Limit of permuted numbers when each of them is approaching $0$

Question: Let  $\sigma:N_n \rightarrow N_n$ be arbitrary permutation of $n$ numbers. Does the following limit exist?
$$\lim_{x_i \to 0} \frac{x_1+x_2^2+ \cdots x_n^n}{x_{\sigma(1)}+x_{\sigma(2)}^2+ \cdots {x_{\sigma(n)}^n}}$$
I've considered the case where $\sigma(n) = n$ for some $n \in N$ and concluded that then the limit doesn't exist but I'm having trouble figuring out when $\sigma(n) \neq n \ (\forall \ n \in N)$. I was given a hint to consider that $\sigma (1) >1$ and $\sigma(n) <n.$
The set $N_n$ I believe to be arbitrary set with $n$ elements, not necessarily natural numbers. Don't have much much more context than that but I don't think this matters for the problem.
Comment: They are all permutations of $x_i$ yes. I considered the case where one of the numbers's permutation is the same as that number. Now I'm trying to figure out the case where no number permutes into itself.
Comment: What is meant by $\sigma(n)=n$ for some $n$? Also in denominator are the $x_{\sigma(n)}$ just a permutation of the $x_k$? Maybe include some small made-up examples, since (to me) your set-up isn't clear.
Comment: Perhaps there is an easier approach but this is what has been suggested to me.
Comment: Could you be more specific on what you mean by $lim_{x_i \to 0}$. Do you take one fixed i?
Answer: Consider $k$ with $\sigma(k)\ne k$. Then along the path $$x_i=\begin{cases}t&i=k\\t^{n+1}&i\ne k\end{cases}\qquad\text{with } t>0,$$ the numerator is between $t^k$ and $t^k+nt^{n+1}$ for $0<t<1$; in fact this is between $t^k$ and $2t^k$ for small enough $t$. Similarly, the denominator is between $t^{\sigma(k)}$ and $2t^{\sigma(k)}$ for small enough $t$. Thus the quotient is between $\frac12t^{k-\sigma(k)}$ and $2t^{k-\sigma(k)}$. If $k>\sigma(k)$ this tends $\to0$ as $t\to 0^+$; if $k<\sigma(a)$ it tends to $+\infty$ instead. But if $\sigma$ is not the identity, we can find both kind of $k$, i.e., the limit does not exist.
Comment: I don't quite understand how you assigned the values $t$ and $t^{n+1}$ to the $x_i$ and what $t$ represents. Could you elaborate please?
Answer: Let $x_1=t,x_2=2t.$ Then we have as required that $x_1,x_2 \to 0$ as $t \to 0,$ and
$$\frac{x_1+x_2^2}{x_2+x_1^2}=\frac{4t+1}{2t+2}\to \frac{1}{2}$$ as $t \to 0.$ So in this case, with a no-fixed point permutation, the limit happens to exist.
The same limit arises for $x_1=t,x_2=2t,x_3=3t$ when the denominator uses order $x_2,x_3,x_1,$ again a no-fixed point permutation.


Folder Permisson for cache folders Centos7 and nginx 1.10

Question: I have a server on which I install Centos 7.2 and nginx 1.10.
I would like zo host Magento
What I have done:

root user is disabled
newuser is admin user for doing stuffs with sudo
I have a new nginx server block enabled
set domain new block root folder to /var/www/example.com/html
set folder permission to

sudo chown -R $USER:$USER /var/www/example.com/html (logged in as 'newuser')
sudo chmod -R 755 /var/www

now the Magento root settings
set permissions to->
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod +x mage

My problem is that the cache and session folder is empty
Fist question why?
NOTE: I don't know where but somewhere the caches are stored because to see changes on Magento Frontend I have to clear the Cache after doing that in the Admin panel I could see changes.
So the second question is it a permission problem?
Should I give the Magento root  and /var/www/example.com/html permission to an normal user?
Answer:
Why might the cache and sessions directories be empty? Because cache and sessions can live in memcache, redis or even mysql if you tell magento that's where to put them!  Check your magento local.xml, and you will see sections for both session and cache.  It may be that you are, for example, using redis for cache and database for sessions.
See (1), without more information, we don't know if it is a permissions problem.  But if it is, you can make the var folder and all sub folders 0777 (or 0775 if you have a group that the nginx / php-fpm user is also a part of) as long as you have already protected your var folder in nginx.


Exchange 2010 ignoring SPF record

Question: we are using Exchange 2010 and have already setup SPF record for our authorized mail server IPs. As a test using our domain name i tried to send an e-mail from another computer on the internet  which has an IP which is not listed in SPF record. Other e-mail services rejected the message due to SPF fail but our own exchange accepted it. This tells me that our Exchange is not rejecting e-mail which fail the SPF record. I enabled SenderID on our exchange to reject e-mail which fail senderID but made no difference.
Below is the SPF info i pulled out from the message header which failed SPF but got accepted by our Exchange.
Received-SPF: None (exchange2010.domainname: user@domainname
 does not designate permitted sender hosts)
Comment: A basic question, but antispam feature enabled on your hub transport server if you dont use a edge server
Answer: If your Exchange server is honoring SPF records for other domains but not yours, then you probably have your internal DNS set to be authoritative for your domain name, but you don't have the SPF record in your internal DNS servers.
Solution: Add your SPF record to your internal DNS servers.
Answer: The Exchange Sender ID agent will take action when the SPF status = FAIL. The SPF status for your test email = NONE. There is no SPF record so the Sender ID agent can't take any action based on the SPF record, because it doesn't exist.
Comment: Here is the result of SPF record check for our domain through mxtoolbox.com " v=spf1 ip4:xxx.xxx.xxx.78/29 -all" which indicates that our domain does have a SPF record somehow our Exchange is not detecting and acting on it. FYI this only happens with e-mails received using our own domain and the Exchange does act on other domains based on their SPF record.
Answer: 0) create an SPF record that contains your servers and the FQDN of the domain thet you want to protect. For example:
richter.hu v=spf1 ip4:184.108.40.206 ip4:18.104.22.168 -all

1) wait dns ttl time to spf record spread on the internet dns servers.
You can check it with mxtoolbox.com (change to spf record).
2) install transport agent
get-transport agent & $env:ExchangeInstallPath\Scripts\Install-AntiSpamAgents.ps1

and restart ms exchange transport service on edge servers.
3) run ipconfig /flushdns on your edge servers.
4)
set-senderidconfig -SpoofedDomainAction Reject
set-senderidconfig -TempErrorAction Reject

5) restart ms exchange transport service on your edge servers.
6) send a test mail from an outside smtp server using powershell
send-mailmessage cmd let.

Exchange 2010 ignoring SPF record


How to pivot single column of a output table in SQL?

Question: I am new to coding and don't understand the Pivot function just wanted to know if someone can help me with below query.
I have a SQL Query below
select distinct hapf.position_code, pg.name
from
hr_all_positions_f hapf, PER_VALID_GRADES_F pvgf, per_grades pg
where
hapf.position_id = pvgf.position_id
and pvgf.grade_id = pg.grade_id
and hapf.position_code = 'ABCD'

This give an output as below
POSITION_CODE    NAME
ABCD             Grade03
ABCD             Grade04
ABCD             Grade05

But I want output as below
POSITION_CODE    Grade1    Grade2    Grade3
ABCD             Grade03   Grade04   Grade05

Can someone help me with the changes I need to make in my SQL query and what happens if I have another column whose value I want to Pivot ?
Thanks,
Shivam
Comment: You say the output of your query gives `Grade03, Grade04 ,Grade05`, but you say tha you need to get `Grade01, Grade02, Grade03`; is it a typo?
Comment: Sorry my bad that is a Typo, I will edit it..
Answer: You may need:
-- test case
with yourQuery (POSITION_CODE, NAME) as (
    select 'ABCD', 'Grade01' from dual union all
    select 'ABCD', 'Grade02' from dual union all
    select 'ABCD', 'Grade03' from dual
)
-- query
select *
from yourQuery
pivot ( max (Name) for name in
        (
            'Grade01' as Grade1,
            'Grade02' as Grade2,
            'Grade03' as Grade3
         )
       )

which gives:
POSITION_CODE GRADE1  GRADE2  GRADE3
------------- ------- ------- -------
ABCD          Grade01 Grade02 Grade03

If you need to handle some more columns, you need to edit your code, because you need to know in advance the number and name of columns of your result set:
-- test case
with yourQuery (POSITION_CODE, NAME) as (
    select 'ABCD', 'Grade01' from dual union all
    select 'ABCD', 'Grade02' from dual union all
    select 'ABCD', 'Grade03' from dual union all
    select 'ABCD', 'Grade04' from dual
)
-- query
select *
from yourQuery
pivot ( max (Name) for name in
        (
            'Grade01' as Grade1,
            'Grade02' as Grade2,
            'Grade03' as Grade3,
            'Grade04' as Grade4
         )
       )

thus getting:
POSITION_CODE GRADE1  GRADE2  GRADE3  GRADE4
------------- ------- ------- ------- -------
ABCD          Grade01 Grade02 Grade03 Grade04

Comment: The 'ABCD' value may vary however you want in this example, but the values 'Grade03', 'GRade04', .. can not, because they are used in the PIVOT. You may want to search for some dynamic pivot, you'll find some good answers about this. [A starting point](https://stackoverflow.com/questions/15491661/dynamic-pivot-in-oracle-sql)
Comment: The values 'ABCD, Grade03, Grade04, Grade05' these are not constant and will change every time with different position_code which I have hard coded  as of now. Will this query work in Dynamic case also ?
Comment: Thanks, can this be achieved by TRANSPOSE function ?
Answer: SELECT POSITION_CODE, Grade03,Grade04,Grade05 FROM
(SELECT POSITION_CODE, NAME, Value_TO_PIVOT FROM mytable)Tab1
PIVOT
(
SUM(Value_TO_PIVOT) FOR NAME IN (Grade03,Grade04,Grade05)) AS Tab2
ORDER BY Tab2.POSITION_CODE

You can refer this link to write a dynamic query which will be required if you do not know values you want to pivot on or values are more
Answer: I solved my question from hit and trail, below is the code hope it helps others.
    select position_code,
max(case when position_num = 1 and pg_num = 1 then grade_name end) as Grade1,
max(case when position_num = 1 and pg_num = 2 then grade_name end) as Grade2,
max(case when position_num = 1 and pg_num = 3 then grade_name end) as Grade3
from
(
select
dense_rank() over (order by hapf.position_code) position_num,
dense_rank() over (partition by hapf.position_code order by pg.name) pg_num,
hapf.position_code,
pg.name as grade_name
from
hr_all_positions_f hapf, PER_VALID_GRADES_F pvgf, per_grades pg
where
hapf.position_id = pvgf.position_id
and pvgf.grade_id = pg.grade_id
and hapf.position_code = 'ABCD'
) group by position_code

Thanks,
Shivam


Troubles using NONE when filtering an NSArray with an NSSet

Question: I'm trying to filter an NSArray by excluding the elements that are in an NSSet. I'm doing something like this:
    NSMutableArray* a = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];
    NSSet* set = [NSSet setWithObjects:@"2", nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NONE SELF IN %@", set];
    NSArray* b = [a filteredArrayUsingPredicate:predicate];

However, this code throws an exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet

What is that I'm doing wrong?
Answer: You should use NOT instead of NONE in the predicate:
[NSPredicate predicateWithFormat:@"NOT SELF IN %@", set]

It is because the predicate is applied to each object (SELF) in the array, which is NSString. On the contrary, None should be applied on the NSArray of NSSet.
If you insist on using NONE. You may change a to
NSMutableArray* a = [NSMutableArray arrayWithObjects:@[@"1"], @[@"2"], @[@"3"], nil];

so that the SELF becomes NSArray.
Comment: Thank you! I didn't realized that :-). This answered my question. Thanks again


How to determine posterior distribution of the parameter in a binomial

Question: Assuming that I performed n iid tests, and the total number of test is n  which is a fixed value, and the observaton of 1 which corresponding to successful results is X observations yeild with probability p, I know X a random variable draw from binomial distribution B(n,p). Now, assuming the prior P(p) from an uniform distribution, I want to calculate a posterior probability P(p|n,X) with respect to different X values.
From some textbooks, I know the conjugate prior for the binomial distritbution is a beta distribution. But the deta distribution is for continueous random variables. So how can I calculate the posterior P(p|n,X)?
Shall I use beta-binomial distribution instead of beta distribution to calculate the posterior probabilty P(p|n,X)?
I tried to calculate the posterior P(p|n,X) directly, using Bayesian rule, but I'm not sure wehther or not I can calculate P(p|n,X) in this way. Suppose n is fixed, P(p) is uniform distribution. My method is that I simply calculate the posterior P(p|n,X) from P(X|n,p)~B(n,p) with different p values. For instance, I calculated a 100X100 2D table of P(X|n,p) with different X (X as the first dimension of the table, range form 1 to n, with interval 1) and p (p as the second dimension of the table range form 0.01 to 1.0, with interval 0.01), then the posterior probability P(p|n,X) for each discretized p with respect to praticular X value from the 2D table by using Bayesian rule. Is this a correct way to calculate the P(p|n,X)?
Comment: Your title seems to suggest a misconception. A posterior is for a *parameter*, not for a distribution. So you're talking about the posterior distribution of the parameter $p$ in a binomial. Note that $p$ is a *continuous* quantity -- it can take any value in (0,1); reasonable priors will generally be continuous distributions on that interval, and in that case posteriors will also be continuous distributions on the same interval. (Please try to fix the spelling and grammar errors in your post.)
Comment: Thanks, yes, they are in the same interval. Let me try to correct the errors.
Comment: thanks for the comment, I changed the title for the post
Answer: A uniform distribution is a special kind kind of beta distribution, which for the binomial distribution we know that it is a conjugate distribution. This means that if we combine the binomial likelihood with our beta prior, then our posterior will be a beta distribution.
Note that assuming a beta prior corresponds to considering the parameter $p$ as a continuous random variable on the (0,1) interval. This needs not be the case in general. For instance, we may assume that the prior is just a two-point distribution, for instance $P(\theta = 0.3) = 0.7$ and $P(\theta = 0.7) = 0.3$, and our posterior will also be a two-point distribution.
Returning to the uniform prior case, we know that our posterior will be of the form
$$p\left(\theta|\mathbf{x} \right) \propto f\left(\mathbf{x} |\theta \right) g\left(\theta\right) = \binom{n}{x} \theta^x \left(1-\theta\right)^{n-x} 1, \quad 0<\theta<1 $$
And you can determine the normalizing constant by figuring out what you need for this integrate to one (as a function of $\theta$). Once you plug in the values of $n$ and $x$ you can plot this as a function of $\theta$ and determine the value you like the most, e.g. mean, median, mode etc. Where did you get stuck?
Comment: Thanks John, your comments solved most my concern. Another question is about the normalize constant, i think the normalize constant calculate by integration to 1 can only be applied to calculate P(p|n,x) when P(p|n,x) is a continuous function, for the discretize senario, intergration to 1 might not be work, how do you think about the method that I mentionn above by using table to calculate the posterior P(p|n,x), i think using this table we even don't need to dervie the equation for posterior, we can directly calculate P(p|n,x) for each x and p with fixed n.
Comment: I tried to calculate some examples, for instance, when n=10, theta = 0.5, x = 5, the P(p|n,X) is a number much greater than 1 when using the normalize constant for continuous function.
Comment: @J.Doe The normalization factor depends on the prior distribution of course. If it is a two point distribution, as in my example, you don't integrate. You apply the theorem of Bayes and sum over all possible values.


Fixing convergence in SIR model using modified fit-model to fit COVID-19 data

Question: I'm trying to model the data for covid-19 using SIR model in R. I followed the answer of the question, and the blog. I'm using the suggested code, However, the data does not converging. Any suggestion what I'm missing.

<code># required libraries

library(deSolve)
library(shape)  # for plotting arrows
library(progress)  # for drawing the progress bar

####################################
##
## The basic model (which does not result in the exact solution)
## Adapted from the previous blogpost but with small adaptations
##
####################################

# the data infected represents cumalative sum (cumsum (infected)- (cumsum(recovered)+cumsum(death) )  )
IpRpD <- c(5,11,26,43,45,45,46,56,56,56,57,57,60,63,63,67,67,75,95,
           97,103,111,118,127,130,137,149,158,159,152,152,159,168,
           171,188,194,216,237,261,335,385,456,561,637,743,798,869,
           1020,1091,1148,1176,1196,1296,1395,1465,1603,1619,1657,1792,
           1887,1986,2217,2249,2254,2241,2327,2459,2745,2883,3169,3291,
           3732,4028,4142,4695,4952,5901,6314,7101,7683,8436,9124,9852,
           10645,11234,11962,12559)
# only recovered not cummalative sum
R <- c(310,320,204,342,246,250,203,189,188,162,194,178,107,156,85,162,187,85,171,73,101,63,150,
       213,164,206,150,43,115,55,31,45,62,25,22,33,19,30,26,8,9,10,12,0,6,2,4,6,11,1,1,7,1,5,3,
       7,8,6,4,9,0,3,5,4,3,3,0,3,2,2,0,0,3,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0)

# Only death NOT cuumalative
D <- c(9,5,3,3,6,5,11,8,6,7,10,7,9,2,3,2,2,0,2,5,3,4,2,1,1,2,1,4,1,1,2,2,2,1,1,2,0,0,1,1,0,0,0,0,
       0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)

Infected <-IpRpD
Day <- 1:(length(Infected))
N <- 4921638 #population

# ODE equation used for fitting
#
# I have removed the R(t) in comparison
# to the function used in the odler blogpost
# because we are not gonna use that value
# also we have anyway: R(t) = N(0) - N(t) - I(t)
SIR <- function(time, state, parameters) {
  par <- as.list(c(state, parameters))
  with(par, {
    dS <- -beta/N * I * S
    dI <- beta/N * I * S - gamma * I
    list(c(dS, dI))
  })
}

#
# cost function to be optimized in the fitting
#
RSS <- function(parameters) {
  names(parameters) <- c("beta", "gamma")
  out <- ode(y = init, times = Day, func = SIR, parms = parameters)
  fitInfected <- out[,3]
  # fitInfected <- N-out[,2] # this would be a better comparison since the data is not the number of Infectious people
  sum((Infected - fitInfected)^2)
}

# starting condition
init <- c(S = N-Infected[1], I = Infected[1])
# init <- c(S = N-Infected[1], I = Infected[1]-R[1]-D[1])  use this starting condition when applying the different line in the RSS function

# performing the fit
Opt <- optim(c(0.5, 0.5), RSS, method = "L-BFGS-B", lower = c(0, 0), upper = c(1, 1)) # optimize with some sensible conditions
Opt$message

Opt_par <- setNames(Opt$par, c("beta", "gamma"))
Opt_par
##     beta     gamma

# plotting the result
t <- 1:120 # time in days
fit <- data.frame(ode(y = init, times = t, func = SIR, parms = Opt_par))

plot(Day,Infected, xlim = range(Day), ylim = range(Infected) )
lines(t,fit[,3])

###########################
##
## Alternative model which provides a better fit
##
############################

# We transform the equations and instead of
# parameters beta and gamma
# we use parameters
#
#    K = beta-gamma
#    R0 = beta/gamma
#
#    or
#
#    beta =   K * R0/(R0-1)
#    gamma =  K *  1/(R0-1)
#
# then the equations become
#
# dS  = I * K * (-S/N *  R0)/(R0-1)
# dI  = I * K * ( S/N *  R0 - 1)/(R0-1)
# note in the beginning, S/N = 1
# then in the start you get this approximate exponential growth
# dI = I * K * (1)

SIR2 <- function(time, state, parameters) {
  par <- as.list(c(state, parameters))
  with(par, {
    dS <- I * K * (-S/N *  R0/(R0-1))
    dI <- I * K * ( S/N *  R0/(R0-1) - 1/(R0-1))
    list(c(dS, dI))
  })
}

RSS2 <- function(parameters) {
  names(parameters) <- c("K", "R0")
  out <- ode(y = init, times = Day, func = SIR2, parms = parameters)
  fitInfected <- out[,3]
  #fitInfected <- N-out[,2]
  sum((Infected - fitInfected)^2)
}

### Two functions RSS to do the optimization in a nested way
###
### This nesting requires a lot more computational power
### However, it makes that we have to worry less about the different scale
### of the parameters

Infected_MC <- Infected
SIRMC2 <- function(R0,K) {
  parameters <- c(K=K, R0=R0)
  out <- ode(y = init, times = Day, func = SIR2, parms = parameters)
  fitInfected <- out[,3]
  #fitInfected <- N-out[,2]
  RSS <- sum((Infected_MC - fitInfected)^2)
  return(RSS)
}
SIRMC <- function(K) {
  optimize(SIRMC2, lower=1,upper=10^5,K=K, tol = .Machine$double.eps)$objective
}

# wrapper to optimize and return estimated values
getOptim <- function() {
  opt1 <- optimize(SIRMC,lower=0,upper=1, tol = .Machine$double.eps)
  opt2 <- optimize(SIRMC2, lower=1,upper=10^5,K=opt1$minimum, tol = .Machine$double.eps)
  return(list(RSS=opt2$objective,K=opt1$minimum,R0=opt2$minimum))
}

# starting condition
#init <- c(S = N-Infected[1], I = Infected[1]-R[1]-D[1])
init <- c(S = N-Infected[1], I = Infected[1])

# performing the fit
# starting K=0.3, R0 = 2
Opt2 <- optim(c(0.3, 2), RSS2, method = "L-BFGS-B",
              hessian = TRUE, control = list(parscale = c(10^0,10^0), factr = 1))
Opt2

Opt3 <- getOptim()
Opt3

Opt_par2 <- setNames(Opt2$par, c("K", "R0"))
Opt_par3 <- setNames(Opt3[2:3], c("K", "R0"))

# plotting the result
t <- seq(1,120,1) # time in days
fit1 <- data.frame(ode(y = init, times = t, func = SIR , parms = Opt_par))
fit2 <- data.frame(ode(y = init, times = t, func = SIR2, parms = Opt_par2))
fit3 <- data.frame(ode(y = init, times = t, func = SIR2, parms = Opt_par3))

plot(Day,Infected, xlim = range(Day), ylim = range(Infected),
          log = "", xaxt = "n",
     main = "Infected(including Recovered and Death)", xlab = "Day", ylab = "number infected")
lines(t, fit3[,3], col = 1)
lines(t, fit2[,3], col = 4, lty = 2)
lines(t, fit1[,3], col = 2, lty = 3)
axis(1, at = 1:90, labels = rep("",90), tck = -0.01)
# these labels are not valid for the current date
axis(1, at = c(1,8,15,22), labels = c("Jan 16", "Jan 23", "Jan 30", "Feb 6"))

text(t[183]+2,fit1[183,3]+1800,"old optim fit",pos=4, col=2)
text(t[183]+2,fit1[183,3],expression(R[0] == 2.07),pos=4, col=2)
text(t[183]+2,fit1[183,3]-1400,expression(RSS == 74.3 %*% 10^6),pos=4, col=2)

text(t[220]+3,fit2[220,3]+3200,"new optim fit",pos=3, col=4)
text(t[220]+3,fit2[220,3]+1400,expression(R[0] == 1.0054626),pos=3, col=4)
text(t[220]+3,fit2[220,3],expression(RSS == 6.5 %*% 10^6),pos=3, col=4)

text(t[240]-3,fit3[240,3],"nested algorithm",pos=1, col=1)
text(t[240]-3,fit3[240,3]+700-2500,expression(R[0] == 1.005332),pos=1, col=1)
text(t[240]-3,fit3[240,3]-700-2500,expression(RSS == 5.9 %*% 10^6),pos=1, col=1)

x1 <- t[240]-3;    x2 <- t[225];
y1 <- fit3[240,3]; y2 <- fit3[225,3]
Arrows(x1,y1,x1+(x2-x1)*0.65,y1+(y2-y1)*0.65, col = 1)

x1 <- t[220]+2;    x2 <- t[227];
y1 <- fit2[220,3]; y2 <- fit2[227,3]
Arrows(x1,y1,x1+(x2-x1)*0.6,y1+(y2-y1)*0.6, col = 4)

x1 <- t[183]+2;    x2 <- t[183];
y1 <- fit1[183,3]; y2 <- fit1[183,3]
Arrows(x1,y1,x1+(x2-x1)*0.6,y1+(y2-y1)*0.6, col = 2)

####################
##
## Graph with various values of R0
##
#######################

# starting condition
#init <- c(S = N-Infected[1], I = Infected[1]-R[1]-D[1])
init <- c(S = N-Infected[1], I = Infected[1])

Infected_MC <- Infected
SIRMC3 <- function(R0,K) {
  parameters <- c(K=K, R0=R0)
  out <- ode(y = init, times = Day, func = SIR2, parms = parameters)
  fitInfected <- out[,3]
  #fitInfected <- N-out[,2]
  RSS <- sum((Infected_MC - fitInfected)^2)
  return(RSS)
}

plot(Day,Infected, xlim = range(Day), ylim = c(1,10^9),
     log = "y", xaxt = "n",
     main = "scenario's for different R0", xlab = "", ylab = "number infected")

axis(1, at = 1:30, labels = rep("",30), tck = -0.01)
axis(1, at = c(1,8,15,22), labels = c("Jan 16", "Jan 23", "Jan 30", "Feb 6"))

for (i in 1:10) {
  R0 <- c(1.005,1.01,1.05,1.1,1.2,1.5,2,2.5,4,20)[i]
  K <- optimize(SIRMC3, lower=0,upper=1,R0=R0, tol = .Machine$double.eps)$minimum
  parameters <- c(K,R0)
  xd <- seq(1,60,0.01)
  if (i == 1) {
    xd <- seq(1,40,0.01)
  }
  if (i == 2) {
    xd <- seq(1,50,0.01)
  }
  out <- ode(y = init, times = xd, func = SIR2, parms = parameters)
  lines(xd,out[,3])
  text(tail(xd,1),tail(out[,3],1),bquote(R[0] == .(R0)), pos =4)
}
</code>
Comment: You copied the entire code, that makes it a bit difficult to find the culprit.
Comment: I have used the same code with different data set. Does that mean the issue with data set or the parameters tweaking.
Comment: I will have to copy paste the code and see how it runs on my computer. It is difficult to read on the screen of my phone (and now I find out how ugly unclear my code is, although it was not meant to be used in a q&a site and a quick example of a problem, it contains several ways to make the fit, and that is redundant code for an example of the problem/question).
Comment: Personally, I think you have made an amazing answer which summarizes the whole SIR issues. Indeed the code can be enhanced and the graphs were until Feb which is not auto scaled. Take your time, and I would appreciate your answer.
Answer: The problem is that search for the optimal $K$ for a given $R_0$ is ending up in a local optimum.
<code>Ks <- seq(0,1,0.001)
plot(Ks,Vectorize(SIRMC2)(1.1,Ks), type = "l",
     xlab = "K", ylab = "RSS",
     main = "RSS as function of K for fixed R0 = 1.1")
</code>

You get the value $K=1$ on the right instead the value around 0.07. I am not sure whether there are simple functions in R that can solve this automatically and easily. My way to improve the code would be to do an initial grid search and improve with an optimizer. (or since you know that the curve is intitally exponential you could use that as starting value).
Comment: I was following the code and I couldn't figure out why it's not showing the bell shape for the  graph fit like the original code and for R0 graph it showing odd lines. I tried to change the value to 0.07 , didn't noticed much difference. I noticed that K=0.09 for both cases for the Opt2 <- optim(c(0.03, 2), RSS2, method = "L-BFGS-B",
              hessian = TRUE, control = list(parscale = c(10^0,10^0), factr = 1))
Opt3 <- getOptim()
It would be a great help for me and other if you add you fix on the code posted, to label it as an answer.


Cacti Graph - Raw value instead of average

Question: Problem 1:
I have the custom script that output's "processes:<value>" and I've graph template Item #1 Graph item type as "Line1" and CF Type "LAST" but that would throw "ERROR: the RRD does not contain an RRA matching the chosen CF".  So I chose CF Type "Average" but then when the script output is "processes:21" the graph shows average "6.5x".
I'm using cacti 0.8.7e-3 and on their forums they are forcing us to use "Average" instead of "LAST" to get rid of "RRD does not contain an RRA matching error"
Problem 2:
Not that just but the units are shown as m which means milli. I want  to show raw value 21 and if its above 1000 then show it as 1k.
How do I solve these 2 problems?
Answer: Solved both the problems.
I had to set "Data Source Type" to "GUAGE" under Data Templates. Now I see raw values and removed unit m (milli).


Problema com jQuery Validation Plugin

Question: Estou utilizando o recurso remote para verificar se existe um cadastro em meu banco de dados com o mesmo cpf.
Mais preciso que esse campo não seja obrigatório seja opcional.
Então tentei colocar required: false mais não dá certo existe essa possibilidade ou se tratando de uma consulta ele só será obrigatório.
cpf: {
cpf: true,
remote: {
    url: "/clientes/consulta_cliente",
    type: "post",
    data: {cpf: function(){ return $("input[name='cpf']").val();}}
}}

código pra fazer a validade cpf:true
jQuery.validator.addMethod("cpf", function(value, element) {
value = value.replace('.','');
value = value.replace('.','');
cpf = value.replace('-','');
while(cpf.length < 11) cpf = "0"+ cpf;
var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
var a = [];
var b = new Number;
var c = 11;
for (i=0; i<11; i++){
    a[i] = cpf.charAt(i);
    if (i < 9) b += (a[i] * --c);
}
if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
b = 0;
c = 11;
for (y=0; y<10; y++) b += (a[y] * c--);
if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
return true;
}, "Informe um CPF válido.");

Comment: jorge eu tirei isso e parece que der certo, não tinha prestado atenção nisso, peguei um exemplo na net mais parece que deu
Comment: Qual é a mensagem que te aparece ao colocares não colocares CPF no Formulário? Que queres dizer com `cpf: true`?
Comment: Qualquer coisa manda ai :)
Comment: precisa sim, o cpf é um função que adicionei no scrip para validar o cpf.
Comment: Vê a minha resposta.
Answer: Quando uma verificação depende de uma entrada pelo utilizadores deves utilizar o depends, que retorna true ou false para o cpf segundo uma condição, neste caso o campo estar vazio ou não:
cpf: {
    cpf: {
        depends: function () {
            return $("input[name='cpf']").val()!='';
        }
    },
    remote: {
        url: "/clientes/consulta_cliente",
       type: "post",
       data: {cpf: function(){ return $("input[name='cpf']").val();}}
   }
}

Assim garantes que só no caso do valor do CPF ser diferente de vazio é que faz a verificação.
Como tens no teu código ele vai sempre verificar o cpf independentemente de existir ou não.
Comment: Muito obrigado funcionou... Deus te abençoe...
Comment: onde devo colocar? poque estou colocando antes cpf:true
Comment: Em vez de `cpf:true`.
Comment: O `depends` vai se encarregar de dizer se é `cpf:true` ou `cpf:false` consoante tenhas ou não o cpf preenchido.
Comment: amigo intendi a sua lógica mais infelizmente não sei onde devo colcoar.
Comment: Vê a minha edição.
Answer: Cara eu utilizo essa função, ela possui 3 metodos, um para validar só CPF outro so para CNPJ e outro chamado documento que valida os dois de acordo com a quantidade de caracteres no campo. Ele valida sem precisar fazer dependências e se o campo tiver vazio ele não da pau no campo.
    jQuery.validator.addMethod("documento", function(value, element) {

    // remove pontuações
    value = value.replace('.', '');
    value = value.replace('.', '');
    value = value.replace('-', '');
    value = value.replace('/', '');

    if (value.length <= 11) {
        if (jQuery.validator.methods.cpf.call(this, value, element)) {
            return true;
        } else {
            this.settings.messages.documento = "Informe um CPF valido.";
        }

    }
    else if (value.length <= 14) {
        if (jQuery.validator.methods.cnpj.call(this, value, element)) {
            return true;
        } else {
            this.settings.messages.documento = "Informe um CNPJ valido.";
        }

    }

    return false;

}, "Informe um documento valido.");

// validação do CPF
jQuery.validator.addMethod("cpf", function(value, element) {
    value = jQuery.trim(value);

    value = value.replace('.', '');
    value = value.replace('.', '');
    cpf = value.replace('-', '');
    while (cpf.length < 11)
        cpf = "0" + cpf;
    var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
    var a = [];
    var b = 0;
    var c = 11;
    for (i = 0; i < 11; i++) {
        a[i] = cpf.charAt(i);
        if (i < 9)
            b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) {
        a[9] = 0;
    } else {
        a[9] = 11 - x;
    }
    b = 0;
    c = 11;
    for (y = 0; y < 10; y++)
        b += (a[y] * c--);
    if ((x = b % 11) < 2) {
        a[10] = 0;
    } else {
        a[10] = 11 - x;
    }

    var retorno = true;
    if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg))
        retorno = false;

    return this.optional(element) || retorno;

}, "Informe um CPF válido.");

// validação do CNPJ
jQuery.validator.addMethod("cnpj", function(cnpj, element) {
    cnpj = jQuery.trim(cnpj);// retira espaços em branco
    // DEIXA APENAS OS NÚMEROS
    cnpj = cnpj.replace('/', '');
    cnpj = cnpj.replace('.', '');
    cnpj = cnpj.replace('.', '');
    cnpj = cnpj.replace('-', '');

    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    digitos_iguais = 1;

    if (cnpj.length < 14 && cnpj.length < 15) {
        return false;
    }
    for (i = 0; i < cnpj.length - 1; i++) {
        if (cnpj.charAt(i) != cnpj.charAt(i + 1)) {
            digitos_iguais = 0;
            break;
        }
    }

    if (!digitos_iguais) {
        tamanho = cnpj.length - 2;
        numeros = cnpj.substring(0, tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;

        for (i = tamanho; i >= 1; i--) {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2) {
                pos = 9;
            }
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0)) {
            return false;
        }
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0, tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--) {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2) {
                pos = 9;
            }
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1)) {
            return false;
        }
        return true;
    } else {
        return false;
    }
}, "Informe um CNPJ valido."); // Mensagem padrão

Comment: valeu Euler mais eu já tinha testado com essa função eu acho que problema é devido a função remoto acho que as duas juntos sem esse macete que o jorge me passou não funciona, porque se tirar a função remote ele funciona certinho

Problema com jQuery Validation Plugin


Export one voice as mid or wav with beat intro in MuseScore

Question: How do I separate a project into a number of sound files, each with only one voice (SATB) and with a three beats intro in the beginning? It would also be nice to have some extra beats where that specific voice is silent. An underlying question is how do I specify which notes that belongs to a certain voice. Do I have to give them a color?
Answer: Suggestion (at least that's how I did it):

Go to Edit -> Instruments
Add a drum staff (under percussion - unpitched)
Insert one or two more bars before where you start your piece. Type in the beats as you desire in your intro on the drum staff. (I usually have closed hi-hats playing 4 crotchet beats)
If you want, go to Style -> General, and hide empty staves.
Go to File -> Parts -> New
Choose a name for the part you want to create, e.g. Soprano. Type that under Part Title.
Tick both the Soprano voice part and your percussion (drums) part in the boxes below, and click OK.

NOTE: I'm assuming your SATB score is in 4 different staves, if not you have to first explode them, under Edit -> Tools -> Explode

Now, you should have your Soprano only score generated (with the percussion). You can export it and save as mp3).
Do the same for your other parts. When you're done exporting all 4 mp3, you can go back to your main score and remove the drum staff + the extra measure in front.

Have fun! :)


How to get attribute by name on TreeView

Question: I have a html element that contains multiple childnodes. i would like to go through till the last childNode's first attribute value. I do not want to make it in a way that i define static string values(like keep giving child node names etc 4 times till the last one) to get the attribute i want. Is there a way to search on the tree in the child nodes by attribute name?
html element
   childNodes: NodeList[11]
      9: div#firstsection
       childNodes: NodeList[1]
         0: div#secondsection
          childnodes: NodeList[1]
           0: div#thirdsection
            childNodes: NodeList[5]
             0: div#finalsection

So basically, I wanna go to the last childNodes that has 5 node list in it and choose the [0] div#finalsection and get the attribute of it.
Comment: Why can't you just access the `div#finalsection` using it's ID, which should be unique? Do you have a practical reason for avoinding CSS selector style lookup?
Comment: yes but how will i achieve this the id is in pretty low level. @TomášZato
Answer: If the ID of the element you're looking for is unique, you can easily access it like this:
const myDiv = document.querySelector("div#finalsection");

You can also search by attribute name, for example if you have

Hello world

then you can do
const myDiv = document.querySelector("div[data-my-attribute]");


Trouble comparing NSString to NSArray object

Question: Ok, so I'm trying to check if an object from an NSArray equals something inputed by the User into a UITextField.  It should work, but for some reason it dosn't.  Here is my code:
    if (theAnswer.text == [correctAnswers objectAtIndex:problemNumber]) {
    NSLog(@"CORRECT");
}
else {
    NSLog(@"wrong");
}

The console always give wrong.
I put this log in:
NSLog(@"%@ %@", theAnswer.text, [correctAnswers objectAtIndex:problemNumber]);

And I get A A
wrong
printed everytime.  Thanks for the help
Answer: Objective-C doesn't support the == operator for NSStrings.  That will do a comparison of the pointers to the NSStrings and not the contents of the string itself.
Try
if([theAnswer.text isEqualToString:[correctAnswers objectAtIndex:problemNumber]]) {

}

Comment: Thank you very much.  I really appreciate both the quick response and the help it provided


Monomorphisms and epimorphisms in full subcategories satisfying a certain property

Question: Let $C$ be a category and $D$ be a full subcategory such that every object of $C$ has a monomorphism to some object of $D$ (or dually, an epimorphism from some object of $D$).

Is it then true that any epimorphism (resp. monomorphism) in $D$ must in fact be an epimorphism (resp. a monomorphism) in $C$?

If so, then this would imply that any epimorphism in a category $D$ with finite limits is also an epimorphism in the reg/lex completion of $D$ (though it will not be regular there unless it was a split epimorphism to begin with). In particular, if $D$ is any finitely complete category with a non-split epimorphism, then $D_{reg/lex}$ will not be balanced, as the mono part of the regular epi-mono image factorization in $D_{reg/lex}$ of any non-split epimorphism in $D$ will be a morphism that is both monic and epic but not an isomorphism.
Answer: Sure. Let $f:x\to y$ be an epimorphism in $D$ and let $g,h:y\to z$ be two morphisms in $C$ with $gf=hf$. We have to show $g=h$. Let $k:z\to w$ be a monomorphism in $C$ with $w\in D$. Then $kgf=khf$. Since $f$ is an epi in $D$ and $kg$ and $kh$ are morphisms of $D$ ($D$ being full), we have $kg=kh$. Since $k$ is a mono in $C$, we have $g=h$ as desired.


How to get a running apache's config file in SunOS (OR: how to get around ps's 126-character output limit)

Question: I am currently running a SunOS 5.9 machine as a web server. It runs several apache instances, each with its own config file. I specify the config file using the -f command-line option.
What I want to do is to check, at any time, what apaches are running and with what config files. The problem is that running ps only gets me 126 characters per line, which is not enough for me to know the file.
Is there any way around this? A way around the 126-character limit would be nice, but if there's another way to get the config file from a running httpd process, that works as well.
Thanks!
EDIT: Alright, so I'm dumb and hadn't been able to find any explanations on this until now. It turns out ps on solaris truncates the arguments to 80 chars. Any idea on how would I go about getting the full arguments? Or knowing what's running?
Comment: As per davey's and hayalci's suggestions, I was able to use /usr/ucb/ps wwwaux, but it still cuts my output.

The funny thing is that if I use "/usr/ucb/ps x" I get less characters on each line, but the lines are STILL cut! Like so:

[ webadmin@machine ~ ] /usr/ucb/ps wwwaux
webadmin 14553  0.0  0.2 8856 1896 ?        S   Dec 04  0:03 /projects/usr/httpd2/bin/httpd -d /projects/usr/www/myproj1 -f /projects/usr/ww

[ webadmin@machine ~ ] /usr/ucb/ps x
 14553 ?        S  0:03 /projects/usr/httpd2/bin/httpd -d /projects/usr/www/myp

So it doesn't seem like a char limit in the output of ps. Weird.
Comment: Damn, output got completely messed up. Sorry about that. :/
Answer: The command:
/usr/ucb/ps wwwaux

only prints the full command if it is run as root.  Add sudo to the front of that or switch to root and it should work as expected.
Comment: Why, I'd never had guessed that...
Thanks for the help!
Answer: To use "www" you will need to ensure you use the BSD "ps" command from /usr/ucb:
/usr/ucb/ps wwwaux

Answer: Try givin 'w' option to ps (optionally, multiple times)
ps www

How to get a running apache’s config file in SunOS (OR: how to get around ps’s 126-character output limit)


The proof of Generic Model Theorem (14.5) in Jech's Set Theory p.218

Question:
Corollary 14.12. For every partially ordered set $(P,<)$ there is a complete Boolean algebra $B=B(P)$ and a mapping $e:P\to B^+$ such that:
(i) if $q\leq p$ then $e(q)\leq e(p)$;
(ii) $p$ and $q$ are compatible if and only if $e(p)\cdot e(q)\neq 0$;
(iii) $\{e(p)\mid p\in P\}$ is dense in $B$.
$B$ is unique up to isomorphism.
Theorem (reduced). Let $M$ be a transitive model of ZFC and let $(P,<)$ be a notion of forcing in $M$. If $G\subseteq P$ is generic over $M$, then there exists a transitive model $M[G]$ such that $G\in M[G]$.
Proof.
  Let $B=B(P)$ and let $M^P=M^B$. Now we define $G$-interpretation of $P$: For every $x\in M^P$,
(i) $\emptyset^G=\emptyset$,
(ii) $x^G=\{y^G\mid (\exists p\in G)e(p)\leq x(y)\}$.
We let $M[G]=\{x^G\mid x\in M^P\}$.
Now let $H$ be the generic ultrafilter on $B$ generated by $e(G)$:
  $$H=\{u\in B\mid (\exists p\in G)e(p)\leq u\}.$$
  It is easily seen that $x^G=x^H$ for all $x\in M^B$. Thus $M[G]=M[H]$.
  To verify that $G\in M[G]$, observe that $G=\{p\in P\mid e(p)\in H\}$.$\Box$

I don't know how to verify that $\{p\in P\mid e(p)\in H\}\subseteq G$. Let $p\in P$ such taht $e(p)\geq e(q)$ for some $q\in G$. I need to check that $p\in G$.
It seems that we can have this statement about filter and Boolean algebra:

If $G\subseteq P$ is generic, then for all $q\in G$ and $p\in P$, $q\leq p$ iff $e(q)\leq e(p)$.

I suppose that $q\nleq p$, then since $p$ and $q$ are compatible, there is $r\in P$ such that $r\leq q$ and $r\leq p$, but it seems not helpful.
Answer: This is easier to see at first under the assumption that $P$ is separative, and then realize that the requirement about $e$ preserving the compatibility is really about "embedding the separative quotient" into the process.
Let's work with your assumptions, $e(p)\geq e(q)$ and $q\in G$. That means that every condition which is compatible with $q$ is necessarily compatible with $p$. But this means that under assumption of separativity, $p\geq q$, so $p\in G$.
Your gap is that you don't assume that $P$ is separative, which means that you cannot finish the proof. But you need to ask yourself, how would a generic filter look like on a non-separative partial order. Then, when you realize that it is—again—just implicitly including the separative quotient in the process, and we're done.
Comment: Sorry I don't got it; I arrived that $h(G)\subseteq Q$ is generic where $Q$ is the separative quotient of $P$ ($h : P \to Q)$ and $h(p)\in h(G)$. Now there is a  $r\in G$ such that $z$ is compatible with $r$ iff $z$ is compatible with $p$. Can you give more details?
Comment: In the non-separative case, prove that if $p$ is compatible with every extension of $q$, then $q\in G$ implies $p\in G$. This has nothing to do with the question anymore, it's an independent fact.


Contagem de array em VUE com condicional

Question: estou precisando descobrir quantos registros da array abaixo tem o campo active como true, como posso fazer?
[ { "name": "Quero Vender", "active": false },
{ "name": "Quero Comprar","active": false } ]

Comment: Você só quer a contagem ou quer saber quais tem `active === true` ?
Answer: TL;DR
Você pode usar o método Array.reduce() para retornar uma soma dos itens, somando 1 quando active é true e 0 caso contrário.
dados.reduce((acc, {active}) => acc + !!active, 0)

Explicação
O método Array.reduce(callback, initialValue) itera sobre um array e salva em uma "variável" o resultado de cada iteração. Esta variável é chamada acumulador e seu valor inicial é definido no segundo parâmetro do método. O acumulador é bastante confundido como "item anterior" onde usam o reduce desta maneira:
[1, 2, 3].reduce((anterior, atual) => anterior + atual)

No último passo do código acima, anterior será igual a 3 e atual também será 3, pois o primeiro é a soma de 1 + 2 que foi o valor acumulado e o segundo é o 3º item do array que contém o valor 3.
É um erro comum e por isso eu sempre aconselho a nomear como acc ou qualquer coisa que lembre que é um acumulador para evitar confusões.
E é bom lembrar que se o valor de acumulador não for definido será utilizado o primeiro valor do array e lançará um erro se o array for vazio (afinal, não existe primeiro elemento em um array vazio). Alguns exemplos de uso:
[1, 2, 3].reduce((acc, num) => acc + num)     // 6
[1, 2, 3].reduce((acc, num) => acc + num, 0)  // 6
[1, 2, 3].reduce((acc, num) => acc + num, 10) // 16
[1, 2, 3].reduce((acc, num) => acc + num, "") // "123"

Ao receber o item do array estou usando (acc, {active}) => ... que é uma funcionalidade do ECMAScript 2015 chamada Destructuring assignment que permite que eu pegue apenas as partes que preciso de um objeto ou array.
Neste caso, estou pegando apenas o valor da propriedade active do objeto, pois é a única informação que preciso dele. Ex.:
let obj = {nome: "Teste", active: true}
let {active} = obj
console.log(active)  // true

E por último me aproveito do fato de que converter valores booleanos para Number geram valores 1 e 0 para true e false, respectivamente.
console.log(Number(true))  // 1
console.log(Number(false)) // 0

Também utilizo o operador ! para converter o valor para um booleano.
console.log(!!1)  // true
console.log(!!0)  // false

Sabendo das informações anteriores fica mais fácil entender que o código cria um acumulador com valor 0 e soma 1 quando active === true, chegando ao resultado que é um contador de itens ativos.

Código funcionando:

let dados = [
  {name: "Quero Vender", active: false},
  {name: "Quero Comprar", active: false}
]

let count = dados.reduce((acc, {active}) => acc + !!active, 0)

console.log(count)  // 0

// Adiciona alguns items ativos
dados.push({name: "Teste", active: true})
dados.push({name: "Teste 2", active: true})

count = dados.reduce((acc, {active}) => acc + !!active, 0)

console.log(count)  // 2
Answer: Você pode fazer algo do tipo

let meuArray = [
  { "name": "Quero Vender", "active": false },
  { "name": "Quero Comprar","active": false },
  { "name": "Quero Tudo","active": true },
  { "name": "Quero Nada","active": true }
]

let contaActive = (array) => {
  let numeroDeActive = 0

  array.forEach(element => {
    if (element.active === true) numeroDeActive++
  })

  return numeroDeActive
}

console.log(contaActive(meuArray))

Como você está usando VueJS, ao invés de declarar uma função, você pode usar um method ou computed, ai vai depender da sua necessidade.


Output node.type in page.html.twig gives "EntityReferenceFieldItemList cannot be printed"

Question: Not sure if this is a bug, but I wanted to add some debug into an HTML comment in my page.html.twig file. I added  but I get:
Uncaught PHP Exception Exception: "Object of type Drupal\Core\Field\EntityReferenceFieldItemList cannot be printed." at /www/cn8/core/lib/Drupal/Core/Template/TwigExtension.php line 443

It took me a while to track down since I was sure this would work. Shouldn't EntityReferenceFieldItemList have a toString() function for this purpose?
Comment: I just worked out that I can write ``node.type.target_id`` and get the content type as a string, but still don't understand why ``node.type`` doesn't output something, but crashes...
Answer: node.type is a reference to the node type entity. You can get the id of the content type with target_id, as you have mentioned in the comment. For debugging this might be OK, but most times you want to get the label, which is nicely formatted and translatable:
{{ node.type.entity.label }}

Comment: Thanks again! How do you know this stuff? :)
Comment: @Nic You just read the source, it's all there :)
Comment: Which class though? Drupal\Core\Entity\Plugin\DataType\EntityReference ?


Ajax request inside ajax request fails - reloads the whole page again

Question: So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")

<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">

FILE open_first.php

<input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;">

Products code
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">

<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">

open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');

And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
    checkedItems.push($(this).val());
});

Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})

To
data: {"checked": checkedItems, "copyTo": productToCopy}

So now it's working just fine :) Cool!
Comment: does your button live inside a FORM element? If yes can you add it to the code sample
Comment: also, you're sure that open_second.php is returning data, not an HTTP redirect or something?
Comment: Hi
There are no form elements on the page and it's just printing out variables but I tried to just add the word "Hello" to the file but no effect whatsoever :)
Answer: WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
  /* method one*/
  event.preventDefault();
  /* handler code here*/

  /* method 2*/
  return false;

})

The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
Comment: It does not work, I've tried that earlier :) It still reloads the page :(
( I could have left that code on, though, but removed it from the original ones too since it did not do the trick this time..)
Comment: then you haven't shown all the code involved, and/or are throwing script errors in page. Look in browser console for errors
Answer: your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid.   Check you selector there.
Comment: Ok.. I tried removing the checkboxes and all references to them it the code. Now I get an Jquery error: "NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument". I'm using Mozilla. In IE it says "Stack overflow at line 2".. Interesting...
Comment: So basicly now I'm only posting.. trying to post the value in field: "productCodeCopy"


Entity reference field definition to auto create entities

Question: I have a field definition set up like below. I want Drupal to do all the heavy lifting for me, so my definitions are minimal and rely on Drupal defaults:
    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setSettings([
            'target_type' => 'target_entity',
            'handler' => 'default',
            'handler_settings' => [
                'auto_create' => true,
            ],
        ])
        ->setDisplayOptions('form', array(
            'weight' => $weight,
        ));
    ;

target_entity is just a simple bundleless entity.
This creates an entity reference auto-complete field in forms, but if I type something that doesn't match any existing entities, Drupal will say that no matching entities found and will refuse to create a new one.
How do I make the auto_create setting work?
Answer: The answer is 'you cannot auto-create bundle-less entities in Drupal 8.2.0. I don't know if this is a bug or a feature, but you have to have a bundle for target entity ('all_target_entities' in my example) and indicate that as target bundle in the settings:
$fields[$field] = BaseFieldDefinition::create('entity_reference')
    ->setSettings([
        'target_type' => 'target_entity',
        'handler' => 'default',
        'handler_settings' => [
            'auto_create' => true,
            'target_bundles' => [
                'all_target_entities' => 'all_target_entities',
            ],
        ],
    ])
    ->setDisplayOptions('form', array(
        'weight' => $weight,
    ));
;

I think it was not the case up to some point, so stating the exact version I am having this issue with.
Comment: You should open a core issue in the entity_reference component with this.
Comment: The issue already exists: https://www.drupal.org/node/2821352
Comment: Yeah, saw that, but it doesn't explicitly say it's a bug, just says it's unnnecessary. Probbaly because no one knows if this was the intention or not - there is no documentation for this feature.


Prove that $a\mathrel{R}b \iff$ **a** is a solution to the equation $X²-2bX+b²=0$ is transitive

Question: Let $\mathrel{R}$ by a relation defined on the set  $\mathbb{R}$
$a\mathrel{R}b \iff$ a is a solution to the equation $X²-2bX+b²=0$
How do I prove that it's a transitive relation?
Here's what I tried :
Let a, b, c in R such that $a\mathrel{R}b$ and $b\mathrel{R}c$
$a\mathrel{R}b \iff$ $a²-2ba+b²=0$
$b\mathrel{R}c \iff$ $b²-2cb+c²=0$
This is where I am stuck, I don't know how to advance any further to prove that $a\mathrel{R}c$
Comment: Have you thought of factoring $x^2-2bx+b^2$?  You should be able to find that your relation can be written in a *much* simpler way without having to mention polynomials or anything of the sort at all.... "*$a\mathcal{R}b\iff a$___$b$____*"  Fill in the blanks.  Use this way of writing the relation to completely trivialize this problem.
Answer: Hint: Factor $x^2-2bx+b^2$

 $(x-b)^2$

Recognize that if $a$ is a solution to $x^2-2bx+b^2=0$ then

 $a=b$

Your relation can then be rewritten as

 $a\mathcal{R} b\iff a=b$


writing a formal proof

Question: If B is a statement form involving only negation, conjunction and disjunction, and B' results from B by replacing each conjunction by a disjunction and each disjunction by a conjunction,  show that B is a tautology if and only if non-B' is a tautology.
It is clear that if non-B' is a tautology then B is also a tautology.That is because B' is obtained from B by switching the connectors so by applying the negation to B' we obtain B.
I just don't know how to write a formal proof.Any help would be appreciated.
Comment: I'm not sure that it's so clear. Consider an arbitrary formula $B$, e.g. $p\lor q$. Then $\neg B' = \neg(p\land q) \equiv \neg p \lor \neg q$. Some assignments of values to $p,q$ make both formulas true; other assignments make one formula true but the other false. You can't say "so by applying $\neg$ to $B'$ we obtain $B$" — we **don't** "obtain $B$". Your 'reasoning' doesn't use any property about tautologies, so why should it work for them and not for arbitrary formulas? More is needed. Toward that end, see the answer :)
Comment: I just started the course and I'm not familiar with all the properties.I also didn't know about De'Morgan's law until I read your proof, I see where I was wrong.Thanks!
Comment: Odd course, if it asks you to prove this nontrivial theorem but doesn't introduce De Morgan's law(s) (which also holds in Boolean algebras, by the way). It seems essential to the proof, and a very important part of why the theorem is true. In actual mathematical reasoning (heck, in general reasoning & argument), De Morgan is used all the time, without mention.
Comment: The course is fine, it introduced De Morgan's but I skipped some content to try and prove my mettle by tackling the problems.
Comment: Ah, ok, good. I like this problem/theorem.
Answer: We need a couple of propositions before proving the statement.
First, define another transform $A^{\neg}$ of propositional formulas $A$: $A^{\neg}$ is the results of negating all propositional variables in $A$.
This transform leaves all connectives unchanged — it distributes over $\neg, \land, \lor$. Note that the two transforms commute: $A'^{\neg} = {A^{\neg}}'$.
For example, if $B = (p\lor \neg p)$ then $B' = (p\land \neg p)$ and $B'^{\neg} = (\neg p\land \neg\neg p)$.
Proposition 1: $B$ is equivalent to $\neg B'^{\neg}$.
We'll use $\equiv$ to denote logical equivalence. Proof is by induction on the complexity of $B$.
Base case: $B$ is some propositional variable $p$. Then $B' = p$, and $B'^{\neg} = \neg p$, so $B = p \equiv \neg\neg p = \neg B'^{\neg}$.
[$B = \neg A$]:  $B'$ is $\neg A'$, and $B'^{\neg}$ is $\neg A'^{\neg}$. By induction hypothesis (IH), $A\equiv \neg A'^{\neg}$, so clearly $B = \neg A\equiv \neg\neg A'^{\neg} = \neg B'^{\neg}$.
[$B = (C\lor D)]$: $B' = (C'\land D')$, and $B'^{\neg} = (C'^{\neg}\land D'^{\neg})$.
By De Morgan, $\neg B'^{\neg} \equiv (\neg C'^{\neg} \lor \neg D'^{\neg})$. By IH, $C\equiv \neg C'^{\neg}$ and $D\equiv \neg D'^{\neg}$, so $\neg B'^{\neg} \equiv (C \lor D) = B$.
[$B = (C\land D)]$: Similar to the previous case, using the other De Morgan law.
Proposition 2: if $A$ is a tautology iff $A^{\neg}$ is a tautology.
Given any assignment of truth values to propositional variables $v\colon Variables\to \{0,1\}$, where $0$ and $1$ represent False and True respectively, let $v^{\neg}$ be the assignment that "flips" $v$: $$v^{\neg}(p) = 1 - v(p).
$$
Obviously this operation on assignments is self-inverse:
$$v^{{\neg}{\neg}} = v, \tag{SI}
$$
and a bijection of assignments.
For any formula $A$, let $A[v]$ be the truth value of $A$ under the assignment $v$. Clearly,
$$A^{\neg}[v] = A[v^{\neg}].\tag{*}
$$
By definition, $A$ is a tautology iff for all assignments $v$, $A[v] = 1$. By (SI), $A$ is a tautology iff for all assignments $v$, $A[v^{\neg}] = 1$. By (*), this holds iff for all assignments $v$, $A^{\neg}[v] = 1$, which is true iff $A^{\neg}$ is a tautology.
Now we can prove the statement:

$A$ is a tautology iff $\neg A'$ is a tautology.

By Prop. 1, $A\equiv \neg (A'^{\neg})$, which therefore is a tautology iff $A$ is. But $\neg (A'^{\neg}) = (\neg A')^{\neg}$, which by Prop. 2 is a tautology iff $\neg A'$ is. This yields the result.

writing a formal proof


Atualizar table após inserir dado no banco AngularJs

Question: Tenho um modal com um form, preencho esse form e clico no botão salvar e os dados são salvos no banco, porém tenho que dar um F5 pra atualizar a tabela. Como posso atualizar a tabela depois de inserir esses dados?
Atualmente é dessa forma que carrego os dados vindos da API:
$scope.colaboradores = colaboradores.data;

Controller completo:
angular.module("oraculo").controller("colaboradorController", function($scope, $routeParams, $location, colaboradores, colaboradorAPI){

    $scope.colaboradores = colaboradores.data;

    $scope.adicionarColaborador = function(colaborador){
        colaboradorAPI.saveColaborador(colaborador).success(function(data){
            console.log("Salvar!");
            $scope.colaboradores = colaboradores.data;
            delete $scope.colaborador;
            $scope.colaboradorForm.$setPristine();
        })
        .error(function(response, status){
            console.log("erro "+status);
        });
    }

});

Configuração da Rota:
angular.module("oraculo").config(function($routeProvider){

    $routeProvider.when("/home", {
        templateUrl: "public/views/colaborador.html",
        controller: "colaboradorController",
        resolve: {
            colaboradores: function(colaboradorAPI){
                return colaboradorAPI.getColaboradores();
            }
        }
    });

    $routeProvider.otherwise({redirectTo: "/home"});

});

Já tentei colocar um $scope.colaboradores = colaboradores.data; no método adicionarColaborador porém não funcionou.
Botão Salvar que fica dentro do modal:
<button class="btn btn-success btn-block" ng-click="adicionarColaborador(colaborador)" ng-disabled="colaboradorForm.$invalid" data-dismiss="modal">

    Salvar
</button>

Comment: Tente dar um $scope.$apply() após $scope.colaboradores = colaboradores.data;
Comment: Quanto tento dar um `$scope.$apply();` da esse erro: `Error: [$rootScope:inprog] $digest already in progress`
Comment: Remova o  delete $scope.colaborador;
Comment: Continua o mesmo erro.
Answer: No teu código ao invés de:

$scope.colaboradores = colaboradores.data

altere para:

$scope.colaboradores.push(colaborador)

Observe que você está setando o valor incial para $scope.colaboradores após salvar um novo colaborador. O correto seria incluir o novo colaborador na lista já existente.
Comment: Dessa forma funciona, porém a tabela não é preenchida corretamente, ou seja, a linha que mostra na table não é a linha retornada do banco.
Comment: Então mude para $scope.colaboradores.push(data), verifique se a data é o colaborador que foi inserido. Precisa ver o que teu server retorna
Comment: agora após clicar no botão salvar não aparece nada na table
Comment: O que vem na variável data?
Comment: essa data vem do `resolve`
Comment: Se não der certo usando `resolve` eu faço da maneira simples, que é passar o resultado da função que faz o GET pra uma variável e chama-la assim que a função que salva os dados for chamada
Comment: @EmirMarques A sua resposta daria certo caso o retorno fosse um array e ele estivesse iterando o array e dando push posição por posição, caso fosse um array isso não iria aparecer da forma esperada.

Techies qual o html que está sendo responsável por estar renderizando os dados e qual o retorno do servidor ?
Comment: Chamando a colaboradorAPI.getColaboradores() não resolve?
Comment: Corrigindo meu comentário:

@EmirMarques A sua resposta daria certo caso o retorno fosse um registro.

 Techies qual o html que está sendo responsável por estar renderizando os dados e qual o retorno do servidor ?
Comment: @FelippeTadeu não entendi, o item que pedi para ele dar push foi justamente no colaborador que acabou de receber. O que acontece é que a forma como foi desenvolvido necessita uma outra consulta que retorne todos os itens da lista, nesse caso o colaboradorAPI.getColaboradores()
Comment: @FelippeTadeu é a página colaborador.html. O servidor retorna um OK e o dado é inserido no banco, porém tenho que dar um F5 pra atualizar a table
Comment: @Techies vc pode dar um console.log(data) dentro do método que salva o dados e postar aqui?
Comment: Não exibe nada, fica vazio. essa data é diferente dessa `$scope.colaboradores = colaboradores.data;`
Comment: @Techies então vc pode rodar o método colaboradorAPI.getColaboradores() dentro do sucess para obter a lista nova. Vc também precisa analisar se a tua API retorna o dado persistido no banco
Comment: Sim, dessa forma eu consigo carregar as tabelas. Eu apenas estava buscando uma solução alternativa
Comment: Então, entendo, existem formas alternativas mais tudo depende do retorno da tua API, vc consegue confirmar se ela retornar o objeto serealizado?
Comment: Sim, está retornando, a dificuldade é apenas carregar os dados quando utilizo o `resolve` na configuração da Rota, mas enfim. Vou utilizar da forma simples mesmo.


Find vector equations of a pair of parallel planes, one containing each of the two skew lines.

Question: Let $\vec p=\pmatrix{1\\1\\0}$, $\vec q=\pmatrix{0\\1\\-1}$, $\vec u=\pmatrix{2\\-3\\1}$, and $\vec v=\pmatrix{0\\6\\-1}$.
Find vector equations of a pair of parallel planes, each containing one of the lines $$\vec x=\vec p + s\vec u$$ and $$\vec x=\vec q + t \vec v$$
I have verified that the pair of lines is skew which was the first task. How do I proceed next? For two planes to be parallel their normal vector should be equal (or colinear). Do I make use of that?
Comment: What is a *skew* line? I know of skew curves, but for lines I don't see…
Comment: Well I was going by the definition in my textbook which corresponds with this definition: https://en.wikipedia.org/wiki/Skew_lines .
Comment: Ah! I see. A skew line does not exist – only pair of skew lines (it would be better called a skew pair of lines!). I'm used to  speak of  'non-coplanar' lines.
Comment: I agree that it is a bit unclear. I edited the question to reflect your suggestion :). Thanks
Answer: Hint:
The planes that you find have to be parallel to the two vectors $\vec u$ and $\vec v$, so his orthogonal vector is $\vec w=\vec u \times \vec v$.
Answer: One plane is given by $\vec x=\vec p+s\vec u+ t\vec v$.  I'm sure you'll find an equation for the second plane.


Boot priority for smbd/nmbd

Question: What would be the ideal boot priority for smbd and nmbd? I have a server that runs samba shares and when it restarts it doesn't seem to resolve netbios requests from other clients even with the smbd and nmbd daemons running. I always have to do a "service smbd restart" for the clients to start accessing shares.
I also get a "standard input is not a socket, assuming -D" from the logs. nmbd doesn't give any log info.
From the logs, my eth0 gets an IP much later even if networking or network-manager has a higher boot priority. So, my other question would be, for all the networking services to run, what would be the preferred boot order of all the services that should run before there is any external communication.
Thanks!
Comment: And your distribution is?
Comment: it's ubuntu 10.10
Answer: Figured it out
It was smbd.conf and inetd.conf issue.
By default, there was no nmbd entry in the inetd which caused the netbios issue at startup.

Boot priority for smbd/nmbd


PhotoSwipe display only one image from Views grid form

Question: I created a grid view to display several node images thumbnails (3 columns, and multiple lines), and following PhotoSwipe usage found whithin the README.txt, I specified the CSS class "photoswipe-gallery" to display the field image.
Now when I click on one image from the view, I got the full sized Image as I wanted, but I can't move to the next or previous image that exist within my view grid.
Is there anybody knowing how to do it?
Thanks in advance
Answer: After some investigations, I hook (?) the views-view-grid-default.tpl.php and wrap the grid  within a:

 ...

block and now the script take correctly all images found in the grid table.
Of course I removed this class from the image field parameter.
Thanks


ANOVA with Repeated Measurements based on randomly assigned repetitions

Question: first of all the basic idea of my experiment: changes/differences of reaction time (RT) after 3 different types of sport (a: no jogging=SP1; b: 10min of jogging=SP2 and c: 30min of jogging=SP3);
36 subjects (SUB) are randomly assigned to one of the 6 possible combinations of "sport" (abc, acb, bac, bca, cab and cba, see variable FCT). So the first subject has "a" on day 1, "b" on day 2 and "c" on day 3; the second one might have "a" on day 1, "c" on day 2 and "b" on day 3 [etc...]
Therefore I have the following table containing my raw data:
<code>SUB    SP1    SP2    SP3    RT1    RT2    RT3    FCT
s01     a      b      c     0.1    0.4    0.8    abc
s02     a      c      b     0.6    0.3    0.8    acb
s03     b      a      c     1.0    1.0    0.7    bac
s04     b      c      a     0.3    0.7    0.1    bca
s05     c      a      b     0.3    0.5    0.4    cab
s06     c      b      a     0.0    1.0    0.3    cba
[.]    [.]    [.]    [.]    [.]    [.]    [.]    [.]
s36     c      b      a     0.1    0.9    0.0    cba
</code>
In general I think I have to use an ANOVA based on a repeated measurement design - but I have no clue on how to deal with the factor "sport" since it also changes with the repeated measures per subject;
Is it OK to use the variable FCT defined by 6 possible combinations of "sport" as one factor with 6 categories with the repeated measurements-ANOVA?
Thank you for comments!
Answer: It  depends on the software you are using for this analysis, but you might need to lay your data out differently.
You have the same information laid out twice in the Sport columns (SP1, SP2, SP3) and in the FTC column.  You don't need both, but depending on the software you are using, you will need this information either laid out as you have done for FTC, or as you have done for SP1, SP2, SP3.
So the simple answer to this questions is that you need to remove either the SP columns or the FCT column, depending on the format of this information that your software requires. However, Rather than removing these columns you should simply ignore them for the purpose of your analysis - or filter them out, as these columns might be useful for further analysis you do.
Can you tell us what software you are using, so we can advise which format you need to use?
It would also help if you make clear your aim.  Are you simply tying to see whether RT varies with type of sport.   This would require a simple repeated measures one-way ANOVA.
Do you also want to know if a particular combination of sports results in consistently better RTs?
Further i'm not clear on where your 'results' are......are these shown in the RT columns.  E.g. S01 obtained an RT of 0,1 for sport A (as shown in the RT1 column).  Should the comma be a decimal point?
Comment: Thank you. I am aware that columns SP1, SP2 and SP3 is sort of "redundant" information - I just wanted to be sure that the basic setting of the study is more clear;
Regarding the results I am interested in:
I want to know if the reaction (=RT) changes over time and I also want to know if the type of sport has an impact on the reaction measuerement. Therefore my idea was to simply define the additional variable FCT wich would be used as an additional factor in the ANOVA... Regardig the software I want to use: SPSS and R - both of them are available here in our departmenet.
Comment: Ok, Firstly:  If you use SPSS you would need the SP1, SP2, SP3 columns but not the FCT column, in order to run a repeated measures One-way anova.  You would then look for a main effect of 'sport' - this will tell you, for example, whether RT  get better with SP3 (30mins jogging) compared with SP2 (10mins of jogging) and SP(0mins of jogging).
Comment: Secondly:  Your 2nd question of interest appears to be "Does the RT  (averaged across all sports)  increase with any particular combination of sports".  Most simply you could do another one-way anova looking at the effect of FCT on RT Score.  The DV would be RT (containing an RT score for each participant averaged across sports) and FCT  as the IV.  This would then tell you if a particular combination of sports resulted in better reaction times across all sports.
Comment: Thirdly: Whether FCT can be added as a factor in your first ANOVA (the oneway anova examining the effect of SP on RT) is a more complex issue.  You could in theory add it as a factor to this anova. However i'm not sure this is justified.   Can you tell me what your is justification for thinking that the order of sports might have an effect on RT is?  This might make it more clear if it is worth examining this at all, and whether it is worth adding it to the first ANOVA model


Upgrading from gwt2.4.0 to gwt2.5.0 giving exceptions

Question: I have a application for that i have updated from gwt2.4.0 to gwt2.5.0.
When i am running the application then seeing the following exception.

<code>18:34:25.338 [ERROR] [OneViewUI] Errors in 'jar:file:/C:/Users/srapolu/.m2/repository/com/google/gwt/gwt-user/2.5.0/gwt-user-2.5.0.jar!/com/google/gwt/core/client/GWT.java'
 18:34:25.391 [ERROR] [OneViewUI] Line 276: The method setBridge(GWTBridge) in the type GWT is not applicable for the
</code>
arguments (GWTBridge)

can you please help.
Comment: Can you share more stack trace...
Answer: I experienced the same issue. it turns out i had some references to the 2.4 version of gwt-dev.jar. make sure you don't have any and try again.


Protect against index out of bounds

Question: I am having trouble only executing objectAtIndex if I have values present.
My code:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *results = [json objectForKey:@"d"];

NSString *error = [results objectForKey:@"error"];
NSLog(@"results::%@", [results objectForKey:@"agency"]);
if ( results !=nil)
{
    item = [[results objectForKey:@"agency"] objectAtIndex:0];
    codeItem = [[results objectForKey:@"agency"] objectAtIndex:1];
}

It works fine if I have data in the json but if the json comes back like this:
{"d":{"success":true,"agency":[]}}

It crashes, I know my if statement is wrong but I dont know the correct method to make this work.
Answer: Just check the value before getting the object:
NSArray *agencyItem = [results objectForKey:@"agency"];

if ([agencyItem count] > 1)
{
    codeItem = [agencyItem objectAtIndex:1];
}

Comment: Just to keep in mind that `[somearray firstObject]` and `[somearray lastObject]` are always safe to use; if `somearray` is empty, then these two methods return `nil`.
Comment: `agencyItem != nil` is redundant.
Comment: I added the != nil just because I was not sure about the output, its removed.

Protect against index out of bounds


Mark/Flag last non-zero (or specific) value in a vector

Question: Seemingly simple question yet I can't figure it out nor find the answer.
I have the following data:
tibble(A = c(0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0),
       B = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2))

I now wish to mark/flag (Not extract) the last non-zero value(or the last time A == 1) in a separate column, per group B.
Ideally I would like to do so using dplyr:
DF %>% group_by(B) %>%
mutate(C = ???)

I've found lots of answers on how to extract this value, but none on how to flag it. The closest I found was last(A[A==1]), but this sets all C values equally. Instead I only want the last non-zero value per group marked.
My expected output would be something like:
tibble(A = c(0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0),
       B = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2),
       C = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0))

Comment: whats your expected output?
Comment: @R.Iersel, I've edited my answer, please check, also in your expected output, why is it 1 at rownumber 5 for first group?
Comment: Silly of me, I've edited the question with the expected output.
Comment: @KarthikS Yes the edited version is perfect, thank you! It is 1 at number 5 as I wanted to demonstrate it should mark the last non-zero value per group even if the last value isn't 1, which might not have been clear with my original tibble. I will edit it to make it clearer for those in the future.
Answer: Does this work:
library(dplyr)
df %>% group_by(B) %>% mutate(C = case_when(row_number() == max(which(A == 1)) ~ 1L, TRUE ~ 0L))
# A tibble: 14 x 3
# Groups:   B [2]
       A     B     C
   <dbl> <dbl> <int>
 1     0     1     0
 2     0     1     0
 3     0     1     0
 4     0     1     0
 5     1     1     0
 6     0     1     0
 7     1     1     1
 8     0     2     0
 9     1     2     0
10     1     2     0
11     0     2     0
12     0     2     0
13     1     2     1
14     0     2     0

Comment: Sadly no, this is similar to the "last(A[A==1])" I found, though that code marks the number itself not the index. I would like all values in the C column to be 0, except for the last non-zero value per group.
Comment: What about `mutate(C = 0, C[max(which(A == 1))] = 1)`?
Comment: The edited version works exactly as intended, thank you! @GregorThomas, this code gives me an error, I thought you maybe meant "== 1" but this simply returns FALSE to me in the extra column. But Karthik's solution works perfectly. Thank you!


In how many ways can the letters of the English alphabet be arranged so that there are exactly 10 letters between a and z?

Question: The Question was: In how many ways can the letters of the English alphabet be arranged so that there are exactly 10 letters between a and z?
My approach was the following:
In between a and z, there are P(26,10) ways to arrange the 10 letters and then since 16 letters remain, we would also take into account the 16! arrangements of those letters. So, by the multiplication rule, the number of ways is 16!*P(26,10).
Answer: There are $24!$ permutations of the letters b through y. For each such permutation, if a is to the left of z, it can appear in any of 15 positions (from before the first letter to before the fifteenth letter), and z appears 10 positions later. Similarly, if z is first, it can appear in any of 15 positions and a appears 10 positions later. So $30\cdot 24!$.
Answer: Several problems:

Using $P(26,10)$ includes arrangements where a and z are not 10 apart.  There are 24 letters excluding a and z.
Once the letters between a and z are chosen, there are $26-(10+2)=14 \neq 16$ remaining letters.
The number of letters to the left of a.  It is possible to have anywhere between $0$ and $26-(10+2)$ letters to the left of a.
a could come before or after z.

Fixing these gives the correct answer.

Another approach:

start with $26$ empty cells and put either "a followed by 10 gaps followed by z" or "z followed by 10 gaps followed by a" into it somewhere.  How many ways can this be done?
fill in the remaining cells.  How many ways can this be done?
Answer: Here's my logic:
There would be 24 letters left after taking A and Z, so the 10 letters can be chosen in C(24,10) ways and then arranged in 10! ways.
Now, having this group of 12 letters leaves us with 14 letters and we can arranged these 15 elements in 15! ways.
Hence the ways that it can be arranged in is:
C(24,10) * 10! * 15!
Edit: I missed out that A and Z can be swapped (thanks Jaap) so that would double the number of ways to C(24,10) * 10! * 15! * 2 which is equal to 1.86134521E25
Comment: You forgot that a and z can be swapped.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Java doesn't change look and feel when invoked from another class

Question: I am new to java, I facing a problem while trying to change the look and feel of a java file when invoked from another class. I have two classes, main.java and auth.java. I have set the look and feel as nimbus in the auth.java file. When I try to invoke auth class from main.java(i have attached the code snippet below) the UI doesn't change. But when i use
public static void main(String[] args) in auth.java and try to run that file individually the UI of the jFrame changes. Kindly let me know if there is a way to change the UI of a jFrame when called from another class. And is there any problem invoking the jFrame from another class, is that a good practice? because we are onto doing a big project and will require calling authentication frame once in a while, so any suggestion guys?
Thank you all in advance! :)
main.java:
package com.package.name;
public class main {
    public static void main(String[] args) {
        new auth();
    }
}

This is a section of my auth.java code:
package com.package.name;
import javax.swing.*;
import java.awt.*;

public class auth extends JFrame {
    public auth() {
        initComponents();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel ( "javax.swing.plaf.nimbus.NimbusLookAndFeel" );
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (UnsupportedLookAndFeelException e) {
                    e.printStackTrace();
                }
                setVisible(true);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                pack();
            }
        });
    }

Comment: Any error message ..?
Comment: no.. nothing, just the same old java laf when we try to call the auth class from main
Answer: You've already called initComponents before changing the look at feel.  This will install what ever is the currently installed look and feel into those components.
Without having to go and instruct each component to update its UI, you could simply swap the installation of the look and feel with the initComponents method, for example...
try {
    UIManager.setLookAndFeel ( "javax.swing.plaf.nimbus.NimbusLookAndFeel" );
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
    e.printStackTrace();
}
initComponents();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();

Now, having said that.  You really should have been within the context of the EDT before you called the auth constructor and auth shouldn't really be making decisions about the Look and Feel.  What happens if you want to use this frame again with a different look and feel?
Instead could do something more like
public class main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel ( "javax.swing.plaf.nimbus.NimbusLookAndFeel" );
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (UnsupportedLookAndFeelException e) {
                    e.printStackTrace();
                }
                new auth();
            }
        });
    }
}

public class auth extends JFrame {
    public auth() {
        initComponents();
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
    }

You should also consider taking a look through Code Conventions for the Java Programming Language, it will make your code much easier to read ;)
Comment: Once you've installed the look and feel, all new components created will use, which is why you had the problem in the first place. So yes, just keep creating objects and they will use the same look and feel.
Comment: yeah i tried this method at first and that worked really nice. but i thought that we need to declare laf in the respective class itself.! :) thanks man. well another question, what if I have another class and wish to change it's LAF too? Just adding new class2(); to the main class will do?


Can't sing high notes anymore after a bad cold

Question: I'm a twelve year old female that sings with a choir (I'm a mezzo soprano that sings alto when there is no sop 2 part).
Around Christmas last year, I got a really bad cold. Like, so bad I could only sing three notes (they were in my mid range). I slowly re-built my range, but I can't reliably sing higher than an E5. If I try to sing higher, it won't even come out. If it does, it's a breathy squeak. I can sing pretty low, down to an E3 with proper warm up.
Any tips or tricks or general advice would be helpful.
Comment: when i hit puberty I remember thinking it was a cold at first, deep ugly voice felt like the result of a sore throat for like a week, and then "resolved" itself back to "normal", but obviously wasn't because... well... puberty was beginning ;)
Answer: It's been about 8 months since your range was limited by illness. You mention slowly re-building your range: How long did this process last?
This article by an otolaryngologist explains:

Fortunately, the common cold and the flu are self-limiting infections, which resolve in 7 to 10 days. For the singer and vocal performer, full recovery may take 2 to 3 weeks, which seems like an eternity when singing is your raison d'etre.

As such, expert advice would suggest that your range should've returned months ago if it were limited by a cold, so we need to expand our differential diagnosis:
You also mention "I can sing pretty low, down to an E3 with proper warm up" (were you able to sing this low before last Christmas, when your upper register was intact?) and that you are a twelve-year-old female. This combination leads me to believe that you're going through puberty-driven physical and hormonal changes. As you grow, your lungs will enlarge and your larynx will lengthen, and increasing androgen levels in adult men and women correspond to a decrease in vocal fundamental frequency. Fortunately, you have relevant academic research at your disposal:
"The Adolescent Female
Changing Voice: A
Phenomenological
Investigation" (Journal of Research in Music Education, Sweet, 2015) is a phenomenological study, meaning that it focuses on the experience of being an adolescent female with a changing voice. It may be useful for you to read about the experiences of other young females who went through this process in a choral setting.

The essence of the experience of female voice change was
  that vulnerability and fear of embarrassment determined all use of the females' singing
  voices, resulting in risk assessment for each singing situation and setting.

Knowing this, you'll be better-prepared emotionally for the hardships and frustrations that come with being a musician whose instrument is not entirely in your control.
"Physiological Changes in the Adolescent Female Voice:
Applications for Choral Instruction" (honors thesis, Haston, 2007) delves into anatomical changes and even includes vocal exercises to maintain and expand your range.

The time in which physiological
  changes occur during vocal development is
   one of the most fragile points in a young woman's life.  If her vocal instrument is misguided and/or mislabeled due to ignorance on the part of the teacher, a talent could be lost, wasted,
  damaged, or at the very least its potential will only be partially realized.  Each
  educator must take the time to educate him/herself in the current research
  available on the changing female adolescent voice.  A music teacher must not
  only teach notes and rhythms, but also instruct his/her students in vocal
  technique and health in order to ensure
   these students have their own unique,
  enduring instruments.

This echoes the best advice I can give you: Find a great teacher. They will guide you through illness, puberty, difficult repertoire, and whatever other musical or personal challenges you bring them. For the time being, you can work on your range with normal exercises, but don't push yourself to the point of discomfort. Right now, your anatomy might be limiting you to an E5 and forcing your voice higher could do damage. Until you find someone who can offer you professional guidance, treat singing like weightlifting: Don't go for the extremes of your range until you're warmed-up and have expert supervision.
Comment: Very good advice, but one additional comment: unlike other aspects of puberty, voices take a LONG time to settle down into adulthood. If you are currently 12, don't expect your voice to be "completely stable and under control" till you are twice your current age! That doesn't mean you can't keep singing and enjoying music making while you are a teenager, but don't get frustrated - there's no reason why you can't still be singing when you are in your 60s, so there's no need to rush things faster than they want to go right now!
Comment: As alephzero said:
> If you are currently 12, don't expect your voice to be "completely stable and under control" till you are twice your current age! It's correct, a second voice change occurs for girls around 22-23 years old :)
Comment: Also, if you are currently 12, you are not allowed to use Stack Exchange


Make all the fields in a form not required

Question: I know that, when I want to run off the #require property of a field in hook_form_alter(), I just need to set #require property of a specific field to FALSE.
How can I remove the #required property  of all the required fields? I want to make the fields not required when the user has a specific role.
Do you have any idea?
Answer: If you're ok with the risks that this might well pose to the integrity of your content you could probably use a simple recursive script like the following in a form alter function:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'myform_name') {
    $form['#after_build'][] = '_MYMODULE_remove_required';
  }
}

function _MYMODULE_remove_required(&$element) {
  $element['#required'] = FALSE;

  foreach (element_children($element) as $key) {
    _MYMODULE_remove_required($element[$key]);
  }
}

Comment: good solution Clive, what is your idea about below answer?
Comment: Putting it in `#after_build` is probably a good idea, but your recursive function isn't recursing at the moment!
Comment: Notice that the `#after_build` function is required to return the element it gets as argument, which is not passed as reference. See [system_check_directory()](http://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_check_directory/7), used in [system.admin.inc](http://api.drupal.org/api/drupal/modules%21system%21system.admin.inc/7).
Comment: +1 just for showing use of element_children(), really useful, and helped me disable all form elements easily
Comment: In Drupal 8, you'll use ``Element::children`` instead of `element_children`.
Answer:    function hook_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'myform_name') {
       if (in_array('administrator', $user->roles) {
         $form['#after_build'][] ='mymodule_recursive_unrequired';
       }
     }
   }

   function mymodule_reqursive_unrequired($element) {
     foreach (element_children($element) as $name) {
       $element[$name]['#required'] = FALSE;
     }

     return $element;
   }

I didn't test it yet; it is just an idea.
Comment: The `#after_build` functions are required to return the element it gets as argument, which is not passed as reference. See [system_check_directory()](http://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_check_directory/7), which is the `#after_build` function used in [system.admin.inc](http://api.drupal.org/api/drupal/modules%21system%21system.admin.inc/7).
Comment: @kiamlaluno , I got this idea from a module disable all form element and worked for me.hoever thanks for antention.
Comment: You just need to remove the _&_ in `function mymodule_reqursive_unrequired(&$element)`, and then is all fine. I would rather accept your answer, as at least it correctly returns `$element`.
Answer: I used this answer and thought I'd share some improvements:
As above, add the following function as an #after_build callback for the appropriate users.
/**
 * Removes "required" from all form elements.
 * Use at your own risk.
 * Use:  in a _form_alter function, $form['#after_build'][] = 'MYMODULE_remove_required';
 * @param array $element
 * @param array $form_state
 * @param int $depth
 * @return mixed
 */
function MYMODULE_remove_required($element, &$form_state, $depth=0) {
  if ( $depth > 6 ) return $element; // put a limit on recursion
  if ( !empty($element['#required']) ) $element['#required'] = FALSE;
  // only iterate over children for likely elements
  if ( empty($element['#type']) || !in_array($element['#type'], array('radios','checkboxes')) ) {
    foreach ( element_children($element) as $name ) {
      $element[$name] = MYMODULE_remove_required($element[$name], $form_state, $depth+1);
    }
  }
  return $element;
}

Comment: This is the only one I could get to work
Answer: You can also try Required by role module.
Answer: UPDATE:
The solution I posted seems to be a bad idea.
When you reset the $form_state['values'] array, what is actually happening is that you are removing the form token id. You could get the same effect by adding:
$form_state['values']['form_token'] = false;

This seems like a bad idea especially if you have multiple content editors. This also creates a Drupal error message:
The form has become outdated. Copy any unsaved work in the form below and then reload this page.

ISSUE: I have an issue with field_collections (embedded). I am unable to add/remove items.
This worked perfectly:
https://drupal.stackexchange.com/a/56350/72908
Basically you just need to reset the $form_state['values'] array in your #after_build function.
    /**
     * Implements hook_form_alter().
     */
    function modulename_form_alter(&$form, &$form_state, $form_id) {
      if ($form['type']['#value'] == 'YOUR FORM TYPE') {
        $form['#after_build'][] = 'custom_function_after_build';
      }
    }

    function custom_function_after_build($form, &$form_state) {
      $form_state['values'] = array();
      return $form;
    }