extending regression lines with geom_line() ggplot2

Question: I used a negative binomial glm to look at vertebrate abundance in seagrass. Because I had an interaction term, I predicted some values for fish abundance. I would like these predicted regression lines to reach the end of the plot space. Right now they are all cutting off at different times, as in the example below:
total<-c(1,0,5,7,9,10,23,45,78,100)
shoots_collected<-c(1,2,3,4,5,6,7,45,67,88)
epi_bio<-c(0.0,11,0.89,1.5,9,5,.04,6,7,.9)
Year<-c(1,1,1,1,2,2,2,2,1,1)
Year<-as.factor(Year)
intertidal<-data.frame(shoots_collected,Year,epi_bio, total)

glm.neg<-glm.nb(total~Year+shoots_collected+epi_bio+shoots_collected*epi_bio,
data=intertidal)
summary(glm.neg)
abun_shoots2015<-data.frame("shoots_collected"=rep(0:30, rep(5,31)),
"epi_bio"=rep(c(0,1,2,3,4), 31), "Year"=rep("1", 155))

# then extracted predicted values using:

p2015<-predict(glm.neg, newdata=abun_shoots2015, se.fit=TRUE, type='response')
abun_shoots2015$fit<-p2015$fit
ggplot(intertidal, aes(x=shoots_collected, y=total)) +
scale_x_continuous(limits = c(0, 30))+
scale_y_continuous(limits=c(0,10))+
 geom_point(pch=1)+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==0.0000),], aes(x=shoots_collected, y=fit), col="red")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==1),], aes(x=shoots_collected, y=fit), col="green")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==2),], aes(x=shoots_collected, y=fit), col="blue")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==3),], aes(x=shoots_collected, y=fit), col="yellow")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==4),], aes(x=shoots_collected, y=fit), col="pink")

I was previously using the lines() command, but switched to geom_lines() so I could use fullrange=TRUE but it still did not work. I see that I have some missing values when I try to plot the lines, and I suspect that is why some are being cut off, but I don't know where to go from here.
Answer: You don't want to use scale_y_continuous etc here as they have the effect of trimming out data entirely that lies beyond the stated limits. Instead you want to limit the range of the plot to show only a portion of the data. This is done with coord_cartesian(), as in:
ggplot(intertidal, aes(x=shoots_collected, y=total)) +
 coord_cartesian(xlim = c(0, 30), ylim = c(0,10)) + ## KEY!
 geom_point(pch=1)+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==0.0000),],
           aes(x=shoots_collected, y=fit), col="red")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==1),],
           aes(x=shoots_collected, y=fit), col="green")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==2),],
           aes(x=shoots_collected, y=fit), col="blue")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==3),],
           aes(x=shoots_collected, y=fit), col="yellow")+
 geom_line(data=abun_shoots2015[which(abun_shoots2015$epi_bio==4),],
           aes(x=shoots_collected, y=fit), col="pink")

Also, I feel compelled to add that your plot could be more nicely produced by treating epi_bio as a factor:
ggplot(intertidal, aes(x=shoots_collected, y=total)) +
  coord_cartesian(xlim = c(0, 30), ylim = c(0,10)) + ## KEY!
  geom_point(pch=1) +
  geom_line(data = abun_shoots2015, aes(y = fit, colour = as.factor(epi_bio))) +
  scale_colour_discrete(name = "epi_bio") +
  theme(legend.position = "top")

Comment: Thanks, I was trying to use 'coord_cartesian' inside brackets instead of its own function. I still had issues with extending my lines on my real data (it worked for the example data but not on my own for some reason). What I did was predict from 0-35 shoots even though my maximum is 30. I'll just clip the graph off early, kind of cheating I know.  Thanks, this looks much nicer! I wasn't looking forward to manually adding a legend.


How to search the text using the string wild card php

Question: I am trying to search the following text if it contains the specific link:
this my test text and it ontains the link to http://example.com/abc/files and http://example.com/def/files

I want that if I search for the link http://example.com/*/files, it should show me the text.
I tried this code but no result:
if (preg_match("/http://example.com/i", $content, $matches, PREG_OFFSET_CAPTURE))
{
     // Code Here
}

Comment: use `#` as delimiters instead of `/` and it will work.
Comment: my question is that how i can use the wild card to search for example anything can come in place of asterisk http://example.com/*/files
Answer: You have two options:

