Expected number of sequences

Question:
Problem: What is the expected number of sequences of $3$ heads in $50$ tosses of a coin?

I am a bit confused about this problem in my course. So far we defined expectation value as:
$$E[X]= \sum_{x=0 }^n  x  \cdot  P[X=x] $$
Which tells us the expected value, or mean of a certain experiment. However, now they go and just pick a certain value without explaining how this is done. Normally instead of 3, it would say "$X$". How is this done?
I know that there are $2^{50}$ possible sequences as every entry can be either heads or tails.
Comment: I don't see an easier way of doing the problem.  And indicator variables are pretty easy to use.  I suggest looking that up.
Comment: Some clarification might be needed.  Suppose your string was $HHHH$.  Is that two sequences of three heads?
Comment: I think they count that as 1. So far we have only been counting $3$ and then we stop.
Comment: Well, you need to clarify that point.  Either way, though, you can do it with indicator variables.  For $i\in \{1,\cdots, 48\}$ let $X_i$ be the indicator variable which is $1$ if a "good" block (however defined) starts at the $i^{th}$ slot.  Easy to compute the expected value of $X_i$ and then use Linearity.
Comment: This sounds way too advanced for a first lecture into introductory probability theory. We only know linearity and coin tosses.
Comment: If you know linearity, then you probably saw the use of indicator variables.  That's usually the first application.
Comment: I saw $E[X+Y]= E[X] + E[Y]$
Answer: This is a straight forward exercise in the use of indicator variables.
Note that a string of the form $HHH$ can start anywhere from the first slot to the $48^{th}$.  For $i\in \{1,\cdots, 48\}$ let $X_i$ be the indicator variable for the $i^{th}$ slot.  Thus, $X_i=1$ if a good sequence begins on the $i^{th}$ slot and $X_i=0$ otherwise.
By Linearity $$E=E\big [\sum_{i=1}^{48}X_i\big ] =\sum_{i=1}^{48}E[X_i]$$
Now, the $X_i$ don't all have the same expectation, $X_1$ and $X_{48}$ are different than all the others (which all equal each other).
To handle $X_1$ note that the only good sequence that starts in the first slot is $HHHT$.  Thus the probability of starting with a good sequence is $\frac 1{16}$, so $E[X_1]=\frac 1{16}$.  A similar computation shows that $E[X_{48}]=\frac 1{16}$ as well.
For $1<i<48$ we get a good sequence starting in slot $i$  by $THHHT$, where the first $H$ is in the $i^{th}$ slot.  Thus the probability that a good string starts in slot $i$ is $\frac 1{32}$
Combining all this we see that $$\boxed {E=2\times \frac 1{16}+46\times \frac 1{32}=\frac {25}{16}=1.5625}$$
Comment: Why is $TTT$ a good string?  As I read the problem we need $THHHT$ if we are in the middle.  We can delete one $T$ at the ends.
Comment: @RossMillikan  My computation takes all that into account, or at least it intends to.  My point was that a $3-$ sequence, either $HHH$ or $TTT$ can start anywhere from slot $1$ to slot $48$.
Comment: @RossMillikan  Oh, sorry.  for some reason I read the problem as looking for three of a kind in a row.  Now I see that only Heads is accepted.  I'll edit accordingly.
Comment: @RossMillikan  reviewing the edit history, the problem originally did accept $HHH$ or $TTT$, the OP changed it at some point after I had posted my solution.  Anyway, I have edited my solution to correspond to the question in its present form.

Expected number of sequences


Why does Applescript run in Script Editor, but error when saved as Application?

Question: My applescript needs to detect its own filename, and the following runs fine on Snow Leopard (10.6)
set my_name to name of me as string
display dialog "Name: " & my_name

It displays "Name: AppleScript Editor" when I run it from AppleScript Editor, and it displays "Name: NewTest" when I save it as an application called NewTest.
When I run it on a Leopare (10.5) machine, it complains "Can't make name of <> into type string."  When I remove the "as string" portion, it runs under Script Editor, returning "Name: Script Editor", but when saved as an application, it errors and says, "Can't get name."
What is different about running in script editor and saving as application under 10.5?
Answer: Here's another thought although I haven't checked. One thing that can cause problems is the command "get". In general when you run a command like "name of me" the command get is implied so you're really running "get name of me". The problem is that the implied "get" is not always the case. So sometimes you have to explicitly say "get". Whenever I have a problem like yours the first thing I try is to add "get" to the command... it's become habit because you just never know. Note that you can always use the word get and never have that issue. As such, try changing your command to "set my_name to (get name of me)". I'd be interested to know if that fixes your 10.5 problem. Also note that a name is already a string so there's no need to coerce the result to a string.
EDIT:
I looked through some of my older scripts. I used the following code to get the name. In my notes I have these comments...
-- this will get the name of the application or script without any file extension
-- it is done using the path because when a script is run from the script menu, and you write set myName to name of me, then the result is "applescript runner" instead of the actual name
-- also it assures that you're getting the name as it appears in the Finder because sometimes the system events process name is different than the Finder name
on getMyName()
    set myPath to path to me as text
    if myPath ends with ":" then
        set n to -2
    else
        set n to -1
    end if
    set AppleScript's text item delimiters to ":"
    set myName to text item n of myPath
    if (myName contains ".") then
        set AppleScript's text item delimiters to "."
        set myName to text 1 thru text item -2 of myName
    end if
    set AppleScript's text item delimiters to ""
    return myName
end getMyName

Comment: I just tried it and the command `get name of me` merely returns the error message "Can't get name". I think this goes back to my theory that an Applescript application is an atypical application.
Comment: Thanks for checking that Philip. I edited my answer so check that out for another solution.
Comment: I appreciate both of your answers, and the help.  My solution ended up closely following the code you have, using the path instead of simply "name of", which for reasons still unknown, returns different things in Leopard and Snow Leopard.  Thanks.
Answer: An Applescript application isn't an "application" in the truest sense of the word. A lot of contexts change, like "get path to me" will be different when run as a script or as an application, because they are still good ol' wonky Applescript as opposed to a Carbon or Cocoa-based application. Running similar code against the Finder...
tell application "Finder"
    set my_name to name as string
    display dialog "Finder: " & my_name
end tell

...behaves as expected because the Finder is a Carbon/Cocoa-based application.
I don't have a real answer other than to say it sounds like there was a change made to the OS relative to the Applescript framework in 10.6 that makes the call to "me" behave more as expected.
I would recommend reading the section in the Applescript guide about the me and it keywords to gain more insight into how me works.


Detect clicks inside google.maps.InfoWindow ({ content: contentString });

Question: Is it possible to detect clicks inside of the infowindow in Google Maps?
var contentString = '
test
';
var infowindow = new google.maps.InfoWindow({
   content: contentString
});

Comment: I edited your question so it did not get closed.
Comment: Your code has invalid string variables, the `href` and the `data-id` attributes should be delimited with `"` to avoid breaking your initial `contentString = '<div  ...`
Comment: thanks, I fixed    var contentString = 'test';
Answer: How about to:

attach click handler to body
utilize Node.contains() to determine whether info window node is clicked or not

For example:
document.body.addEventListener("click", function(event) {
    var anchor = document.querySelector('a[data-id="click"]');
    if (anchor && anchor.contains(event.target)) {
       console.log("Info window is clicked..");
    }
});

Demo
Comment: Hi Vadim Gremyachev, document.body.addEventListener does not work inside iframe


What does "Caching service dependencies ..." mean?

Question: When I shut down Tomcat I get the following:
* Caching service dependencies...                 [ ok ]
* Stopping Tomcat...                              [ !! ]

What does Caching service dependencies mean?
Answer: Are you using Gentoo? When you stop a service, Baselayout checks if there are other services depending on the service you are stopping. If it is the case, they are stopped before, in order of dependencies.
Whenever you restart a service in a distro based on Baselayout, it runs the /sbin/depscan.sh script, which stores dependencies in /var/lib/init.d/depcache. You will observe however that the message is not always printed. That's because while depscan.sh is run each time, it only creates a new cache if any file in /etc/rc.d/, /etc/conf.d/or the file /etc/rc.conf is changed.
For more details, refer to the script itself.
Comment: Yes, it's Gentoo. Is *caching* == *stopping*?
Comment: No, just updating the /var/lib/init.d/depcache file. All services are left in their current started/stopped state.


SQL Server stored procedure - Output Parameters

Question: I have a stored procedure with 25 output parameters. Should all these parameters be supplied / declared or is there a way to selectively declare just a few?
Answer: You have to declare all the assigned OUTPUT parameters in your Execute statement.
Answer: You must declare all of the parameters in the stored procedure definition and in the actual call or execution of the stored procedure, as well as specifying the OUTPUT keyword in declaration and call.
Example:
<code>CREATE PROCEDURE gtest (
    @col1 int,
    @col2 int OUTPUT,
    @col3 int OUTPUT
)AS
SET @col2=@col1;
SET @col3=@col1*@col1;
GO

DECLARE @out INT, @out3 int;

EXEC gtest 12, @out output, @out3 output
SELECT @out, @out3
</code>


Ways of modeling the same variable as both a time-invariant and time-varying predictor

