Probability of at least $k$ Bernoulli successes with varying probabilities conditional on an event

Question: Suppose a female in  a given species has, on a given year $x$, PMF $Bernoulli(f(x))$ of finding a mate given she doesn't yet have one. Once she finds a mate, she doesn't need another.
This same female has, on a given year $x$, PMF $Bernoulli(g(x))$ of conceiving and giving birth to 1 offspring, given she already has a mate.
The question is: by age $x$, what is the probability that a female will have at least $k$ offspring?
Is there an analytical solution to this problem when $f,g$ are constants? What is a suitable numerical method for solving this problem when $f,g$ are arbitrary functions?
Comment: I'm missing something. Isn't this just the binomial distribution with chance of reproductive success in a given year equal to f(x)*g(x) for that year?
Comment: Not quite. Have a look at Antoni's answer.
Answer: The probability of mating at any given year is $\small \Pr(\text{mate})=m$, and the probability of offspring given a mate has been found is $\small \Pr( \text{single offspring} \vert \text{mate} ) =o$ and it does not change after the mate is found.
The probabilities of getting $k$ offspring after $x$ years depends on the year at which the mate came into the picture.
If we label the beginning of the "experiment" as year zero, $\small \text{Yr}=0$, the probability of having a single offspring at year $0$ is simply $\small \Pr(\text{mate } \cap \text{ offspring})=  \Pr(\text{offspring}\vert \text{mate})\Pr(\text{mate})=o\times m.$
At year $1$ (one year later) the probability of a single offspring is simply going to be $\small\Pr(\text{offspring}\vert \text{mate})=o$: the participation of a mate is now guaranteed.
So we just need to treat every year after the appearance of the mate as a binomial, focusing on the year the mate is "realized": the probability that year $1$ is the first year with a mate is calculated based on the probability of absence of mate at year zero, $1-m$, as $\small \Pr_{\text{Yr=1}}(\text{mate})=(1-m)\,m$. At year two, $\small \Pr_{\text{Yr=2}}(\text{mate})=(1-m)^2\,m$; and in general, $\small \Pr_{\text{Yr=yr}}(\text{mate})=(1-m)^{\text{yr}}\,m.$
So we have that the probability of having $k$ offspring by year $x$ and that the mate appears at year $\small \text{Yr=yr}$ is:
\begin{align}
\small \Pr(\text{Off= }k\text{ by time } x \cap \text{mate @ Yr=yr})&=\small \Pr(\text{Off= }k\,\vert \,\text{mate @ Yr=yr})\,\Pr(\text{mate @ Yr=yr})\\
&=\small\left({x-\text{yr}+1\choose k}\,o^k\,(1-o)^{x-\text{yr}+1 -k}\right)\, m(1-m)^{\text{yr}}\tag{*}
\end{align}
Now, the probability of getting $k$ offspring by year $x$ can happen in any of these scenarios where the mate appears in some year or other, so:
$$\small \Pr(\text{Off}=k\text{ by time } x)=\sum_{\text{Yr=0}}^{x-k+1} m(1-m)^{\text{yr}}{x-\text{yr}+1\choose k}\,o^k\,(1-o)^{x-\text{yr}+1 -k}$$
Notice that the mate cannot appear any later than $x -k + 1$ years if we need $k$ offspring, explaining the upper limit of the sum.
Finally, your question is $\text{at least }k$, inviting another summation:
$$\small\Pr(\text{Off}\geq k\text{ by time } x)= \sum_{\text{Yr=0}}^{x-k+1}\,\, \sum_{\text{K}=k}^{x-\text{yr}+1} \,\, m(1-m)^{\text{yr}}{x-\text{yr}+1\choose k}\,o^k\,(1-o)^{x-\text{yr}+1 -k}$$
This answers the first part of the question in the OP:

Is there an analytical solution to this problem when f,g are
  constants?

However, there was a second part, which I tried to resolve slop... quickly... leading to too much poetic license, so poorly tolerated in math circles. So after being called on it, that part is now erased, and I'm trying again. First the second part of this question:

What is a suitable numerical method for solving this problem when
  f,g are arbitrary functions?

Specifically (see initial comments) the functions Alexandre has in mind are linearly changing probabilities over time as:
$\color{blue}{m_t} = f(\text{yr})= \text{max} \{0, 1−a\times\text{yr}\}$
and
$\color{blue}{o_t} = g(\text{yr})= \text{max} \{0, 1−b\times \text{yr}\}.$
The problem then becomes apparent in, for example, the expression above for $\small \Pr(\text{Off= }k\,\vert \,\text{mate @ Yr=yr})$: treated as a binomial, it prompts to select any combinations of $k$ successes (offspring), and treats each one with fixed probabilities of success and failure. Unfortunately, the summations over years that follow don't correct for this (my oversight).
So back to the drawing board... The hope is that generalizing $\text{Eq. } *$ will do the trick for the rest of the post. This equation is the multiplication of two probabilities. Starting with the least challenging term:
$$\Pr(\text{mate @ Yr=yr})= m_{\small t=\text{yr}}\,\prod_{t=0}^\text{yr}(1-m_t)$$
This is probably clear, although technically, it could be labeled as a geometric distribution with varying probability values.
The challenge, then, is in $\Pr(\text{Off= }k\,\vert \,\text{mate @ Yr=yr})$. This turns out to be a Poisson binomial distribution, and adapting the notation to our case would result in a beautiful expression:
$$\Pr(\text{Off= }k\text{ by time } x\,\vert \,\text{mate @ Yr=yr})=\sum_{A\in F_k}\,\,\prod_{i\in A}\,o_{t\in i}\,\prod_{j\in A^c}(1-o_{t\in j})$$
As in the Wikipedia link, $F_k$ is the set of all subsets of $k$ integers selected from $\{\text{yr}, \text{yr}+1, \cdots, x\}.$
And just when I was searching for a link to The Scream imagining the process of actually inserting this thing into the other two equations, I realized that the actual challenge would be the numerical calculations, at which point @Zen came to save the day, together with @wolfies.
So just for fun, the final equation formulating the probability of a certain number of offspring ($k$) by a given age ($x$, capped at 10 years in the code formulations below), and having found a mate at year $\text{yr}$, would now look something along the lines of:
$$\Pr(\text{Off by time } x\geq k)= \sum_{\text{Yr=0}}^{x-k+1}\,\, \sum_{\text{K}=k}^{x-\text{yr}+1} \,\,\small \left( m_{\small t=\text{yr}}\,\prod_{t=0}^\text{yr}(1-m_t)\right) \left(\sum_{A\in F_k}\,\,\prod_{i\in A}\,o_{t\in i}\,\prod_{j\in A^c}(1-o_{t\in j})\right)$$

Finally, what would this look like in R:
Yr = 1:11 # Years zero to 10. x corresponds to 10, which is Yr[11].

a = .055
# Arbritarily chosen slope of the function for p(mating at time = yr)
(m_t = ifelse((1 - a * Yr) > 0, 1 - a * Yr, 0))
# Ifelse to reject potential negative prob. values

# [1] 0.945 0.890 0.835 0.780 0.725 0.670 0.615 0.560 0.505 0.450 0.395

b = .09
# Doing the same for the slope to calculate P(offspring | mate)
(o_t = ifelse((1 - b * Yr) > 0, 1 - b * Yr, 0)) # Same trick to avoid neg values

# [1] 0.91 0.82 0.73 0.64 0.55 0.46 0.37 0.28 0.19 0.10 0.01

Prob_Off_k_and_mate_yr = function(k=1:11, yr= 0:10){
  # Probability Offspring = k AND mating at Yr = yr
  #k needs to be between yr and x
  if(k > (length(Yr) - yr + 1)){stop('Number of spring selected is impossible')}else{
    #Probability to mate at year Yr = yr:
    P_mate_at_yr = ifelse(yr==0, m_t[1], prod(1 - (m_t)[1:yr]) * m_t[yr + 1])
    #Probability of Offspring = k having mated at Yr = yr
    S = seq(yr, length(Yr) - 1)
    # All the years remaning to choose from, including the mating year.
    A = combn(S, k)
    # All possible combinations of k times from S
    P_off_k_having_mated_yr = 0 # Starting an empty vector
    for (i in 1:ncol(A)) {
      # For all subsets of k elements from the years "available"
      P_off_k_having_mated_yr = P_off_k_having_mated_yr +
        prod(o_t[A[,i] + 1], 1 - o_t[setdiff(S, A[,i]) + 1])
      # Poisson binomial
    }
    Prob_Off_k_and_mate_yr = P_mate_at_yr * P_off_k_having_mated_yr
    return(Prob_Off_k_and_mate_yr)
  }
}

# Trying the function for Offspring = 6 and mating at year 1:
k = 6
yr= 1
Prob_Off_k_and_mate_yr(k,yr)

# [1] 0.005674715

# What about the probability of Offspring = 6
# regardless of the mating year (summation over years):
Prob_Off_k = 0
for(i in 0:(length(Yr) - k)){
  Prob_Off_k =  Prob_Off_k + Prob_Off_k_and_mate_yr(k, i)
}
Prob_Off_k

# [1] 0.2238927

# Finally, the actual question in the OP: AT LEAST 3 Offspring (for example):
k=3
Prob_at_least_k = 0 # Starting empty vector
for(i in 0:(length(Yr)- k)){
  # Loop over mating year, which can't go beyond len(Yr) - k
  Prob_Off_k = 0
  # Probability of k and any max allowable k depending on the year of mating (i)
  for(j in k:(length(Yr) - i)){ # Index for k's
    Prob_Off_k =  Prob_Off_k + Prob_Off_k_and_mate_yr(j, i)
  }
  Prob_at_least_k = Prob_at_least_k + Prob_Off_k
}
Prob_at_least_k

# [1] 0.9682951

A more elegant way of coding this process, thanks, so many thanks to the wisdom of whuber, in this instance on this post, could be achieved using a convolution with the R function convolve(), which calculates it using a Fast Fourier Transform (FFT). This would be the modified Prob_Off_k_and_mate_yr function:
Prob_Off_k_and_mate_yr_convolution = function(k=1:11, yr= 0:10){
  # Probability Offspring = k AND mating at Yr = yr
  #k needs to be between yr and x
  if(k > (length(Yr) - yr + 1)){stop('Number of spring selected is impossible')}else{
    #Probability to mate at year Yr = yr:
    P_mate_at_yr = ifelse(yr==0, m_t[1], prod(1 - (m_t)[1:yr]) * m_t[yr + 1])
    #Probability of Offspring = k having mated at Yr = yr

    z = 1
    for (u in sort(o_t[yr+1:length(o_t)])) z <- convolve(z, c(u, 1 - u), type = "open")
    Prob_Offspring = z *  P_mate_at_yr
    return(Prob_Offspring[k + 1])
  }
}

It is shorter in coding lines, more elegant mathematically, and so much faster:
microbenchmark(Prob_Off_k_and_mate_yr_convolution(k,yr), Prob_Off_k_and_mate_yr(k,yr))
Unit: microseconds
                                      expr      min        lq      mean    median       uq      max neval
 Prob_Off_k_and_mate_yr_convolution(k, yr)  281.220  288.7165  298.6452  294.5675  301.333  376.300   100
             Prob_Off_k_and_mate_yr(k, yr) 3959.012 4046.9615 4236.5416 4111.1405 4187.023 6195.602   100