Escape /
if (preg_match("/http:\/\/example.com/i", $content, $matches, PREG_OFFSET_CAPTURE)) {

Use # instead of /
if (preg_match("#http://example.com#i", $content, $matches, PREG_OFFSET_CAPTURE)) {

Also to use *, you need . in Regular Expression, so like this:
if (preg_match("#http://example.com/.*/files#i", $content, $matches, PREG_OFFSET_CAPTURE)) {

But be sure that simple wild card will match http://example.com/abc/files and http://example.com/def/files from your string. Since, you are trying to match any character(s) between http://example.com/ and /files. So, in this case, it finds the first instance and the last instance. Trying to match all in-between! To match only the first instance, use .*?. So you have to insert two extra symbols.
Comment: my question is that how i can use the wild card to search for example anything can come in place of asterisk example.com*/files
Comment: @Saqib Hmm. Updated at the same time!
Comment: it worked for me. thanks
Answer: you can do like this, don't use .* it match result as http://example.com/abc/files and http://example.com/def/files use [^/]+ or .*? instead
$content = 'this my test text and it ontains the link to http://example.com/abc/files and http://example.com/def/files';

if(preg_match("#http://example.com/[^/]+/files#i", $content, $matches)) {
    echo $matches[0];
    # http://example.com/abc/files
}

Answer: Another suggestion other than using regular expressions is fnmatch() since that can do match checks on strings as well. Supports shell wildcards
http://php.net/fnmatch
if (fnmatch("*http://example.com/*/files*", $content)) {}
There may be limitations though such as a character limit (4096? Since it's normally used on file names) and not being supported in Windows.


jQuery UI resizable/selectable not working in Backbone View

Question: I have a view for my model, and in the initialization I use the following code
initialize: function (){
        _.bindAll(this, 'render');
        this.listenTo(this.model, "change", this.render);
        this.$el.draggable({
            opacity: 0.5,
            containment: "parent"
        });
        this.$el.resizable();
        this.$el.selectable();
    },

Although draggable works, resizable and selectable do not (I haven't tested other jQuery UI interactions to check if they work). I tried placing this.$el.resizable inside the render function, but that wouldn't work either. I'm using jQuery 1.8.3 and jQuery UI 1.9.2 (I do include the necessary jquery-ui.css in my html). When the view renders, I inspect the element in my browser and it does indeed have a class of ui.draggable, ui.resizable and ui.selectable as it is supposed to, yet it's only draggable.
Trying to work around this issue, I've used CSS3 property resize: both in the class of the  element I want to resize and it works just fine, but I'd really like to utilize jQuery UI for resizing, and I'm curious why it won't work.
Any ideas what I might be doing wrong?
EDIT: Added jsfiddle example http://jsfiddle.net/IgnorantUser/u7JkX/ the problem described is in the initialization of the ButtonInCanvas backbone view
Comment: When is the element being inserted into the DOM?
Comment: you can check out the jsfiddle, but the element gets appended to the DOM once a 'drop' event has occured. The drop occurs in the CanvasView, but utilizing a method called passDrop, I pass the drop event (along with the coordinates) to the draggable "ButtonInToolbar" that was dropped into the canvas. Then with dropHandler method I append a new "ButtonInCanvas" into the DOM
Comment: Should I report a bug on this? From what I've read, previous versions of jQuery UI had issues with event delegation, maybe I stumbled upon a bug?
Comment: also tested with jQuery 1.9.0 and jQuery UI 1.10.0 and the problem persists
Answer: ok so, apparently using this.$el.html(this.template(this.model.toJSON())); in my render function on the ButtonInCanvas view was causing the problems. The aforementioned gets the "caption" attribute of the model, and passes it into the view as html content.
There solution is to put this.$el.html(this.template(this.model.toJSON())); in the init function.
In case it's needed to be done in the render function, there should be another div, within the one we want to resize, that will get the caption property from the model. In the following JSBIN you can see a solution using a div inside the button. (thanks to user shoky, from the #jquery freenode irc channel for the implementation and his heads up)
http://jsbin.com/uxequq/1/edit
I don't really understand why the problem was occurring though (maybe this.template(this.model.toJSON()) in my render function, was causing a re-rendering of the view?) so feel free to point me out why, and help me understand further!
Cheers!
Comment: since you change the html of the element which has ui-selectable or ui-resizable, the selectable and resizable need to be updated or re-applied. Because all the html which the selectable / resizable were based on (and had applied events to) has been removed or completely altered


Convolution of an $L^{1}(\Bbb{R})$ function with $\frac{1}{\sqrt{|x|}}$ is well defined?

Question: I think this should be true.
Let $f\in L^{1}(\Bbb{R})$ and consider $g(x)=\frac{1}{\sqrt{|x|}}$ , then is $(f*g)\,(y)$ well defined for $y$ almost everywhere?
I know that convolution of two $L^{1}$ functions is well defined but here $\frac{1}{\sqrt{|x|}}$ is not $L^{1}(\Bbb{R})$.
Instead what I was thinking was to consider $$\int_{\Bbb{R}}\frac{f(y-x)}{\sqrt{|x|}}\,dx=\int_{[-1,1]}\frac{f(y-x)}{\sqrt{|x|}}\,dx+\int_{\Bbb{R}\setminus[-1,1]}\frac{f(y-x)}{\sqrt{|x|}}\,dx$$
Now, for $|x|\geq 1$ we have $\frac{1}{\sqrt{|x|}}\leq 1$ hence $\displaystyle\int_{\Bbb{R}\setminus[-1,1]}\frac{|f(y-x)|}{\sqrt{|x|}}\,dx\leq ||f||_{L^{1}}$.
Hence  $\int_{\Bbb{R}\setminus[-1,1]}\frac{f(y-x)}{\sqrt{|x|}}\,dx$ is well defined almost everywhere in $\Bbb{R}\setminus [-1,1]$ as the integrals over the positive and negative parts of the above function will be finite.
We have that $\frac{1}{\sqrt{|x|}}$ is $L^{1}([-1,1])$. Hence, By Tonelli's Theorem, we have
$$\int_{[-1,1]^{2}}\frac{|f(y-x)|}{\sqrt{|x|}}\,d(x,y)=\int_{[-1,1]}\int_{[-1,1]}\frac{|f(y-x)|}{\sqrt{|x|}}\,dy\,dx\leq 4\cdot||f||_{L^{1}} $$
where the $4$ comes from $\int_{[-1,1]}\frac{1}{\sqrt{|x|}}\,dx$ and we have used the translational invariance property to conclude that $\int_{[-1,1]}|f(y-x)|\,dy\leq\int_{\Bbb{R}}|f(y-x)|\,dy=||f||_{L^{1}}$.
Hence as $\displaystyle\int_{[-1,1]}\frac{f(y-x)}{\sqrt{|x|}}\,dx$ is integrable over $[-1,1]$, it is finite almost surely over $[-1,1]$
Coupling both we have $\int_{[-1,1]}\frac{f(y-x)}{\sqrt{|x|}}\,dx+\int_{\Bbb{R}\setminus[-1,1]}\frac{f(y-x)}{\sqrt{|x|}}\,dx=\int_{\Bbb{R}}\frac{f(y-x)}{\sqrt{|x|}}\,dx=(f*g)(y)$ is well defined for $y$ almost everywhere.
Question: Is the above argument correct and is there any other (possibly shorter) way to do this? By shorter I obviously don't mean the omission of the (possibly) verbose justifications I gave at each step. Also, if the above is correct, we can say that the convolution with $\frac{1}{|x|^{a}}$ is well defined when $0<a<1$.
Comment: Sorry for my (now deleted) stupid comment. I agree with your argument.
Answer: It works for every $g=g_1+g_\infty\in L^1 + L^\infty$. This is essentially the same idea of cutting the function, but a shorter proof is by using Young's inequality. Indeed, it follows from Young's inequality that
$$
g_1* f\in L^1
$$
and
$$
g_\infty* f\in L^\infty
$$
Therefore $g* f\in L^1+L^\infty$ is defined almost everywhere.
Comment: Thanks! Indeed, I just treated $\frac{1}{\sqrt{|x|}}$ as an $L^{\infty}$ function subconciously for $[-1,1]^{c}$ but forgot to actually see that by Young's inequality, the justification is trivial and I need not write too much. Your way is both precise and short (+1).


Smoothing random noises with different amplitudes

Question: I have a function that returns a bounded noise. For example, let's imagine that out input range is [-1, 1]. With my method I can return a bounded/in range noise (depending on the biome we are currently).
<code>    /// <summary>
    /// Converts the range.
    /// </summary>
    /// <param name="originalStart">The original start.</param>
    /// <param name="originalEnd">The original end.</param>
    /// <param name="newStart">The new start.</param>
    /// <param name="newEnd">The new end.</param>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static float ConvertRange(
        float originalStart, float originalEnd, // original range
        float newStart, float newEnd, // desired range
        float value) // value to convert
    {
        float scale = (newEnd - newStart) / (originalEnd - originalStart);
        return (newStart + ((value - originalStart) * scale));
    }

    /// <summary>
    /// Gets the bounded noise.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <param name="meanHeight">Height of the mean.</param>
    /// <param name="amplitude">The amplitude.</param>
    /// <returns></returns>
    // [InRange(-.5f, .5f)] && [InRange(0, 1)]
    public static float GetBoundedNoise(float value, float meanHeight, float amplitude)
    {
        return Mathf.Clamp01(ConvertRange(0, 1, -amplitude, amplitude, ConvertRange(-1, 1, 0, 1, value)) + (meanHeight + .5f));
    }
</code>
Check this to understand what is mean height and amplitude: https://i.gyazo.com/9dc9cbe949f82d7342d7778e904563de.mp4
Note: Noise value is given by FastNoise library. (You can see it on Github)
The problem is that there is an height unmatch on each region border:
Normal region:

Noised region:

Black pixel is equal to y=0, and white pixel to y=1. (You can ignore yellow pixels)
But as you can see, there is diffent biomes with different amplitudes and mean heights (Water, Grass, Grass, DryGrass, Asphalt).
I have tried gaussian convolution, but there is a problem: Too many iterations for CPU (it would be optimal to be executed in GPU).
Why? Well, I apply a gaussian convolution for each region border pixel (I have an optimized method to get that). Imagine we get 810k points. And apply a convolution foreach pixel has 81 iterations (to get the mean of heights from that portion). But this is only for one pixel, now we have to do the mean for another 81 pixels (9x9) or 25 pixels (5x5) or whatever.
There are (in the best case) 1,640,250,000 iterations to do (to get a very small smoothed grid around each region border).
You can see my old code for this:
<code>            // Smothing segments

            //var kernel = Kernels.GAUSSIAN_KERNEL_9;

            //int kernelSize = kernel.GetLength(0);

            //if (pol != null && !pol.Segments.IsNullOrEmpty())
            //    foreach (Segment segment in pol.Segments)
            //    {
            //        int d = segment.Distance;

            //        for (int i = 0; i <= d; ++i)
            //        {
            //            Point p = (Vector2)segment.start + segment.Normal * d;

            //            //if (d % kernelSize == 0) // I tried to get less itwrations by checking if the current d modulus from kernelSize was 0. But no luck.
            //            Filters<Color32>.ConvolutionAtPoint(mapWidth, mapHeight, p.x, p.y, target, kernel, 1, pol.Center.x, pol.Center.y, true);
            //        }
            //    }
            //else
            //{
            //    if (pol == null)
            //        ++nullPols;
            //    else if (pol != null && pol.Segments.IsNullOrEmpty())
            //        ++nullSegments;
            //}
</code>
++ are debug counters, ignore them.
And Convolution at Point does the following:
<code>     private static void ConvolutionAtPointFunc(int width, int height, T[] source, params object[] parameters)
    {
        float[][] kernel = (float[][])parameters[0];
        int kernelSize = kernel.Length;
        int iteration = (int)parameters[1];

        int _x = (int)parameters[2];
        int _y = (int)parameters[3];
        int xOffset = (int)parameters[4];
        int yOffset = (int)parameters[5];
        bool withGrid = (bool)parameters[6];

        for (int ite = 0; ite < iteration; ++ite)
        {
            Color c = new Color(0f, 0f, 0f, 0f);

            for (int y = 0; y < kernelSize; ++y)
            {
                int ky = y - kernelSize / 2;
                for (int x = 0; x < kernelSize; ++x)
                {
                    int kx = x - kernelSize / 2;

                    try
                    {
                        if (!withGrid)
                        {
                            c += ((Color)(dynamic)source[F.P(_x + kx + xOffset, _y + ky + yOffset, width, height)]) * kernel[x][y];
                            ++FiltersDebug.convolutionIterations;
                        }
                        else
                        {
                            for (int i = 0; i < 81; ++i)
                            {
                                int __x = i % 9,
                                    __y = i / 9;

                                c += ((Color)(dynamic)source[F.P(_x + __x + kx + xOffset, _y + __y + ky + yOffset, width, height)]) * kernel[x][y];
                                ++FiltersDebug.convolutionIterations;
                            }

                            source[F.P(_x + kx + xOffset, _y + ky + yOffset, width, height)] = (dynamic)c;
                        }
                    }
                    catch
                    {
                        ++FiltersDebug.outOfBoundsExceptionsIn;
                    }
                }
            }

            if (!withGrid)
                try
                {
                    source[F.P(_x + xOffset, _y + yOffset, width, height)] = (dynamic)c;
                }
                catch
                {
                    ++FiltersDebug.outOfBoundsExceptions;
                }
        }
    }
</code>
As you can see very unoptimized. The code is from this: http://wiki.unity3d.com/index.php/TextureFilter
I can't imagine any other way to do this approach. The best I could imagine to do this, is to do draw a perpendicular line (perpendicular to the current segment (I have a util to get edges of a polygon (segment is formed by a start point and an end point where segment start = current edge and segment end = previous edge))) (with a mean noise for each point in the line). But there is also a problem:

There is a gap (marked with yellow) between segments with a obstuse projection. And an overlapped noise gradient on segments with sharp projection.
Another approach I realized is to get an gradient contour from all region borders that need it.
Something like that:

I also saw Cuberite implementation (http://cuberite.xoft.cz/docs/Generator.html#heightgen):
But I don't understand this part, and if I can extract something from this:

If we take the area of 9x9 biomes centered around the queried column,
  generate height for each of the biomes therein, sum them up and divide
  by 81 (the number of biomes summed), we will be effectively making a
  9-long running average over the terrain, and all the borders will
  suddenly become smooth. The following image shows the situation from
  the previous paragraph after applying the averaging process.

Note: I already created a distorted voronoi function to get the current biome at a terrain point (following this guide, but I don't fully understand what to do, because I don't understand this approach and I neither can see any code relative to this text).
But I don't where to start and neither how to resolve problem with an optimized algorithm. Also, I don't know what to research. So I have a problen, by this reason, any help is welcome.
Answer: I think this is not the best way to do this.
But, to everybody that visit this question, you should visit Part 2: Smoothing noises with different amplitudes (Part 2)
There is a very nice answer.


Pooling basic descriptives from several multiply imputed datasets (using mice)

Question: I am somewhat new to mice but I am trying my best. So I successfully imputed my data and created five datasets.
For the sake of simplicity, let's just use the nhanes dataset that comes with mice
 imp <- mice(nhanes, seed = 23109)

In my paper, I need to show basic descriptives (so for example: mean, standard deviation, skewness, kurtosis etc.). I understand that I can pool the parameters and results of my analysis with Rubin's rules using the following syntax:
fit <- with(imp, lm(chl ~ age + bmi))
print(pool(fit))

Call: pool(object = fit)
Pooled coefficients:
(Intercept) age bmi
-34.158914 34.330666 6.212025
Fraction of information about the coefficients missing due to nonresponse:
(Intercept) age bmi
0.5747265 0.7501284 0.4795427

But how would I go about this to report basic descriptives? Is there a way to combine these and a function in the mice package that does this for me, or do I have to do this manually? So for example I tried:
mean.fit <- with(data=imp, expr=mean(bmi))
pool(mean.fit)

and , I get the warning:
Error in pool(mean.fit) : Object has no coef() method.

which obviously means that is not how it should be done.
A different (and easier) possibility would be to pick just one of the imputed datasets to showcase (they are all very similar anyway. However, it feels like this wouldn't be a recommended thing to do because the whole upside of using multiple imputation should be that I am not pretending that the imputed values are the real values but that they come with a certain uncertainty.
If anyone could help me, I'd be very happy. Thanks.
Comment: I had this problem a few years ago. I cannot now remember what I did. I don't have time to dig out my archives tonight, but I'll have a look tomorrow.
Answer: If your goal is just to complete descriptives with no standard error around the descriptives (i.e., no confidence interval around the sample mean or sample standard deviation), you can use complete() to recover the imputed data sets and then perform actions on them. For example, to compute the average sample mean and variance across the imputations, you might do the following:
imp.data <- complete(imp, "long")
(means <- with(imp.data, tapply(bmi, .imp, mean)))
mean(means)
(variances <- with(imp.data, tapply(bmi, .imp, var)))
mean(variances)

If you want inference, you can manually apply Rubin's rules to the estimates.
Answer: Consider using miceadds package if you want to calculate standard deviations etc. See https://www.rdocumentation.org/packages/miceadds/versions/3.5-14/topics/with.miceadds
Comment: more of a comment


Seeking explicit bounds on the error term for the reciprocal product over primes in Mertens Third Theorem

Question: The reciprocal expression of Mertens Third Theorem should give us the following limit.
$$\lim_{x\to \infty}\Pi_{p \leq x} (1-\frac{1}{p})^{-1} = e^\gamma \;log(x)$$
I would be interested in learning of any known explicit upper and lower bounds on the "error term" (not sure if "error term" is the correct terminology here) as a function of $x$. Specifically, given
$$y=\Pi_{p \leq x} (1-\frac{1}{p})^{-1} - e^\gamma \;log(x)$$
what are the tightest known upper and lower bounds on the range of $y$ at $x$?
Additionally, is anything known concerning if and how many times $y$  changes sign? Thanks in advance.
Edit: I appreciate the quick responses on MSE. But I feel I should clarify what it is I'm hoping for.
1)  A concrete inequality for each bound. As an analogy or example, Robin gave the following upper bound governing his own famous inequality:
$$\sigma(n)-e^{\gamma}nloglogn<  \frac {0.6483n}{loglogn}$$
so that given $n$ one can quickly calculate a maximum value for the difference. Someone certainly must have made a similar computation for this Mertens asymptote.
2)  I think I may have read somewhere that it is not even known whether $y$  in the original question changes its sign at all or whether it remains positive for all $x$. I have been unable to find that source again and was wondering if that is correct.
2nd edit: After running a program to get a feel for this asymptote, I would just like to include the results here in order to share how quickly and nicely the product appears to converge to $e^\gamma \;log(x)$.
The five columns below are as follows:
1)  $k$ 2)  $k$th prime3)   $\Pi_{p \leq p_k}  (1-\frac{1}{p})^{-1}$4)   $ e^\gamma \;log(p_k)$  5)  $\Pi_{p \leq p_k}  (1-\frac{1}{p})^{-1}- e^\gamma \;log(p_k)$
<code>2    3         3                   1.95671             1.04329
3    5         3.75                2.86653             0.883475
4    7         4.375               3.46581             0.909193
5    11        4.8125              4.27083             0.541675
6    13        5.21354             4.56836             0.645181
7    17        5.53939             5.04616             0.49323
8    19        5.84713             5.24426             0.602873
9    23        6.11291             5.58454             0.528368
10   29        6.33123             5.9974              0.333831
11   31        6.54227             6.11618             0.42609
12   37        6.724               6.43131             0.292693
13   41        6.8921              6.61414             0.277959
....
2086 18211     17.4867             17.4719             0.014736
2087 18217     17.4876             17.4725             0.0151092
2088 18223     17.4886             17.4731             0.0154824
2089 18229     17.4895             17.4737             0.0158555
2090 18233     17.4905             17.4741             0.016424
2091 18251     17.4915             17.4758             0.015625
2092 18253     17.4924             17.476              0.0163881
2093 18257     17.4934             17.4764             0.016956
2094 18269     17.4943             17.4776             0.0167433
2095 18287     17.4953             17.4793             0.0159461
.....
5091 49547     19.2618             19.2546             0.00720897
5092 49549     19.2622             19.2547             0.00752583
5093 49559     19.2626             19.255              0.00755509
5094 49597     19.263              19.2564             0.00657834
5095 49603     19.2634             19.2566             0.00675124
5096 49613     19.2638             19.257              0.00678049
5097 49627     19.2641             19.2575             0.00666615
5098 49633     19.2645             19.2577             0.00683897
</code>
The main question asks: Is there a known upper bound on the 5th column strictly in terms of the 2nd column, much in the same fashion as Robin's bound given above?
3rd editUpon snooping around on MO, I came across this posting:
https://mathoverflow.net/questions/249147/mertens-3rd-theorem-upper-bound
With just a little reworking of the answer provided, it seems we have the following explicit lower bound from Rosser and Schoenfeld, thereby answering one part of the original question:
$$-\frac{e^\gamma}{2\ln x}<\ \prod_{p\le x}\frac p{p-1}-e^\gamma\ln x\ <\quad?$$
Obviously the question mark is my own as I am still seeking an explicit upper bound on the RHS. One would suspect it approaches zero far faster than the lower bound by considering the above table of values.
I'll try to gain access to the Rosser-Schoenfeld and Diamond/Pintz material, and if I come across an explicit upper bound will share it here.
Answer: Mertens' theorem states that $\prod_{p \leq x} (1- 1/p) = \frac{e^{- \gamma}}{log x}(1+ O(\frac{1}{log x}))$. By taking the reciprocal on both sides,
$\prod_{p \leq x} (1- 1/p)^{-1} = e^{\gamma}(log x)(1+ O(\frac{1}{log x}))$. As $x \rightarrow \infty$, you have the result stated in your post. Now,
$\prod_{p \leq x} (1- 1/p)^{-1} -e^{\gamma}log (x) = e^{\gamma}log (x)O(\frac{1}{log (x)})=O(1)$ as $ \gamma  =0.577215...$, which is the Euler - Mascheroni constant.
Comment: Curiously, though the difference _should_ be $O(1)$, it looks like it might be $o(1)$; I think this may be related to OP's question about whether the difference ever changes sign. Is anything more than just '$O(1)$' known about this term?
Answer: Also the error term  encodes the Riemann hypothesis. The first step is $\log(\prod_{p\le x} (1-p^{-1})) = -\sum_{p\le x}p^{-1}+B+O(x^{-1/2})$. Then