Question: This question has been asked and not answered before here.
I am building a model attempting to predict heroin use over time in patients based on their use of amphetamine-type substances (ATS). ATS use and heroin use are measured in the same questionnaire and therefore any time heroin use is recorded, ATS use is also recorded. There are two potential models I am considering.
Model 1
Model 1 is a three-predictor model. The predictors are:
(i) ATSUseAtBaseline (a time-invariant categorical predictor based on days of ATS use in the 28 days previous to baseline, with three levels of ATS use, none (0 days), low (1-12 days' use), and high (13-28 days' use); the none category is the reference category)
(ii) yearsFromStart a continuous variable indicating how many years from start of treatment the measurement was made
(iii) ATSUseAtBaseline x yearsFromStart interaction
This is the output from the model, a longitudinal mixed effects repeated measures regression with the above predictors as fixed factors and random slopes (i.e. yearsFromStart|participant id. The model was fit in R using the lme() function in the nlme package.
Linear mixed-effects model fit by maximum likelihood
 Data: workDF
       AIC      BIC    logLik
  33606.85 33672.54 -16793.42

Random effects:
 Formula: ~yearsFromStart | pID
 Structure: General positive-definite, Log-Cholesky parametrization
               StdDev   Corr
(Intercept)    4.018394 (Intr)
yearsFromStart 2.992416 -0.871
Residual       4.777283

Fixed effects: heroin ~ yearsFromStart + ATSUseAtBaseline + yearsFromStart:ATSUseAtBaseline
                                        Value Std.Error   DF   t-value p-value
(Intercept)                          1.331320 0.1153107 3335 11.545503  0.0000
yearsFromStart                      -0.741715 0.2332848 1924 -3.179440  0.0015
ATSUseAtBaselinelow                  2.853880 0.2878873 3335  9.913185  0.0000
ATSUseAtBaselinehigh                 4.308878 0.5171080 3335  8.332647  0.0000
yearsFromStart:ATSUseAtBaselinelow  -2.594455 0.5637359 1924 -4.602252  0.0000
yearsFromStart:ATSUseAtBaselinehigh -7.339846 1.8286941 1924 -4.013709  0.0001
 Correlation:
                                    (Intr) yrsFrS ATSUsAtBslnl ATSUsAtBslnh
yearsFromStart                      -0.410
ATSUseAtBaselinelow                 -0.401  0.164
ATSUseAtBaselinehigh                -0.223  0.091  0.089
yearsFromStart:ATSUseAtBaselinelow   0.170 -0.414 -0.428       -0.038
yearsFromStart:ATSUseAtBaselinehigh  0.052 -0.128 -0.021       -0.327
                                    yrsFrmStrt:ATSUsAtBslnl
yearsFromStart
ATSUseAtBaselinelow
ATSUseAtBaselinehigh
yearsFromStart:ATSUseAtBaselinelow
yearsFromStart:ATSUseAtBaselinehigh  0.053

Standardized Within-Group Residuals:
        Min          Q1         Med          Q3         Max
-2.49102026 -0.16320514 -0.16320514 -0.08182908  5.11315552

Number of Observations: 5265
Number of Groups: 3338

So far so good. All predictors are significant, with no ATS use predicting less heroin use at baseline than low ATS use or high ATS use. The rate of reduction in heroin use (in days use in the previous 28 days) each year of treatment is lowest in the group using no ATS at baseline and highest in the group with high ATS use at baseline. There are 3338 participants with 5265 observations (i.e. the overwhelming majority only have one measurement, at baseline).
Model 2
Model 2 is a four-predictor model, including the three predictors in the first model and
(iv) atsFactor: the time-varying equivalent of ATSUseAtBaseline, with the same three levels, none, low, and high.
Here is the output
Linear mixed-effects model fit by maximum likelihood
 Data: workDF
       AIC      BIC    logLik
  33560.04 33638.87 -16768.02

Random effects:
 Formula: ~yearsFromStart | pID
 Structure: General positive-definite, Log-Cholesky parametrization
               StdDev   Corr
(Intercept)    4.085715 (Intr)
yearsFromStart 2.892861 -0.89
Residual       4.716549

Fixed effects: heroin ~ yearsFromStart + ATSUseAtBaseline + atsFactor + yearsFromStart:ATSUseAtBaseline
                                        Value Std.Error   DF   t-value p-value
(Intercept)                          1.299861 0.1154830 3335 11.255865  0.0000
yearsFromStart                      -0.877436 0.2253863 1922 -3.893033  0.0001
ATSUseAtBaselinelow                  0.818656 0.4252261 3335  1.925226  0.0543
ATSUseAtBaselinehigh                 0.933265 0.8938787 3335  1.044062  0.2965
atsFactorlow                         2.312577 0.3586254 1922  6.448447  0.0000
atsFactorhigh                        3.584153 0.7797614 1922  4.596473  0.0000
yearsFromStart:ATSUseAtBaselinelow  -1.346094 0.5846532 1922 -2.302381  0.0214
yearsFromStart:ATSUseAtBaselinehigh -5.079803 1.9771895 1922 -2.569204  0.0103
 Correlation:
                                    (Intr) yrsFrS ATSUsAtBslnl ATSUsAtBslnh atsFctrl atsFctrh
yearsFromStart                      -0.408
ATSUseAtBaselinelow                 -0.248  0.180
ATSUseAtBaselinehigh                -0.116  0.080  0.179
atsFactorlow                        -0.032 -0.093 -0.735       -0.182
atsFactorhigh                       -0.016 -0.033 -0.173       -0.816        0.219
yearsFromStart:ATSUseAtBaselinelow   0.148 -0.415 -0.536       -0.017        0.363   -0.006
yearsFromStart:ATSUseAtBaselinehigh  0.044 -0.114  0.013       -0.499       -0.042    0.405
                                    yrsFrmStrt:ATSUsAtBslnl
yearsFromStart
ATSUseAtBaselinelow
ATSUseAtBaselinehigh
atsFactorlow
atsFactorhigh
yearsFromStart:ATSUseAtBaselinelow
yearsFromStart:ATSUseAtBaselinehigh -0.009

Standardized Within-Group Residuals:
        Min          Q1         Med          Q3         Max
-2.52320797 -0.15744819 -0.15744819 -0.06879067  5.32278040

Number of Observations: 5265
Number of Groups: 3338

The addition of the time-varying predictor has changed things. The significant differences in intercept coefficients for the time-invariant ATS use predictor ATSUseAtBaseline are no longer significant. Even the interaction coefficients for these time-invariant versions of the predictor are no longer as strong. The time-varying predictor is a strong predictor in this model. Low ATS use at any time is associated with an increase in heroin use of 2.31 days, and high ATS use is associated with an increase heroin use of 3.6 days!
A likelihood ratio test of the two models...
         Model df      AIC      BIC    logLik   Test  L.Ratio p-value
tiModel1     1 10 33606.85 33672.54 -16793.42
tvModel2     2 12 33560.04 33638.87 -16768.02 1 vs 2 50.80377  <.0001

...shows that the addition of the time-varying predictor in tvModel2 has increased the predictive power of the first model (tvModel1) considerably.
However the problem for interpreting this model is that the values of the time-invariant predictor ATSUseAtBaseline and the time-varying predictor atsFactor at time = 0 are identical. The fact that these baseline measurement make up 3338/5265 = 64% of all observations makes me think that there is some serious confounding of the two predictors going on, making interpretation of either variable very tricky.
So my questions are:
1. Is it ok to use the same variable as both a time-invariant and a time-varying predictor in the same model?
Even if the answer is "No." that will help.
2. If it is ok to include both, how do I resolve the ambiguities between the time-invariant and the time-varying predictors?
Comment: It is a bit difficult to understand how atsusebaseline and atsfactor are exactly related.. baseline is the first observation of atsfactor? Or the mean over atsfactor over individual observations? Or other?
Comment: @Alex.C-L-ReinstateMonica I have the same thought, though it would appear your suggestion would not be true otherwise the there would be perfect multicolinearity between `ATSUseAtBaseline` and the `atsFactor0` dummy which should generate a warning.  @llewmills, please can you clarify and also include the actual model output for both models.
Comment: ...I mean including the model formula, random effects estimation etc..and an 'str(data` and `summary(data)' would also be useful.
Comment: thanks for commenting everyone. Yes @Alex. C-L - Reinstate Monica (who is Monica by the way, have seen this tag many times?), `ATSUseAtBaseiline` is the first observation of `atsFactor`. It is compulsory for all patients being admitted to the drug and alcohol treatment service where this study was conducted to have their frequency of drug and alcohol use in the previous 28 days recorded on the first day of treatment. Follow-up measurements during treatment are far less common as they are not compulsory.
Comment: @Robert Long I have added the full summary output to my origonal post.
Answer: In general, it would not be a problem including the value of ATS at baseline in the model and also its time-varying version. This is also some times done in longitudinal data for the time variable itself. The motivation to do this, for example, when you have a significant increase or decrease in your outcome after baseline (e.g., in patients after an operation).
With that being said, with time-varying covariates, in general, you need to be careful of the functional form, i.e., the type of association you postulate. By simply including the time-varying covariate in the model you assume a kind of a "cross-sectional" association, i.e., the outcome at time $t$ is associated with the value to the covariate at the same time point $t$. On some occasions, this may not be what you want. For example, it could be more meaningful to include a lagged association postulating that the outcome at time $t$ is associated with the value of the covariate at $t - c$ or that the outcome at $t$ is associated with all past values of the covariate via a cumulative effect.
Comment: Thank you @Dimitiris Rizopoulos that is very heartening news. I think both versions of the predictor would offer slightly different insights. And I love the idea of a lagged predictor. So if one believed that increased ATS use leads to increased heroin use 3 months after the increase in ATS use one would what, create a lagged predictor via something like `df$yearsFromStart_lag <- df$yearsFromStart - 0.25`(bearing in mind the `yearsFromStart` variable is in years), is that correct?


What is the y value for the circle whose radius is $\frac{1}{4}$ that makes it tangent to the function $e^{-x^2}$

Question: I have seen videos explaining why the area under the curve of the graph whose equation is $y = e^{-x^2}$ is $\sqrt{\pi}$
So I thought myself we can probably inscribe circles in there since the area is related to $\pi$
So I tried this with a circle whose radius is $\frac{1}{\sqrt{2}}$ and started trying to find the $y$ coordinate of the circle that'd make it perfectly tangent to the graph of the function.
I tried calculating that value, but to no avail, too complicated for me.
I tried to round it using Desmos and I went on to see at which value the circle is approximately tangent to the graph of the function, and it gave me this:

A y value of approximately $\frac{1}{3.7168943212}$ or $0.269041$
What is the exact value that makes the circle perfectly tangent to the function?
Comment: Why not take the circle tangent to the graph at $(0,1)$? Or anywhere else? The area under the entire curve has nothing to do with this notion.
Comment: You are exactly looking for the osculating circle (see https://en.wikipedia.org/wiki/Osculating_circle). To find radius the osculating circle in you have to find the arc lenght parametrization of the curve $(x,e^{-x^2})$ and then compute the curvature. For the center of the osculating circle you can compute the coordinates directly through the derivatives of $e^{-x^2}$ as explained in Wikipedia. Unfortunately it is not always possible to find the arc lenght parametrization because one have to solve integrals and it isn't always possible.
Comment: The OP hasn't defined "best" in "best circle. The way I read it, they are open to circles of different radii and maybe centers. So I don't think they're explicitly looking for the osculating circle.  I read it as @FShrite did in his solution.
Comment: Please play around with $t$. When $t = 0$, you can see unit circle centered at $(0, 1/2)$ tangent to curve at a single point and then on two points owing to symmetry. https://www.desmos.com/calculator/cpaohkj6oc
Answer: Take an arbitrary point on the curve, let $(t,e^{-t^2})$. The slope of the normal at this point is the opposite inverse of the derivative, $\dfrac{e^{t^2}}{2t}$ giving the intersection with the axis at $x=0,y=e^{-t^2}-\dfrac{e^{t^2}}2$. Hence the radius of the tangent circle, $r=\sqrt{t^2+\dfrac{e^{2t^2}}4}$.
Clearly, this relation is not analytically invertible, and if you want to choose the radius, you'll need to solve numerically.

It is possible to eliminate $t$ to establish a direct relation between $y$ and $r$. By solving a quadratic equation, we have
$$e^{t^2}=\pm\sqrt{y^2+2}-y$$ and
$$r=\sqrt{\log\left(\pm\sqrt{y^2+2}-y\right)+\dfrac{\left(\pm\sqrt{y^2+2}-y\right)^2}4}$$ but this brings no simplication...
Answer: $$D_x[e^{-x^2}]=-2x\cdot e^{-x^2}$$
A circle about the origin has the implicit derivative:
$$x^2+y^2=r^2,\,2x+2y\cdot y'(x)=0,\,y'(x)=-\frac{x}{y}$$
We seek a circle $y(x)$ such that:
$$D_x[e^{-x^2}]=y'(x)$$
At some point $x$, or:
$$-2x\cdot e^{-x^2}=-\frac{x}{y}$$
Which implies the trivial solution $x=0$ or the solution:
$$y(x)=\frac{1}{2}e^{x^2}$$
A circle's upper half, about the origin, may be described by $y(x)=\sqrt{r^2-x^2}$. Then we have:
$$\tag{1}r^2-x^2=\frac{1}{4}e^{2x^2}$$
But of course you wish for the circle to actually touch the graph at this point too, so we require also that:
$$\tag{2}r^2-x^2=e^{-2x^2},\,e^{2x^2}=\frac{1}{r^2-x^2}$$
Which must be satisfied for some $x$ for the circle to be tangential. By symmetry of the circle and the exponential, wlog $x\ge0$. Note that the trivial solution $x=0$ requires $r=1$ and this circle doesn't work as it intersects elsewhere.
Substituting $2)$ into $1)$, and multiplying by $r^2-x^2$ gives:
$$(r^2-x^2)^2=\frac{1}{4},\,r^2-x^2=\frac{1}{2},\,x=\sqrt{r^2-\frac{1}{2}}$$
Then substituting the middle equation into $1)$ we find:
$$e^{-2x^2}=\frac{1}{2}\implies-2x^2=-\ln2,\,x=\sqrt{\frac{1}{2}\ln 2}\approx0.588705$$
And:
$$r^2-\frac{1}{2}=\frac{1}{2}\ln 2\implies r=\frac{1}{\sqrt{2}}\sqrt{1+\ln2}\approx0.920094$$
Let's plot this to see if it really works, or if it suffers from other intersections:

There are no other intersections, so this is your desired circle. As commented, this has nothing to do with the integral being $\sqrt{\pi}$.


Remove path on double click d3

Question: I have the following code to append a line on an SVG canvas. I am able to get the scope run when I double click on the path as the alert box pops up but the line itself doesn't gets removed. Where am I going wrong? Am I using this incorrectly?
var lineFunction = d3.svg.line()
                     .x(function(d) { return d.x; })
                     .y(function(d) { return d.y; })
                     .interpolate("step");

lineGraph = layer.append("path")
              .attr("d", lineFunction(lineData))
              .attr("stroke", "black")
              .attr("stroke-width", 1)
              .attr("fill", "none")
              .attr("id","aggregation")
              .attr("data", "newline")
              .style('marker-end', "url(#end-arrow)")
              .on("dblclick",function(d){
                alert("double");
                d3.this.remove();
              });

Answer: The method .remove() needs to be called on a D3 selection. In an event handler you can obtain the selection containing the element which was target of the event by doing
d3.select(this)

Thus, changing your handler to
.on("dblclick",function(d){
   d3.select(this).remove();
});

should do the trick.

Remove path on double click d3


On the gradient of the squared Euclidean norm

Question: A differentiable function $f$ is strongly convex if
$$ f(y) \geq f(x) + \nabla f(x)^T (y-x) + \frac{\mu}{2} \| y - x \|^2$$
for some $\mu >0$ and all $x, y$. How to minimize with respect to $y$ on both sides above?
The answer from the reference website is:
$$ f(x^*) \geq f(x) - \frac{1}{2 \mu} \| \nabla f(x) \|^2 $$
I didn't figure out the last term above.
Comment: [Related](https://math.stackexchange.com/q/222894/339790)
Comment: (verbiage) What is $x^*$?
Comment: @SuzuHirose it should be critical point. i.e., the minimal point.
Answer: It looks like he is taking the gradient of equation 1 with respect to $y$ and then taking the minimum:
$$
\nabla_y\left(\nabla f(x)^T (y-x) + \frac{\mu}{2} \| y - x \|^2\right)=
\nabla f(x)
+ \mu(y-x)=0,
$$
where the final "$=0$" comes from the minimization, and all the terms in $x$ drop out, so $$\nabla f(x)=-\mu(y - x)$$ at the minimum. If you insert that back into his equation 1 again, you get
$$
\begin{align}
f(x^*) &\geq f(x) - {1\over\mu}\nabla f(x)^T \nabla f(x) + \frac{\mu}{2}{1\over\mu^2}\Vert \nabla f(x)\Vert^2\\
&=f(x)-{1\over 2\mu}\Vert \nabla f(x)\Vert^2\\
\end{align}
$$
(Just in case people are having difficulty understanding this answer, the top equation is the gradient (vector partial derivative) with respect to the $y$ variable, so terms like $\nabla_y \nabla f(x)= 0$ because there are no terms in $y$ in $\nabla f(x)$. The equation is a vector equation, so $y-x$ and $0$ here both mean the vectors. The next equation is also in vectors, then I substitute the vector $y-x$ with $\nabla f/\mu$, and the final inequality is a scalar one.)


How to calculate socially optimum provision of a public good?

Question: Utility = $\ln (x_i) + 0.5 (g_1 + g_2)$ subject to $x_i + g_i = 15$.
I have substitued the budget constraint into the utility function:
Utility = $\ln (15 - g_i) + 0.5 (g_1 + g_2)$
I have tried differentiating the budget constraint but am unable to get anywhere.
Answer: You differentiate $U_i$ w.r.t. $g_i$ and set it equal to zero. Let´s differentiate $U_1=\ln(15-g_1)+0.5(g_1+g_2)$ w.r.t $g_1$. For $\ln(15-g_1)$ we have to apply the chain rule.
Let´s say we differentiate $\ln(f(x))$ w.r.t. x. Then the derivative is $\frac1{f(x)}\cdot f^{'}(x)$. That means that the derivative of $U_1$ w.r.t. $g_1$ is
$$\frac{\partial U_1}{\partial g_1}=\frac1{15-g_1}\cdot (-1)+0.5=0$$
It remains to solve the equation for $g_1$.


theming date format

Question: I am kind of lost here for hours, trying to make a translated date format work for my content type(Drupal 7.22). There are the 2 configuration issues:
 1. Format
I want my formated date (say Apr 27) to be wrapped as following:

   Apr
   27

Although I create the date format I can't find the way to template it the way I want. The month and date shown in these spans is set when I create a content type (through a custom field populated with the help of date module), and so I should do sth like <?php echo render($content['field_date']); ?>. Unfortunately this renders the date with a different markup than the one I want and so I believe I have to change sth in a preprocess function.
 2.Translation
Say I have a date: Apr 27 and I want it to be in my language (greek) which would be Απρ 27.
I imported the greek http://localize.drupal.org/ successfully and inside this .po I can see
msgid "Apr"
msgstr "Απρ"

After a very helpful answer and a good comment below I now understand that translation isn't the way to go, since I only want to change the values of the months, and not translate the whole site. So what I look for is a function to do this.
P.S. I could make 2 seperate questions but I feel that they fit well under the title: configuring date formats. Also I have been trying for hours to find clear(to me at least) solutions and it proved harder than I thought. Can anyone help?
Comment: I sincerely dont understand why such a question would be downvoted. It describes 2 specific, common case scenarios of drupal theming, it may be a lot useful to others, especially those new searching for theming guidelines.

Back to the point, I went to `/admin/config/regional/language`, and added the second language(greek). Do I have to make it default (apart from enabling) in order for the translation of the months, provided inside the el.po file to take place? Truth is I want to only translate the months in the date format, not the whole site
Comment: By default, Drupal translations will affect the entire site.  If you want to translate only the months and nothing else you are better off writing your own custom function that does not make use of Drupal's built-in translation system.  The alternative would be not to import any .po files and create your own translation and only translate the months.  Then you would have to make this custom translation the default language of the site.
Comment: thank you, I am trying to find a way to achieve one of the 2 options you gave, namely the custom function or my custom translation.
Answer: Translations in Drupal are global, and will effect the entire site when you enable a non-english default language.  However, for translations to be acted upon, you need to wrap the term you want translated in the function t().
So to have 'Apr' in the snipped below translated, you must do something like this:

   <?php echo t('Apr'); ?>
   27

However, if you do not want to use Drupal' localization machinery, and just display the 4th month in greek, you may do something like this:

   Απρ
   27

Also note Drupal let you define standard date format string if you navigate to Home » Administration » Configuration » Regional and language » Date and time.  These get localized to your site's language when you set language, and have the added advantage of enforcing consistent date formats throughout the site.
Comment: thank you for the answer but I want the echoed values to be dynamic and not static. The month and date shown in these spans is set when I create a content type (through a custom field populated with the help of date module), and so I should do sth like ``. Unfortunately this renders the date with a different markup than the one I want and so I believe I have to change sth in a preprocess function. I'll add it to the question for clarity
Answer: after some searching and experimenting, I came up with this solution for my first problem:

I went to my theme in the template.php file
I created a function:
<?php  //if the opening php tag exists already, then don't put it again here :)

function awesome_preprocess_node(&$variables) {

// checking if this field_mydate has a value
if (isset($variables['field_mydate']['und'][0]['value'])) {

  //if it has, let's cache this point down the path
  $date1 = $variables['field_mydate']['und'][0];

  // I create a instance of the DateObject here. I pass the $date1['value'] which
  // corresponds to the date-path produced by my custom field of type: date. I found
  // this path with the help of helper function: kpr($variables);

  $date_object = new DateObject($date1['value'], new DateTimeZone($date1['timezone_db']));
  $date_object->setTimezone(new DateTimeZone($date1['timezone']));

  // Using the following 2 calls of function date_format_date I manage to
  // seperate month and day.
  // These variables will be available for my .tpl.php files

  $variables['date_month'] = date_format_date($date_object,'custom','M');
  $variables['date_day'] = date_format_date($date_object,'custom','j');
  }
}

In my node.tpl.php I use

   <?php print $date_day; ?>
   <?php print $date_month; ?>

(take into account that 'awesome' is the machine name of my custom theme. If someone else uses it, they'll have to provide their own theme name. Also the 'field_mydate' is the machine name of the date field I created. This will also need changing for another person's needs)
Although this does the trick, it seems (a bit) hacky and also it doesn't seem to load the [attributes] that used to be there before. Is there a better, clearer solution?
maybe overriding theme_date_display_single ?! or
maybe using sth like $event = node_load($nid); inside the preprocess function to get the date object from there instead of creating a new one is preferable ?!
As for my second question, I see nothing else than translating the whole site

theming date format


What's an "injective" function $f(i, j)$ such that $i \lt j, k \lt l \implies f(i,k) \lt f(j,l)$?

Question: For example $f(i,j) = i^2 + j^2$ won't work because there are numbers that can be written as the sum of squares in two ways.  It only has to work on the natural numbers.  It only has to be injective across differing pair sets $\{i,j\} \neq \{k,l\}$ and it should be commutative: $f(i,j) = f(j,i)$.
Comment: Does $\exp$ work?
Answer: Assuming $\mathbb{N}$ contains $0$ (if not, just shift everything by $1$):
Let
$$ f(i,j) = \left\{\begin{matrix} \frac{i(i+1)}{2} + j &\text{ if }i\le j \\ f(j,i) &\text{ if } i> j\end{matrix}\right. $$
The idea is to let $f(0,0) = 0$, $f(1,0) = 1$, $f(1,1) = 2$, $f(2,0) = 3$, $f(2,1) = 4$, $f(2,2) = 5$, $f(3,0)=6$, and so on.
Answer: Assuming $f: \mathbb{N} \times \mathbb{N} \rightarrow \mathbb{N} $, I think $f(i,j)=2^i 3^j$ will work.
Comment: This is not "commutative," $f(i,j)\neq f(j,i)$ unless $i=j$.
Comment: This is a good idea though.  I will select this as an answer since I found problems with my motivation part.  The non-commutativity isn't as bad.


Crystal Report Formula IF Then Else Remove Decimals

Question: I would like to remove 2 digit decimals in Crystal Report formula using if then else.
The way that I have tried does not help me to solve myproblem. How do I fix it ?
Here is my code;
if ({purchaseorder.CUR} = "IDR")
then Truncate({purchaseorder.UPRI})

Answer: Right-click your number field, select Format Field, Number Tab, Customize...
Set the following expression for the Decimals property:
if ({purchaseorder.CUR} = "IDR") then 0 ELSE 2

Comment: It works, I am sorry I did not relize it that the code it was so simple. Thank you for your kind information


Prove that $\sum\limits_{k=1}^n (k!)^2$ is not a perfect square when $n\ge2$

Question:
Prove that $\displaystyle \forall n\geq 2, \sum_{k=1}^n (k!)^2$ is never a perfect square.

I'm far from well-read in number theory and I can't make any significant progress with this problem.
I tried to look at the sum $\text{mod}$ some small numbers, to no avail.
Comment: This is not the case: $(5!+1)^2 = 14641 < 15017 = \sum_{k=1}^5 (k!)^2$.
Comment: Did you try modulo $5$?
Comment: @Arthur yeah, that's right, $2$ is not a square mod $5$...
Answer: Hint: In base $10$, a square number can end only with digits $1, 4, 6, 9, 0$, or $5$. Now note that from $\left(5!\right)^{2}
 $ all factorials are multiple of $10$ and $$\sum_{k=1}^{4}\left(k!\right)^{2}=617.$$


Postfix relayhost parameter for a null client

Question: I'm trying to set up postfix as a null client, that is, I just want local linux users to be able to send mails outside using postfix's sendmail binary.
No reception of emails, no relaying for other hosts, no local mail delivery to users (I don't see any use for it).
I just want to allow sending emails outside.
I have set these parameters in /etc/postfix/main.cf:
myhostname = mail.thisisadomain.com
inet_interfaces = loopack-only
mydestination =

Should I set other parameters or change anything else in the configuration ?
I'm particularly interested in knowing what to do with the relayhost parameter, since I don't understand what it does.
I've read the doc here http://www.postfix.org/STANDARD_CONFIGURATION_README.html#null_client but I still don't understand what the relayhost parameter does, and if it matters for a null client.
Thanks for your help.
Answer: As far as I understood, the author of http://www.postfix.org/STANDARD_CONFIGURATION_README.html#null_client assumed that null client is not an always-online-server e.g. sometimes it can safely be turn off or isolated from internet. This snippet from that page
1 /etc/postfix/main.cf:
2     myhostname = hostname.example.com
3     myorigin = $mydomain
4     relayhost = $mydomain
5     inet_interfaces = loopback-only
6     mydestination =
...
Line 4: Forward all mail to the mail server that is responsible for the "example.com" domain.
This prevents mail from getting stuck on the null client if it is turned off while some remote destination is unreachable.

Without relayhost parameter, whenever the null client turned off, the email on your deferred queue will not retried until the server goes back online or turn on. So it possible when your machine turn on, the email queue already expired.
The reason why you should provide relayhost parameter is no matter the state of your box (online or offline), the relayhost server (the one who always stays online) will retry the stuck emails from your null client.
Comment: Think of null client as being sort of like what your desktop does (at least if you're not using webmail).  It forwards outgoing email to a relayhost which is commonly provided by your ISP.  The relayhost parameter is where to send that email.


How do I prevent the HTML markup in an item list from being escaped?

Question: As you can see in the code below, I try various ways to prevent Drupal from escaping the HTML and passing the link tags to the output, including the use of '#allowed_tags' and the Markup class.  None of these approaches are working.
$text = t('Administer books');

$markup = new Markup();
$link = $markup->create(Link::fromTextAndUrl($text, $url)->toString());

$items[] = $link . ': ' . t('Browse books and edit fields') . '.';

$text = t('Import books');
$url = new Url('mei_marc.import');

$items[] = Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.';

$array['mei_marc_list'] = array(
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => '',
  '#items' => $items,
  '#allowed_tags' => ['a'],
);

$txt = drupal_render($array);

$markup = new Markup();

$list = $markup->create($txt);

return ['#markup' => $list];

The output is the following.

<a href="/mei_marc/list">Administer books</a>: Browse books and edit fields.

<a href="/admin/mei_library/import">Import books</a>: Visit this page to import a book.

Answer: $items[] = [
  '#markup' => Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.',
];

$form['mei_marc_list'] = [
  '#theme' => 'item_list',
  '#items' => $items,
];

return $form;

Comment: Wow.  I didn't see that approach anywhere in my searches, and it works.


Preciso colocar 4 cards na mesma linha, estou usando: display: flex e flex-flow: row; mas eles ficam um abaixo do outro, alguem sabe o que fazer?

Question:

.carrosel {
  display: flex;
  flex-flow: row;
  margin-left: 160px;
}

.cards {
  width: 266px;
  height: 493px;
  border: 1px solid #FFFFFF;
  box-shadow: 0px 4px 8px -4px rgba;
  border-radius: 8px;
  box-shadow: 2px 4px 8px -4px rgba(0, 0, 0, 0.2);
}

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

      <button class="btncards">
        Saiba mais
      </button>

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

        <button class="btncards">
          Saiba mais
        </button>

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

          <button class="btncards">
            Saiba mais
          </button>

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

            <button class="btncards">
              Saiba mais
            </button>

Answer: Estava faltando fechar as tags div das classes "cards", então o segundo card estava dentro do primeiro, o terceiro dentro do segundo e assim por diante. Não havia como ficar lado a lado dentro do "carrosel", já que só havia efetivamente, um card dentro do carrosel.
Segue o abaixo o código com as alterações de fechamento de tags seguidas do comentário

.carrosel {
  display: flex;
  flex-flow: row;
  margin-left: 160px;
}

.cards {
  width: 266px;
  height: 493px;
  border: 1px solid #FFFFFF;
  box-shadow: 0px 4px 8px -4px rgba;
  border-radius: 8px;
  box-shadow: 2px 4px 8px -4px rgba(0, 0, 0, 0.2);
}

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

      <button class="btncards">
        Saiba mais
      </button>

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

      <button class="btncards">
        Saiba mais
      </button>

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

      <button class="btncards">
        Saiba mais
      </button>

Teste A/B

Um teste A/B consiste em comparar o desempenho de uma ou mais versões (variantes) de uma página em relação à original por meio da análise de métricas como taxa de conversão, funil de vendas, dados de tráfego, entre outros.

      <button class="btncards">
        Saiba mais
      </button>


Integral with e and log

Question: so I have the following integral $$\int_0^\infty e^{-\log^2x}dx$$  I tried the following substitution $\log x=t \, ; \log^2x =t^2$ and substituted got to $$\int_0^\infty e^{-t^2}e^{-t}dt$$ should I split this integral and use Gauss integral?or what method should I approach I get blocked after substituting.
Comment: @Isham: the procedure you refer to is called "completing the square" in English.
Comment: finish the square. then use gaussian integral  look here  https://en.wikipedia.org/wiki/Gaussian_integral
Comment: @fabian thank you ....
Answer: Actually, the first step seems wrong. If $x=e^t \iff t = \ln x$ then
$$
I = \int_0^\infty e^{-\ln^2 x}dx = \int_{t=-\infty}^{t=\infty}e^{-t^2}e^{-t}dt
$$
and we can complete the square in the exponent, noting that
$$
-t^2-t = 1/4-(t+1/2)^2
$$
and hence (using $u=t+1/2$)
$$
I = e^{1/4} \int_{-\infty}^\infty e^{-(t+1/2)^2}dt
  = e^{1/4} \int_{-\infty}^\infty e^{-u^2}du
  = e^{1/4} \sqrt{\pi}
  = \sqrt[4]{\pi^2e}
$$
using the usual trick with polar coordinates.
Comment: @Isham thanks, fixing -- no change really :)
Comment: @Isham thanks again, hope it's right this time :)

Integral with e and log


Jmeter Write data into Csv and read the same in another thread group

Question: My requirement is to Create users in one thread group and save the users in row format in csv.
Use another thread group to read the csv and run it in loop for all users in csv.
But ReadData2 thread group is not reading the data when ran sequentially.
and is working when ran independently.
Answer: The CSV file needs to be present when "ReadData2" Thread Group starts so make sure that the file is there and contains i.e. a header line or something like this.
The file can be created in i.e. setUp Thread Group or create it beforehand and append new entries programmatically as needed.
With regards to using Beanshell: it's a some form of a performance anti-pattern, since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting so consider migrating.


check if nested checkboxes are triggered using jquery

Question: I have 2 divs with check boxes nested in each. I basically would like to trigger an alert if a checkbox is clicked in the 1st one and second one, but I cannot seem to reach that scope. The checkboxes are classes.

if ($("#result1 .tb2:checked").length == 1 && ($("#result2 .tb4:checked").length == 1  ) {
    alert("both clicked");
}

<input type="checkbox" class="tb1" />  Yes
<input type="checkbox"class="tb2" />  No

<input type="checkbox" class="tb3" />  Yes
<input type="checkbox"class="tb4" />  No

Comment: When are you running that Javascript code? It needs to be in an event handler, like `$(":checkbox").change()`.
Comment: As i understand your expected behaviour, you want to check that at least one checkbox is checked in each `div`, is it?
Comment: For instance, i need it to check if the yes in result 1 and the yes in result 2 has been clicked.
Answer: You should have a button, and bind the click event handler to it. You iterate through both divs with each and count the number of checked items. For this, you can use the :checked selector.
$("button").on("click", function() {
    $("div").each(function() {
        if ($(this).find("input:checked").length === 2) {
            alert("Both checked");
        }
    });
});

http://jsfiddle.net/sjygn4t1/
Answer: You need to put the test inside an event handler, so it will run whenever the checkboxes are changed.

$(":checkbox").click(function() {
  if ($("#result1 .tb2").is(":checked") && $("#result2 .tb4").is(":checked")) {
    $("#output").text("both clicked");
  } else {
    $("#output").empty();
  }
});

  <input type="checkbox" class="tb1" />  Yes

  <input type="checkbox" class="tb2" />  No

  <input type="checkbox" class="tb3" />  Yes

  <input type="checkbox" class="tb4" />  No

Comment: The problem with this is that it only works for the first div. You should use the `each` method to iterate over both divs
Comment: What do you mean? I specify the div IDs explicitly in the selectors, just like in the question.
Comment: What if i want to place this code in the document ready event instead of :checkbox selector?
Comment: Why would you do that? That will just run when the page loads, before the user has had a chance to check any of the boxes.


How to find scaling to get minimum positive integer proportion?

Question: Suppose we have x is a strictly positive vector and y=b*x where b is a positive scaling scalar. The problem is to find the function to get the scaling factor b such that y becomes minimum positive integer. Here are some examples:
x=[1, 3, 1.5] then y=[2, 6, 3];
x=[0.5, 0.25, 0.75] then y=[2, 1, 3];
x=[1.75, 1, 0.5, 2] then y=[7, 4, 2, 8];
x=[0.5, 0.333, 1, 2.75] then y=[500, 333, 1000, 2750]
My question: what is the function of the scaling factor b such that y=b*x becomes the minimum positive integer proportion for any positive vector x?
Comment: Are the entries of $x$ rational?
Comment: yes, the entries are all rational numbers
Comment: If $x=[3,3,3]$, will you take $b=\frac13$?
Comment: yes, if x=[3,3,3] then y=[1,1,1]
Answer: Step 1: Clear denominators)
Write your vector $x$ entries in fractions (in simplest form), then $b$ will be the lowest common multiple (LCM) of the denominators.
For example write x=[0.5, 0.25, 0.75] as $x=[\frac 12, \frac 14, \frac 34]$.
Since LCM(2,4)=4, $b_1=4$. Then $y=[2,1,3]$.
Step 2: Simplify)
At this stage $y$ should already have all entries integers, then divide throughout by the GCD of all the integers.
E.g. if $x=[3,3,3]$, $b_2=1/3$ to get $[1,1,1]$.
(As pointed out by peterwhy)
Overall, the scalar $b$ will be the product of the $b_1b_2$ used in the two stages.
Comment: It appears that you also have to consider the GCD of the numerators.
Comment: Ah yes, that is correct
Comment: the actual length of x can be very long. I can find vector nominator N and vector denominator D but I am not sure about how to get the LCM because LCM requires two vectors.
Comment: Are you finding out the LCM by computer or by hand? LCM is defined for more than two integers: see for instance https://www.khanacademy.org/math/pre-algebra/factors-multiples/least_common_multiple/v/least-common-multiple-lcm
Comment: I mean, even if $x$ are not all integers from the begining, it is probably still necessary to consider the GCD of the numerators. Consider $x=[4/3, 2]$.
Comment: I am using Matlab. There is built-in GCD and LCM
Comment: @Hajar I believe what you need is: http://www.mathworks.com/matlabcentral/newsreader/view_thread/240937
Comment: I tried your answer above using this code but it does not work. It produces integer but not the minimum: function y=num2whole(x)
if nargin<1,
    x = [1   , 3    , 1.5;
         0.5 , 0.25 , 0.75;
         1.75, 1    , 0.5 ;
         0.5 , 0.333, 2.1]
end
A=x;         % copy
D=ones(size(A));
while (sum(sum(abs(double(int64(A))-A)))~=0),
    A=A*10;  % numerator
    D=D*10;  % denominator
end
k = lcm(A,D)
g = gcd(A,D)
y=x.*k.*g


Rule fails to send email to billing address

Question: I'm trying to create notification emails which are sent when the checkout has been completed. (Drupal Commerce module)

I added a rule to send the email to site owner. It works.
I created a new rule to send email to to the customer's billing address. I Used <code>[commerce-order:mail]</code> replacement pattern as suggested, but unfortunately the email fails to arrive.

What could cause this problem? I even considered add new data selectors, but couldn't find anything fitting to add.
Comment: `[commerce-order:mail]` will use the email address that is directly attached to the order, not the "billing address".
Answer: As per one of the comments below this question (which kept showing up as a question with no answers):

It seems that for the email field an additional field was added to customer profile form. Thus obviously it couldn't be accessed.
A solution which works is to continue using the "Account information" checkout pane instead.

Credits: Gugols


CoreLocation/Mapkit Altitude

Question: Just a quick question, does CoreLocation/Mapkit measure altitude from sea level (elevation)?
I am using the following code
NSString *altitudeString = [NSString stringWithFormat: @"%.2f m", newLocation.altitude];

Thank You
Answer: Yes, you can check the altitude via the locationManager like this :
locationManager.location.altitude

you can also check the vertical accuracy with :
locationManager.location.verticalAccuracy

Comment: Do you know if this data comes from the device barometer or it's data from a flat map?

CoreLocation/Mapkit Altitude


Silverlight Entity Framework Dynamic Connection String

Question: I have the same data model on a bunch of different servers.  I want to dynamically create a connection string based on who my user is and what they are doing.
My users can have multiple databases on multiple servers.  I need a clean way to build a connectoin string when I create my DomainService.
I see that the DomainService has an override (inherited from LinqToEntitiesDomainService)  called CreateObjectContext() that would allow me to set any connection string I want, then return the new entity and life is good.  The problem is, the CreateObjectContext() gets called after the constructor, so I can't set a string via an invoke method. Also, I've tried to create a new parameterized constructor on the DomainService, but it never gets copied to the DomainContext on the client.
The CreateObjectContext() would work great if I was able to pull my connection string, but since I have to use data from the client to figure out which DB to connect, this obviously won't work.
The more I think about it, the more I feel a custom constructor is exactly what I need - just can't figure out how to get that done.
What am I missing?
Comment: What about WCF Data Services?
Answer: I found a solution.  For those that are interested, here it is:
This feels a bit like a hack, but it's the only solution I could come up with.  Thanks to Sally Xu over at forums.silverlight.net for the ideas.
Since each of my users can have mulitiple databases on multiple servers, I needed to find a way to create the ConnectionString before the DomainService was used the first time.  Each time the user selects a new project from the UI, I set a cookie like this:
private void SetCookie(string cookieName, string cookieValue)
{
  DateTime expireDate = DateTime.Now + TimeSpan.FromDays(1);
  string newCookie = cookieName + "=" + cookieValue + ";expires=" + expireDate.ToString("R");
  HtmlPage.Document.SetProperty("cookie", newCookie);
}

The cookieName is SelectedProjectId and the cookieValue is the current selected project in my UI.
Then I create a new DomainService as normal, but I override CreateObjectContext().  This method gets called the very first time you reference your DomainService object.  My override looks like this:
protected override ProjectEntities CreateObjectContext()
{
  long projectId = -1;
  StringBuilder connection;
  if (System.Web.HttpContext.Current.Request.Cookies["SelectedProjectId"] != null)
  {
    projectId = Convert.ToInt64(System.Web.HttpContext.Current.Request.Cookies["SelectedProjectId"].Value);
  }
  else throw new Exception("Selected Project ID Exception");  // temporary

  // Verify this user has access to the DB just in case it's spoofed

  // Lookup project ID in my database to get the database name and server name

  // Load template connection string found in web.config
  // Replace the template holders for SERVER_NAME and DATABASE_NAME with above lookup values

  return new ProjectEntities(MyDynamicConnectionString);
}

Again, this is a bit hackish, but it was the only way I could find to dynamically create a connection string for my needs.  I hope this helps someone else...


"Herança" de tabela é uma prática ruim nesse caso?

Question: No meu banco de dados preciso armazenar funcionários, clientes e fornecedores. Como todos esses compartilham dados em comum, porém não são todos os dados, resolvi criar uma tabela pessoas com as colunas em comum:
id // chave primária
tipo // tipo F para funcionário, C para cliente e F para fornecedor
nome
data_nascimento
endereco
inativo

E para armazenar os dados específicos de cada tipo fiz outras tabelas, como o funcionarios:
id_pessoa // único, não nulo e chave estrangeira em pessoa(id)
data_admissao
data_demissao
salario

O relacionamento entre funcionarios e pessoas deve ser de um para um (ou nenhum), já que um registro de pessoa só pode ter um registro de funcionário, de cliente ou de fornecedor.
O que tentei abordar foi uma "herança". funcionarios herda todas as colunas de pessoas.
Não sei se tomei a decisão correta aqui. Isso é uma prática ruim? Se for, existem outras alternativas? Deveria repetir todos os campos de pessoas em funcionarios, clientes e fornecedores e eliminar pessoas?
Devo ter me expressado mal pois esse tipo de relacionamento não parece um pra um e sim um pra um ou zero. Estou certo?
A coluna pessoas.tipo é realmente necessária?
Comment: Relacionado: [Pode ser considerada uma má prática de modelagem armazenar todas as pessoas (clientes, funcionários, fornecedores) em uma mesma tabela?](https://pt.stackoverflow.com/q/54177/1658)
Answer: Não dá para dizer que está errado, mas eu não gosto desse tipo de separação na maioria dos casos. Acho que ela é válida se o cadastro é muito grande e as partes costumam ser acessadas de forma independente na maioria das vezes. Aí funciona como uma otimização. Não que ela seja necessária e útil na maioria dos casos.
Se a pessoa só pode exercer um papel na organização, então determine que ela é aquele papel, ou seja, pra que ter um cadastro de pessoa? Não há repetição alguma porque você está garantindo que ela tem só um papel. Se não há repetição, não há porque falar em normalização (leia o link porque é um pouco mais complicado que isto).
A maioria dos sistemas não conceitua certo e usa a abordagem de ter apenas os papéis e não as pessoas. Se uma pessoa for um funcionário e cliente ao mesmo tempo terá dois cadastros da mesma pessoa.
Separação de papéis e da pessoa
Só que é comum a pessoa exercer mais de um papel, aí começa ser interessante ter essa separação. Então a pessoa pode se vincular a vários papeis (tipo) e não apenas um, como está modelado na pergunta.
Se adotar o modelo separado, pode ser interessante também ter uma forma de ligar diretamente aos cadastros específicos dos papéis. Mas é só otimização. Se for garantido que o cadastro do papel terá o mesmo id da pessoa, aí nem precisa porque você sabe qual é o id lá. Mas acho isso um pouco arriscado. Precisa saber fazer e precisa saber que não vai mudar para um dia a pessoa ter duas contas separadas em alguma tabela de papéis.
Em tese pode até eliminar o tipo porque tem como descobrir isso, mas exigirá mais esforço de código e de execução. Eu só não descartaria. A não ser que mantenha um código de ligação para as tabelas específicas, porque se estiver preenchido para aquele papel você sabe que ele é daquele tipo.
Respondi algumas perguntas sobre isto:

Pode ser considerada uma má prática de modelagem armazenar todas as pessoas (clientes, funcionários, fornecedores) em uma mesma tabela?
O que fazer se cliente pode ser tanto PF quanto PJ?
Modelagem de lançamentos usando clientes e fornecedores
Modelagem para cadastro de entidades abrangente

Coloquei no GitHub para referência futura.
Answer: Isso por si só não é uma prática ruim.
No mundo de bases de dados relacionais que interagem com sistemas orientados a objetos (acredito ser o seu caso), o maior desafio de design para a base é como montar um schema que faça sentido e que seja fácil de manter. A discussão sobre se é melhor repetir informação ou não no banco, e o quanto repetir, trata de um assunto chamado normalização.
No seu caso, você normalizou a tabela. Normalização costuma ser visto como boa prática, contanto que não seja exagerada ou desnecessária.
Eu só faria uma coisa diferente: passaria o tipo de pessoa para a tabela filha. Afinal, vai que um dia alguém se torna cliente e fornecedor ao mesmo tempo... Da forma como esta essa pessoa precisaria de duas entradas na tabela mãe.
Nos comentário o Maniero chamou a atenção a um fator importante. Como eu falei, a normalização tem suas vantagens, mas esqueci de mencionar algumas desvantagens. Dentre elas, o espalhamento de informações entre tabelas diferentes. Isso pode tornar as consultas mais custosas.
Supondo que você mantenha o modelo normalizado que propõe na pergunta. Se você quiser pesquisar, por exemplo, por um funcionário que, por exemplo:

more em um endereço específico, e;
receba salário dentro de determinada faixa...

Você terá que pesquisar nas duas tabelas. Um JOIN entre tabelas pode acabar sendo mais caro em termos de performance do que pesquisar em uma única tabela. Se a performance das pesquisas for o fator mais importante no design da base de dados - e para grandes sistemas, geralmente é - então vale a pena desnormalizar para acelerar as consultas.
Comment: Mas se ele não sabe se é funcionário, cliente, fornecedor, banco, etc., tem que pesquisar em todas.
Comment: mas se ele for funcionário, cliente e fornecedor, **também** vai ter que pesquisar em todas do mesmo jeito, não?
Comment: Mas a tabela filha já indica o que ela é. E como vai saber em qual tabela pesquisar os dados extras? Procurar em todas possíveis?
Comment: @Maniero a lógica sobre onde pesquisar pertence à aplicação. E no exemplo na pergunta, a tabela que indica o tipo de pessoa é a tabela mãe.
Comment: Mas você acha bom pesquisar em várias tabelas só para descobrir em qual tem cadastro?
Comment: No caso do exemplo na pergunta eu só vejo necessidade de se pesquisar em uma, já que existir na filha implica em existir na mãe.
Comment: @Maniero Agora entendi. Se a performance de pesquisa for realmente o fator mais importante (e geralmente é), então seria melhor desnormalizar. Vou editar a resposta com relação a isso.


How to make a brass instrument quieter?

Question: I play trumpet at home. I feel a little uncomfortable playing because of the loudness. I found the Silent Brass series by Yamaha, which makes brass sound quieter, and you can still hear everything through headphones, but in my country they are very expensive. I don't need excellent sound, or some digital system, I just need to be quieter. Could you please suggest a cheaper alternative?
Comment: I know you've already accepted an answer, but I just thought I should mentioned buzzing on the mouthpiece.  You can practice all of your music just on the mouthpiece while at home, and when you're away, you can put the mouthpiece back in the trumpet and play - you will find your accuracy, flexibility, and tone production significantly improve.
Answer: The Silent Brass is really just a practice mute with a microphone in it, and the rest of the system is just a cheapo headphone amp.  I have one but I rarely bother putting the headphones on.  So the first thing to check out would be a simple practice mute.  They produce a ton of back pressure so you don't want to play on them exclusively and get used to it, but it's fine for short sessions.
If the practice mute turns out produce too much back pressure, then any other mute is an option.  I find that cup mutes cut a ton of sound without affecting the feel of the instrument much at all.  Harmon mutes with the stem out are even quieter but with more significant back pressure.
Comment: One more thing to mention is that mutes typically push the tone sharp, requiring you to pull out the main slide a touch. It can be a pain when switching several times during a piece.
Answer: You should try out practice mutes in a shop. Look for the one with best intonation, that the one that detunes your horn as little as possible.
My experience with the Yamaha silent brass is awful, especially with the headphones. Last time I played with it I could barely play at the next rehearsal. I guess it's easy to overblow since the headphones kind of give you the impression that you are without mute. I found it easier to avoid overblowing with a real practice mute.
I like my Shhh mute, but you really need to try them to find out which one fits for you.
Answer: An alternative to buying a pricey mute like the Silent Brass system is to simply make your own, if you don't mind spending some time on a do-it-yourself project. When I was a poor college student looking to save all the money I could, I found instructions for making a practice mute out of a Renuzit brand air freshener with some simple electronics to hook up to a pair of headphones and it worked fairly well. A copy of the instructions is available online here. Here's some choice pictures:

The electronics portion of the project is obviously more complex than the construction of the mute itself, but if you're handy with a soldering iron (or have a friend who is!), it shouldn't be terribly difficult. Otherwise, you can simply build the mute without the wiring and put some extra padding in its place - you'll miss out on the headphone playback but it will still have the quieting effect.

How to make a brass instrument quieter?


Split git diff --name-status by line break

Question: I'm trying to export a list of changed files from two commits with git, with this command:
read -ra ADDR <<< `git diff --name-only HEAD..HEAD~1 | sed -e "s/ /\\\ /g"`
for i in "${ADDR[@]}"; do
    echo "$i"
done

This works fine. I get a nice list printed out to the terminal with each file on a new row.
file1.txt
file2.txt
file3.txt

However, I want to use --name-status instead of --name-only. The reason is so I can later do different things depending on what kind of change was made (e.g. M or D).
This doesn't work though. I get a list in the following format:
M
file1.txt
M
file2.txt
M
file3.txt

I have tried to changed the IFS variable to $'\n' (returns everything on one row), $'\t' (returns first row, e.g. M file1.txt) and ' ' (same as \t) without success.
Comment: can you just add ';/^M$/d' to your sed script to delete the lines that are just M. Good luck.
Comment: When I run `git diff --name-status ..` I get a  list of file names, with the status in the first column. I'm not sure what your `sed` command is offering you. My bash is not the best, so I can't give an example, but I think you can get what you want with `awk`, which will let you grab fields by position, and output them. http://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/
Answer: while read STATUS ADDR
do
    echo "$ADDR ($STATUS)"
done  < <(git diff --name-status HEAD..HEAD~1)

E.g. for git output like
M       INSTALL
M       debian/changelog
M       src/lib/libnvpair/SConscript
M       src/lib/libzfscommon/SConscript
M       src/lib/libzpool/SConscript
M       src/zfs-fuse/main.c

the following is printed by the while loop:
INSTALL (M)
debian/changelog (M)
src/lib/libnvpair/SConscript (M)
src/lib/libzfscommon/SConscript (M)
src/lib/libzpool/SConscript (M)
src/zfs-fuse/main.c (M)


Paired test or two-sample t-test?

Question: I am looking at whether there is a difference in the extent of emotional tone in student essays on two exams - one at T1 and another at T2. Some of the students who took the exam at T1 also took exam at T2. But there are students unique to each exam as well.
In order to examine the hypothesis that the mean emotional tone in essays at T2 is greater than mean emotional tone at T1, should I be doing a paired t-test or two-sample t-test?
Or do you suggest that I separate students who took both exams and do a paired t-test on this sample and a two-sample t-test for test takers who only took the exam at T1 or T2?
Comment: Another Q on combined paired/unpaired data:   https://stats.stackexchange.com/questions/25941/t-test-for-partially-paired-and-partially-unpaired-data
Answer: Your plan seems OK. But you have to understand that the paired test for subjects who took both tests will be more likely to show a difference in emotional tone, if such a difference exists. (The two-sample test for two groups of independently selected subjects will have lower power.) The following example, with data suitably simulated in R, illustrate.
Paired scores. Suppose we have 50 subjects who took both tests.
They average around 100 on the first test, and there
is an average increase of several points in 'emotional tone' for each student. Because data are paired, we
are able to look mainly at the increase in emotional tone
without being distracted by the variability of test
scores due to differences among the 50 subjects.
Data might look somewhat like the data simulated in R below.
set.seed(2020)
x1 = rnorm(50, 100, 15)
et = rnorm(50, 4, 2)
x2 = .98*x1 + et + rnorm(50, 0, 1)
d = x2 - x1
summary(d);  sd(d)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-2.5581  0.4485  1.6450  2.0571  3.6346  8.5226
[1] 2.442555  # SD of differences

Due to pairing, there is a positive correlation between
first and second test scores, illustrated in the plot below. The $40$ points above the line (through the origin with unit slope) represent students with
higher scores on the second exam, mainly due to the
emotional tone effect. A paired t test (that is, a one-sample test on differences in scores) shows a highly
significant effect (P-value very nearly $0)$.
cor(x1,x2)
[1] 0.9892561
plot(x1,x2,pch=20)
 abline(a=0,b=1,col="green")

t.test(d)

        One Sample t-test

data:  d
t = 5.9553, df = 49, p-value = 2.742e-07
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 1.362981 2.751314
sample estimates:
mean of x
 2.057147

Two independent samples of subjects. Suppose that
50 randomly chosen subjects took the first test and
a different 50 randomly chosen subjects anticipated
to score several points higher in emotional tone took the second test.
We have two separate samples, and so inevitable variability in exam-taking ability
among subjects (modeled here by $\sigma = 15)$ will be apparent when we compare
scores on the first and second tests.
set.seed(420)
y1 = rnorm(50, 100, 15)
y2 = rnorm(50, 104, 15)
summary(y1); sd(y1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  55.77   90.20   98.28   98.50  108.76  128.80
[1] 15.25291
summary(y2); sd(y2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  72.71   88.47  105.48  100.88  111.72  127.97
[1] 14.01788

A stripchart plots the two samples; group means are shown as red Xs. We are looking through a heavy 'fog' of variability, trying to discern the difference between $\mu_x = 100$ and $\mu_y = 104.$
y = c(y1, y2);  g = rep(1:2, each=50)
stripchart(y ~ g, ylim=c(0.5,2.5), pch="|")

Because we have two independent samples with no inherent order relationship between them, it is not meaningful to find a sample correlation. Various randomly selected 'pairings' might give correlations anywhere between $\pm 0.95,$ about half of them between $\pm 0.1.]$
A Welch 2-sample t test shows no significance.
t.test(y2,y1)

           Welch Two Sample t-test

data:  y2 and y1
t = 0.81253, df = 97.31, p-value = 0.4185
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
 -3.433908  8.194846
...

Comment: I think you need to make it clear that you have two parts to your study. One with a relatively efficient paired model model. The other with a less efficient two-sample model. (If the two-sample test doesn't find an effect, you might mention the two-sample part only in a footnote of your report, explaining that it was somewhat of a long shot.)
Comment: Many thanks! So do you suggest that I do both the tests and only conclude that emotional tone is significantly higher at T2 than T1 if BOTH the paired t-test and Welch test show significance?

Paired test or two-sample t-test?


protoc-gen-go-rpc: program not found or is not executable - Where do I get protoc-gen-go-rpc?

Question: We are using protoc-gen-go v2 (v2 is google.golang.org/protobuf, v1 is github.com/golang/protobuf)
When we are trying to compile our gRPC services, it tells us that plugins is not supported anymore and we should instead use --go-grpc_out:
$ protoc --go_out=plugins=grpc:. *.proto
--go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC

And when using --go-grpc_out, it is telling us we need the protoc-gen-go-rpc:
$ protoc --go-rpc_out=. *.proto
protoc-gen-go-rpc: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable

Where do you find, or how do you install protoc-gen-go-rpc?
Update: We also just found this post on Reddit for additional information
https://www.reddit.com/r/golang/comments/fe3a4k/documentation_on_getting_grpc_working_with_the/
Answer: I'm not sure about protoc-gen-go v2, because the latest protobuf tag I can see is v1.4.
Here is the example how we call protoc to generate source code for sevice called crab that has no external dependencies (e.g. no external protofile imports). The only binary dependency is protoc-gen-go
protoc -I $(pwd) -I /home/isaev/go/src \
 $(pwd)/crab/error_codes.proto \
 $(pwd)/crab/goproxy.proto \
 $(pwd)/crab/crab.proto \
 --go_out=plugins=grpc:/tmp/crab

Comment: Hey, yes. Since you use "plugins", you are still using an old version of protocol-gen-go

https://github.com/protocolbuffers/protobuf-go/releases/tag/v1.20.0#v1.20-grpc-support


What does this pedal notation mean for the piano?

Question: I've never seen this pedal notation used before and would appreciate it if someone could help me understand what it means?
Comment: This is Beethoven's Pathétique Sonata, mvt. 1.
Answer: The └ mark means "apply pedal", and the ┐ mark means "release pedal".
Here is a more standard notation from the Godowsky edition of the piece:1

1Ludwig van Beethoven, Sonata in C Minor (1798), Op. 13, "Pathétique", mm. 1-2. The pedal markings both in the OP and Godowsky are editorial, not Beethoven's. Beethoven did not give pedal indications here.
Comment: Surely that sign would be more intuitive with an upturn at the end, showing which way the pedal actually goes.
Comment: Yup.  Which is probably why the more standard pedal line does that, with 'Ped' at the beginning and an upturn at the end.  I like this one though.  Less cluttered than all those 'Ped' objects.
Answer: The beginning of the pedal mark indicates that you need to suppress the sustain pedal and at the end it needs to be released.


Letting $r \rightarrow 1$ in $\frac{1}{2\pi}\int_{0}^{2\pi}\log |f(re^{i\theta})|\, d\theta$

Question: Suppose $f$ is continuous on $\{z: |z| \leq 1\}$, analytic on $\{z: |z| < 1\}$, and $f(0) \neq 0$. For $0 < r < 1$, consider the integral $$\frac{1}{2\pi}\int_{0}^{2\pi}\log |f(re^{i\theta})|\, d\theta.$$ Let $r_{n}$ be a sequence such that $\inf_{|z| = r_{n}}|f(z)| > 0$ and $r_{n} \rightarrow 1^{-}$ as $n \rightarrow \infty$. Is $$\lim_{n \rightarrow \infty}\frac{1}{2\pi}\int_{0}^{2\pi}\log |f(r_{n}e^{i\theta})|\, d\theta = \frac{1}{2\pi}\int_{0}^{2\pi}\log |f(e^{i\theta})|\, d\theta?$$
Answer: You have to assume that $f(z)\neq 0$ for $|z|<1$. Note that $\ln|f(z)|$ is the real part of $\ln f(z)$ and
$$ \frac{1}{2\pi i}\int_{|z|=r}\frac{\ln f(z)}{z}dz=\ln f(0). $$
Hence
$$  \frac{1}{2\pi i}\int_{|z|=r}\frac{\ln f(z)}{z}dz=\frac{1}{2\pi i}\int_{|z|=r_n}\frac{\ln f(z)}{z}dz=\ln f(0). $$
Separate the real part from the imaginary part and use $z=re^{i\theta}$ and $z=r_ne^{i\theta}$ and you will get.
Comment: What if $f=0$ on $|z|=1$ ?


Efficient server configuration for imagemagick

Question: I am operating a system with heavy image editing processed by imagemagick.
Now for a new server I was wondering which system requirements are most important to boost performance of imagemagick and image editing such as converting and composing gifs, jpgs and pngs.
The resolution of the images is usually between 800x400 and 1980x1080 px. Multiple images may be processed at the same time.
I was thinking that a lot of (fast) RAM would be most important but then even full hd in 32bit only takes around 8MB, so maybe CPU is more important?
Any insights are highly appriciated!
Update:
htop shows that CPU is the most probably the bottleneck.
Since imagemagick needs a lot of resources I could imagine that I would hit CPU limits with one server pretty quickly. Any ideas how I could balance the load dynamically (there could be huge peaks)? Something like Amazon Web Services but quicker since images are rendered on the fly?
Comment: What is your current bottleneck? Benchmark, see what limits you and then improve this.
Comment: I think you've answered your own question.
Comment: @SvW From htop it looks like the CPU would be the bottleneck. It goes up to 100% work load meanwhile RAM is under 1% on a 4 CPU, 4 GB RAM server.
Comment: Well, other variables also leads to CPU bottleneck. Just saying what htop reports is not the full truth. CPU could be waiting on I/O, then it's your block device subsystem that is holding CPU back. More CPU will allow you to context switch faster, to instantiate more parallel process, but it won't help anymore if your HDDs are 5400 rpm, for instance. Your bottleneck appears to be CPU but CPU waits for disk I/O, synchronously, you should dig deeper.
Answer: Processing such small images (and 1920x1080 is small) doesn't require much memory, CPU is dominant.
You need lots of CPU power, if you have many pictures to convert at a time, running the conversions in parallel is a good idea. Also, because it's easy to run it in parallel having CPU with more cores vs higher frequency will give you higher performance. You just need to make sure to run many jobs at the same time.
In other words, look for machines with minimal amount of memory (4-8GB) and many cores or even many CPUs. If you're using Amazon, then High-CPU Instances is what you're looking for. For very large load, it may be good idea to look at cluster instances.
Depending on the specific number of conversion requests, you may have better luck scaling horizontally - getting more machines and spreading your load over them. But that depends on your exact use case, collocation costs or VM costs, etc.
Answer:
From htop it looks like the CPU would be the bottleneck. It goes up to 100% work load ...

If your CPU is pegging and everything else is at nominal values then you need to add More CPU.
Comment: @lain: since imagemagick needs a lot of resources I could imagine that I would hit CPU limits with one server pretty quickly. Any ideas how I could balance the load dynamically (there could be huge peaks)? Something like Amazon Web Services but quicker?
Comment: @horen, you would need to create/utilize a queueing system where workers will poll some place to look for more work to do. That way you can have exact and controlled number of imagemagik workers to utilize all the available CPUs/cores without overwhelming them. Read up on Message Queues, available products and services.
Answer: I've done photobooth project, based on opensource software, we use ImageMagick for image processing. We've experimented with both x86 and ARM v6/v7 platforms. Different image sizes, different effects, combining of images etc. We've tested with 256 RAM for both old x86 PC and ARM (Raspberry Pi). CPU was the bottleneck and we were practically unable to use 1 core for instant processing - it was taking about 30 secs to complete on ARMv6, 10 secs on P3 and 1 sec for 1 GHz newest Core. It's a CPU. If you are running ImageMagick apps from command line, then you should check /tmp, which is usually tmpfs/shared memory. For us it was taking about 64MB per one large print image, combined from four jpegs from Canon cameras.
If you are running several processes at once - just add more cores.
How to balance the load? Depends on your configuration, how your system works. Do you use web services, running ImageMagick with php or have your own programs etc... Please clarify...
Answer: HAProxy will let you 'load balance' between multiple servers from the networking side... And provide fail over.


Calculo de sobrevida em C

Question: Pesquisando sobre calcular dias de sobrevida de uma pessoa através da diferença de dias encontrei um programa aqui que me serviu de base para isso
então adicionei os cálculos necessários para saber os a quantidade de: horas, minutos segundos, dias, meses, anos.
Acontece o seguinte, tenho a seguinte data abaixo:
dias entre 29/03/1987 a 21/12/2017
30 anos, 8 meses 18 dias
diaspassados=11225

De acordo com essa calculadora. Então faço o mesmo input no meu programa e ele retorna a seguinte saída abaixo:
    Digite data1: 29/03/1987

    Digite data2: 21/12/2017

    30 ano(s) 9 mes(es) e 5 dia(s) de vida
    269400 horas
    16164000 minutos
    969840000 segundos
    374 mes(es)
    11225 dia(s)
    1603 semana(s)

Aparentemente, acredito que o cálculo dos meses tem que subtrair pelos dias em excesso, por exemplo: nesta calculadora. Baseando se na mesma data de input do comentário acima e do da calculadora ele me retorna 368 meses exatos e meu programa retorna 374.
Eu sei que teria que fazer o seguinte calculo:
meses_totais((dias/30)-qtd_dias);

Aqui eu subtraio onde vai me dar exatos 368 meses, mas se eu digitar uma data equivalente a 1 ano e 3 meses ele me da problema nos cálculos de dias:
Por exemplo:
Digite duas datas no formato DD/MM/YYYY

Digite data1: 29/03/1987

Digite data2: 30/06/1988

1 ano(s) 3 mes(es) e 4 dia(s) de vida
11016 horas
660960 minutos
39657600 segundos
15 mes(es)
459 dia(s)
65 semana(s)

Mas a calculadora online me retorna: 1 anos, 3 meses, e 1 dias e 459 dias.
Queria entender onde que ele está dando essa brecha no erro somando dias a mais ou seja meu programa esta dando 3 dias a mais queria entender o porquê.
O quê está faltando nos cálculos para ser algo mais preciso em relação as horas, minutos, segundos, milissegundos, meses, anos, dias e meses a mais decorrente a partir da data de aniversario na quantidade de dias.
   int dias(daysDiff(d1,d2)); // diferença entre datas em dias contando anos bisextos

   int idade(dias/365); //idade em anos

   int qtd_dias((dias%365)%30); // qtd dias adicionais a partir do dia de nascimento

   int qtd_meses(((dias%365)/30)); // qtd meses adicionais a partir do mes de nascimento

   int meses_totais(dias/30);

   //int meses_totais((dias/30)-qtd_dias); // total de meses decorridos nos dias - dias a mais

   int qtd_semanas(dias/7); // qtd semanas total dos dias

   int horas(dias*24); // qtd horas total dos dias

   int minutos(horas*60); // qtd minutos total dos dias

   int segundos(minutos*60); // qtd segundos total dos dias

o programa é este abaixo:

#include <cmath>
#include <iostream>

//https://stackoverflow.com/questions/9987562/determining-the-difference-between-dates

    struct Date
    {
     int d, m, y;
    };

    int daysTill(int month)
    {
     int days=0;

     switch(month)
     {
      case 1: days=0; break;

      case 2: days=31; break;

      case 3: days=59; break;

      case 4: days=90; break;

      case 5: days=120; break;

      case 6: days=151; break;

      case 7: days=181; break;

      case 8: days=212; break;

      case 9: days=243; break;

      case 10:days=273; break;

      case 11:days=304; break;

      case 12:days=334; break;
     }

     return days;
    }

    int daysDiff(Date d1, Date d2)
    {
     int dd1=0;
     int dd2=0;
     int y=0;
     int yref=0;

     yref=((d1.y<d2.y) ? d1.y : d2.y);

     for(y=yref;y<d1.y;y++)
     if(__isleap(y))dd1++;

     if(__isleap(d1.y) && d1.m>2) dd1++;

     dd1+=((daysTill(d1.m) + d1.d)+((d1.y - yref) * 365));

     for(y=yref;y<d2.y;y++)
     if(__isleap(y))dd2++;

     if(__isleap(y) && d2.m>2)dd2++;

     dd2+=((daysTill(d2.m) + d2.d)+((d2.y - yref) * 365));

     return abs(dd2-dd1);
    }

int main()
{

 Date d1, d2;

   printf(
          "\n\tDigite duas datas no formato DD/MM/YYYY"
          "\n\n\tDigite data1: "
         );

   scanf("%d/%d/%d",&d1.d,&d1.m,&d1.y);

   printf(
          "\n\tDigite data2: "
         );

   scanf("%d/%d/%d",&d2.d,&d2.m,&d2.y);

   int dias(daysDiff(d1,d2)); // diferença entre datas em dias contando anos bisextos

   int idade(dias/365); //idade em anos

   int qtd_dias((dias%365)%30); // qtd dias adicionais a partir do dia de nascimento

   int qtd_meses(((dias%365)/30)); // qtd meses adicionais a partir do mes de nascimento

   int meses_totais(dias/30);

   //int meses_totais((dias/30)-qtd_dias); // total de meses decorridos nos dias - dias a mais

   int qtd_semanas(dias/7); // qtd semanas total dos dias

   int horas(dias*24); // qtd horas total dos dias

   int minutos(horas*60); // qtd minutos total dos dias

   int segundos(minutos*60); // qtd segundos total dos dias

   /*
   int segs(dias*86400);
   int horas(segs/3600);
   int minutos((segs-(horas*3600))/60);
   int segundos((segs - (horas * 3600)) - (minutos * 60));
    */

    printf(
           "\n\t%d ano(s) %d mes(es) e %d dia(s) de vida"
           "\n\t%d horas"
           "\n\t%d minutos"
           "\n\t%d segundos"
           "\n\t%d mes(es)"
           "\n\t%d dia(s)"
           "\n\t%d semana(s)\n\n",
           idade,
           qtd_meses,
           qtd_dias,
           horas,
           minutos,
           segundos,
           meses_totais,
           dias,
           qtd_semanas
          );
  return 0;
}

Answer: Para aumentar a precisão sugiro você usar variáveis do tipo float ou double ao invés do int que apenas armazena 4 bytes na memoria.
Comment: sim mas primeiro preciso entender o que esta faltando nos calculos o que tenho que incrementar para deixar preciso fora usar variaveis double...

Calculo de sobrevida em C


Can you tune one string on a Floyd Rose bridge without having to retune them all?

Question: Like if you want to go from EADGBE to DADGBE, can you just tune the 6th string down and be done with it, or will that offset the bridge and throw the other strings out of whack?
Comment: @AlbrechtHügli do you have a Floyd Rose on an acoustic guitar?
Comment: Don't FR systems always have a locking nut? Let's just assume so.
Comment: Is there a locking  nut..?
Comment: I used to do ithis quite  often with my acoustic guitar. There was no big problem. Just try it out!
Comment: Note that on my guitars with *fixed* tailpieces/bridges, I can't just tune the 6th string down to D and be done, I always have to fix the tuning of the other strings also. It's pretty minor, but it's clearly out of tune if I don't fix the other strings.
Answer: There's a simple way to find out. But more than likely they'll all be affected slightly. The springs balance the strings, and the strings' tension is being altered.
Answer: Sadly, no. With almost any vibrato bridge, when you change one string, it will change the position of the bridge, and you'll have to retune all the strings several times to find the bridge's new home position.
That's actually true for all string instruments, even guitars without vibrato bridges, it's just much more obvious with a vibrato bridge. That's because other things besides the bridge can move or change shape, primarily the neck. On acoustic instruments, the top often rises or falls slightly when tuning.
If you want to make sure you are tuned as well as possible, you should always go back and check each string until they are already in tune when you check them.
Answer: This actually is unrelated to whether the bridge is Floyd Rose or a non-locking model, the important distinction is whether it is set up as floating. Floating means the springs aren't so tight that the bridge is pressed against the top, but instead is balanced in an equilibrium between string- and spring tension. It it easy to find out whether a bridge is floating by pulling the lever, or simply pressing your hand flat on the bridge: if it's floating, the pitch will go up a bit, otherwise it will stay constant.
If the bridge is floating then yes, re-tuning any string will detune all the others, because the change in total string tension will shift the equilibrium. You could in principle re-tune the one string and then re-adjust the springs to compensate, but this isn't actually very practical – usually, instead the other strings will be tuned.
You can make a floating vibrato fixed by tightening the springs, or adding one more spring. The reason some guitarists prefer floating, apart from the ability to whammy up a bit, is that it allows a more gradual response. If it's fixed, you need to apply some initial force before the pitch changes at all, and then it goes down suddenly. But if you're only using the vibrato system for some violent drops anyway, then just don't set it up floating and you also won't have cross-string detuning problems (at least not more than with a fixed bridge).
Again, all of this applies just as much to Fender- Ibanez- and Floyd Rose style vibrato systems. About Bigsby I don't know.


Trying to find expected time between calls and find the associated variance

Question: The waiting time h (in hours) between each telephone call a person receives is random with the density function $f\left(h\right)=2e^{-2h}\:for\:h\ge 0$
Question: Find the expected time between calls and find the corresponding variance.
I am pretty much clueless on this question, I thought I could use this $V\left(a_1x_1+a_2+x_2\right)\:$
to find the variance, but for some reason, things are not adding up.
Answer: Hint: Suppose $H$ is the random variable for the waiting time between each telephone call a person receives with the corresponding density function $f(h)$. Then
$$Var(H)=\mathbb E\left(H^2\right)-\left[\mathbb E\left(H\right)\right]^2=\int\limits_0^{\infty} h^2\cdot  2e^{-2h} \, dh-\left[\int\limits_0^{\infty} h\cdot  2e^{-2h} \, dh\right]^2 $$
Comment: $\left(\int _0^{\infty \:\:}x\cdot \:2e^{-2x}\right)^2$ is it suppose to be like this or like this $\int _0^{\infty \:}\:\left(x\cdot \:\:\:\:2e^{-2x}\right)^2$ for where you wrote $-\left[\int\limits_0^{\infty} h\cdot  2e^{-2h} \, dh\right]^2 $
Comment: At the first one  you calculate the integral and then square the result. That is what I´ve posted. This is $[\mathbb E(x)]^2$. since $\int_0^{\infty} x\dot f(x) \, dx=\mathbb E(x)$ At the second one you square the term and then you calculate the integral of it.
Comment: Yeah but the thing is I  am not sure if $(∫)^2$ should be like that, I thought only the function was supposed to get cubed in 2 like this $((h⋅2e^{-2h})^2$
Comment: Look at the fomula $Var(X)=...-[\mathbb E(X)]^2$. So you calculate the expected value and square the result.
Comment: By the way, apply the product rule two times to calculate $Var(X)$.
Comment: $\int _0^{\infty \:}x^2\cdot 2e^{-2x}-\int _0^{\infty \:}\:\left(x\cdot \:\:\:\:2e^{-2x}\right)^2$ then this should be correct?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/113933/discussion-between-papps-and-callculus).
Comment: No, I´ve written the opposite. $\int _0^{\infty \:}x^2\cdot 2e^{-2x} \, dx-\left(\int _0^{\infty \:}\:x\cdot \:\:\:\:2e^{-2x} \, dx \right)^2$
Comment: @Papps If you have no further question accept the answer. Thanks.