Comment: Thank you for the fantastic answer. The only thing missing is the case where $f,g$ are not constants. Can  you shed some light on that so that I can accept your answer?
Comment: @Alexandre Tough... So I can mull over it and feel inadequate :-) ... in plain English the second part of the question makes reference to a case where we still have a Bernoulli experiment in finding a mate with a given probability, and having offspring (provided a mate exists), *but* with the parameter $p$ in $X \sim \text{Bern}(p)$ changing from year to year?
Comment: Would the inter-annual change follow any pattern?
Comment: Yes, your first comment is correct. In my case, it will be a linear function that decreases towards 0, but for the purpose of helping others in the future, I think it would be more interesting to allow arbitrary functions. Sorry for giving you so much work! Loved your answer though. I can't find a fault in it, and I can imagine it being useful to others in the future.
Comment: @Alexandre It would be really cool to just plug in a $f(\text{time})$ into $o$ and $m$ if available. Otherwise, the summation would become an indicial notation nightmare...
Comment: Will that work? Can you just replace $m$ by $f(x)$ and $o$ by $g(x)$? Will the binomial still hold when the probability of an event isn't constant?
Comment: Ok, but I think as it is it won't work. The binomial assumes all combinations of the outcomes be equally likely, which seems to be violated here.
Comment: I think the problem is here: $\Pr(\text{Off= }k\,\vert \,\text{mate @ Yr=yr})\ = \left({x-\text{yr}+1\choose k}\,o^k\,(1-o)^{x-\text{yr}+1 -k}\right)$. Say a mate was found at $Yr = 0$ and we are inspecting $k = 1$ and $x = 1$. Either of these 2 outcomes satisfy 1 offspring:  $\left\{(\text{OffspringOnYear0}, \not\text{OffspringOnYear1}), (\not\text{OffspringOnYear0}, \text{OffspringOnYear1})\right\}$. Plugging in values, I believe $\left({1-0+1\choose 1}\,o(1)^1\,(1-o(1))^{1-0+1 - 1}\right) \neq  \left(o(0)\,(1-o(1)) + (1-o(0))\,o(1)\right)$ if $o(x) \neq o(x+1)$
Comment: Sorry, unable to edit comment. Read above $\not\text{OffspringOnYearX}$ as $\neg\text{OffspringOnYearX}$.
Comment: that looks good!  I haven't spotted any problems at first glance. Will have a closer look and get back to you.  Love that it has an analytic solution, and I don't any reliance on linear $f, g$ which is fantastic. So it looks like both problems have analytic solutions,  and for some values of $x$ and $k$ might it be possible to find closed forms?
Comment: @Alexandre It was a fun challenge. Can you please liberate some space by deleting comments that may be now irrelevant?
Comment: Alright, will do!
Comment: Stunning work! The R code was an unnecessary but great addition!
Comment: There seems to be an issue with the code! If I set $a,b = 0.2$, the probability returned in the last line is $1.42016$. Any idea why? Thanks!
Comment: @Alexandre I finally got a chance to look at it with peace around me... Believe it or not it might be the silliest slight of pen, now hopefully fixed: in the mathjax $LaTex$ the indicial limits are probably OK, but when I translated this into loops in R (with R starting at `1` (Python would have been a blessing for our problem with `year 0` included), I added a `+ 1`.
Comment: @Alexandre  I appreciate your tenacity in getting it right. It has prompted me to go beyond shortcuts, and get the details straight. As I mentioned to you, I think the code can be greatly improved using convolutions, but I am far from this goal (I will get to it at some point). Now the `a=b=0.2` returns `0.2336`, which would make sense, because a lot of $m_t$ and $o_t$ become $0$ with these settings. Let me know if you still find glitches - the limits are a pain to code.
Comment: Alright, will play around with it tomorrow. Thank you again for your tremendous effort.
Comment: @Alexandre I changed the code with a convolution. Check the difference in time!
Comment: Will do! As a sidenote, shouldn't $x$ somehow be incorporated into the event formulations in equations where it is referenced?
Comment: @Alexandre I defined explicitly $x$ now  before introducing the last equation. The time is printed in the answer.
Comment: I mean like here $Pr(Off = k \cap mate @ Yr = yr)$ in Eq $*$. Shouldn't the $x$ appear in there somehow? Like $Pr(Off = k \, By \, Yr = x \cap mate @ Yr = yr)$
Comment: @Alexandre Good point. I changed it.
Comment: Perfect! I'm not exactly versed in the grammar of events (or event formulations or whatever you want to call it), but can we write something like that? It's the kind of thing you don't see in textbooks, but sure looks handy.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/46251/discussion-between-antoni-parellada-and-alexandre).


Why take the derivative with respect to time (or some other variable) when solving related rate problems?

Question: I know mechanically how to solve related rate problems. What I'm trying to do is understand the motivation or rationale behind taking the derivative with respect to time (or some other variable) when solving related rate problems.
For example, the equation for the volume of a sphere relates volume to its radius:
$$V = \frac{4}{3} \pi r^3$$
Because there's a relation between $V$ and $r$, we can infer that the rate at which $V$ changes is related to the rate at which $r$ changes and vice versa.
It makes sense to me that if we were given either the rate of change for volume or radius that we could solve for the other's rate of change.
What I don't fully understand is why take derivative of the equation with respect to time when it seems like $V$ is a function of $r$ (or at least related to it), so wouldn't it make sense to take the derivative with respect to the independent variable $r$ instead?
Also, taking the derivative of both sides of the equation with respect to $t$ assumes that the variables $V$ and $r$ are functions of  $t$ (parametric equations?). But I don't understand the motivation for assuming this since the equation only shows the relation between $V$ and $r$.
As a recap my two questions are:

Why take the derivative of an equation or function with respect to time instead of the independent variable?

Why assume the variables are functions of time or some other variable not explicitly present in the equation?
Comment: Just my humble comment. Suppose you have a sphere full of water. If you empty it as time passes, the volume will change and the radius will also change as a function of the time.
Comment: Because the "independent" variable $r$ depends on $t$. Also, parameterization is an important technique, even under some circumstances where the notion of the "third" variable is implicit.
Answer: When concerned with rate related problems, it is often assumed that the functions that we want to study are dependent on time, although these time dependencies are sometimes omitted, or are obtained via a generalisation.
Now, it is true that for a given sphere, its volume $V$ depends on its radius $r$ via the relation
$$V = \frac{4}{3}\pi r^3,$$
although this equation holds true for some fixed value of $r$, which in turn yields a fixed value of $V$.
Now, we can assume the existence of time in our equation, and then assume that our radius $r$ varies with time $t \in [0,T]$ for some $T > 0$. Then, indeed $r$ is a function of time, i.e. $r : [0,T] \to \mathbb{R}$. Since we know what the volume of a sphere is with respect to its radius for a fixed value of radius, we can generalise the above volume equation to:
$$V(t) = \frac{4}{3}\pi (r(t))^3,$$
where the time dependence of the volume came about due to the time dependence of the radius. That is, we can apply the time independent equation for each time $t \in [0,T]$.
Thus, if we want to study the rate of change of the variable volume $V(t)$, we would differentiate with respect to its time variable, to obtain
$$\frac{d V(t)}{dt} = 4\pi \frac{dr(t)}{dt} (r(t))^2.$$
If say we have a function $r : [0,T] \to \mathbb{R}$, but the radius is constant with respect to $t \in [0,1]$, i.e. $r(t) = r_0$ for some $r_0 \in \mathbb{R}$, then $\frac{dr(t)}{dt} = 0$ for all $t$, thus giving us that $\frac{dV(t)}{dt} = 0 $ for all $t$. Therefore $V$ is constant, i.e. $V(t) = V_0$ for some $V_0 \in \mathbb{R}$ for all $t \in [0,T]$.
Looking back at the generalised equation for the volume (with respect to time), we therefore obtain
$$V_0 = \frac{4}{3}\pi r_0^3$$
which is precisely the time independent equation we have described above.
To answer the questions more precisely:

It does not make sense to take the derivative of $V$ with respect to $r$ to determine the rate of change of $V$ with respect to time, $t$. Unless say you wanted to determine the rate of change of $V$ with respect to its radius, in which case you can indeed differentiate with respect to $r$.

This is done as to bring the time variable that we want to study into our problem, I've described this above.
Comment: This makes more sense now. Especially the part about $r$ varies with time means that $r$ is a function of time, $r(t)$, and since $V$ is a function of $r$ then it's implied that $V$ must be a function of time as well. Thinking back it makes sense now that the rates of change were often given as per units of time. For example, the radius changing at a rate of  5cm/sec, which mathematically would be $\frac{dr}{dt}=5$. And this notation informs us that $r$ must be a function of $t$ since derivatives are taken with respect to the independent variable. Thank you for your help!
Comment: This explanation also ties in nicely with the chain rule. That a change in $t$ will cause a change $r$ which will then cause a change $V$.
Comment: Glad it helped :)


Is the composition in locally small categories always the set-theoretic composition of functions?

Question: Is the composition in locally small categories always the set-theoretic composition of functions?
The definition of a locally small category simply says:
A category $\mathcal{C}$ is called locally small if for any $X, Y \in \text{ob}\mathcal{C}$ we have that $\text{Hom}_\mathcal{C}(X,Y)$ is a set.
But is it always implicitly assumed that for $f,g \in \text{Mor}\mathcal{C}$ we have $fg = f \circ_{set} g$?
I also think that this assumption is used to prove that the $\text{Hom}$ functor of a locally small category is actually a functor.
Comment: No: there is no assumption that morphisms are functions.
Answer: Locally small just says that the $Hom_\mathcal{C}(X, Y)$ is a set, it tells us nothing about what might be in that set. For many categories we naturally consider, this is actually the set of maps between certain mathematical structures (e.g. group homomorphisms, continuous maps, etc). This does not always need to be the case.
For example, any poset $P$ can be considered as a category and it is definitely locally small. However, the composition of $x \leq y$ and $y \leq z$ is just $x \leq z$.
Another example would be any group $G$. We can consider $G$ as a category with one object $X$ and a morphism $X \to X$ for every element in the group. Composition is then given by the group operation.
More generally, there is a notion close to what you are describing. That of a concrete category (Wikipedia, nLab). This is a category $\mathcal{C}$ equipped with a faithful functor $U: \mathcal{C} \to \mathbf{Set}$. A very natural example is the forgetful functor on for example the category of groups, or the category of topological spaces.
This idea also gives another non-example to your question: the category of topological spaces where the morphisms are homotopy classes of continuous functions. It turns out that this category does not admit a faithful functor into $\mathbf{Set}$ and can thus not be viewed as a concrete category.


If I delete an Azure VM do I lose the drives?

Question: I have an Azure VM with an OS disk and a 1TB data disk.  I am going to delete the VM today but I do not want to lose the disks.  I'm assuming if I delete the VM the disks will still be available to use in the future.  Am I correct in my assumption?
Comment: Why not make a proper backup and remove any uncertainty?
Comment: Why not make a second VM, then delete it and see what happens?
Answer: When you delete a VM in Azure the disks are not deleted.
https://docs.microsoft.com/en-us/azure/virtual-machines/windows/find-unattached-disks
Answer: Nope With new Azure Resource Manager VMs components are independent, so if you delete the VM doesn't delete any other resources are attached to it. For example Managed disks, NICs, Public IPs.


Best Practice/Workflow for bulk renaming domain PC's