$\sum_{p\le x} p^{-1}=\log \log x+M+O(x^{\sigma-1+\epsilon}) \tag{1}$ iff $\zeta(s)$ has no zero for $\Re(s)>\sigma$.

This is because $(1)$ is equivalent to $$\sum_{p\in [x,y]}p^{-1}-\sum_{n\in [x,y]} \frac1{n\log n} = O(x^{\sigma-1+\epsilon})\tag{2}$$
which implies that $$\sum_p p^{-1-s}-\sum_{n\ge 2} \frac{n^{-1-s}}{\log n}=P(s+1)+\int (\zeta(s+1)-1)$$
converges for $\Re(s) > \sigma-1$. Thus, $P(s)+\int ( \zeta(s)-1)$ is analytic for $\Re(s) >\sigma$, since $P(s)=\sum_k \frac{\mu(k)}{k}\log \zeta(ks)$ has a singularity at each non-trivial zero of $\zeta(s)$ of real part $\ge 1/2$ it means that $\zeta(s)$ has no zero for $\Re(s) >\sigma$.
The converse, that if $\zeta(s)$ has no zero for $\Re(s) >\sigma$ then $\sum_p p^{-1-s}-\sum_n \frac{n^{-1-s}}{\log n}$ converges for $\Re(s) > \sigma-1$, is a much deeper tauberian theorem, its proof follows the same lines as in the prime number theorem.
The convergence of $\sum_p p^{-1-s}-\sum_n \frac{n^{-1-s}}{\log n}$ implies $(2)$ and $(1)$.


Como ecoar o valor de uma variável a partir do resultado da query

Question: Para automatizar o meu processo de gerar um JSON, eu salvo o nome da variável no banco de dados (Ex: $teste_value_1).
No meu arquivo.php eu tenho o valor dessa variável, por exemplo $teste_value_1 = "Isso é um teste";.
Depois eu faço uma query para ecoar essa variável, porém, ao invés dele me retornar o valor  da variável prevista anteriormente no PHP ("Isso é um teste"), ele sempre retorna sem interpretar a variável, apenas como texto ("$teste_value_1").
Abaixo a minha estrutura de dados para entender melhor o processo:
Tabela: attributes
id_attribute |  attribue_string | attribute_value
1            |  teste_string_1  | $teste_value_1
2            | teste_string_2   | $teste_value_2

Variáveis:
$teste_value_1 = "Isso é um teste";
$teste_value_2 = "Esse é outro teste";