Question: So I've had to deal with renaming whole rooms of PC's before due to them being swapped out and incorrectly named or generally being moved around but I've never settled on a decent workflow.
I'll give an example of the most recent situation. (Win 7 PC's and a Win 2012 server) Approx. 30 PC's numbered from 1 to potentially anything, mostly within that 1-30 range though.
As it was a complete mess all the computer objects were removed from AD to start fresh.
In many cases I can simply change the name of the PC, restart and it will fine. If that doesn't work going through the Join a Domain or Workgroup wizard works and then finally if they don't work, changing to a workgroup, restart, re-join the domain and restart does it. Occasionally get trust relationship errors and have to re-do the last one.
As you can tell, it's messy, inefficient and potentially wrong in a few ways. I know I'm at risk of sounding vague and there's unlikely to be one single answer but it's time consuming and I'm very interested in improving my methodology and hopefully it will help some people.
Comment: Wait a sec-- do you work at my K-12 educational Customer?  >smile<  (This keeps happening there year-after-year... I *finally* got them to start using the Dell Service Tag as the computer name. No more renaming! Problem solved...)
Comment: That's interesting, we might be moving that way as we're doing a big move this summer and an external company will be setting us up and I think I've heard they'll be doing something similar to this, they may include room number though, not 100% yet.
Comment: Haha maybe I do! Out of curiosity, how does it work with keeping OU's organised, just good management?
Comment: We're just about a year into using the Dell Service Tags, so it's hard to say-- we haven't had any major PC moves yet. It's going to take discipline, but it should be less work than the wild gyrations of disjoining and rejoining machines that we've seen in the past. We won't know until August - September, when we get our next round of PCs.
Answer: I have been in a similarl situation before; The way I did is was using netdom, less clicks, and you can use a batch file or psexec to make life a lot easier/quicker.
e.g.
netdom renamecomputer member /newname:member1.exampledomain.com /userd:administrator

netdom add /d:exampledomain member1 /ud:exampledomain\admin /pd:password

shutdown /r

Comment: Presumably that includes removing the object from AD first (of the new name)
Comment: @Crimsonfox  Well, netdom won't do that for you, but you can manipulate AD over a command line too.  I'd use PowerShell over `cmd`, especially given Windows 7, but the principle is the same.  Type out your command(s), use the command buffer and change the number, instead of RDPing into every machine and clicking around for a couple minutes.
Comment: Apologies, I didn't mean using Netdom to remove anything from AD, just in general.

I should have also pointed out, unfortunately, the computers ideally need to be ordered so I've got to be in the room to find out which ones need changing to which names.
Answer: Based on your reply to metacom ("I should have also pointed out, unfortunately, the computers ideally need to be ordered so I've got to be in the room to find out which ones need changing to which names"), it sounds like you need an information gathering phase first.

Create a startup script in the language of your choice that writes the computer name to a network share. (echo %computername% >> \\server\share\room.txt or whatever)
Assign it to the OU in question.
Reboot the computers one by one in the sequence you want so the names are appended in order.

There's also sneakernet and a thumb drive or that network share, if, for whatever reason, you don't have the computers in their own little OU.
After you have those lists of computers, you could either use metacom's netdom script or something like this to rename the computers.


Icones maiores que a caixa de texto

Question:
Como diminuo o tamanho desses icones no meu layout?
Answer: Se calhar era melhor por ImageView e EditText dentro de um LinearLayout com orientação horizontal
Comment: porque a votação negativa?

Icones maiores que a caixa de texto


Error on sequelize full text search raw sql query

Question: Attempting to use raw sql in sequelize db, not sure why it is not working.
Here is the controller with the query:
const db = require("../../models");
const Book = db.book;
const User = db.user;
const Sequelize = require('sequelize');
const { sequelize } = require('../../models/index.js');

exports.getAllBooks = async (req, res) => {
    console.log('query: ', req.query);
    let books;
    if (Object.keys(req.query).length === 0) {
        books = await Book.findAll();
        res.json(books);
    } else {
        [books, metadata] = await sequelize.query(`
            SELECT ('title')
            FROM Book
            WHERE searchable @@ to_tsquery(${req.query});
        `);
        res.json(books);
    }
};

get request to

http://localhost:8080/api/books?searchable=humor

the tsvector column in the db is named "searchable"
the log response:
Server is running on port 8080.
query:  { searchable: 'humor' }
Executing (default): SELECT ('title')
            FROM Book
            WHERE searchable @@ to_tsquery([object Object]);
node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error
    at Query.run (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/sequelize/lib/dialects/postgres/query.js:50:25)
    at /Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/sequelize/lib/sequelize.js:314:28
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async exports.getAllBooks (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/app/controllers/book.controller.js:16:29) {
  name: 'SequelizeDatabaseError',
  parent: error: syntax error at or near "["
      at Parser.parseErrorMessage (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/parser.js:287:98)
      at Parser.handlePacket (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/parser.js:126:29)
      at Parser.parse (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/parser.js:39:38)
      at Socket.<anonymous> (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/index.js:11:42)
      at Socket.emit (node:events:513:28)
      at addChunk (node:internal/streams/readable:315:12)
      at readableAddChunk (node:internal/streams/readable:289:9)
      at Socket.Readable.push (node:internal/streams/readable:228:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
    length: 90,
    severity: 'ERROR',
    code: '42601',
    detail: undefined,
    hint: undefined,
    position: '83',
    internalPosition: undefined,
    internalQuery: undefined,
    where: undefined,
    schema: undefined,
    table: undefined,
    column: undefined,
    dataType: undefined,
    constraint: undefined,
    file: 'scan.l',
    line: '1180',
    routine: 'scanner_yyerror',
    sql: "SELECT ('title')\n" +
      '            FROM Book\n' +
      '            WHERE searchable @@ to_tsquery([object Object]);',
    parameters: undefined
  },
  original: error: syntax error at or near "["
      at Parser.parseErrorMessage (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/parser.js:287:98)
      at Parser.handlePacket (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/parser.js:126:29)
      at Parser.parse (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/parser.js:39:38)
      at Socket.<anonymous> (/Users/darius/IdeaProjects/node-jwt-auth-postgresql/node_modules/pg-protocol/dist/index.js:11:42)
      at Socket.emit (node:events:513:28)
      at addChunk (node:internal/streams/readable:315:12)
      at readableAddChunk (node:internal/streams/readable:289:9)
      at Socket.Readable.push (node:internal/streams/readable:228:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
    length: 90,
    severity: 'ERROR',
    code: '42601',
    detail: undefined,
    hint: undefined,
    position: '83',
    internalPosition: undefined,
    internalQuery: undefined,
    where: undefined,
    schema: undefined,
    table: undefined,
    column: undefined,
    dataType: undefined,
    constraint: undefined,
    file: 'scan.l',
    line: '1180',
    routine: 'scanner_yyerror',
    sql: "SELECT ('title')\n" +
      '            FROM Book\n' +
      '            WHERE searchable @@ to_tsquery([object Object]);',
    parameters: undefined
  },
  sql: "SELECT ('title')\n" +
    '            FROM Book\n' +
    '            WHERE searchable @@ to_tsquery([object Object]);',
  parameters: {}
}
[nodemon] app crashed - waiting for file changes before starting...

Answer: First, you passed the whole query object instead of the searchable prop only.
Second, it's better to use bind option to pass such values safely (remember about SQL injection!).
await sequelize.query(`
            SELECT ('title')
            FROM Book
            WHERE searchable @@ to_tsquery($searchable);
        `, {
   type: QueryTypes.SELECT,
   bind: {
     searchable: req.query.searchable
   }
})