Query:
    $query_array = mysqli_query($connect,"
                    SELECT GROUP_CONCAT(CONCAT('{id:', a.attribute_string, ',value_name:', a.attribute_value, '}') SEPARATOR ', ') AS concat
                    FROM rel_categories_attributes AS rca
                    INNER JOIN categories AS c ON c.id_category = rca.categories_id_category
                    INNER JOIN attributes AS a ON a.id_attribute = rca.attributes_id_attribute
                    WHERE id_category = '{$id_category}'
                    ");
WHILE ($reg_cat = mysqli_fetch_array($query_array)){

echo $teste_query = $reg_cat["concat"] . ",";

Resultado:
{id:teste_string_1,value_name:$teste_value_1},
{id:teste_string_2,value_name:$teste_value_2},

Resultado esperado:
{id:teste_string_1,value_name:Isso é um teste},
{id:teste_string_2,value_name:Isso é outro teste},

Comment: Talvez fosse mais viável salvar o json diretamente no banco.
Salvar no nome da variável php não vai funcionar. O php interpola a variável escrita no arquivo sob algumas condições. Uma string contendo a variável não será interpretada assim.
Answer: Você pode fazer isso através de um método chamado gambiarra. Com esse método você pode chamar a função get_defined_vars() e ela irá retornar todas as variáveis declaradas. Assim você pode buscar e substituir o valor $nome_da_variavel no valor retornado pelo banco de dados.
Segue exemplo comentado:
<?php

$teste_value_1 = "###########";
$teste_value_2 = "***********";

$text = '{id:"teste_string_1",value_name:"$teste_value_1"}, {id:"teste_string_2",value_name:"$teste_value_2"}';

/* Percorre todas as variáveis declaradas. */
foreach(get_defined_vars() as $variable => $value) {

    /* Verifica se o valor da variável é do tipo String */
    if (is_string($value)) {

        /* Realiza a busca e substituição */
        $text = str_replace(
                "\${$variable}",
                $value,
                $text
            );
    }
}

echo $text;

Obs.: Isso não é o recomendado, mas, no seu caso, vai funcionar. O ideal é que você pudesse salvar o conteúdo no DB.

Caso você saiba o nome das variáveis e caso elas não mudem o nome, basta utilizar apenas o str_replace, por exemplo:
$text = str_replace('$teste_value_1', $teste_value_1, $text);
$text = str_replace('$teste_value_2', $teste_value_2, $text);

echo $text;


Does the Lie derivative of a form $\alpha$ in the direction of $X$ at $p$ depend only on $X(p)$?

Question: Let $\alpha$ be a differential $k$-form and $X$ a smooth vector field on a Riemannian manifold $(M,\,g)$. Let $p\in M$. Then, if I'm given another smooth vector field $Y$ with $Y(p) = X(p)$, is it true that
$$
(\mathcal{L}_X\alpha)_p = (\mathcal{L}_Y\alpha)_p\,?
$$
The reason I ask is that from the definition of the Lie derivative
$$
(\mathcal{L}_XT)_p = \frac{\text{d}}{\text{d} t}\Bigg|_{t=0}\left((\Phi^X_{t})^*T_p\right)
$$
it seems like the above should be true. However, suppose that $M = \mathbb{R}^n$ with the standard metric. Then for an arbitrary vector field $X$ it is not true that $\mathcal{L}_X\star\alpha = 0$ implies $\mathcal{L}_X\alpha= 0$ because the Hodge star operator $\star$ commutes with $\mathcal{L}_X$ only if $X$ is a Killing field. But at each point $p\in M$,  can't we find a Killing field $Z$ that is parallel to $X$ so that $\mathcal{L}_Z\star\alpha = 0 \implies\mathcal{L}_Z\alpha = 0\implies \mathcal{L}_X\alpha = 0$?
Comment: Consider the special case of $\alpha=dx^1$ in some coordinates.  Then $\mathcal L_X(dx^1)=d(\mathcal L_X x^1)=dX^1=X^1_jdx^j$, so the above is not true.  (In contrast, it works for the covariant derivative, which is part of the motivation for its definition).
Answer: Here's a hint: You know that for a vector field $Z$, $\mathcal L_X Z = [X,Z]$. Does the value of the Lie bracket at $p$ depend only on $X(p)$? To use this to answer your question, then note that, for a $1$-form $\alpha$, $\mathcal L_X(\alpha(Z)) = (\mathcal L_X\alpha)(Z) + \alpha(\mathcal L_X Z)$.


Inpainting pixels between regions with nearest color in MATLAB

Question: Is there an efficient way to fill in pixels with a value of zero between pixels with non-zero values  with the nearest non-zero value, while leaving the rest of pixels at zero untouched?
To clarify, I am looking to inpaint those pixels whose closest distance to a non-zero pixel is lower than a given value (e.g. 4 pixels).
The image is initially represented as a matrix of uint32 integers.

In the example above, all the thin cracks between the  colored regions should be filled with the surrounding color, while large black regions should remain the same (i.e. the routine should  inpaint the pixels between the colored regions).
I imagine there is a way to do this via interpolation. In either case, I am looking for a relatively efficient solution.
Answer: Given an input matrix A:
b = imclose(A==0,ones(3,3)) %only the big zero regions
c = imdilate(A,ones(3,3)) %inpainting all neighboring pixels
d = zeros(size(A));
d(b==0) = c(b==0); %copy the inpainting only in places where there are no big regions

I haven't tested it, so there may be some problems with the code. (if you made changes to the code to make it work please edit my answer)


ZFS (NexentaStor) and 4k Advanced Format Partition Alignment

Question: I have a storage system that contains 8 x 1TB drives that use the 4k sector size "Advanced Format". I'm planning to run NexentaStor on this hardware and want to ensure that I'm taking the 4k sector size into account. Is there anything special I need to keep in mind when creating the root pool and subsequent data pools with ZFS?
Answer: ZFS handles 4k sectors well as long as the drive advertises them correctly.
However, some drives have 4k sectors internally but present a logical 512 sector size to the operating system for backwards compatibility. If ZFS believes the drive, and writes in 512 byte chunks to 4k sectors, you'll suffer a heavy read-modify-write penalty.
Have a look at the Solarismen blog:

Checking the physical sector size of disks on Solaris

If your drive reports a sector size of 4k, you're fine. If your drive reports a sector size of 512, you may be able to work around it by using the modified zpool binary from the same site:

Modified zpool program for newer Solaris versions

The modified binary hardcodes the sector size to 4k. Note that you only need to use it for the initial zpool creation. This may be a bit difficult for your root pool - you may need to slipstream the modified binary in to the NexentaStor ISO.
Comment: Thanks @PatJames - it looks like solarismen.de has changed to solaris.kuehnke.de, so I have updated the links
Comment: Thank you. I may not have a nice way to get this into the Nexenta installer, but depending on what the disks report, I may have to use the modified zpool binary. Is there any harm in having a misaligned syspool?
Comment: It will work but performance won't be ideal. You may not care about performance of the root pool if you hardly ever boot. It is technically possible to re-create the root pool at a later date if you need to, but not easy.
Comment: And your suggestion is to replace the binary in the ISO *before* I create the root pool?
Comment: Correct. The only time the modified binary matters is at pool creation time. However, you only need to do this if the disk requires it and if the performance of the root pool is important to you.
Comment: By the way, a trickier but possibly quicker solution would be to interrupt the Nexenta installer, use an lofs mount from an NFS share to overlay the zpool binary, and then resume the installer. Not easy though.
Comment: Thank you. This did work, and there was a noticeable impact on iozone benchmarks this hardware after testing zpools created with the native and the modified binaries. I did not bother to fix the root pool, though.
Comment: No worries, glad I could help.
Comment: fyi the links to solarismen.de are dead


Links not clickable on mobile devices in WordPress

Question: I am experiencing weird behaviour with links in WordPress. See attached screenshot. The links in the piece of text are clickable on desktop, but when switching to mobile they can not be clicked anymore.

I inspected the element to check if some z-index or layer is blocking it, but I can't seem to find it. Also the rest of the blocks in the website click fine on mobile.
If you want to try for yourself, website link: https://www.keeperstalent.nl
The part that gives trouble is on the homepage somewhere around the middle.
Any help is appreciated!
Comment: lol calm down it was just to show where the area is of the issue because the website is not in English.. There was no error in the console
Comment: You still have issues because you have not posted a [mcve] with your markup and code here within your question and not an image or link to any third party source.
Answer: I was able to fix it by adding:
a {
position: relative;
display: inline-block;
z-index: 2;
}

I'm not sure what was the problem, I just noticed that it works. And it only works with all of the three properties.
Comment: @RafRasenberg as @Cheslab mentioned, there is not need for `z-index` to be set so high because it overlaps with the header. So be sure to assign a lower value to `z-index` of your ``  than to `z-index` of your header. I just checked your website again, and it looks like even `z-index: 2;` for `` works.
Comment: Imagine there's a button tomorrow. You'll have to add same css for buttons? What about `input`s, `textarea`s, other clickable elements? Don't forget that `div`s can be clickable with js, as well as any other element. I think restore the normal flow of the document is a much preferable solution.
Comment: @Cheslab Of course making HTML and CSS valid is a preferable solution, but sometimes it's not possible to edit HTML because of using different kind of builders, plugins, etc.
Answer: You actually have a problem with columns overlap.

All you need to do is to make these two columns to have the same classes:

Though Andrey's answer will do the trick it may lead to undesirable consequences like this:

Now all links are placed over your header and popups
Comment: Great notice, though the "undesirable consequences" can be fixed by changing `z-index` to a desired value.
Comment: Thanks man!! I noticed the problem for the other fix indeed. This is the right solution.
Comment: Hi @Rob, you're taking it wrong, it's a help page about "how to ask," section "Help others reproduce the problem." It has nothing to do with my answer. Nonetheless, I have posted all the code needed and typed the description of the problem and the solution, so my answer carries the message even without all the images.
Comment: Before your edit, if one removed your image, would it provide an answer to the question? That was the issue.


Angular2 - How can I retry after an HTTP Request fails and still subscribe to the error?

Question: I'm buiding an application that is suppose to trigger an http.get request and retrigger
 the request every 5 seconds if an error occures. But I need to be able to display this error on Screen while the request is retriggered.
I didn't find any solution with rxjs's retry/retryWhen because they simply intercept the error before retriggering, and I can't get to subscribe to the error.
Here's my code:
Service:
@Injectable()
export class CompanyService extends WabelService {
    constructor (private http: Http) {
      super();
      this.service_uri = "company";
    }

    getCompany(id: string): Observable<Company> {
        return this.http.get(this.url+"/"+id)
            .retry()
            .map(response => response.json());
    }
}

Component:
@Component({
  selector: 'app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.less'],
  providers: [CompanyService]
})
export class EeeComponent implements OnInit {
  target: any;
  error: CustomError;

  constructor(
      private route: ActivatedRoute,
  ) {}

  ngOnInit(): void {
      this.route.params
          .switchMap((params: Params) => this.companyService.getCompany(params['id']))
        .subscribe(
            (company) => this.target = company,
            (error) => {
              // Can't reach this !
              this.error = error;
            }
        );
    }
}

Answer: I'd suggest moving the retry logic out of the companyService.
ngOnInit(): void {
  this.route.params
   .switchMap(({id}) =>
     this.companyService.companyService.getCompany(id)

       // Handle the retry logic here instead so you have access to this.error
       .retryWhen(e =>

         // Set the error when you receive one
         e.do({
           error: err => this.error = err
         })

         // Delay each error by 5 seconds before emitting for a retry
          .delayTime(5000)

         // Optionally stop trying after a while
         .take(10)
       )

       // If you get out here then the error has been dealt with
       // and you can disable your error state
       .do(_ => this.error = null)
   )
   .subscribe(
     company => this.target = company,
     fatalError => console.error('Something really bad happened', fatalError)
   );
}

Comment: Thanks! this is very helpful.  But in my version of Angular, i have to use `delay(5000)` instead of delayTime
Answer: implement an Observable.Interval to make your http request every 5s. have a look at this thread : Angular2 http at an interval
Comment: Okay my bad, I did saw this thread but gave it up for some reason. It works like a charm !


Como usar o javascript para enviar dados do Form para um endereço de email?

Question: Bom dia, estou trabalhando em um código que usa um FORM com método POST e preciso que os dados desse FORM ao serem submetidos sejam encaminhados para um email e não para um servidor. Isso tudo utilizando apenas JavaScript, procurei mas não encontrei nos outros post's, encontrei soluções apenas com PHP. Se alguém puder me ajudar a como realizar essa Action usando JS.
<form class="formulario" action="" method="post">

Answer: O que você quer fazer não é possível pelo lado do cliente. De acordo com a própria documentação do elemento <form>:

O elemento HTML <form> representa uma seção de um documento que contém controles interativos que permitem ao usuário submeter informação a um determinado servidor web.

Desse modo, levando em conta que servidores de e-mail não são, de fato, "servidores web", não é possível enviar dados a eles. Geralmente servidores de e-mail utilizam outros protocolos, como o SMTP, diferentes dos protocolos usados pela web.
O máximo que você pode fazer é utilizar o protocolo mailto, que geralmente abre o cliente de e-mail padrão do sistema operacional com os campos já pré-definidos:

<form method="get" action="mailto:firstname.lastname@example.com">
  <input name="subject" placeholder="Assunto" />
  <textarea name="body" placeholder="Mensagem"></textarea>
  <button type="submit">Enviar</button>
</form>

Note que isso não irá "enviar" o e-mail, apenas abrir o cliente padrão do sistema. Para saber mais como esse protocolo funciona no elemento <form>, consulte a especificação.
Comment: Muito obrigado pela ajuda amigo.


i have 10000 images in a vector form how do i convert it for my Convolution neural network?

Question: I am new to Convolutional Neural Network. Instead of getting my data in image format i have been given flattened images matrix which is [10000x784].
Means 10000 images of size 28x28
Considering one image size is 28x28, how should i give the data matrix to my input for CNN?
My model is:
model = models.Sequential()
model.add(layers.Conv2D(64, (3, 3), activation='relu', input_shape=(28,28,1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
#model.add(layers.Flatten())
model.add(layers.Dense(2500, activation='relu'))
model.add(layers.Dense(2500, activation='relu'))
model.add(layers.Dense(1, activation='relu'))
model.compile(optimizer='adam',
              loss='mean_squared_error',
              metrics=['mae','mse'])
callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=15)
#Fits model
history= model.fit(x_trained, y_train, epochs = 7000, validation_split = 0.2, shuffle= True, verbose = 1, callbacks=[callback])

I get error at model.fit.
P.S: I am doing regression and for every image i have one value as output
Comment: Use the `reshape()` function of numpy to reshape the images. `img = img.reshape((10000, 28, 28, 1))`
Comment: There's also `reshape` node in [tf](https://www.tensorflow.org/api_docs/python/tf/reshape).
Answer: Begin with a Reshape layer:
model = models.Sequential()
model.add(layers.Reshape((28, 28, 1), input_shape=(784,)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# ...

Comment: I already tried that. But then at the model.fit() what should be X? Should i reshape here too?
Comment: @AR. If you add a reshape layer like this, then you keep your training data as `(num_images, 784)`. Alternatively, you could reshape your training and test data before feeding it to the Keras model, like `x_train.reshape(-1, 28, 28, 1)`, then you would not need to change the layers in the model.
Comment: Hi, i am training the same dataset with LSTM and get the following error.. what can i modify?
**Keras ValueError: Input 0 is incompatible with layer conv_lst_m2d_16: expected ndim=5, found ndim=4**


Fitting n number of rectangles of n L & W into n number of probably Large Rectangles

Question: I have n number of rectangles(small ones) of n length and width and have n number big rectangles of n length and width. In short there is one list of rectangles to be fitted and another list of rectangles in which these rectangles will be fitted.
I am studying about various package fitting algorithms and I know various questions has been asked for the same but can't help me with this type of problem.
My question is how to optimally choose which big rectangle to choose first and how to fill small rectangles into it without being overlapped and minimum wastage area, until all the small rectangles are fitted in the big ones. It is OK, if the big rectangles are left unfilled when all the small rectangles are fitted.
Please help me where to start with and if the question doesn't give much clarity then please let me know. My purpose is to write an algorithm for the same problem.
Comment: Too broad for SO. You may want to search for "packing problem".
Comment: Optimally or just some "hopefully good" approximation?
Comment: Are the target rectangles of the same size?
Comment: @Codor No the target rectangles can be of both different sizes as well as same size.
Comment: @harold Optimally will be great but it will be good to start with "Hopefully good" approximation, so do you have any point from where I can start with ?
Comment: @Henry yes I know it is a broad question with n number of solutions, but I am just asking from where I can start and thanks for suggesting to look into "packing problem". I am currently digging into it and will get back if I find something useful.
Answer: To answer the question in part, the problem under consideration is NP-hard as it contains the Partition problem as a subproblem.


Whats the best way to return values in my Youtube Downloader .dll?

Question: So I'm basically making a youtube downloader .dll. What I need is to return two different types of values with their own values. I have tried writing these to a temporary file but this is resource consuming.
I need to return a collection of values called the youtube links
I need to return a collection of values called the youtube link qualities
I need to return a collection of values called the youtube link types
How should I do this?
Dictionary?
Comment: Why do the `out` or `ref` specifiers not cover the requirements?
Answer: How about just defining a custom class which describes the returned data?
<code>public class YouTubeLink
{
   int Quality{get;private set;}
   string Type{get;private set;};
   string Url{get;private set;};
   public YouTubeLink(...){...}
}

public class YouTubeVideoInfo
{
   public ReadOnlyCollection<YouTubeLink> Links{get;}
   ...
}
</code>


How to delay between animation and appear after previous animation in css

Question: I want to ask, how to make the delay between animation in css? I've tried to make it but it still appears at the beginning and then the animation function.
What I want is the object / text only show after the previous animation (object 3).
Here is my code in jsfiddle: [http://jsfiddle.net/sugoi/bV6Pc/]
Thank you
Comment: jquery? [jquery delay](http://api.jquery.com/delay/)
Answer: You need to play with the opacity.
Let see : fork jsfiddle
<code>.slideRight {
    opacity: 0.0;
}

@keyframes slideRight {
    0% {
        transform: translateX(-150%);
        opacity: 1;
    }
    <!--...-->
    100% {
        transform: translateX(0%);
        opacity: 1;
    }
}
</code>
But it seems to need some js..
Comment: Thanks for the quick reply. But, why after it the animation is disappear? How to make it always show at the end? Thank you.
Answer: Within the css animation, you can specify a delay, so you can manipulate the two animations
syntax - animation: name duration timing-function delay iteration-count direction;


Existence of a complete norm on $\ell^2$ which extends $\|۰\|_1$ (on $\ell^1$)

Question: We know that norm-1 is a complete norm on $\ell^1.$ Also $\ell^1$ is a subspace of $\ell^2.$ Now, is there a complete norm
on $\ell^2$ which extends norm-1 (on $\ell^1$)?
Answer: Let $V$ be an algebraic complement of  $\ell ^1$ within $\ell ^2$,  so that $\ell ^2 = \ell ^1 \oplus  V$.  It is easy to see that the algebraic
dimension  of $V$ is $2^{\aleph_0}$,  so $V$ is algebraically isomorphic to any separable infinite dimensional Banach space $X$.  Choosing such
an $X$ let
$$
  \varphi :V\to X
  $$
be an algebraic  isomorphism and define a norm on
$\ell ^2$
by
$$
  \|x\| = \|x_1\|_1 +  \|\varphi (x_2)\|,
  $$
where
$$
  x = x_1+x_2
  $$
is the decomposition of any given $x$  in $\ell ^2$ according to
$\ell ^2 = \ell ^1 \oplus  V$.  This norm satisfies the requirements.

EDIT.  I guess my statement above that "the algebraic
dimension  of $V$ is $2^{\aleph_0}$" is not so immediate,  so let me make up for this.
That statement is clearly equivalent to
$$
  \text{dim}(\ell ^2/\ell ^1) = 2^{\aleph_0},
  $$
so let us  prove this instead.
For each $\alpha >0$, consider the vector
$$
  x_\alpha =(1/n^\alpha )_{n\in {\mathbb N}},
  $$
and observe that $x_\alpha \in \ell ^p\Leftrightarrow p\alpha >1$.  In particular
$$
  x_\alpha \in \ell ^2,  \quad \text{and}\quad x_\alpha  \notin  \ell ^1,\quad \forall \alpha \in (1/2,1].
  $$
We next claim that the set
$$
  \{x_\alpha : \alpha \in (1/2,1]\}
  $$
is a linearly independent set in $\ell ^2/\ell ^1$.  To prove  this we must verify  that, whenever
$$
  \lambda _1x_{\alpha _1}+  \lambda _2x_{\alpha _2}+\cdots  + \lambda _nx_{\alpha _n} \in  \ell ^1,
  \tag 1
  $$
one necessarily has $\lambda _1=\lambda _2=\cdots =\lambda _n=0$.  Assuming by contradiction that this is not so, we may discard the zero terms in
the above sum and hence suppose  that the $\lambda _i$ are all nonzero.  We may also assume that  the $\alpha _i$ are organized such that
$$
  \frac 1{\alpha _1}<  \frac 1{\alpha _2}<\cdots <  \frac 1{\alpha _{n-1}}<\frac 1{\alpha _n}.
  $$
Chosing any real number $p$ in between the last to terms above, that is,
$$
  \frac 1{\alpha _{n-1}}<p<\frac 1{\alpha _n},
  $$
we then have that $p\alpha _n<1$, so $x_{\alpha _n} \notin \ell ^p$,  while $p\alpha _k>1$, for all $k=1,2,\ldots ,n-1$,  so $x_{\alpha _k} \in \ell ^p$.
However,   (1) implies  that
$$
  \lambda _nx_{\alpha _n}\in    \ell ^1-  \lambda _1x_{\alpha _1}-  \lambda _2x_{\alpha _2}-\cdots  - \lambda _{n-1}x_{\alpha _{n-1}} \subseteq  \ell ^p,
  $$
a contradiction.
This shows that
$$
  \text{dim}(\ell ^2/\ell ^1) \geq  2^{\aleph_0},
  $$
but since the cardinality of the whole of $\ell ^2$ is
$2^{\aleph_0}$,  it is evident that the opposite inequality holds as well.
Comment: It is indeed simple, but of course highly non constructive!
Comment: Hello Ruy, do you mean that $V$ is an "algebraic complement" of $\ell^1$ in $\ell^2$? I mean, when taking $V$ you are doing so topology-less right?
Comment: Yes.  Edited accordingly.
Comment: Thanks; it is a very nice and simple answer,  thumbs up from me!
Comment: Thanks. In your answer, why the algebraic dimension of $V$ is $2^{\aleph_0}?$
Comment: Can we claim the dimension of the algebraic complement of a Banach space $Y$ in the Banach space $X$ never equals $\aleph_0?$ Here, $Y$ is a linear subspace of $X?$
Comment: Yes.  Bay Baire, $X$ cannot be a countable union of proper, closed subspaces of the form $$Y+\text{span}\{x_1,x_2,\ldots,x_n\}.$$


Calculating proportion to find sample size

Question: I have population, and I need to find a sample size using the equation
<code>MoE = 1.96*/sqrt(p(1-p)/n * (N-n)/(N-1))
</code>
I know all values except n (obviously) and p...I am supposedly able to get a value of p from this information

Calculate the required sample size that would need to be distributed among survey interviewers if you do not want to allow more than 3% margin of error for all percentages calculated from the sample

Any ideas of how to find the value of p?
Answer: I believe you misunderstood the question. When it asks: "Calculate the required sample size" this means that the value of interest is $n$ and not $p$. The trick here is that you need to find a single value of $n$ that works for all possible values of $p$.
Since we are interest in finding $n$ we should isolate it in the expression for $MoE$:
$$n = N\left(1 + \frac{MoE^2(N-1)}{1.96^2p(1-p)}\right)^{-1}$$
I strongly encourage you to derive yourself the previous expression. Maybe I did something wrong :)
If we knew $p$ than all we have to do is compute the value given by the previous expression and select the first integer grater than the resulting value. But since we do not know $p$ we need to find a value of $n$ that works for all $p$.
Note that we can write $n = N*f(p)$ where $f(p) = \left(1 + \frac{MoE^2(N-1)}{1.96^2p(1-p)}\right)^{-1}$ and now it is clear that the correct value of $n$ is
$$n = N*\underset{0\leq p \leq 1}{\max}f(p)$$
But now we need to find $\underset{0\leq p \leq 1}{\max}f(p)$. First we note that $p(1-p)$ has a maximum in $p = 1/2$, consequently $1 + \frac{MoE^2(N-1)}{1.96^2p(1-p)}$ has a minimum at $p = 1/2$ and finally $\left(1 + \frac{MoE^2(N-1)}{1.96^2p(1-p)}\right)^{-1}$ has a maximum at $p = 1/2$.
After all of this we get that the value of $n$ that works for all $p$ is
$$n = N*f(1/2) = N\left(1 + \frac{4MoE^2(N-1)}{1.96^2}\right)^{-1}$$
Comment: Mur1lo makes a good point.  You can get a conservative required sample size by taking p=1/2.  Sometimes there is prior information that allows you to choose a p different from 1/2.  One way is to do a small pilot study and use the result to determine the sample size you will need.
Comment: Your equations indicate that you have a finite known population size N and you need to fina a sample size n<N that proviides a sufficiently accurate estimate of p.  You did not mention this.


Is there an x86 intrinsic that generates the AVX512 broadcast operation from a 32 bit floating point value in memory to a 512 bit register?

Question: The instruction exists (vbroadcastss zmm/m32) but there seems to be no intrinsic to generate it.
I can code it as
static inline  __m512 mybroadcast(float *x) {
    __m512 v;
    asm inline ( "vbroadcastss %1,%0 "
                 : "=v" (v)
                 : "m" (*x)
                 );
    return v;
}

Is there a way to do this without inline asm?
Comment: @JL2210: yup, it's a typo and the `x` operand should be `"m"(*x)` to tell the compiler you want the *float* in memory, not a pointer in memory.  Or maybe better, `"xm"(*x)` might let the compiler give it to you in an XMM register instead of memory in case that was convenient; unlike AVX1, the AVX2 and AVX512 versions of `vbroadcastss` work as a reg-reg shuffle as well as a load.  https://www.felixcloutier.com/x86/vbroadcast.  Anyway, that's still worse than an intrinsic because it defeats constant-propagation optimization among other things.
Comment: @PeterCordes You shouldn't make sweeping edits like this.
Comment: @JL2210: Why not?  It's asking the exact same question better, without errors in the example.  I'm not going to start an edit war, but I'd recommend that Steve roll back to my edit.  I don't see that it's changing the intent in any way, and the original being totally broken was a distraction.  As a gold badge holder in several relevant tags (`[gcc]`, `[x86]`, `[c]`, etc.), I think improving questions to clearly ask what the OP clearly intended is a Good Thing when I understand the topic well enough to make edits like this.
Comment: you forgot to specify in which language in tags
Comment: It would depend entirely on the compiler ... but I suspect "No: you've already got the best solution you're likely to find".
Comment: @FoggyDay I'm thinking of the standard intel intrinsics.
Comment: It looks as if it doesn't exist: `test.c:5: Error: no such instruction: 'vpbroadcastss %zmm0,-64(%rsp)'`
Comment: Change it to `vbroadcastss` and it says `test.c:5: Error: operand size mismatch for 'vbroadcastss'`
Comment: @JL2210: Just for fun I fixed the code in the question in case anyone's curious :P
Comment: @JL2210: After your edit, it still won't compile with just `gcc -march=skylake-avx512`.  The inline asm uses intel-syntax.  That comment was important; you'll still get your operand size mismatch error.  I also included links to the asm manual to justify the question as not being "lack of research effort" - usually you can find intrinsics for instructions in the asm manual entry.  And more details about why inline asm was sub-optimal because at least one commenter thought asm might already be optimal!  Anyway, the OP can choose between my edit or yours with a rollback.
Comment: @PeterCordes Thanks for pointing that out. I've fixed the operand order.
Comment: Why do you assume the OP wanted AT&T syntax instead of Intel syntax?  Both are technically valid choices.  (Although AT&T is usually standard).
Answer: I think _mm512_set1_ps is what you want.
https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm512_set1_ps&expand=5236,4980
Comment: @SteveLinton: if you search for `broadcast` in that same intrinsics guide, `_mm_set1` intrinsics show up in the results (buried under a ton of AVX512 masked, unmaked, etc. stuff).  But if you control-f search within page for `float`, you find them quickly along with AVX1 `_mm256_broadcast_ss`.  (But there's no AVX512 version of that intrinsic.)


Drupal 7 - How to loop foreach in multiple value in custom view

Question: I'm customizing a view (in views-view--myview.tpl.php) based on a node which has a field with multiple value (field_galerie_image).
I'm trying to list in a foreach loop that particular field, and I am wondering how to write it down.
In the following code, I can access a value with $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; but I need to loop through it.
$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][1]["filename"];
$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][2]["filename"];

The code I am using is the following one.
<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php print $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; ?>
  <?php endif; ?>
<?php endforeach; ?>

Answer: I found it out; the correct code is the following one.
<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php foreach ($vue->_field_data["nid"]["entity"]->field_galerie_image['und'] as $val): ?>
      <?php print $val['filename']; ?>
    <?php endforeach; ?>
  <?php endif; ?>
<?php endforeach; ?>


How to limit access to certain users for those who have "administer users" permission

Question: EDIT: I have found out how to solve the 'administer users permission needed' problem so I don't really need to know the answer for this. I will not delete the question however, since I would like to know the answer out of curiosity anyway.
Because of this I need to give the permission 'administer users' to everyone while still being able to manage access to individual users (to their view and edit pages as well as to their cancellation).
Therefore I need to restrict users with 'administer users' permission to be able to edit just certain users (based on their id and the id of the user that is to be viewed or edited). (the access function itself is not the problem I already have that one)
I thought about doing something like 'Administer Users by Role' plugin but as it seems there are just too many potential security issues there (the 'administer users permission' is not used only in access to user edit/view but e.g in access to user fields settings page as well.
Any ideas?
Comment: please revise your question to make it clear without linking readers to another questions with 'like this'.
Comment: Done.
//The first one 'because of this' is actually not important therefore I left it there.
Comment: Thanks. It's not very convenient to go through many links to understand what is asked for, especially for the readers on mobile devices. I'll post tomorrow an answer that would give you some hints, if you get none till then. I must go offline now.
Answer: The administer users permission is a VERY powerful permission and you shouldn't give this permission anyone that you don't trust. Otherwise, the users with that permission can do all nasty things. For example:

They can manage fields on user accounts at admin/config/people/accounts/fields
They can manage permissions and grant/revoke users including themselves other permissions at admin/people/permissions
They can add/cancel/edit users including admins!

Conclusion: Never, ever give this permission to ANYONE!
There are a few modules that let users granularly administer other users. One of them is the Administer Users by Role. Although, its latest version for Drupal 7 requires to give this mighty permission to the users, but there's a patch, which I also contributed, at this issue page. With this patch, you don't need to give 'administer users' permission to the users and still allow them to administer other users.
There are also other related modules, but I cannot tell anything about them since I don't use them:
Subuser

This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.

Role Delegation

This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.


What is the type of xs in NStepBiLSTM in Chainer?

Question: The manual on the NStepBiLSTM says its forward function expects xs to come in the format of a list of Variable-wrapped sequences. However I get an error that implies xs is supposed to be a np array. What am I missing?
I use this function to turn an input array into a list of variable(array) with array shape (n,1).
def cut_data(data, batchsize):
    q = data.shape[0] // batchsize
    data = data[:q*batchsize]
    data = data.reshape((batchsize, q))
    xs = []
    for i in range(q):
        a = data[:,i].reshape(batchsize,1)
        xs.append(Variable(a))
    return xs

But when I call my predictor with such an xs I get this error:
<ipython-input-27-cb554613ad71> in __call__(self, xs, ts)
     10         batchlen = len(xs)
     11         loss = F.sum(F.mean_squared_error(
---> 12         self.predictor(xs), ts, reduce='no')) / batch
     13
     14         chainer.report({'loss': loss}, self)

<ipython-input-28-ce9434e91153> in __call__(self, x)
     12     def __call__(self, x):
     13         self.h, self.c, y = self.lstm(self.h,self.c,x)
---> 14         output = self.out(y)
     15         return output
     16

~\Anaconda2\lib\site-packages\chainer\links\connection\linear.py in __call__(self, x)
    127             in_size = functools.reduce(operator.mul, x.shape[1:], 1)
    128             self._initialize_params(in_size)
--> 129         return linear.linear(x, self.W, self.b)

~\Anaconda2\lib\site-packages\chainer\functions\connection\linear.py in linear(x, W, b)
    165
    166     """
--> 167     if x.ndim > 2:
    168         x = x.reshape(len(x), -1)
    169

AttributeError: 'list' object has no attribute 'ndim'

This is my simple network:
class LSTM_RNN(Chain):

    def __init__(self, n_hidden, n_input=1, n_out=1):
        super(LSTM_RNN, self).__init__()
        with self.init_scope():
            self.lstm = L.NStepBiLSTM(n_layers=n_hidden, in_size=n_input, out_size=n_out, dropout=0.5)
            self.out = L.Linear(n_hidden, n_out)
            self.h = None
            self.c = None

    def __call__(self, x):
        self.h, self.c, y = self.lstm(self.h,self.c,x)
        output = self.out(y)
        return output

    def reset_state(self):
        self.h = None
        self.c = None

Answer: The error message
---> 14         output = self.out(y)

indicates that your error is triggered by self.out() method, not self.lstm()
According to the official API reference, L.NStepBiLSTM.run() returns a tuple of hy, cy, and ys, which ys is a list.
Your code
    def __call__(self, x):
        self.h, self.c, y = self.lstm(self.h,self.c,x)
        output = self.out(y)
        return output

indicates that y (which is referred as ys in the official document) is directly passed to self.out, which is L.Linear.__call__. This causes type-mismatch.
In general, the shape of y in ys differs each other, because x in xs can be a sequence of different lengths.
If you need more help, please feel free to ask questions!


Rsyslog convert msg timestamp to rfc3339 format

Question: I've got the following rsyslog conf and the below log message I'm receiving. I'm extracting the timestamp from the log message using regex but since it's a not so nice format, I want to convert the timestamp to rfc3339.
I find rsyslog's documentation is missing a lot of things for someone starting fresh. Is this something which can be done within the template? I appreciate any hints/clues how to achieve this.
/path/to/log/file.log
 11955 - [Mon Apr  6 20:40:03 2023] [Info   ] This message can contain anything [d54d13fa-4657-4891-f99d08674ee]

/etc/rsyslog.d/mylog.conf
module(load="imfile")
input(type="imfile" tag="mylog" file="/path/to/*/file.log")

template(name="jsonFormat" type="list") {
    property(outname="timestamp" name="msg" regex.expression="^[^[]*\\[([^]]*)\\]" regex.type="ERE" regex.submatch="1" format="jsonf")
}

if ($syslogtag == "mylog") then {
    action(type="omfile" file="/path/to/output/file.log" template="jsonFormat")
}

Answer: RainerScript has some functions you can use to manipulate the input line with. For example,
template(name="myformat" type="string" string="%$.date% %msg%\n")
set $.date = re_extract($rawmsg, "\\[... (.{15})", 0, 1, "");
if ($.date != "") then {
 set $.unixtime = parse_time($.date);
 if($.unixtime != 0) then {
  set $.date = format_time($.unixtime, "date-rfc3339");
  action(type="omfile" file="output" template="myformat")
 }
}

The re_extract() function works like the regex.expression in your
template property. Here it finds the [, skips the 3 character weekday,
and captures the next 15 characters, omitting the year as that is not part
of RFC3164. The year is assumed to be approximately "this year".
The returned value is saved in a local variable of your choice, $.date. Note the obligatory ; at the end of lines beginning set.
If
the match worked, parse_time() is used to convert it from RFC3164 to Unix
seconds-from-the-epoch. If this worked, format_time() converts it to an
RFC3339 string. The variable is used in a template just like any property with
%$.date% in a string or property(name="$.date" ...).
Comment: Thank you for the detailed breakdown. I'll give this a go tonight and adjust it slightly to match my config.


Showing that a one-relator group, $\langle a,b \mid W \rangle$, is not a free product.

Question: Let $W=W(a,b)$ be a cyclically reduced word in $\langle a,b;\emptyset\rangle$ not equal $1$ that contains at least one non-zero power of $a$ and at least one non-zero power of $b$.
How can be proved that the group $G=\langle a,b;W\rangle$ is not a free product of two non-trivial factors?
Comment: I was wondering whether, rather than $W$ contains non-zero powers of $a$ and $b$, you meant proper powers i.e. powers $a^n$ with $n \ne -1,0,1$.For example $W=a^2bab^{-1}ab^{-3}$. That would be a more difficult question. I think that in that case $G$ cannot decompose as a free product, but I can't quite prove it. If it was a free product then it would have to be ${\mathbb Z}_n * {\mathbb Z}$ for some $n>1$.
Comment: It can't be proved, because it is not true: e.g. $G=\langle a,b \mid a^2 \rangle$ is a free product.
Comment: OK, how about $\langle a,b \mid (ab)^2 \rangle$ (which isomorphic to $\langle a,b \mid a^2 \rangle$)?
Comment: I have to edit the question because the problem is interesting when W contains a non-zero power of both $a$ and $b$.
Comment: you are right. If this would be shown as  an answer, I would definitely accept it.
Answer: First off, as pointed out by Derek Holt, your "conjecture" is wrong. You want to decide when $F_2/\langle \langle W \rangle \rangle$ (that is mod out by the normal closure of $W$) splits as a free product.
$F_2$ can split to be $F_1 * F_1'$, but there are many different ways to split $F_2$ in that way (any basis for $F_2$ provides such a splitting.) This provides the ideas for the "obvious" splittings. If $W \in F_1$, you get that your one-relator group will be isomorphic to $F_1/\langle \langle W \rangle  \rangle * F_1'$. In this case, $W=U^n$, where $U$ is some basis element of $F_1$. It is algorithmically decidable to determine whether or not an element $U$ is an element of a basis, hence you can determine whether or not you have a one-relator group of the above form, hence have a group that splits as a free product of nontrivial groups. The algorithm is described in Lyndon and Schupp (of course), Ch I, Prop 4.19. The basic idea is that you will have to transform $U$ into $x^{\pm 1}$ or $y^{\pm 1}$ using a sequence of Whitehead transformations, and you can prove you only have to do finitely many before you shorten $U$ has much as you can, and if it isn't one of those, it isn't a basis element. (the algorithm actually is more general than this, but it is the basic idea).
To actually apply the idea, you can find a different basis, for example $(a,ab)$ is a basis, hence you know that $\langle a ,b  \mid (ab)^n \rangle $ splits non-trvially, when $n\neq \pm 1,0$. Basically you use the automorphism group of $F_2$ to construct a different basis.
If your group does not have torsion then it does not split as a free product, since it would have to split into cyclic factors, and the one-relator group on two generators can't be isomorphic to $F_2$ ($F_2$ is hopfian). A nice result is that a one relator group has torsion only if the relation is a proper power of a word (this is Lyndon and Schupp, Ch IV, Thm 5.2). Using this you can tell that Derek Holt's example in the comments, $a^2bab^{-1}ab^{-3}$, can not split the group into a non-trivial free product, since it is not a proper power, hence the group does not have torsion.
A natural follow-up question: is whether this is the only way for the group to split? Yes it is! In fact the idea essentially holds for one-relator groups in any number of generators (greater than $1$). You can see the nice answer on mathoverflow.  (The "essentially" comes from the fact that the one-relator does not have to be of the form $U^n$, since we don't have to split into cyclic factors as in your special case)
Comment: I think Derek's conjecture in the comments, about both $a$ and $b$ having proper powers might be correct,(maybe it could be worked out by doing some induction on Whitehead transformations or something) but I have not thought about it much.


Spring - migrando de MVC para Rest

Question: Eu fiz um CRUD com Spring Boot, MVC, Security e outros módulos do Spring. Para o front-end usei Thymeleaf. Aparentemente está tudo funcionando, mas na descrição do problema pede "A aplicação deverá conter algumas APIs Rest para o consumo externo: cadastro e consulta de usuários e recursos".
O que devo alterar na minha aplicação?
mudar de @Controller para @RestController?
os retornos dos métodos das controllers podem continuar retornando ModelAndView e String ou tem que retornar ResponseEntity?
O front-end pode continuar com Thymeleaf?
O que exatamente tem que fazer o consumo externo da API Rest? Só responder a requisição em JSON para o postman?
Comment: Olá bom dia leo, sim meu caro @RestController, ModelAndView não porque agora vc não terá uma View, a Api será consumida por qualquer client então JSP, JSF, PHP, Postman, e ou até uma aplicação Web Spring +Thymeleaf, HTML + Jq, quem consumir terá que indicar o end-point ex http://localhost:8080/api/usuarios o retorno pode ser um JSON mais pode ser um XML, Texto ..... isto é negociável, vá em frente que vc esta perto.
Answer: Você está complicando um pouco o requisito. Ao pedir:

"A aplicação deverá conter algumas APIs Rest para o consumo externo: cadastro e consulta de usuários e recursos".

Não quer dizer que precisa usar o mesmo Controller de tela para isto. Os Controllers existentes, que retornam ModelAndView, continuam da mesma forma como estão hoje.
O que você pode fazer é criar um novo Controller, no caso, um RestController (ou mais de um, se achar melhor).
Ele ficará exclusivamente responsável para atender a estes consumos externos, podendo assim definir o formato de saída (Json), segurança, versionamento da API, endereço de acesso diferente, etc, sem interferir nos Controllers existentes.
Naturalmente, o código de Service e e Repository serão compartilhados internamente entre os Controllers e RestControllers, para evitar duplicação de código e etc.

Spring - migrando de MVC para Rest


Conditional probability question about children

Question:
Sushma has $2$ children. Let $A$ be the event that the oldest child is a girl, $B$ be the event that at least one child is a girl, and $C$ be the event that both children are girls. Which of the following are correct statements:
  (a) $P(C\mid A)=\frac{1}{2}.$
  (b) $P(C\mid B)=\frac{1}{2}.$
  (c) $P(C\mid A)=\frac{1}{3}.$
  (d) $P(C\mid B)=\frac{1}{3}.$

I tried doing it by venn diagram but couldn't get the result.
Comment: latex style is preferd over pictures
Comment: some Information is missing? Is it given that probability of  boy or girl both $0.5$?
Comment: @JoeyDoey Nothing about the probability of any event is given !
Comment: @SR810 What? A and B are independent???
Comment: How are A and B independent events? @SR810
Comment: I am sorry I slightly misread the question
Answer: By definition, $P(C|A) = \frac{P(C \cap A)}{P(A)}$ and $P(C|B) = \frac{P(C \cap B)}{P(B)}$.
If we assume $P(A) = \frac{1}{2}$, then $P(C|A) = \frac{0.5 \times 0.5}{0.5} = \frac{1}{2}$.
Clearly $P(B) =\frac{3}{4}$ and so $P(C|B) = \frac{0.5 \times 0.5}{0.75} = \frac{1}{3}$.
So (a) and (d) are the only true statements here.
Alternatively, we can use some quick intuition. $P(C|A)$ means the probability that both children are girls, given that the oldest child is a girl. Clearly, this is just the probability of the youngest child being a girl: $\frac{1}{2}$. $P(C|B)$ means the probability that both children are girls, given that at least one of them is a girl. In this case, we see that there are three possibilities: the oldest child being a girl, with the youngest being a boy, the oldest being a boy with the youngest being a girl, and both children being girls. Of these three possibilities, only one of them meets our criteria, so clearly the probability is $\frac{1}{3}$.


CakePHP JsController could not be found.

Question: When trying to access Javascript files from the webroot, I get the following error:
Missing Controller
Error:

JsController could not be found.
Error:

Create the class JsController below in file: app\Controller\JsController.php

<?php
  class JsController extends AppController {

  }
?>

I'm running without .htaccess files. Here is my configuration:
Listen 9090

<Directory "c:/wamp/apscmdb/">
    #
    # 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.2/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:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride none

    #
    # Controls who can get stuff from this server.
    #

#   onlineoffline tag - don't remove
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1

</Directory>

<VirtualHost *:9090>
    DocumentRoot "c:\wamp\apscmdb"

    <Directory "c:/wamp/apscmdb/">
            RewriteEngine On
            RewriteBase /app/webroot
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ index.php [QSA,L]

    </Directory>

</VirtualHost>

I'm trying the following code:
echo $this->Html->script('portal');
Which outputs:

I found this that sounds similar, but no solution has been provided:
Error: JsController could not be found
Comment: You are on localhost or live server?
Comment: @FazalRasel ATM, its local development yes... using WAMP.
Comment: You have to use .htaccess file inside app directory
Comment: @Anubhav I'm trying to replicate this without the use of .htaccess files as they're not available in my production environments.
Comment: See /js/portal.js will always look for controller without .htaccess so you can change HTML helper so that it will create different path for js and css files
Comment: @Anubhav funny enough, if I add app/webroot/js/portal.js, they resolve just fine. I could modify the helper to output that path?
Comment: @Anubhav Did you want to provide your comment as an answer so that I can accept it?
Comment: @No my agenda is help, nothing else!
Comment: put this App::uses('AppController', 'Controller'); on top of your controller and then try
Answer: Solution:

Either use .htaccess files
Or modify the HTML helper to output the appropriate URLs for webroot


Calculus - Solving limits with square roots

Question: I am having trouble understanding how to solve this limit by rationalizing. I have the problem correct (I used Wolfram Alpha of course), but I still don't understand how it is completed. I was trying to solve this by multiplying both the numerator and the denominator by $\sqrt{x^2+11}+6$, but I am stuck. Is that the way to solve this? If so, could you walk me through it so I can solve others?
Problem:
Comment: Can you factor $x^2-25$?
Comment: I'm really really new to this and haven't taken algebra in a very long time, you are going to have to explain more @GitGud
Comment: Do you know what 'factoring a polynomial' means?
Comment: i have done that before, but I don't understand what you are factoring? the bottom? As you can see i already have the correct answer and unfortunately my book is so cryptic i can't understand it (as most pearson books are), I only need to see how it is done one time and I will understand it, im not asking for bits and pieces. I'm asking for a full explanation.
Comment: I may have misjudged where you are stuck. Factoring $x^2-25$ will be useful, hence my question.Your idea of multiplying top and bottom by $\sqrt{x^2+11}+6$ is good though. I'm sure someone will help you momentarily.
Answer: $$\begin{align}
\lim_{x\to 5}\frac{\sqrt{x^2+11}-6}{x-5}
  &= \lim_{x\to 5}\frac{\left(\sqrt{x^2+11}-6\right)
    \left(\sqrt{x^2+11}+6\right)}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{\left(\sqrt{x^2+11}\right)^2-6^2}
    {(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{x^2+11-36}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{x^2-25}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{(x-5)(x+5)}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{x+5}{\sqrt{x^2+11}+6} \\[2ex]
  &= \frac{5+5}{\sqrt{5^2+11}+6} \\[2ex]
  &= \frac{10}{12} \\[2ex]
  &= \frac{5}{6}
\end{align}$$
Comment: I see now what @Git Gud was talking about. this is very clear now....i was missing the 5th & 6th step. Thank you. This will help me with further problems like this
Answer: A possible step-by-step solution: write $x=y+5$ (so that you are looking for a limit as $y\to 0$), and the denominator is $x-5=y$
$$\begin{align}
\sqrt{x^2+11} &= \sqrt{(y+5)^2+11} = \sqrt{y^2+10y + 36} = \sqrt{36}\sqrt{1+\frac{10}{36}y+\frac{y^2}{36}} \\
&= 6 \sqrt{1+\frac{5}{18}y+\frac{y^2}{36}}
\end{align}
$$
From there,
$$\begin{align}
\sqrt{x^2+11} - 6 &= 6 \left(  \sqrt{1+\frac{5}{18}y+\frac{y^2}{36}} - 1\right)
\end{align}
$$
Now, if you know Taylor series, you can immediately apply the fact that $\sqrt{1+u} = 1+\frac{u}{2} + o(u)$ when $u\to 0$ to get that
$$\begin{align}
\sqrt{x^2+11} - 6 &= 6 \left(  1+\frac{5}{36}y+ o(y) - 1\right)
= 6 \left(  \frac{5}{36}y+ o(y)\right)
= \frac{5}{6}y+ o(y)
\end{align}
$$
and now
$$\frac{\sqrt{x^2+11} - 6}{y} = \frac{\frac{5}{6}y+ o(y)}{y} = \frac{5}{6} + o(1) \xrightarrow[y\to 0]{} \frac{5}{6}.$$


git : nothing changed but mark every line "changed"

Question: IDE : Eclipse & VS code
Git tool : source tree, VS code
Action : Nothing changed in my code. But when pressing ctrl+s, it's able to save and suorceTree will show every line has been edited. The only change I found (show by sourceTree) :
form:
import org.apache.poi.ss.usermodel.Cell;␍import org.apache.poi.ss.usermodel.CellType;
to this:
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType;
I'm quite sure that I'm not using any "format code on save" settings, is it a git bug in this version?
trying : ctrl + s in vs code, eclipse, wordPad
excepting : to edit a line (not changing the whold file when saving) and push to git branch.
Comment: I would guess a mistake by you rather than a mistake by Git, considering that you don't even mention your configurations like `core.autocrlf`, etc.
Answer: By default Git uses LF (Linux) Line Endings, Windows on the other hand pushes CRLF Line Endings.
Git tries makes the assumption that if you are using Windows, you want CRLF, this is good for normal users because programs generally come pre-configured to use CRLF.
If you are using Windows and you are getting false changes reports, it is likely that Git is ignoring the line endings, so when you clone or pull code, it will be in LF. Then when you save your progress in your CRLF-configured editors, each line ending is being changed back to CRLF, modifying the whole file.
This behavior can be altered during the Windows installation of Git, pay close attention to it next time you install Git.
Solution 1: Configure Git
You can configure Git to *replace LF to CRLF when checking out (cloning, pulling...) so you can work in CRLF, and then replace CRLF back to LF when you commit so that you don't commit whole practically unchanged files. The option you want is core.autocrlf, you can do it in your terminal:
git config --global core.autocrlf true

The --global parameter makes this change for your entire user (which you probably want to)
Solution 2: Start using LF
You could configure your Text Editors and IDEs to use LF by default, that way when you clone or pull in LF, you will keep working and saving your work using LF, retaining Git's default line endings.
You can usually find this option refeered to as EOL (End Of Line).
Comment: After reviewnig code (showing all hidden character), I found that there's a line ends with CR instead of CRLF, the change of that line make git think that I change the whole file.
Letting git ignore white spaces changes true helps, thank u!
Comment: Thanks so much for answering me! Just like u said, I'm using Windows. Is there a solution not to make the "replace movement" happens? or not commiting all lines on git? I believe non of my coworkers would be glad to slove tons of conflict just cause by line endings.
Comment: While researching a bit more into the problem I found out that I was mixing up some things... I updated my answer with more accurate information and added the proper solutions. I hope this works for you!


Vertical text sliding animation

Question: I want to create animation similar to lving.io where different text reveals. I tried to recreate this but the animation is not smooth.
I tried assigning different animation delays to the texts, but they are not working in sync.
The texts are revealed at the same time when they should be revealing one at a time.

    .animation-container {
      display: flex;
      align-items: center;
      height: 1.5em; /* Adjust this based on your content size */
      font-size: 1.2em; /* Adjust this based on your design */
      overflow: hidden;
    }

    .base-text {
      white-space: nowrap;
    }

    .spans-container{
    margin-left: 5px;
    display: flex;
    flex-direction: column
    }

    .word {
      margin: 0;
      opacity: 0;
      animation: fadeInOut 9s linear infinite;
    }

    .word:nth-child(2) { animation-delay: 3s; }
    .word:nth-child(3) { animation-delay: 6s; }

    @keyframes fadeInOut {
      0% {
        opacity: 0;
        transform: translateY(100%);
      }
      15% {
        opacity: 1;
        transform: translateY(0);
      }
      30% {
        opacity: 1;
        transform: translateY(0);
      }
      45% {
        opacity: 1;
        transform: translateY(0);
      }
      60% {
        opacity: 0;
        transform: translateY(-200%);
      }
      75% {
        opacity: 0;
        transform: translateY(-200%);
      }
      90% {
        opacity: 0;
        transform: translateY(-200%);
      }
      100% {
        opacity: 0;
        transform: translateY(100%);
      }
    }

    The future of home

       living
       owning
       renting

Answer: Have the words be on top of each other before we apply the animation. This will simplify the animation since the words are in the same place, but with the animation offset:

.animation-container {
  display: flex;
  align-items: center;
  height: 1.5em;
  /* Adjust this based on your content size */
  font-size: 1.2em;
  /* Adjust this based on your design */
  overflow: hidden;
}

.base-text {
  white-space: nowrap;
}

.spans-container {
  margin-left: 5px;
  display: grid;
}

.word {
  margin: 0;
  grid-area: 1 / 1 / -1 / -1;
}

  The future of home

     living
     owning
     renting

For the animation, we have 3 elements, so our keyframe "active" duration should be 33.33%, since 100% ÷ 3 = 33.33…%. This is so our animations can be offset seamlessly:
■ Visible
◻ Invisible

 0%/100%     33.33%      66.66%     0%/100%
1: |■ ■ ■ ■ ■ ■|◻ ◻ ◻ ◻ ◻ ◻|◻ ◻ ◻ ◻ ◻ ◻|■ ■ ■
2: |◻ ◻ ◻ ◻ ◻ ◻|■ ■ ■ ■ ■ ■|◻ ◻ ◻ ◻ ◻ ◻|◻ ◻ ◻
3: |◻ ◻ ◻ ◻ ◻ ◻|◻ ◻ ◻ ◻ ◻ ◻|■ ■ ■ ■ ■ ■|◻ ◻ ◻

.animation-container {
  display: flex;
  align-items: center;
  height: 1.5em;
  /* Adjust this based on your content size */
  font-size: 1.2em;
  /* Adjust this based on your design */
  overflow: hidden;
}

.base-text {
  white-space: nowrap;
}

.spans-container {
  margin-left: 5px;
  display: grid;
}

.word {
  margin: 0;
  grid-area: 1 / 1 / -1 / -1;
  animation: fadeInOut 9s infinite both;
}

.word:nth-child(2) {
  animation-delay: -6s;
}

.word:nth-child(3) {
  animation-delay: -3s;
}

@keyframes fadeInOut {
  0%, 33.33%, 100% {
    opacity: 1;
    transform: translateY(0);
  }
  33.34% {
    opacity: 0;
    transform: translateY(-100%);
  }
  99.9% {
    opacity: 0;
    transform: translateY(100%);
  }
}

  The future of home

     living
     owning
     renting

We then add some animation either side of 0% and 33%. It should be the same percentage amount so that the outgoing and ingoing animation happen together and at the same speed. For example, 10%:
■ Visible
◻ Invisible
◧ Transitioning out
◨ Transitioning in

 0%/100%     33.33%      66.66%     0%/100%
1: |■ ■ ■ ■ ■|◧|◻ ◻ ◻ ◻ ◻ ◻|◻ ◻ ◻ ◻ ◻|◨|■ ■ ■
2: |◻ ◻ ◻ ◻ ◻|◨|■ ■ ■ ■ ■ ◧|◻ ◻ ◻ ◻ ◻|◻|◻ ◻ ◻
3: |◻ ◻ ◻ ◻ ◻|◻|◻ ◻ ◻ ◻ ◻ ◨|■ ■ ■ ■ ■|◧|◻ ◻ ◻
           23.33%                   90%

The trick is to ensure the 10% transitioning overlaps by subtracting/adding 10% to the appropriate keyframe.

.animation-container {
  display: flex;
  align-items: center;
  height: 1.5em;
  /* Adjust this based on your content size */
  font-size: 1.2em;
  /* Adjust this based on your design */
  overflow: hidden;
}

.base-text {
  white-space: nowrap;
}

.spans-container {
  margin-left: 5px;
  display: grid;
}

.word {
  margin: 0;
  grid-area: 1 / 1 / -1 / -1;
  animation: fadeInOut 9s infinite both;
}

.word:nth-child(2) {
  animation-delay: -6s;
}

.word:nth-child(3) {
  animation-delay: -3s;
}

@keyframes fadeInOut {
  0%, 23.33%, 100% {
    opacity: 1;
    transform: translateY(0);
  }
  33.33% {
    opacity: 0;
    transform: translateY(-100%);
  }
  90% {
    opacity: 0;
    transform: translateY(100%);
  }
}

  The future of home

     living
     owning
     renting

Comment: Wow. that's exactly what I was looking for. Thanks for explaining it step by step.
Answer: If you want to do it with css only, you can create individual animations for each word.
To avoid having to do it myself, I used a generator that was created in another stackoverflow answer.
You might find it useful:

.animation-container {
  font-size: 1.2em;
}

.spans-container {
  display: inline-flex;
  position: relative;
  overflow: hidden;
}

.word {
  position: absolute;
  inset: 0;
}

/* the largest word width */
.word:nth-child(2) {
  position: relative;
}

/* code from the generator */
.word:nth-child(1) {
  animation: slide1 12s infinite;
}
@keyframes slide1 {
  0% { transform: translateY(100%); }
  3.333333333333334%, 30% { transform: translateY(0); }
  33.333333333333336%, 100% { transform: translateY(-100%); }
}

.word:nth-child(2) {
  animation: slide2 12s infinite;
}
@keyframes slide2 {
  0%, 33.333333333333336% { transform: translateY(100%); }
  36.66666666666667%, 63.333333333333336% { transform: translateY(0); }
  66.66666666666667%, 100% { transform: translateY(-100%); }
}

.word:nth-child(3) {
  animation: slide3 12s infinite;
}
@keyframes slide3 {
  0%, 66.66666666666667% { transform: translateY(100%); }
  70%, 96.66666666666667% { transform: translateY(0); }
  100% { transform: translateY(-100%); }
}

  The future of home

    living
    owning
    renting

Comment: That looks amazing.

Vertical text sliding animation


How to grab the last 12 months from cygwin "date" and use the months for git sync

Question: I'm trying to compare the trees of a repo as they were at the end of the month for the past 12 months, to see what changed.  I am a newb - so far my code basically looks like this:
for month in Jan Feb Mar Apr May Jun Jul Aug Sep
git checkout $(git rev-list --before "$month 1 2011" -n 1 HEAD)
I'd like to make this work for the last 12 months, going back to the previous year.  I want it to by dynamic - how do I make a loop that iterates over the last 12 months, ending on the current month?  I want the month value to be a variable I can use both in for "..." and in my git checkout ... line.
Thanks!
Answer: You might want to try something like this:
for i in {1..12}; do
    git checkout $(git rev-list --before "$(date -d "$(date -d +%Y-%m-15) -$i months" +%Y-%m)-01" -n 1 HEAD)
    ...
done

Comment: fatal: ambiguous argument 'months': unknown revision or path not in the working tree.
Comment: Use '--' to separate paths from revisions
Comment: Which command is giving the fatal error?  The git command should never have seen the word "months", as that was a parameter to `date`.
Comment: Are you sure you entered that command exactly as I wrote it? There are a number of potential quoting issues if you aren't careful.
Comment: Missed a parenthesis!  Thanks a lot!
Comment: Almost!  One issue:  it seems that the is an error for February...  As a test I wrote `mkir "$(date -d "$i months ago" +%Y-%m)-01"` just to see if I'd get 12 months worth of directories.  Instead of making `2011-02-01` it tries to make `2011-03-01` twice.  Ideas?!


WPF Conditionally Enable KeyBinding

Question: I have a WPF project in which I am trying to enable/disable keyboard shortcuts based on the state of public property from my viewmodel. Maybe there is a super simple solution to this, but I'm new to WPF and I couldn't find anything from google. Here is my working XAML:
 <KeyBinding Modifiers="Control" Key="p" Command="{Binding PrintCommand}" CommandParameter="{Binding OpenEvent}"/>

Here is what I would like to do:
<KeyBinding Modifiers="Control" Key="p" Command="{Binding PrintCommand}" CommandParameter="{Binding OpenEvent}" IsEnabled="{Binding IsOnline}"/>

Basically, I'm wondering if there is something similar to the "IsEnabled" property of WPF buttons that I can apply to this. I have about 20 different shortcuts that are depending on this variable. I could go into the code behind for each of the 20 commands and add logic, but that seems fairly kludgy and I'm thinking there has to be a better way. I've seen solutions using "CanExecute", but that is for commands of type ICommand and I'm using commands of type RelayCommand.
Comment: hello, are you using `mvvm-light`?
Comment: @dellywheel Yes, sorry I should have mentioned that.
Comment: Good framework :) I'll post an example in a sec
Answer: You can use the mvvm-light RelayCommand CanExecute in your KeyBinding Commands. Heres a simple example where I have blocked the use of the P Key based on SomeProperty
MainViewModel.cs
private bool someProperty = false;

    public bool SomeProperty
    {
        get { return someProperty = false; }
        set { Set(() => SomeProperty, ref someProperty, value); }
    }

    private RelayCommand someCommand;
    public RelayCommand SomeCommand
    {
        get
        {
            return someCommand ??
                new RelayCommand(() =>
            {
                //SomeCommand actions
            }, () =>
            {
                //CanExecute
                if (SomeProperty)
                    return true;
                else
                    return false;
            });
        }
    }

and the Binding on the front end
MainWindow.xaml
<Window x:Class="WpfApplication12.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
<Window.InputBindings>
    <KeyBinding Key="P" Command="{Binding SomeCommand}" />
</Window.InputBindings>
<Grid>
    <TextBox Width="200" Height="35" />
</Grid>

Hope it helps
Answer: Use the command's CanExecute method on your view-model.
Then you could remove your IsEnabled property within your XAML.

WPF Conditionally Enable KeyBinding