Piano fingering for fast right hand arpeggio (B-A#-F#-C# in 3 octaves)

Question: What would be the recommended fingering for this descending arpeggio?
(I'm currently using 5-4-2-1 but it's tricky to shift between positions.)
The tempo is somewhere around 1/4 @ 135 bpm.
Comment: If this arpeggio was ascending, how would you play it?
Answer: Hm, maybe something like 5-4-3-2 | 1-4-3-2 | 1-4-3-2 | ...
Comment: ...or maybe 5 4 3 2 | 1 4 3 2 | 1 4 2 1 depending on what's next.
Answer: My preference
The fingering that is most comfortable and accurate for me at speed is
5-3-2-1  4-3-2-1  4-3-2-1
The initial 5-3 is because it's easier for me when my hand is that distance out from my body, but 4-3 is easier otherwise. The only drawback I found was the potential for a "gap" between 1 and 4, but that was easily covered with some half-pedaling.
Other attempts
My first instinct was the 5-4-3-2  1-4-3-2  ... fingering suggested elsewhere, but I wasn't comfortable or accurate (at speed) with covering the F#-C# distance with 3-2.
I also tried the more "radical" 1-3-1-3  1-3-1-3  ..., which seemed like a good idea in my head, but was a disaster for me on the keyboard.
Comment: Funny, I find 4-3-2-1 harder than 1-4-3-2, because it requires a weird movement for switching 1 on c# → 4 on b. Putting the thumb on the c# requires you to either move your hand further in or to angle your hand, both making this somewhat harder. Playing the c# with 2 instead allows your hand to remain in a natural position. But again we see, fingering is something very personal, and also this is not a particularly nice arpeggio to play ...
Comment: @Lazy I do tend to be comfortable with my hand far forward (toward the fall board), but the disadvantage is just as you say. I don't even try to make a legato connection between 1 on C# and 4 on B. I just make a horizontal shift, which gets close to legato, but then I use the pedal to cover for me.
Answer: 1 on the second B, turn 4 onto the A (like @Lazy said).  Or 5 4 3 2 [shift] 5 4 3 2...
Answer: Find a new teacher. You don't want to attempt applying what you read on the internet.  A teacher will not only tell you what to do correctly but sleuth out what you may be doing wrong and you don't know it.  Often it is not enough to know what to do because what not to do is often insidiously invisible. IOW, you may be doing everything right but there is an invisible movement holding you back. Only a knowledgeable teacher will be able to find it. Not the internet.
To answer your question though, it is not which fingers but how you use them.  I'd have to see you play this section but I'd focus on the elbow for the shifts, pronation and supination of the forearm, playing to the point of sound with the proper in/out movements because your fingers are all different lengths and the black keys are higher than the white ones, and, slap you if you abduct any of your fingers.  Abduction creates muscular co-contractions which will destroy legato every time.  Oh, this passage can be ripe with ulnar and radial deviations of the wrist which will destroy the line, too.  Your bones can only move in one direction at a time and when you use two muscles to pull one bone in two directions . . . anarchy reigns.
There is another problem:  Muscle memory.  If you already tried to work on this, you may have already hardwired improper movement into your muscle memory and SOME PEOPLE (like me) will never master what they learned first-incorrectly.  For example, if you sloppily played something as a beginner, years later as you advance beyond that piece, if you played that first piece years later, some of the old improper movements will come back. It is not because you are rusty, took a day off or are having a bad day, muscle memory is rearing is ugly head.
Comment: Sorry, but I find this answer not only not helpful, but to some extent abusive. You are literally claiming you'd need to slap the OP if he did something wrong. There is nothing wrong with asking on a music related site for fingering suggestions. Yes, a teacher might help in that regard. But you do not know anything about the OPs situation. Also this same argument could be applied to pretty much any technique-related question, to any practise-related question, even to theory and history-related questions.


Inclusão de método na classe própria

Question: Imagine um sistema OO que tenha pelo menos 2 classes:
Admins.php
Clientes.php

Na vida real, isto é, no sistema, clientes não podem se cadastrar. Nesse caso, a função de cadastrar o Cliente é do administrador.
A dúvida é: onde eu devo incluir o método cadastrarCliente($Cliente)?
Na Classe Admins ou na Classe Clientes?
Estou fazendo assim:
Clientes.php
 class Clientes {

     private $idCliente;
     private $nome;
     private $documento;
     private $senha;
     private $endereco;
     private $numero;
     private $complemento;
     private $bairro;
     private $estado;
     private $cidade;
     private $cep;
     private $email;
     private $telefone;
     private $celular;
     private $bloqueado;

     public function __construct(
         $_nome,
         $_documento,
         $_senha,
         $_endereco,
         $_numero,
         $_complemento,
         $_bairro,
         $_estado,
         $_cidade,
         $_cep,
         $_email,
         $_telefone,
         $_celular,
         $_bloqueado
    )
     {
         $this->nome = $_nome;
         $this->documento = $_documento;
         $this->senha = $_senha;
         $this->endereco = $_endereco;
         $this->numero = $_numero;
         $this->complemento = $_complemento;
         $this->bairro = $_bairro;
         $this->estado = $_estado;
         $this->cidade = $_cidade;
         $this->cep = $_cep;
         $this->email = $_email;
         $this->telefone = $_telefone;
         $this->celular = $_celular;
         $this->bloqueado = $_bloqueado;
     }

     public function setIdCliente ($_idCliente){
         $this->idCliente = $_idCliente;
     }

    public function getIdCliente () {
        return $this->idCliente;
    }

    public function getNome () {
        return $this->nome;
    }

    public function getDocumento () {
        return $this->documento;
    }

    public function getSenha () {
        return $this->senha;
    }

    public function getEndereco () {
        return $this->endereco;
    }

    public function getNumero () {
        return $this->numero;
    }

    public function getComplemento () {
        return $this->complemento;
    }

    public function getBairro () {
        return $this->bairro;
    }

    public function getEstado () {
        return $this->estado;
    }

    public function getCidade () {
        return $this->cidade;
    }

    public function getCep () {
        return $this->cep;
    }

    public function getEmail () {
        return $this->email;
    }

    public function getTelefone () {
        return $this->telefone;
    }

    public function getCelular () {
        return $this->celular;
    }

    public function getBloqueado () {
        return $this->bloqueado;
    }

}

ClientesDao.php
 class ClientesDao {

     private $conexao;

     public function __construct ($_conexao) {
         $this->conexao = $_conexao;
     }

     public function bloquear ($idCliente, $bloqueio) {

         $string = "UPDATE clientes SET bloqueado = '".$bloqueio."' WHERE idCliente = ".$idCliente;

         $this->conexao->query($string);

     }

     public function excluir ($idCliente) {

         $string = "DELETE FROM clientes WHERE idCliente = ".$idCliente;

         $this->conexao->query($string);

     }

     public function cadastrar ($cliente) {

         $string = "INSERT INTO clientes (nome, documento, senha, endereco, numero, complemento, bairro, estado, cidade, cep, email, telefone, celular, bloqueado)
                    VALUES (
                       '".$cliente->getNome()."',
                       '".$cliente->getDocumento()."',
                       '".$cliente->getSenha()."',
                       '".$cliente->getEndereco()."',
                       '".$cliente->getNumero()."',
                       '".$cliente->getComplemento()."',
                       '".$cliente->getBairro()."',
                       '".$cliente->getEstado()."',
                       '".$cliente->getCidade()."',
                       '".$cliente->getCep()."',
                       '".$cliente->getEmail()."',
                       '".$cliente->getTelefone()."',
                       '".$cliente->getCelular()."',
                       '".$cliente->getBloqueado()."'
                       )";

         $this->conexao->query($string);

     }

     public function ultimoIdCadastrado () {
         return $this->conexao->insert_id;
     }

     public function editar ($cliente) {

         $string = "UPDATE clientes
                    SET
                      nome = '".$cliente->getNome()."',
                      documento = '".$cliente->getDocumento()."',
                      senha = '".$cliente->getSenha()."',
                      endereco = '".$cliente->getEndereco()."',
                      numero = '".$cliente->getNumero()."',
                      complemento = '".$cliente->getComplemento()."',
                      bairro = '".$cliente->getBairro()."',
                      estado = '".$cliente->getEstado()."',
                      cidade = '".$cliente->getCidade()."',
                      cep = '".$cliente->getCep()."',
                      email = '".$cliente->getEmail()."',
                      telefone = '".$cliente->getTelefone()."',
                      celular = '".$cliente->getCelular()."',
                      bloqueado = '".$cliente->getBloqueado()."'
                    WHERE
                      idCliente = ".$cliente->getIdCliente();

         $this->conexao->query($string);
     }

     public function alteraSenha ($senha, $idCliente) {
         $string = "UPDATE clientes SET senha='".$senha."' WHERE idCliente = ".$idCliente;
         $this->conexao->query($string);
     }

     public function pesquisaClienteId($idCliente) {
         $cliente = null;

         $string = "SELECT idCliente, nome, documento, senha, endereco, numero, complemento, bairro, estado, cidade, cep, email, telefone, celular, bloqueado
                    FROM clientes
                    WHERE idCliente = ".$idCliente;

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;

         if ($quantasLinhas > 0)
         {

             list ($idCliente, $nome, $documento, $senha, $endereco, $numero, $complemento, $bairro, $estado, $cidade, $cep, $email, $telefone, $celular, $bloqueado) = $registros->fetch_row();

             $cliente = new Clientes($nome, $documento, $senha, $endereco, $numero, $complemento, $bairro, $estado, $cidade, $cep, $email, $telefone, $celular, $bloqueado);
             $cliente->setIdCliente($idCliente);
         }

         return $cliente;

     }

     public function pesquisaClienteDocumento($doc) {

         $string = "SELECT idCliente
                    FROM clientes
                    WHERE documento = '".$doc."'";

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;

         if ($quantasLinhas > 0)
         {
             return true;
         }

         return false;

     }

     public function pesquisaClienteEmail($email) {

         $string = "SELECT idCliente
                    FROM clientes
                    WHERE email = '".$email."'";

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;

         if ($quantasLinhas > 0)
         {
             return true;
         }

         return false;

     }

     public function pesquisaClienteNome($nomeCliente) {
         $cliente = null;

         $string = "SELECT idCliente, nome, documento, senha, endereco, numero, complemento, bairro, estado, cidade, cep, email, telefone, celular, bloqueado
                    FROM clientes
                    WHERE nome = '".$nomeCliente."'";

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;

         if ($quantasLinhas > 0)
         {

             list ($idCliente, $nome, $documento, $senha, $endereco, $numero, $complemento, $bairro, $estado, $cidade, $cep, $email, $telefone, $celular, $bloqueado) = $registros->fetch_row();
             $cliente = new Clientes($nome, $documento, $senha, $endereco, $numero, $complemento, $bairro, $estado, $cidade, $cep, $email, $telefone, $celular, $bloqueado);
             $cliente->setIdCliente($idCliente);
         }

         return $cliente;

     }

     public function pesquisaNomeCliente($idCliente) {
         $cliente = null;

         $string = "SELECT nome FROM clientes WHERE idCliente = ".$idCliente;

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;

         if ($quantasLinhas > 0)
         {

             list ($nome) = $registros->fetch_row();
             $cliente = $nome;
         }

         return $cliente;

     }

     public function pesquisaClientes() {
         $Clientes = null;

         $string = "SELECT idCliente, nome, documento, senha, endereco, numero, complemento, bairro, estado, cidade, cep, email, telefone, celular, bloqueado FROM clientes";

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;

         if ($quantasLinhas > 0) {

             while (list ($idCliente, $nome, $documento, $senha, $endereco, $numero, $complemento, $bairro, $estado, $cidade, $cep, $email, $telefone, $celular, $bloqueado) = $registros->fetch_row()) {

                 $cliente = new Clientes($nome, $documento, $senha, $endereco, $numero, $complemento, $bairro, $estado, $cep, $cidade, $email, $telefone, $celular, $bloqueado);
                 $cliente->setIdCliente($idCliente);

                 $Clientes[] = $cliente;
             }
         }

         return $Clientes;

     }
 }

Answer: Carlos, cadastrarCliente($Cliente) dentro da classe admins faz sentido imaginando que é uma página ou ação da controladora Admins. Seria também uma organização mais atrelada ao diagrama de casos de uso do padrão UML, onde esse método seria exclusivo do ator Administrador.
Answer: Métodos descrevem comportamentos dos objetos que o possuem. Se o comportamento de cadastrar cliente é inerente ao administrador, o mesmo deveria possuir o método. Apesar disso, é interessante desacoplar as regras de negócio de POJOS. O ideal mesmo seria que você tivesse outro objeto para gerenciar o cadastro de clientes (e.g. ProcessadorCliente). Esse processador seria ativado pelo administrador, garantindo assim que o cadastro seja feito apenas por eles.
Comment: Adicionei os códigos para ver se fica mais claro.

Inclusão de método na classe própria


Nginx and fcgiwrap, incremental output problems

Question: When I run a cgi script under Apache any output is rapidly sent to the client. However when I run it under nginx with fcgiwrap it seems nothing is sent to the client until the script either finishes or produces a lot of output. In particular when using git-http-backend this leads to gateway timeouts on cloning large repositories (and lack of progress information on cloning smaller ones).
This behaviour can be seen with the following script.
<code> #!/bin/bash
 echo "Content-type: text/html"
 echo
 while :
 do
       echo this is a test.
       sleep 5
 done
</code>
Under apache the client will get some data every 5 seconds.
Under nginx with fcgiwrap I get no data and a gateway timeout.
nginx and fcgiwrap are packages from Debian Jessie. Versions  1.1.0-5 and  1.6.2-5+deb8u4
So the questions

Does anyone know which is responsible for this behaviour? nginx itself? fcgiwrap? both?
Is it something that can be fixed through configuration?
If it's a fcgiwrap problem are there alternative cgi wrappers available that don't suffer the problem?
Answer: Ok, figured it out. It seems both nginx and fcgiwrap have undesirable buffering in place. For nginx it seems it can be disabled through configuration while fcgiwrap needs a patch.
I have posted a debdiff for fcgiwrap at http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=863478 this adds a new option NO_BUFFERING
(update: Debian has now applied said patch, so if you are running Debian Buster or later you don't need to apply it yourself).
Then the nginx configuration needs changing to pass the NO_BUFFERING option to fcgiwrap and to disable buffering inside nginx.
To do this I added some settings immediately before and after the "include fastcgi_params;" line.
<code>    #note: NO_BUFFERING relies on a patched fcgiwrap.
    fastcgi_param NO_BUFFERING 1;
    include fastcgi_params;
    gzip off;
    fastcgi_buffering off;
</code>
Comment: I'm trying to follow your answer, and I've applied the patch but it still does not seem to work. Any hint at what might be missing?
Comment: Asked on SO as well: https://stackoverflow.com/q/57060705/3206471


How to change views pager with View All links

Question: I am using the full pager in views module. I am displaying 40 items per page. The full pager display links like this
1 2 3 4 5 next last
I want to change it to this
View All 1 2 3 4
How will I do this? Any idea about this?
Answer: The only way I can think of you achieving such a thing would be to create another display page in addition to the display page which already has a pager. And using html/CSS add a link to the footer of the views with pager called View all linking to the display page you created that shows all content.
Comment: Don't you need next and last buttons... You just want 1 2 3 4....??
theme_pager() is used to alter pager functions in general


What is the optimal way to draw repeatedly from (0,1) with a vector of varying probabilities? (R)

Question: I often face the problem that I want to draw samples repeatedly with replacement from c(0,1) with varying vector of 'success' probabilities prob, such as
prob <- c(1:5/10)

Two options using both a for loop are:
A <- numeric()
n <- length(prob)
for(i in 1:n){
  A[i] <- rbinom( 1 , 1 , prob = prob[i] )
}

and
for(i in 1:n){
  A[i] <- sample( c(0,1) , 1 , prob = c(1-prob[i],prob[i]) )
}

Are there more straight forward (optimal, ellegant) ways to do this, e.g. without using the for loop?
Comment: `rbinom(n, 1, prob)`
Comment: I see. `?rbinom` not very clear in this regard.
Comment: All the distribution functions are fully vectorized, e.g., you can also do `rnorm(2, mean = c(1, 1e3))`.
Answer: All the distribution functions are fully vectorized, e.g.:
set.seed(42)
rbinom(2, 1, c(0.01, 0.99))
#[1] 0 1

rnorm(2, mean = c(1, 1e3))
#[1]    0.4353018 1000.3631284

rf(2, c(1, 10), c(10, 1))
#[1] 1.408771 4.677464

etc.


Ember Error: Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number

Question: Router.js
Router.map(function() {
  this.route('artists', function() {
    this.route('artist', {path: ':id'}, function() {
      this.route('songs');
    });
  });
});

routes/artists.js
export default Ember.Route.extend({
    model(){
        return this.store.findAll('artist');
    }
});

routes/artists/artist.js
export default Ember.Route.extend({
    model(params){
        console.log(params.id);  //printed a valid id (-KP_nH0EMk3zYqhiWJZ1)
        return this.store.findRecord(params.id);
    }
});

templates/artists.hbs
{{#each model as |artist|}}

 {{#link-to 'artists.artist.songs' artist}} {{artist.name}} {{/link-to}}

{{/each}}

error
ember.debug.js:28535 Error while processing route: artists.artist.songs Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number Error: Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number
    at new Error (native)
    at Error.EmberError (http://localhost:4200/assets/vendor.js:26708:21)
    at assert (http://localhost:4200/assets/vendor.js:16548:13)
    at Object.assert (http://localhost:4200/assets/vendor.js:26472:34)
    at assert (http://localhost:4200/assets/vendor.js:68333:37)
    at Class.findRecord (http://localhost:4200/assets/vendor.js:76157:41)
    at Class.model (http://localhost:4200/assets/ember-basics.js:259:22)
    at Class.deserialize (http://localhost:4200/assets/vendor.js:37088:19)
    at Object.applyHook (http://localhost:4200/assets/vendor.js:63718:30)
    at Object.runSharedModelHook (http://localhost:4200/assets/vendor.js:61926:33)logError @ ember.debug.js:28535error @ ember.debug.js:28478triggerEvent @ ember.debug.js:28594trigger @ ember.debug.js:53473trigger @ ember.debug.js:53287(anonymous function) @ ember.debug.js:53107tryCatch @ ember.debug.js:53806invokeCallback @ ember.debug.js:53821publish @ ember.debug.js:53789publishRejection @ ember.debug.js:53724(anonymous function) @ ember.debug.js:32054invoke @ ember.debug.js:333flush @ ember.debug.js:397flush @ ember.debug.js:205end @ ember.debug.js:560run @ ember.debug.js:682run @ ember.debug.js:21139(anonymous function) @ firebase.js:134c @ firebase.js:396(anonymous function) @ firebase.js:387Ub @ firebase.js:283vc @ firebase.js:271wc @ firebase.js:270(anonymous function) @ firebase.js:454(anonymous function) @ firebase.js:427h.wd @ firebase.js:432af.wd @ firebase.js:335(anonymous function) @ firebase.js:333yd @ firebase.js:286La.onmessage @ firebase.js:285
ember.debug.js:32096 Error: Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number
    at new Error (native)
    at Error.EmberError (http://localhost:4200/assets/vendor.js:26708:21)
    at assert (http://localhost:4200/assets/vendor.js:16548:13)
    at Object.assert (http://localhost:4200/assets/vendor.js:26472:34)
    at assert (http://localhost:4200/assets/vendor.js:68333:37)
    at Class.findRecord (http://localhost:4200/assets/vendor.js:76157:41)
    at Class.model (http://localhost:4200/assets/ember-basics.js:259:22)
    at Class.deserialize (http://localhost:4200/assets/vendor.js:37088:19)
    at Object.applyHook (http://localhost:4200/assets/vendor.js:63718:30)
    at Object.runSharedModelHook (http://localhost:4200/assets/vendor.js:61926:33)

I am facing this error when navigatiing to "artists/{id}" and "artists/{id}/songs". I tried printing params.id in artists/artist route. i can see a valid id in console. can someone guess what could be the possible mistake
Comment: in artists route try this.store.findRecord('artist',params.id)
Answer: findRecord requires two mandatory arguments modelName and id, in your case model name is missing.
routes/artists/artist.js
export default Ember.Route.extend({
    model(params){
        console.log(params.id);  //printed a valid id (-KP_nH0EMk3zYqhiWJZ1)
        return this.store.findRecord('artist',params.id);
    }
});

Reference: http://emberjs.com/api/data/classes/DS.Store.html#method_findRecord


Take some value from a vector

Question: i have 2 vectors like these:
std::vector <svm_node *> vettProbX;

std::vector <double> vettProbY;

Where svm_node is a structure.
I need to take, from  these vectors, only an element each 50. For example, if the dimension of vettProbY was 1000, i would obtain only 20 values (0,50,100,150,200..).
How can i implement this algorithm for both of them?
i think that for the vettProbY i could implement something like this:
std:: vector <double> NewVettProbY

for(int i=0; i<vettProbY.size(); i++)
{
 if((i % 50)=0)
  NewVettProbY.push_back(vettProbY[i]);
}

but i don't know how to implement the same thing for the vector vettProbX.
Thanks for any help.
Comment: Why can't you do it exactly the same way? (Although the method you have doesn't seem too efficient, why not just increement i by 50 each time?)
Comment: makes it sense to put both - the svm_node* and the double - together? Like this: struct Foo { svm_node* nd_; double d_; }; std::vector< Foo > vettProb;
Comment: Does it need to be a new vector, or can it be a [stride view](https://ericniebler.github.io/range-v3/index.html#range-views)?
Answer: The first thing to note is that you are storing raw pointers inside vettProbX:

std::vector<svm_node *> vettProbX;

Are you sure about that? Raw pointers inside STL containers are fine if they are observing pointers; but owning raw pointers are bad and source of leaks!
Another option can be using an STL container with a smart pointer like shared_ptr, e.g.:
std::vector<std::shared_ptr<svm_node>> vettProbX;

(For unique ownership, std::unique_ptr is fine, and more efficient and more lightweight than shared_ptr.)
Anyway, you may want to use some code like this:
std::vector<double> newVettProbY;
for (size_t i = 0; i < vettProbY.size(); i += 50 /* step */)
{
    newVettProbY.push_back(vettProbY[i]);
}

// Assuming:
// std::vector<std::shared_ptr<svm_node>> vettProbX;

std::vector<std::shared_ptr<svm_node>> newVettProbX;
for (size_t i = 0; i < vettProbX.size(); i += 50 /* step */)
{
    newVettProbX.push_back(vettProbX[i]);
}

Answer: Assuming that you need to make copy, not reference sharing. You can do it like that:
std::vector <double> newVettProbY;
std::vector <svm_node *> newVettProbX;
svm_node * newNode;

for(int i=0; i<vettProbY.size(); i+=50)
{
  NewVettProbY.push_back(vettProbY[i]);
  newNode = new svm_node;
  memcpy(newNode, vettProbX[i], sizeof(svm_node));
  newVettProbX(newNode);
}

Here I have assumed that the two vectors are of the same size. Also note that I have improved your for cycle.
Comment: seems fine, i try it now. To delete correctly the created newNode ?
Comment: @zzari delete it when you no longer need the copy. If you do not need to copy the contents, just do not allocate with `new`. Push immediately the pointer. Btw i had a small error in my answer i will edit it immediately
Comment: Better You call the copy constructor `newNode = new svm_node(*vettProbX[i]);`
Comment: @cpp-progger are you sure such exists?
Comment: even if svm_node is a POD, it exists. Of course check for `nullptr` first.
Answer: You could do it with a template function. So you can use it for all your types.
template<typename T>
std::vector<T> get_50th(std::vector<T> const& l) {
    std::vector<T> r;

    for(size_t it=0; it<l.size(); it+=50)
        r.push_back(l.at(it));

    return r;
}

Take some value from a vector


Permutation optimization with three sequences

Question: I have three increasing sequences, $\{a_{i}\}_{i=1}^n$, $\{b_{i}\}_{i=1}^{n}$, $\{c_{i}\}_{i=1}^{n}$, all of which are positive real numbers. And the following optimization problem
$$\min_{(s_1,s_2,\dots,s_n)\\(p_1,p_2,\dots,p_n)}\max\limits_{i} \left\{ \frac{a_i}{b_{s_i}} + c_{p_i} \right\},$$
where $(s_1,s_2,\dots,s_n)$ and $(p_1,p_2,\dots,p_n)$ are permutations of $(1,2,\dots,n)$.
I only can solve the problem when I fix one permutation. How can I optimize the two permutations simultaneously?
Here are my solutions when I fixed one permutation.
If we fixed $(s_1,s_2,\dots,s_n)$, then the value of $\frac{a_i}{b_{s_i}}$ are fixed. We only need to set $(p_1,p_2,\dots,p_n)$ such that the greatest $\frac{a_i}{b_{s_i}}$ matches the smallest $c_{p_i}$ (i.e., $c_1$), the second greatest $\frac{a_i}{b_{s_i}}$ matches the second smallest $c_{p_i}$ (i.e., $c_2$) and so forth.
If we fixed $(p_1,p_2,\dots,p_n)$, we can not do the same operators like before.
This case is much more difficult than the former and I have not formed clear solutions yet.
So sorry to all, I am not a native English speaker and I do my best to express my ideas clearly.
Comment: It comes from my project and I stuck here for a long time.
Comment: I want to give an algorithm to find the solution and use the optimal objective.
Comment: [Related](https://mathoverflow.net/a/307532/91764)
Answer: You can solve the problem via integer linear programming as follows.  For $(i,j)\in \{1,\dots,n\}^2$, define binary decision variables $p_{i,j}$ and $s_{i,j}$.  The problem is to minimize $z$ subject to
\begin{align}
\sum_j p_{i,j} &= 1 &&\text{for all $i$} \tag1\\
\sum_i p_{i,j} &= 1 &&\text{for all $j$} \tag2\\
\sum_j s_{i,j} &= 1 &&\text{for all $i$} \tag3\\
\sum_i s_{i,j} &= 1 &&\text{for all $j$} \tag4\\
z &\ge \sum_j \left(\frac{a_i}{b_j} s_{i,j} + c_j p_{i,j}\right) &&\text{for all $i$} \tag5
\end{align}
Constraints $(1)$ and $(2)$ define $p$ as a permutation.
Constraints $(3)$ and $(4)$ define $s$ as a permutation.
Constraint $(5)$ enforces the minimax objective.
Comment: I will try to solve it analytically in this way.


docker run: how to avoid overlap between Docker and external host on 172.18.x.x IP range

Question: i'm using docker run to test my container locally. I found that it is unable to connect to a certain host in my company's network, failing with "no route to host". It turns out this host has an IP address of 172.18.x.x, which overlaps with Docker's networking.
So, is there a way to change the docker run configuration so that it doesn't claim this particular IP range? I've already tried changing the bip and default-address-pools options in the Docker daemon configuration file, but that didn't solve the problem.
Comment: please check if this helps: https://serverfault.com/questions/916941/configuring-docker-to-not-use-the-172-17-0-0-range
Comment: Thanks, but I tried that and it unfortunately doesn't help, still getting the "No route to host". With other hosts in the same network it works fine, it's really the overlap with the 172.18 range.
Answer: Create a docker config file if one doesn't exist in /etc/docker/daemon.json
Add an entry to the daemon.json with the subnet for the docker bridge0 to run in (you can add your desired subnet here), under the "bip" entry e.g. - "bip": "192.168.1.5/24"
Restart docker service : sudo systemctl restart docker
NOTE: Be ware not to use the loopback address in the subnet, i.e. IPs that end with 0 like 192.168.1.0/24 The bridge0 subnet should have enough addresses for all the containers on the machine that use the default network. skyformation does NOT use the default network.
Verify it worked by running ifconfig docker0 | grep -Po '(?<=inet )[\d.]+' . It should print out the IP address specified in "bip" example of daemon.json like this
{ "bip": "192.168.1.5/24" }

Now in your docker-compose file, add network tab as this.
networks:
  isolated_nw:
    driver: bridge
    ipam:
      config:
        - subnet: 184.108.40.206/16

Now restart your docker container, verify by grepping IP Address of the container. It should work as expected.
Comment: Thanks! This works, but my Docker container is more like a batch job and as I mention this is for testing locally, so I would prefer to not use docker-compose and provide these options to `docker run` instead.
Comment: Yep, it should work with docker run command as well.
Comment: Is it working for you or you need help in attaching network to container ? @KeesKist
Answer: The 172.18.x.x network (ifconfig showed with name br############) seemed to be created when I start the docker-compose.
And this network will be deleted when I run docker-compose down.
Before it being deleted and recreated, the IP address range will not change.
Once it recreates, the default-address-pools options is activated, and the new IP range is up.

My work around solution
Step1:
Add the following to /etc/docker/daemon.json.
{
  // ...
  "default-address-pools": [
    {
      "base": "172.31.0.0/16",
      "size": 24
    }
  ]
  // ...
}

Step2:
Restart docker service.
sudo systemctl restart docker

Step3:
Rebuild the docker-compose.
!!DANGER!! Before you do this, ensure that removing the container then recreate is acceptable.
docker-compose down
docker-compose up -d


wsadmin + jython restart WAS appserver

Question: Is it possible to stop/start WAS appserver using wsadmin (jacl/jython). I want to detele all caches on profile and then restart WAS appserver. I'm using wsadmin as standalone.
Comment: Why don't you use stopServer and startServer command?
Comment: You didn't specify whether your question applies to a WebSphere ND deployment or a standalone application server and from where you want to run wsadmin (locally or remotely).
Answer:
From wsadmin you may issue a command (using Jython):
AdminControl.invoke(AdminControl.queryNames('WebSphere:*,type=Server,node=%s,process=%s' % ('YourNodeName', 'YourServerName')), 'restart')

works with WAS Base & ND.
With ND you have another option:
AdminControl.invoke(AdminControl.queryNames('WebSphere:*,type=Server,node=%s,process=%s' % ('YourNodeName', 'YourServerName')), 'stop')
# now your server is stopped, you can do any cleanup
# and then start the server with NodeAgent
AdminControl.invoke(AdminControl.queryNames('WebSphere:*,type=NodeAgent,node=%s' % 'YourNodeName'), 'launchProcess', ['YourServerName'], ['java.lang.String'])

Answer: Check out the wsadminlib script. It has over 500 methods written for you to perform specific wsadmin tasks. Also check out related wsadminlib blog - you'll definitely want to view the powerpoint on this site to get an overview of usage.
You don't specify which caches you would like to clear. If you want to clear dynacache, wsadminlib offers clearDynaCache, clearAllProxyCaches, and others as well as server restart methods.
Example usage:
import sys
execfile('/opt/software/portalsoftware/wsadminlib/wsadminlib.py')
clearAllProxyCaches()
for (nodename,servername) in listAllAppServers():
    clearDynaCache( nodename, servername, dynacachename )
    save()
    maxwaitseconds=300
    restartServer( nodename, servername, maxwaitseconds)

wsadmin + jython restart WAS appserver


illegal cyclic reference involving object models

Question: When I try to pass a list to the view page of a Play application I receive an error:
illegal cyclic reference involving object models

Error screenshot:

models.scala.html:
@(liValues: List[String])
@for(value <- liValues){

@value

}

entry in routes files:
GET     /models/tictactoe                    controllers.ModelController.index

index method in ModelController.scala where I pass the values:
def index = Action {
  Ok(views.html.models(List("Link1" , "Link2" , "Link3")))
}

Complete ModelController:
package controllers

import javax.inject._
import play.api.libs.json.Json
import play.api.mvc._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class ModelController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  /**
   * Create an Action to render an HTML page with a welcome message.
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index = Action {
    Ok(views.html.models(List("Link1" , "Link2" , "Link3")))
  }

  def sj = Action {

      Ok(Json.toJson(List(1,2,3)).toString());

  }
}

it seems I'm not declaring the list value in the view page correctly ?
Answer: It seems DummyPlaceHolder.scala
package models

/*
 * Empty placeholder object to make sure templates keep compiling (due to
 * imports in template files), even if projects don't have any models.
 */
object DummyPlaceHolder

is interfering with your views.html.models which also has models so the generated template target/scala-2.13/twirl/main/views/html/models.template.scala will have something like
import models._

object models extends ...

which causes illegal cycle. Try changing the name of your template from views.html.models to say views.html.model.


Python equivalent of golang's defer statement

Question: How would one implement something that works like the defer statement from go in python?
Defer pushes a function call to a stack. When the function containing the defer statement returns, the defered function calls are popped and executed one by one, in the scope that the defer statement was inside in the first place. Defer statements look like function calls, but are not executed until they are popped.
Go example of how it works:
func main() {
    fmt.Println("counting")

    var a *int
    for i := 0; i < 10; i++ {
        a = &i
        defer fmt.Println(*a, i)
    }

    x := 42
    a = &x

    fmt.Println("done")
}

Outputs:
counting
done
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0

Go example of a usecase:
var m sync.Mutex
func someFunction() {
    m.Lock()
    defer m.Unlock()
    // Whatever you want, with as many return statements as you want, wherever.
    // Simply forget that you ever locked a mutex, or that you have to remember to release it again.
}

Answer: To emulate defer fmt.Println(*a, i) example, you could use contextlib.ExitStack:
#!/usr/bin/env python3
from contextlib import ExitStack
from functools import partial

print("counting")
with ExitStack() as stack:
    for i in range(10):
        a = i
        stack.callback(partial(print, a, i))

    x = 42
    a = x
    print("done")

Output
counting
done
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0

It is easy to emulate the mutex case:
def some_function(lock=Lock()):
    with lock:
        # whatever

Answer: Python's with statement serves a similar purpose to Go's defer.
The similar code in Python is:
mutex = Lock()

def someFunction():
    with mutex:
        # Whatever you want, with as many return statements
        # as you want, wherever. Simply forget that you ever
        # locked a mutex, or that you have to remember to
        # release it again.

Comment: One thing to remember here is that you need to have a context manager defined to use `with`. Lots of things (`file`s, `threading.Lock`, for instance) come with this built-in, but if you want to do something specific like in the first example, you have to custom build it.
Comment: I build this custom thing  https://github.com/tintin10q/python_json_database_manager
Answer: I've made one there (compatible with 2.x):
@defers_collector
def func():
    f = open('file.txt', 'w')
    defer(lambda: f.close())

    defer(lambda : print("Defer called!"))

    def my_defer():
    recover()

    defer(lambda: my_defer())

    print("Ok )")
    panic("WTF?")

    print("Never printed (((")

func()
print("Recovered!")

Source of defers_collector is:
# Go-style error handling

import inspect
import sys

def panic(x):
    raise Exception(x)

def defer(x):
    for f in inspect.stack():
    if '__defers__' in f[0].f_locals:
        f[0].f_locals['__defers__'].append(x)
        break

def recover():
    val = None
    for f in inspect.stack():
    loc = f[0].f_locals
    if f[3] == '__exit__' and '__suppress__' in loc:
        val = loc['exc_value']
        loc['__suppress__'].append(True)
        break
    return val

class DefersContainer(object):
    def __init__(self):
    # List for sustain refer in shallow clone
    self.defers = []

    def append(self, defer):
    self.defers.append(defer)

    def __enter__(self):
    pass

    def __exit__(self, exc_type, exc_value, traceback):
    __suppress__ = []
    for d in reversed(self.defers):
        try:
            d()
        except:
            __suppress__ = []
            exc_type, exc_value, traceback = sys.exc_info()
    return __suppress__

def defers_collector(func):
    def __wrap__(*args, **kwargs):
    __defers__ = DefersContainer()
    with __defers__:
        func(*args, **kwargs)
    return __wrap__

Comment: A _defer_ implementation partly inspired by this answer is available as part of [pygolang](https://pypi.org/project/pygolang/): https://stackoverflow.com/a/53069630/9456786
Answer: A defer implementation partly inspired by @DenisKolodin answer is available as part of pygolang, 2:
   wc = wcfs.join(zurl)    │     wc = wcfs.join(zurl)
   defer(wc.close)         │     try:
                           │        ...
   ...                     │        ...
   ...                     │        ...
   ...                     │     finally:
                           │        wc.close()

Answer: This complement to jfs' answer pushes the ExitStack idea a bit further with the help of decorators:
@with_exit_stack
def counting(n, stack):
    for i in range(n):
        stack.callback(print, i)

@with_exit_stack
def locking(lock, stack):
    stack.enter_context(lock)
    # whatever

with_exit_stack is defined as follows:
import functools
import contextlib

def with_exit_stack(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        with contextlib.ExitStack() as stack:
            return func(*args, **kwargs, stack=stack)

    return wrapper

Answer: I've tried to make an equivalent for fun (only tested as a proof of concept)
Here is is:
import os
import inspect

class defer:
    """
    Proof of concept for a python equivalent of golang's defer statement

    Note that the callback order is probably not guaranteed

    """
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

        # Add a reference to self in the caller variables so our __del__
        # method will be called when the function goes out of scope
        caller = inspect.currentframe().f_back
        caller.f_locals[b'_' + os.urandom(48)] = self

    def __del__(self):
        self.callback(*self.args, **self.kwargs)

Usage example:
def main():
    first()
    second()

def first():
    print('- first')
    defer(lambda: print('   - deferred'))
    print('- first exit')

def second():
    print('- second')

if __name__ == '__main__':
    main()

Answer: Little late to the party but I built a pip-installable library that does just this! Check out python-defer.
from defer import defer

def foo():
  print(", world!") in defer
  print("Hello", end="")
  # do something that might fail...
  assert 1 + 1 == 3

$ python foo.py
Hello, World!
Traceback (most recent call last):
  File "foo.py", line 7, in <module>
    assert 1 + 1 == 3
AssertionError


Rewrite link field in views

Question: I'm trying to rewrite the output of a link field in a view in Drupal 8, to include a font-awesome icon, I have tried overriding my view field template in twig, but all i'm getting in the twig template is {{ output }}, which contains a rendered link already.
Desired output

Current output
http://www.facebook.com/profile

Answer: Have you tried doing this through the Views UI? You can use the Rewrite results as per the image below. In the rewrite output you should be able to add your font-awesome div.
You might need to use the output this field as a link option to make it clickable (you can use the replacement token of your link field) but that dependends on the field, so I am not sure if it is required.

Source: https://www.drupal.org/node/1578524
Comment: I can confirm this will work, however there is a bug at the moment with external url's and rewrite as link in core (8.0.2):  https://www.drupal.org/node/2488540

Rewrite link field in views


How to do push data to datalayer after Ajax callback?

Question: I have a view with many elements and use views load more -> view using views load.
Modules:

Views Load More.
dataLayer.

Is it possible send datalayer event after load elements with AJAX?
I am tracking with Tag manager (Google).
Answer: I had the same problem. Events were only sent first time and then never.
I solved it purging completely cache, and fixing my google tag.


Find the sum of the following infinte series

Question: $0<a<b<1$
$$\sum_{k=1}^{\infty} \int_{1/(k+b)}^{1/(k+a)} \frac{1}{1+x} \, dx$$
I found out the integral directly. But how to find sum? I've got suggestion that it can be tackled by telescoping technique, but couldn't find anything that gets cancelled.
Thank you.
Comment: HINT $$1 + \frac 1{k+a} = \frac{k+a+1}{k+a}$$
Comment: If you've already computed the integral, then include that work in your question statement.
Comment: @Semiclassical Integral is pretty obvious. We have a direct formula for that. That's why I didn't include.
Answer: $$
\int_{1/(k+b)}^{1/(k+a)} \frac{1}{1+x} \, dx \\
= \log(1 + 1/(k+a)) - \log(1 + 1/(k+b))  \\
= \log\frac{a + k + 1}{b + k+1} - \log\frac{a + k }{b + k}
$$
So here the telescoping comes in:
$$
\sum_{k=1}^{N} \int_{1/(k+b)}^{1/(k+a)} \frac{1}{1+x} \, dx
= \log\frac{a + N + 1}{b + N+1} - \log\frac{a + 1 }{b + 1} \\
= \log(1 + \frac{a -b}{b + N+1} ) - \log\frac{a + 1 }{b + 1}
$$
Taking the limit $N \to \infty$ finally gives
$$
\sum_{k=1}^{\infty} \int_{1/(k+b)}^{1/(k+a)} \frac{1}{1+x} \, dx =   \log\frac{b + 1 }{a + 1}
$$
Comment: Thanks for the detailed answer.


Interceptação e redirecionamento

Question: Minha estrutura
localhost/sistema
localhost/sistema/.htaccess
localhost/sistema/site/index.php

Objetivo: Ao acessar qualquer url dentro do domínio ocorrer a interceptação e o redirecionamento à página index.php que está no diretório localhost/sistema/site
tentativa no .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -t [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.$ - [NC,L]
RewriteRule ^.$ site/index.php [NC,L]

Resultado.
Erro 500

Onde estou errando?
Observação:
Linha
LoadModule rewrite_module modules/mod_rewrite.so

descomentada no httpd.conf
e,
DocumentRoot "C:\Program Files\Apache24\Apache24/htdocs"
<Directory "C:\Program Files\Apache24\Apache24/htdocs">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

Erro do log do Apache:
htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Porém, o .so está na pasta
Comment: O que a linha `RewriteRule ^.$ - [NC,L]` faz?
Comment: pega as requisições da raíz
Answer: uso algo mais simples , funciona para o que eu preciso aqui , testa ai
RewriteEngine On
# pasta base de referencia
RewriteBase /app
# Proteje pastas de serem acessadas diretamente
RewriteRule ^(classes|includes|logs) - [F,L]
# arquivo que pode abrir diretamente
RewriteCond %{REQUEST_URI} !(homologa.*.php)$
# qualquer outro arquivo e redirecionado para o index.php
RewriteRule . index.php

Comment: Entõ, só de eu colocar RewriteEngine On já dá o erro 500
Comment: você talvez não tenha compilado o apache com o modulo rewrite , se tiver acesso ao prompt digite o comando:
apachectl -t -D DUMP_MODULES | grep rewrite_module
, verifica se aparece o modulo do rewrite
Answer: Embora tenha sido uma solução que eu não aprove. Mas o que há de se fazer.
Deve haver um recurso à isso. Mas saberemos em breve.
A solução é:
<Directory />
    AllowOverride All
    #Require all alowed
</Directory>

Ou seja, alterar para todo o Apache e não apenas para o localhost como a linha abaixo sugere
DocumentRoot "C:\Program Files\Apache24\Apache24/htdocs"
<Directory "C:\Program Files\Apache24\Apache24/htdocs">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #

    #
    # Controls who can get stuff from this server.
    #
    AllowOverride All
    Order allow,deny
    Allow from All
</Directory>

Interceptação e redirecionamento


How do I kick from my hip ?

Question: I am trying to relearn swimming and notice the importance of kicking from the hip as being the most effective for propulsion and energy consumption. I have tried to imagine am kicking from my hip and I am not. I record myself doing a flutter kick and can see the kick really isn't originating from the hip but the knee. I have tried to visualise that my knee and ankle are made of rubber but it hasn't helped. Unfortunately, am a big guy and heavy at the waist.
Are there any exercises that can specifically help me make my kicks begin at the hip ?
Answer: I am not a swimmer but after searching on many website vertical flutter kicking is the best technique for improving kick and make kicks begin at the hip.
Article on triathlete has a conversation that mention these two drills for focusing on strengthening your core, glute and hip extensors.

Extend Leg Drill
  Swim with one leg extended out of water, then switch to the opposite leg after a 25.
Vertical Kicking With Weight
  Try vertical kicking sets holding a 1–5-pound object out of the water (10 rounds, 45 seconds kicking, 15 seconds off). "During this set, the legs are forced to kick with equal force and direction, while the core and shoulders contract in unison,".

Article from azcentral

Competitive swimmers typically utilize the two-beat cycle, kicking two times for each arm cycle -- essentially one kick per arm stroke. Another option is the six-beat cycle, in which you kick six times for each arm cycle. This is also called the flutter kick. Because it's so fast, it can be tougher to incorporate the hips with the six-beat cycle.

and many websites articles mention vertical kicking as the best way to improve hip kicking. Links to other website articles UWhealth, US MASTERS SWIMMING, Swymnut Masters, SEAHIKER and Enjoy Swimming.
At last Article from SwimSmooth:

A good way to think about kicking from your hips is to squeeze your bum when you kick. It's a bit crude, but imagine you have a large coin between your butt cheeks and you're trying to hold it there whilst you swim. Keep your knees relaxed and drive the kick from the hips.

Note: All the quotes are copied from the respective website and i'm not original author. If I have failed to mention any copyrighted material that is clearly my mistake.

How do I kick from my hip ?


True or False $Re f(z)>0$

Question: Make an examples $f:\Bbb{C}\to\Bbb{C}$ holomorph (If it exists) with the property:(Justify your answer)
$Re f(z)>0$ for all $z\in\Bbb{C}$ and $f$ is not constant.
My attemp: I find a question in Conway that is discussed in
$f : D \rightarrow \mathbb{C} $ analytic. Show $\operatorname{Re}(f(z)) \geq 0$.
But my question is difference. Because we have not the hypothesis   $Re f(z)\geq 0$ and the domain is $\Bbb{C}$ instead of $D$.
So we can not use the open mapping theorem and I think there is not such function!
Comment: Also related: https://math.stackexchange.com/q/229312/42969.
Answer: No such $f$ exists. Suppose a non constant function $f(z)$ and let $f(z)=u+iv$ and consider the function $F(z)=e^{-f(z)}$. Then, $$|F(z)|=|e^{-u-iv}|=e^{-u}$$ Note that since $\Re f(z)= u>0$, it follows that $|F(z)|<1$ and by Liouville's Theorem $F(z)$ is constant.
This implies that $F'(z)=-f'(z)e^{-f(z)}=0$ and this further implies that $f'(z)=0$. Hence, $f(z)$ must be a constant.

True or False $Re f(z)>0$


What is the connection between $(G/K)(H/K) \cong G/H$ and this commutative diagram? (Lang's Algebra, p. 17)

Question: There are two questions here and here that concern the same diagram and result, but they seem to have to do with verifying the details of the diagram. I think I've handled that on my own.
(I have also checked Dummit and Foote p. 98, Aluffi p. 101, and the Wikipedia page on the isomorphism theorems, but none of them show a comparable diagram.)
My question has to do with the connection between $(G/K)(H/K) \cong G/H$ and the diagram. Specifically, is the diagram supposed to say the same thing as the $\cong$ statement? What is the intuition here? I feel like these two things are supposed to be connected in my mind, but at the moment they exist separately in my mind.
For context, the way I understand the $\cong$ statement is by following Lang's explanation that there is a surjective homomorphism $G/K \to G/H$ that has $H/K$ as its kernel. Applying the fact that $G/\text{ker } \phi \cong \text{im } \phi$ gives the result.
Excerpt:

Edit:
Looking at the diagram again, I see that we have two exact sequences that go $\text{trivial group} \to \text{kernel} \to \text{group} \to \text{image} \to \text{trivial group}$. But I still don't see the connection to the $\cong$ statement.
Comment: This is all about https://en.m.wikipedia.org/wiki/Exact_sequence and the first isomorphism theorem.
Comment: For any exact sequence of groups $0 \to A \to B \to C \to 0$ we have $B/A \cong C$ by the isomorphism theorems. Since $A$ is the kernel of the second map (which is surjective)
Answer: A sequence of the form,
$$ 1 \to G_1 \to G_2 \to G_3 \to 1 $$
being exact (in the category of groups) is exactly the same information as,
(1) an inclusion $G_1 \subset G_2$ making $G_1$ a normal subgroup of $G_2$
(2) an isomorphism $G_2 / G_1 \xrightarrow{\sim} G_3 $
Explicitly, the exactness of the sequence says
(1) $G_1 \to G_2$ is injective
(2) the image of $G_1 \to G_2$ equals the kernel of $G_2 \to G_3$
(3) $G_2 \to G_3$ is surjective
Putting these together with the first isomorphism theorem gives what I claimed.
Lang's diagram shows that $(G / K) / (H / K) \cong (G / H)$ $\textit{via the given map}$ $G/K \to G/H$. So you get a bit more than the isomorphism you also get an explicit description of the isomorphism and the fact that the diagram commutes tells you this isomorphism is compatible with the "tautological" isomorphism $G/H \to G/H$ which is what the top row expresses.
Comment: Thanks for your answer. What I think I understand so far is that the bottom row of the diagram contains the statement $(G/K)(H/K) \cong G/H$, and then there is a sort of "compatibility" with the top row because it describes the tautological isomorphism, which has the same image as the isomorphism in the bottom row.
Comment: @Novice that is a good way to think about what the diagram says
Answer: Perhaps it would be more enlightening if you wrote it a bit more abstractly.
You have short exact sequences $H\to G\to Q_1$ and $H/K\to G/K\to Q_2$. This means that $Q_1\cong G/H$ and $Q_2\cong (G/K)/(H/K)$.
Then you have an isomorphism $Q_1\to Q_2$ (denoted by $\operatorname{id}$ on your diagram) and quotient maps $G\to G/K$ and $H\to H/K$ making the diagram commute. This means that $Q_1$ and $Q_2$ are isomorphic and the isomorphism is exactly what you expect it to be, namely, the $H$-coset of $g\in G$ is taken to the $H/K$-coset of $gK$.
Answer: So the idea is that this is a commutative diagram and these are something called exact sequences. The gist is that a sequence $H \xrightarrow[]{\phi} G \xrightarrow[]{\psi} K$ is said to be exact if $\ker(\psi) = \text{im}(\phi)$. Here, the maps are group homomorphisms and $G,H,K$ are groups.
Claim: If $0 \xrightarrow[]{\phi} H \xrightarrow[]{\psi} G$ exact, then $\psi$ is injective.
Proof: We have $\ker(\psi) = \text{im}(\phi)$, $\text{im}(\phi) = 0$ (since there's only one way to have a homomorphism from $0$ to $H$), and so $\ker(\psi) = 0$ is trivial.
Claim: If $G \xrightarrow[]{\phi} K \xrightarrow[]{\psi} 0$ exact, then $\phi$ is surjective.
Proof: There's only one homomorphism from $K$ to $0$ (map everything to $0$) so $\ker(\psi) = K$. Since the sequence is exact, $\text{im}(\phi) = \ker(\psi) = K$.
Now we can extend the definition of exact sequences to include multiple terms in the (hopefully) obvious way. Let's look at the exact sequence $0 \rightarrow H \xrightarrow[]{\phi} G \xrightarrow[]{\psi} K \rightarrow 0$, where these are all groups and group homomorphisms. I omit the names for the maps $0 \rightarrow H$ and $K \rightarrow 0$ since, as noted above, there's only one way to do it. Now $\ker(\psi) = \text{im}(\phi) = H$ (here I'm identifying $H$ with its image as a subgroup of $G$) since $\phi$ is injective. We know $\psi$ is surjective by above, so use the first isomorphism theorem to get
$$ G/\ker(\psi) = G/H \cong K.$$
Now you need to verify that your sequences are actually exact sequences (use the commutativity of the diagram) and then you can invoke this result.


Is there a jquery video player that handle mp4 video files?

Question: I need to find a jquery video player that can play mp4 files.
please help me
Thanks.
Comment: searching "jquery video player +mp4" in google gave me http://jquery.malsup.com/media/
Comment: You just need a JS video player that handles MP4, not a jQuery-specific video player... (At least, in my opinion.)
Answer: I've come across a couple of free jQuery based video player scripts:
http://flarevideo.com/
http://videojs.com/jquery/
Both of those first try a HTML5 video tag then fallback to Flash.


How to test for differences between two distributions with percentages?

Question: Imagine there are two distributions:
Distribution 1 lists the shares of each ice cream flavor of all favourite flavors in village A:
Vanilla 20%
Chocolate 60%
Strawberry 20%

Distribution 2 lists the shares of each ice cream flavor of all favourite flavors in village B:
Vanilla 30%
Chocolate 40%
Strawberry 30%

How can I test these two lists for significant differences? I think a Chi-squared-test is not possible, because the values are percentages.
Comment: If all you have are percentages then there's no way to do a formal test since you have no information on sample size.
Comment: With an N of 600, you will be able to conduct a chi-square test, absent very unusual circumstances (like many flavors and low frequencies).
Comment: The round numbers suggest a very small sample size. Do you know the sample size?  If so, you can run a chi sq.
Comment: @JoelW. It's a notional distribution. My original sample size is much larger. It contains more than 600 samples.
Answer: If you have 600 respondents in each city, then you can do a chi-squared
test for homogeneity (of distributions in the two cities). In R, the
basic computation looks like this:
DTA = matrix(c(120,180, 360,240,  120,60,  0,120), byrow=T, nrow=4)
DTA
     [,1] [,2]
[1,]  120  180
[2,]  360  240
[3,]  120   60
[4,]    0  120
chisq.test(DTA)

        Pearson's Chi-squared test

data:  DTA
X-squared = 176, df = 3, p-value < 2.2e-16

The small P-value indicates people in the two cities have different
preferences for flavors of ice cream. I will leave it to you to find
the expected counts in each cell and to compute the chi-squared statistic.
For the so-called chi-squared statistic to have approximately the
distribution $\mathsf{Chisq}(df = 2),$ all of the expected counts should
be above 5. (Some authors say all above 3 and most above 5.)
However, if you have only 20 subjects in each city, then the data table
and chi-squared test are as shown below:
DTA2 = DTA/30
DTA2
     [,1] [,2]
[1,]    4    6
[2,]   12    8
[3,]    4    2
[4,]    0    4

chisq.test(DTA2, sim=T)

    Pearson's Chi-squared test with simulated p-value (based on 2000 replicates)

data:  DTA2
X-squared = 5.8667, df = NA, p-value = 0.1229

Here not all of the expected counts are sufficiently large.
For example, $$E_{41} = E_{42} = \frac{4(20)}{40} = 2 < 5.$$ Thus, the chi-squared
statistic does not have distribution $\mathsf{Chisq}(df = 2).$ In R statistical
software, the procedure chisq.test can simulate the distribution of the chi-squared statistic and provide an approximate P-value; here above 5%.
There is much less information with only 20 subjects in each city. Unfortunately,
for the (presumably fake) percentages you provided, differences are not large
enough that the test can find a significant difference in the preference distribution between
the two cities.
Notes:
(a) Clusters of bar charts for the two cities would look the same (except
for numbers on axes) in our examples whether we have 1200 subjects overall
or 40. In general, it is not possible to tell from looking at bar charts
whether the two cities differ. Such bar charts should always have
footnotes with results of chi-squared tests.
(b) For a chi-squared test, the degrees of freedom depend on the
number of levels of each categorical variable [here $(r-1)(c-1) = 3)],$
not on the sample sizes.


Use Cocoapods for private iOS Framework

Question: I'm working on an iOS framework and I would like to make it available to other developers to integrate within their "client" apps by including them in their Podfile, such as:
pod 'MyFramework'

But I can't share the actual source code for it due to some licensing restrictions. The examples I found online for developing iOS frameworks and setting up their podspec files are typically pointing to a repository on github or others and that seems to make the source code available in the developers' app after they run:
pod install

Do I have to share the source code from my framework with the developer? What is the best way (on both the framework setup in cocoapods and the client app in its Podfile) to make sure I can share MyFramework.framework but not its source code?
Note that I'm using Swift 3 for this project.
Thank you
al

Podfile (client):
target 'TestSDK' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
pod 'MySDK', :path => '/path/to/SDK/'
  # Pods for TestSDK
end

MySDK.podspec:
Pod::Spec.new do |s|
    s.name              = 'MySDK'
    s.version           = '1.0.0'
    s.summary           = 'A really cool SDK that logs stuff.'
    s.homepage          = 'http://example.com/'

    s.author            = { 'Name' => 'firstname.lastname@example.com' }
    s.license           = { :type => 'Apache-2.0', :file => 'LICENSE' }

    s.platform          = :ios
s.source = { :http => 'https://bitbucket.org/username/reponame/src/master/MySDK.zip' }
    s.ios.deployment_target = '9.3'
    s.ios.vendored_frameworks = 'MySDK.framework'
end

Comment: https://eladnava.com/publish-a-universal-binary-ios-framework-in-swift-using-cocoapods/
Comment: Thank you @New16. I will go through it and if you don't mind I'll let you know if I have any other questions.
Comment: I guess I'm almost there.. but the test project still shows the source code under Pods > Development Pods > FRAMEWORK_NAME
Comment: I uploaded the zip file that contains my framework to a bitbucket repository instead of a website and I initially struggled to get the URL that I should use for it in the podspec, but then I got it, but the source code still shows up in the demo project.
Comment: Development Pods is for team. Please show the podspec file.
Comment: `code`
d::Spec.new do |s|
    s.name              = 'MyFram'
    s.version           = '1.0.0'
    s.summary           = 'A really cool SDK that logs stuff.'
    s.homepage          = 'http://example.com/'
    s.author            = { 'Name' => 'email@example.com' }
    s.license           = { :type => 'Apache-2.0', :file => 'LICENSE' }

    s.platform          = :ios
s.source = { :http => 'https://bitbucket.org/myuserid/testsdkrepo/src/master/MyFram.zip' }
    s.ios.deployment_target = '9.3'
    s.ios.vendored_frameworks = 'MyFram.framework'
end
`code`
Comment: `d::Spec.new do |s|
    s.name              = 'MyFram'
    s.version           = '1.0.0'
    s.summary           = 'A really cool SDK that logs stuff.'
    s.homepage          = 'http://example.com/'
    s.author            = { 'Name' => 'email@example.com' }
    s.license           = { :type => 'Apache-2.0', :file => 'LICENSE' }

    s.platform          = :ios
s.source = { :http => 'https://bitbucket.org/myuserid/testsdkrepo/src/master/MyFram.zip' }
    s.ios.deployment_target = '9.3'
    s.ios.vendored_frameworks = 'MyFram.framework'
end
`
Comment: Sorry, novice user of stackoverflow :(
Comment: With the above set up, it shouldn't show. Give me the Folder Structure where the source code is visible. If your class is public, the public methods are visible and not its implementation.
Comment: I added a picture of my dir structure above.
Comment: I can tell when I run the pod install on the client project that it doesn't take time to download the framework from the link that I provided, which is on bitbucket.
Comment: Okay run `pod cache clean YOUR_FRAMEWORK` and `pod install`. CocoaPods master repo doesn't update unless there is any changes in the PodSpec.
Comment: $ pod cache clean MySDK
1: MySDK v1.0.0 (External)
2: MySDK v1.0.0 (External)
It asked: "Which pod cache do you want to remove?"
I entered 2 then issued the command again and it removed both.
But I still can't see the MySDK.framework in the TestSDK project (after I open TestSDK.xcworkspace)
By the way, my Podfile under TestSDK directory contains:
`target 'TestSDK' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
pod 'MySDK', :path => '/path/to/SDK/'
  # Pods for TestSDK
end`
Comment: It is difficult to understand what you are saying. Can you send a copy of your Podfile and Podspec files.
Answer: Hopefully this will help others. I ended up solving this issue by hosting the zip file that contains the framework along with my README.md and LICENSE (and later a CHANGELOG.md) and pointed the podspec's s.source to it. The only issue that I have now is that on cocoapods.org, it shows that the language is in Objective-C rather than Swift, but I think that should be an easy fix. Otherwise, I'm now able to have the framework on trunk and use Pod MySDK in a client app.
Comment: Thanks @New16 for your assistance. Not sure if you know about that language setting, but I got the private pod working by following your leads and doing more research :)

Use Cocoapods for private iOS Framework


NodeJS: How to get absolut path - as 'path' is not working

Question: In my nodeJS application (meteorJS) I need to use an absolut path for creating a file via fs.createWriteStream:
const absolutePath = '/Users/Anybody/Documents/Project/imports/temp'
if (Meteor.isServer) {
  const result = new Promise(function (resolve, reject) {
    const gfs = Grid(
      MongoInternals.defaultRemoteCollectionDriver().mongo.db,
      MongoInternals.NpmModule
    )
    const readerStream = gfs.createReadStream({ _id: id })
    const writerStream = fs.createWriteStream(absolutePath + 'temp.mp4')
    // ...
  })
}

This is how the code looks like for development, which I do on macOS. The production version of the application is deployed to an ubuntu server.
So the absolute path is different.
I tried to use path:
const path = require('path')
const absolutePath = path.resolve('/imports/temp')

But this gives me only /imports/temp (on macOS)
Comment: Possible duplicate of [Determine project root from a running node.js application](https://stackoverflow.com/questions/10265798/determine-project-root-from-a-running-node-js-application)
Answer: You can use process.env.PWD to get your base path of you project. Then you can add your remaining folder segment path.
var base = process.env.PWD;
const absolutePath = base + '/imports/temp';