Should you or shouldn't you wear two pair of socks?

Question: I skate in hockey skates, but for recreational purposes.
I am wondering if one should really wear two pair of socks? When I was buying skates, they guys in the shop adviced me to wear them, but now when I am suffering ugly lace bites I doubt the logic behind it:

the skate feel is more puffy, because of all cushioning from all sides
the foot is placed higher
I cannot insert anything extra in front, because there is already very little room inside skate

So maybe it is all wrong, and I should go with single pair of socks, get maximum fit from the skates, and forget about wearing anything extra because of the folk-tradition?
I am not looking for opinions, I am looking for hard reasons (and late update: it is from fit perspective, not insulation/warmth).
Answer: I've looked around and no where can I find instances where skaters wear 2 pairs of socks. I actually found someone's post saying that he did this and his feet slid around too much.
If you wear two socks, your feet will slide around because of the two layers. This causes foot blisters and a decreased amount of control you will have while skating. I hope it makes sense when I say two socks will make your feet slide around yet make the skate tight. You do not want this. You want the skates tight without the aid of wearing two socks. You want the skates to fit perfectly with one pair of socks. A point brought up by many is...

If you wear double socks, doesn't that mean your skates don't fit?

Many recommend thin socks or even underarmor-like tights. These allow the skate to be tight on your foot but also allow you to feel where your foot is thus resulting in better performance and control. Some players don't even wear socks with skates. LA Kings goalie Jonathan Quick is  rumored to not wear any socks!
Comment: Yeah you should look up more professional shops around you. Also buy hockey socks that are comfortable and wear them to your skate fitting.
Comment: Thank you for your informative answer. Control is something I would like to have. Unfortunately the shop I was buying skate is not very pro, they recommended wearing double socks while adjusting skates and now I have ugly lace bites.
Comment: Just a quick add-up, thanks to your advice (and changing pattern of the laces) I almost (almost!) eliminated lace bite. How great is that! On the other side of flip coin -- now I realized my skates are a bit too big.
Answer: I found skating barefoot worked best though a thin sock should be fine also.  By going barefoot your skate boot can form to your foot and reduce the amount of slop you would get from wearing a sock (and especially from more than one sock). It is best if the skate boot fits like a glove so you can have better control of the four skate blade edges.  When you skate you have an inside edge and outside edge on each foot being able to control what edge(s) you are on will make you a better skater.  Any slop in controlling your edges results in wasted energy. The only reason I can think of for wearing two socks is to keep your feet warm but if you are skating your feet should be plenty warmm enough.  As far as blisters go if your skates are dry and fit correctly (no slop) you shouldn't get any blisters by skating barefoot.  The only time I got blisters from my skates, when I skated barefoot, was when my skates didn't get a chance to dry properly.
Answer: We always wear 2 pair of socks when skating outside in cold minus winter weather and it doesn't affect the fit of our skates but our feet do stay much warmer. Maybe it's what your used too. You can't skate much outside if your feet are frozen and skates have to fit pretty tight which doesn't help keep your feet any warmer. I would think it's personal preference and the environment you skate in. Do what ever works best for you and your situation I think. Skating for fun doesn't create as much body heat as hockey does so that is also a factor maybe. Just my thoughts and experience of many different skating experiences.
Comment: Thank you. I was not clear, my question was about fit, rather than warmth :-).


What is the correct way to rename an uploaded file using tokens?

Question: I am building a webform. I have a Name field that uses first and last name.
I have an image upload field where I want to rename the image to lastname-firstname.jpg.
In the properties for the file upload, I selected Rename files for the pattern [webform:element:name:last__title]-[webform:element:name:first__title].
When I test this using John Smith, the file is getting renamed, but it is being renamed to last-name-first-name.png instead of smith-john.jpg.
I'm guessing I'm doing something wrong with the pattern, but I don't know what.
This is the field definition.
<code>name:
  '#type': name
  '#title': Name
  '#title__access': false
  '#first__title': 'First Name'
  '#middle__access': false
  '#last__title': 'Last Name'
  '#suffix__access': false
  '#degree__access': false
</code>
Answer: I had the same issue. The answer was buried way down in Browse available tokens.
I wanted to rename an uploaded file based on the responses to the last_name and first_name fields. The pattern that worked was [webform_submission:values:last_name]_[webform_submission:values:first_name].


Perl syntax error printing list index

Question: I am trying to print an index of a list returned from a function call.  I am wrapping the function call in parenthesis in an attempt to convert the list to an array.  The program fails to compile saying 'syntax error at file.pl line 4, near ")["'.  If I create a temporary variable $a or use printf indexing is fine.  Why does print brake, is there a better alternative?
sub get{
    return (1,2);
}
#print (get())[0]; #fails
printf("%d",(get())[0]);
my $a = (get())[0];
print $a;

Answer: I assume that you are foolishly not using
use warnings;

Which is quite a bad thing to not do. If you had used it, you would get the warning:
print (...) interpreted as function

Which is to say, what you wrote
print (get())[0]

Is something Perl interprets as you trying to put a subscript on the print() function. This does not work.
For the code to do what you expect, you need to be explicit about the parentheses:
print ( (get())[0] );

You should always use
use strict;
use warnings;

There is a slight learning curve to using these, but they only show you your errors. Not using them only hides your errors, and your code does not work better.
Answer: Try this :
sub get{
    return (1,2);
}
print((get)[0]);

or
my $a = (get)[0];
print $a;

OUTPUT
1

Perl syntax error printing list index


How can I find the interval of x? I apply ratio test and get indeterminate. $\sum_{n=1}^\infty({(n+1)(n+2)....(2n)\over n^n})\space (x-2)^n$

Question: $$\sum_{n=1}^\infty({(n+1)(n+2)....(2n)\over n^n})\space (x-2)^n$$
Find the radius and interval of convergence of the power series given above.
Hi! I am trying to find the interval of x first; however, whenever I apply ratio test, I get indeterminate. How can I find the interval of x?
Here is what I've done:
Convergence:
$$\lim_{n\to\infty}{\cfrac{\lvert(n+2)(n+3)...(2n+2)\space(x-2)^{n+1}\rvert}{\lvert(n+1)^{(n+1)}\rvert}\over\cfrac{\lvert(n+1)(n+2)...(2n)\space(x-2)^n\rvert}{\lvert n^n\rvert}}<1$$
$=>$
$$\lim_{n\to\infty}\cfrac{\lvert 2(2n+1)(x-2)n^n\rvert}{\lvert(n+1)^{n+1}\rvert}<1$$
$=>$L'Hospital:
$$\lvert x-2\rvert\space\lim_{n\to\infty}\cfrac{\lvert (4n+2)\space n^n\rvert}{\vert(n+1)^{n+1}\rvert}<1$$
$=>$
$$\lvert x-2\rvert\space\lim_{n\to\infty}\cfrac{\lvert 4n^n+(4n+2).n^n.\ln(n)\rvert}{(n+1)^{n+1}.\ln(n).(\ln1)}$$
As you can see, ln1 makes it indeterminate and I am unable to find.
How can I find the interval of x, so that I can find the interval of convergence and then the radius of convergence?
Comment: You may also try the root test:$$\lim_{n\to\infty}\sqrt[n]{\left|\frac{(n+1)(n+2)\cdots(2n)}{n^n}(x-2)^n\right|}=|x-2|\lim_{n\to\infty}\frac{\sqrt[n]{n+1}\sqrt[n]{n+2}\cdots\sqrt[n]{2n}}n$$and the remaining limit has the [same value](https://www.wolframalpha.com/input/?i=Limit%5BProduct%5B%28n%2Bk%29%5E%281%2Fn%29%2C+%7Bk%2C+1%2C+n%7D%5D%2Fn%2C+n-%3EInfinity%5D) as provided by the root test (though I'm not exactly sure how one would approach this form of the limit...)
Comment: Yeah, you are right! We learned this way first, so, I just sticked to it. Thanks anyway!
Answer: Let $$ a_n=\frac{(n+1)...2n}{n^n}$$
$$\frac{a_{n+1}}{a_n}=\frac{(2n+1)(2n+2)}{(n+1)^2}(\frac{n}{n+1})^n$$
using the fact that $$\lim_{n\to +\infty}(1+\frac 1n)^n=e$$
we find that
$$\lim_{n\to +\infty}\frac{a_{n+1}}{a_n}=\frac 4e$$
The radius of convergence is $$R=\frac e4$$
You can also write $ a_n $ as
$$a_n=\frac{(2n)!}{n!n^n}$$
and use Stirling formula.
Comment: Thank you Mr.; however, Mr. Martund's answer was a little more useful for me. Thanks anyway!
Answer: $$\lvert x-2\rvert\space\lim_{n\to\infty}\cfrac{\lvert (4n+2)\space n^n\rvert}{\vert(n+1)^{n+1}\rvert}<1\\
\iff|x-2|\lim_{n\to\infty}\dfrac{4n+2}{n}\times\lim_{n\to\infty}\dfrac{n\cdot n^{n}}{(n+1)^{n+1}}<1\\
\iff4|x-2|\times\lim_{n\to\infty}\left(1-\dfrac{1}{n+1}\right)^\frac{1}{n+1}<1\\
\iff|x-2|<\dfrac e4$$
Therefore, the required radius of convergence is $\boxed{\dfrac e4}$.
Comment: Thank you so much! I get it!
Comment: Hi, again Mr. @Martund ! I just wondered how did you find the interval of x. Because I am unable to get e/4 without interval of convergence. And to find the interval of convergence, I need to find the interval of x.

How did you find it, can you show it step by step? ;-;
Comment: Hi again! I managed to solve! Thanks again.
Comment: @ColleganDelta, You're welcome!
Comment: @ColleganDelta, $|x-2|<\dfrac e4\implies -\dfrac e4<x-2<\dfrac e4\implies 2-\dfrac e4<x<2+\dfrac e4$.
Comment: So, you did find the radius of convergence first? We first find the interval of x and thenfind the interval of convergence and THEN the radius of convergene.

How did you manage to find radius, directly?
And one more thing, we check if x less equals or less than any side of the equation at the end. Yes, we have "less than" sign but no matter what, we learned that we should check if it is convergence at the extreme points.

And you haven't checked it, right? If you haven't, why?


Difference between $dy$ and $dx$

Question: I've been taught about $dy/dx$ and how it can be split into $\frac{dy}{dx}=\frac{d}{dx}y$. I'm confused as to why this happens. Don't $dy$ and $dx$ both refer to infinitely small changes in their respective variables? In that case, what is different about a $dy$ that allows it to split into $d$ and $y$?
Comment: One of the ideas behind the notation is to denote a change in $y$ wrt $x$, so too you can denote a change wrt $x$ by an analogous shorthand $\frac{d}{dx}$.
Comment: What's different is that usually $y=f(x)$ so it makes sense to ask how $y$ changes with respect to $x$. There is no such thing as an infinitely small change.
Comment: And this is one more reason to avoid the differential notation for derivatives...
Answer: This is just a notational convention.
$\frac d{dx}y$  does not mean anything different than $\frac{dy}{dx}$. When instead of having $y$ we have some expression we want to differentiate and do not wish to introduce some new variable just for the sake of one equation, writing something like $$\frac{d\left(\frac{e^{-2x^2} - 7x}{\log_\pi(x^2-1)}\right)}{dx}$$ is not really convenient to work with. So instead we prefer to write $$\frac d{dx}\left(\frac{e^{-2x^2} - 7x}{\log_\pi(x^2-1)}\right)$$

Admittedly, there is a somewhat different concept involved in the $\frac d{dx}y$ notation as opposed to $\frac{dy}{dx}$. You can think of it as the operator $\frac d{dx}$ acting upon the function $y(x)$. But even in this case, the operator $\frac d{dx}$ is an atomic notation, not some conglomeration. It is not "something called $d$" divided by "something called $dx$". It is defined only as a whole.
Answer: When we prefix $\Delta$ to a variable, it implies a discrete difference: $$\Delta x = x_2-x_1$$ where $x_2$ and $x_1$ are two values that the variable $x$ can assume. In this case, these two values can have a finite difference. When the two values approach each other (as shown in the limit below), the difference approaches to zero: $$\text{as }{x_2\to x_1},\ \Delta x = 0$$
Wrong Way to Think about Differentials
However, some mathematicians interpreted $\text{as }{x_2\to x_1},\ \Delta x \neq 0$ and rather an infinitesimally small number. Unfortunately, this interpretation pertains till date and is taught in many schools and textbooks.
$$
\lim_{x_2\to x_1}\Delta x \equiv dx
$$
In other words, operator $d$ is same as operator $\Delta$ under the said limit. Prefixing $d$ to any element (or variable like $x$) operates on the element in order to create an infinitesimally small (or in some approximate methods, very small) difference of values of that variable is considered.
Thus $dx$ means a very small difference on $x$ while $dy$ means a very small difference on $y$.
As pointed out in the comments as well, this interpretation is just wrong.
Less Wrong Way to Think about Differentials
Prefixing the operator $\dfrac{d}{dx}$ means evaluating a derivative of the element following the operator with respect to x. $\dfrac{d}{dx}y$ means to find the derivative of $y$ with respect to $x$. The notation $\dfrac{dy}{dx}$ is derived from the tangent-slope interpretation of the derivative, that is to take the ratio of the opposite side with the adjacent side. The discrete product (using $\Delta$) provides the slope of the secant. Consider a secant along $x$ to a function $y$:$$ \text{slope of secant} = \dfrac{\Delta y}{\Delta x}$$ To calculate the running slope of the tangent to the function:$$\boxed{\text{slope of tangent} = \lim_{\Delta x \to 0} \dfrac{\Delta y}{\Delta x} \overset{\text{old notation}}{=} \dfrac{dy}{dx}}$$
Thus, $\dfrac{d}{dx} y$ is less wrong way to use the derivative-along-$x$ operator on a function $y$ while $\dfrac{dy}{dx}$ is a notational convention hinting towards the slope interpretation of the derivative operator.
Precautionary Note
There is no algebra involved here. $y$ is not being multiplied with $\dfrac{d}{dx}$, we are simply switching notation for convenience.
Comment: This answer is just straight up wrong. First of all, $\lim_{x_2\to x_1}\Delta x=0$, so setting $\mathrm{d}x=\lim_{x_2\to x_1}\Delta x$ literally just means that $\mathrm{d}x=0$. There is no "infinitesimal" here. The limit **equals** zero.
Comment: @BertrandWittgenstein'sGhost - ??? When you break down the meanings of $\Delta y$ and $\Delta x$ here, $\lim_{\Delta x\to 0} \frac{\Delta y}{\Delta x}$ is exactly the common definition of $\frac{dy}{dx}$.
Comment: @BertrandWittgenstein'sGhost - You are the one who is confused here. In every means of defining differentials, rigorously or not and including the one you are trying to describe (but are failing to do so properly), $\frac{dy}{dx}$ is **always** the limif of the difference quotient. In most of them, it is that limit *by definition*, and then $dy = \frac{dy}{dx}dx$ is used define the differential $dy$ in terms of the independent differential $dx$. There are some ways of defining diffs. where this arises as a theorem instead, but in what you are describing, it is a definition, not a theorem.
Comment: Your definitions are wrong, 1: $\lim_{\Delta x \to 0} p\Delta x= 0$. 2: $\lim_{\Delta x \to 0} \frac {\Delta y}{\Delta x}$ does not make any sense because $y=f(x)$, which you need to indicate. Even then, it is definitely NOT equal to $\frac {dy}{dx}$
Comment: Which means your answer as a whole, is wrong.
Comment: Thank you for pointing out the ambiguity in assigning the equal to sign to the limit. $x_2 \to x_1$ doesn't mean that $x_2 - x_1 = 0$. The limit equations have been corrected.
Comment: @ananta doesn't change that fact that almost everything else is wrong. $\frac {dy}{dx}$ is NOT $\lim_{\Delta x \to 0} \frac{\Delta  y}{\Delta x}$
Comment: @ananta - on the other hand, replacing the equals sign with an equivalence sign in your earlier formula merely changed it from being patently false to being patently meaningless, and therefore of no value. Differentials have been a very problematic concept in mathematics, and while several rigorous definitions have be proffered in the last century or two, all have weaknesses and require significant sophistication to understand. The concept you are pushing here, is *not* amongst them, as it is fundamentally flawed. Best to think of them at this stage as intuitive, not rigorous math.
Comment: So you will not listen to me, in that case, you will listen to Apostol. Please refer to **Calculus Volume 1, 2nd edition: Section 4.8 by Apostol** for reference. Let me emphasize that, as I mentioned, the limit definition of differential is not quite correct, it is a notational convention based on a historical interpretation of the derivative which 'hints' towards to slope of a tangent. The better interpretation is looking at $\dfrac{d}{dx}$ as an operator that acts on y. STOP downvoting folks!
Comment: @PaulSinclair It's not $\frac{dy}{dx}$ stop confusing derivetive of a function, defined in terms of limits and quotients, with a differential. Yes, $\lim_{h \to 0}\frac{f(x+h)-f(x)}{h}=\frac{df}{dx}$, for some particular function $f$, but each $dy,dx$, is a differential, the two are not the same. The former is the derivetive of some particular function, while the latter elements of a set with cardinailty two.
Comment: One thing to consider, in the former case, where we take the limit of a quotient; the quotient $dy$, $dx$ can be undefined (or $0/0$) but not in the latter case because they won't be orthogonal anymore.
Comment: @PaulSinclair it's alright... If that makes you happy, still doesn't change the fact that you are wrong.
Comment: So I understand that $dy$ and $dx$ are, in fact, two independent terms and not part of the same formula. Thank you for making it clear.

Difference between $dy$ and $dx$


How to access the project documentation pages created using Gdoc in grails

Question:
I followed the tutorial on the grails documentation was successfully able to create project specific documentation pages by running the following command
grails doc

I was able to view the HTML pages from my desktop and I found them on the following directory:
..\target\docs\index.html
I was wondering how to access these generated HTML pages from the server. What is the URL to view them from the server?
I tried the following URL but did not work?
http://localhost:8080//docs/index.html
Also, the grails documentation states that the command will output an docs/manual/index.html
 page. Rather I found the index.html page on the following directory:
..\target\docs\index.html
Can anyone help me in this?
Thanks
Answer: They're not built to be viewed from the running application, so they're not automatically exposed as a url. But you can move them to the web-app folder and they'll be accessible.
You can also configure the build location to be under web-app. Add this line to grails-app/conf/BuildConfig.groovy:
grails.project.docs.output.dir = 'web-app/docs'


Avoid adding custom CSS to a node editing form?

Question: Situation

custom module adding styles
don't add styles to node editing form

How to avoid adding the style to the editing forms?
function crossfade_page_attachments(array &$page) {
  $page['#attached']['library'][] = 'crossfade/crossfade';
}

Answer: Currently discovered answer derived from the metatag module)
function crossfade_page_attachments(array &$page) {
  if (\Drupal::service('router.admin_context')->isAdminRoute()) {
    return FALSE;
  }
  $page['#attached']['library'][] = 'crossfade/crossfade';
}


The more LibGDX Box2D bodies, the slower the falling speed

Question: I'm trying to write a test game with LibGDX Box2D, bodies can fall down quickly within the amount of 5, but if I change the amount to 10, 12 or more, the falling speed becomes slower and slower. I Cannot figure out why this happen that when the number of bodies increase, the falling speed decreases. As far as i understand, the amount of body should not affect the gravity, even if it is possible, it is only a dozen.
class GameViewActivity : ApplicationAdapter() {
    companion object {
        private const val SCALE = 2.0f
        const val PIXEL_PER_METER = 100f
        private const val TIME_STEP = 1 / 60f
        private const val VELOCITY_ITERATIONS = 6
        private const val POSITION_ITERATIONS = 20
        private const val VELOCITY_Y = -9.85f
        private const val VELOCITY_X = 0f
}

private var orthographicCamera: OrthographicCamera? = null
private var world: World? = null
private var batch: SpriteBatch? = null
private var ground: Ground? = null

private var discList = ArrayList<Disc>()
private var shapeRenderer: ShapeRenderer? = null

override fun create() {
    orthographicCamera = OrthographicCamera()
    orthographicCamera!!.setToOrtho(false, Gdx.graphics.width / SCALE, Gdx.graphics.height / SCALE)

    world = World(Vector2(VELOCITY_X, VELOCITY_Y), false)
    world!!.setContactListener(WorldContactListener())
    batch = SpriteBatch()
    val shape = PolygonShape()
    shape.setAsBox(orthographicCamera!!.viewportWidth, 2f)
    ground = Ground(world!!, shape)

    for (i in 1..12) {
        val d = Disc(world!!, 60f, 10f + i.toFloat()*2, 150f, 30f)
        discList.add(d)
    }
}

override fun render() {
    update()
    Gdx.gl.glClearColor(0.5f, 0.8f, 1f, 1f)
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

    shapeRenderer = ShapeRenderer()
    shapeRenderer!!.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer!!.color = Color.YELLOW;
    shapeRenderer!!.rect (
        0f,
        ground!!.body!!.position.y * PIXEL_PER_METER  - 12f / 2 / SCALE,
        orthographicCamera!!.viewportWidth * SCALE,
        2f * PIXEL_PER_METER
    )
    shapeRenderer!!.end();

    for (disc in discList) {
        val discRenderer = ShapeRenderer()
        discRenderer.begin(ShapeRenderer.ShapeType.Filled);
        discRenderer.color = disc.getColor()
        discRenderer.rect(
            300f,
            disc.body!!.position.y * PIXEL_PER_METER ,
            disc.getWidth() * SCALE,
            disc.getHeight() * SCALE
        )
        discRenderer.end()
    }
}

private fun update() {
    world!!.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS)
    cameraUpdate()
}

private fun cameraUpdate() {
    orthographicCamera!!.update()
}

}

Comment: Java or Kotlin?
Comment: @kiner_shah The code is Kotlin
Comment: Then you should remove the Java tag.
Comment: @kiner_shah I thought someone who knows java can also provide me a suggestion :-)
Comment: Not everyone who can understand Java code can understand Kotlin code.
Answer: I am pretty sure that the problem is the update method.
You only make one world.step in every render method, without taking the Gdx.graphics.getDeltaTime() into account.
So the more objects there are, the longer the render will take, the slower the game will become.
Example:
Update + render of 5 objects takes 0.0125s. You call world.step with a fixed TIME_STEP of 1 / 60 (0.0167s), so your updated uses 0.004s more then it should. With a speed of 5 m/s and a pixel / m ratio of 100, an object would go 2 pixels further then it should.
5m/s * 100px/m -> 500px/s
500px/s * 0.004s -> 2px

Now if you add more and more objects, the update and render will take a little longer to complete, resulting in bigger delta times. If update and render takes  0.02s now, your objects would go 1.65px less then it should.
So the correct update should look something like this (Java code):
float frameTime = Math.min(deltaTime, 0.25f);  // Avoid spiral of death on slow devices
accumulator += frameTime;  // Increase member variable accumulator
while (accumulator >= TIME_STEP) {
    world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
    accumulator -= TIME_STEP;
}

So basicaly you check the delta time (time between the last render and this render call). On slow devices, the delta time might get to big, resulting in a lot of world.step calls, making delta time even bigger. This is the so called spiral of death, which we avoid by limiting the delta to 0.25f.
Now we add this delta time to an accumulator. This allows us to store the rest of the delta time, if it is not a multiple of TIME_STEP.
Next we call world.step in a loop, as long as our accumulator is bigger then TIME_STEP.
After all of this, the game logic has been updated correctly and we can render the changes to the screen.
Other notes:
You are using a pixel to meter conversion. I wouldn't do that, as LibGDX already offers Camera and Viewport for this.
Basically thos objects allow you to specify the width in x and y and scale it up to fit the screen (in different ways).
So if you specify a width of 8 and move by 1, you will move by 1 / 8 of the screen width, independent of the resolution.
Comment: I had used JBox2D before using LibGDX, JBox2D used a fix `TIME_STEP`, so I set the same value. And now I trying to build `Screen`, `Stage`, `Actor` with LibGDX, important like your advice, use `delta` time, it's working great so far. Thanks a lot.
Comment: It's the same in LibGDX, you should use a fixed time step, otherwise the physics might get messy. But you have to take the delta time (time since last update) into account and thats what you do with the accumulator and the loop.
Comment: I got the physics messy as you mentioned. I happened to view this article [fix your timestep](https://gafferongames.com/post/fix_your_timestep). OK, I need time to understanding, and need trying :]


Como usar ckeditor junto com javascript

Question: Estou Tentando ativar uma função dentro da area de texto do ckeditor como onclick, onload, onkeypress ou onkeyup, funciona perfeitamen`te em textareas "normais" mas quando implemento o ckeditor ele "bloqueia" isso
echo"<textarea   id='editor1'  name='descricao' class='form-control' rows='10' required >$descricao</textarea>"; ?>

 CKEDITOR.replace( 'editor1' );
$(document).ready(function(){
 $.fn.modal.Constructor.prototype._enforceFocus = function(){};
});

Answer: Você pode usar o evento keyup, por exemplo, desta forma:
var editor = CKEDITOR.replace('editor1');
editor.on('pluginsLoaded', function(){
   editor.on('contentDom', function(){
      var editable = editor.editable();
      editable.on('keyup', function(){
         // fazer algo aqui com keyup
      });
   });
});

É sempre bom atribuir a instância do CKEditor à uma variável para usar como referência. No caso, atribuí à variável editor.
Comment: Não consegui fazer um alert      echo"$descricao"; ?>

Comment: Poderia me ajudar?
Comment: Vc colocou `CKEDITOR.replace( 'editor1' );` duas vezes. Apague a primeira e deixe apenas o `var editor = CKEDITOR.replace('editor1');`.

Como usar ckeditor junto com javascript


Can you get metrics and statistics from Hibernate OGM?

Question: I'm trying to get performance data from Hibernate OGM.  It doesn't seem to have the Hibernate statistics classes like Hibernate ORM.   Is there something equivalent?
Answer: The reason there are not specific classes is that you should be able to use the existing one in ORM.
For example:
<code>org.hibernate.stat.Statistics statistics = getSessionFactory().getStatistics();
statistics.setStatisticsEnabled( true );
final Session session = openSession();
...
statistics.logSummary();
session.close();
</code>
If you think that something is missing or not working, you can signal it on the Hibernate OGM Jira or forum.
Davide


MySQL Workbench: 'Disk Space in Data Dir' limited to 20G

Question: I have an OVH private server (Ubuntu 12.04, 8 GB RAM, i3-2130, 2x500 GB HDD) and I'm dealing with MySQL administration. I have installed MySQL Community server 5.6.16 correctly and it works fine(it responds all the queries requested by a tomcat server). However, when I check 'Server Status' in MySQL Workbench there is a parameter called 'Disk Space in Data Dir' with a '13G of 20G avalaible' value.
I use a laptop with Windows 7 and no partitions (one 1 TB HDD) to develop and try changes in a local copy of this server. Here, when I check this parameter in MySQL Workbench, it shows '782.00 GB of 911.00 GB avalaible'.
My current my.cnf file: http://pastebin.com/Gfw53Lbi
So, I guess it's something related to partitions or the way OVH has formatted the hard disk space. Any ideas?

<code>Filesystem      Size  Used Avail Use% Mounted on
rootfs           20G  6,3G   13G  33% /
/dev/root        20G  6,3G   13G  33% /
none            789M  252K  788M   1% /run
none            5,0M     0  5,0M   0% /run/lock
none            3,9G     0  3,9G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/md2        911G  9,1G  856G   2% /home
</code>
Thanks in advance.
Comment: Show us the output of `df -h`
Comment: My df -h shows: http://pastebin.com/zzMt3szj
Answer: Yes, the df -h output shows that your server is partitioned so that the /home directory has most of the space on the hard disk.
A quick and dirty fix would be to move the mysql data directory from /var/lib/mysql to /home/mysql/ and then change my.cnf accordingly.
Comment: Ok, thanks, I'll try it. Anyways, which would be the most elegant solution? I'm just a developer and I ignore most of the administration details but I'd like to improve my knowledge.
Comment: Elegant solution would be to make a new partition for the MySQL data directory, and then mount it to /var/lib/mysql directory. Another option is to re-install the whole system and allocate space differently.


Floating items in WPF

Question: How can I create a control container where every item (control) behaves like a Floating DIV (in HTML), like this video (considering that each folder is a control)?
Answer: Take a look at the WrapPanel class. MSDN
It has the functionality you are looking for.

Positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box. Subsequent ordering happens sequentially from top to bottom or from right to left, depending on the value of the Orientation property.

Floating items in WPF


Why do we normalize variables in classification, but not regression

Question: I understand that we need to normalize data for classification problems because otherwise the variable with the larger scale will dominate the result. But why don't we normalize for linear regression?
Could someone please provide an intuitive explanation or an example to explain the difference between classification algorithms (like logistic regression) and linear regression?
Thanks!
Comment: It doesn't really have anything to do with whether the problem is regression or classification.  So you normalize in regression in the same circumstances as classificaton: you want the independent variables to occupy the same scale.  Two give two common examples: this is important for distance based models (KNN, clustering), and when using regularization (regression or classification).
Comment: Ordinary least squares regression is unaffected by scaling of the variables, so normalizing is usually not done as it is unnecessary effort.  But if scaling affects the results (whether classification or other forms of regression) then you need to consider whether normalizing is desirable or not
Comment: Your premise is flawed... Where did you hear that you must normalize variables in classification problems?  There are many reasons to normalize, none of them are "is a classification problem"/
Comment: Okay I might be mistaken, but we rarely normalize variables in regression problems, is that correct?
Comment: @MatthewDrury: do you want to post your comment as an answer?
Comment: @StephanKolassa Sure!
Comment: Look at my answer here:  https://stats.stackexchange.com/questions/244507/what-algorithms-need-feature-scaling-beside-from-svm/252625#252625
Comment: @Henry Although in theory OLS is unaffected by scaling, in practice the computation of OLS solutions can be heavily affected by scaling.  That's why good OLS software automatically standardizes variables (or does something equivalent) internally, whether the user knows it or not.
Answer: It doesn't really have anything to do with whether the problem is regression or classification. So you normalize in regression in the same circumstances as classification: you want the independent variables to occupy the same scale. Two give two common examples: this is important for distance based models (KNN, clustering), and when using regularization (regression or classification).


Harmony - four part vocal style and pianoforte style

Question: I've been preparing for my Grade 5 AMEB (the Australian music board) music theory test and the harmony section really stumps me. I understand how it works, but not really all the rules.
I'd just like to get, (if possible) all the rules anyone knows for four-part and pianoforte harmony, especially the latter? And things like the forbidden octave and fifths?
Cheers.
Comment: ... from the AMEB web site it looks like their exam syllabus is not available free (unlike ABRSM which do provide a free syllabus for all their exams), so you can't really expect other people here to pay for it just to understand what your question means!
Comment: Does "pianoforte style" mean three-note chords played with the right hand and the bass line played with the left hand? If that is correct, the "rules" for forbidden octaves etc are the same, but the options you have to avoid breaking them are more limited.  Contrary motion between the bass and the right hand parts is often the simplest way to avoid problems.
Answer: Well, as mentioned they are too many to write them in a post, however you could check this link for some very important rules and, moreover, you could google whatever you want about the conventional rules of four-part choral and pianoforte harmony.
As for the second, I would like to make some remarks:

In four-part choral harmony there is no restriction that two voices should not sing a fourth while the other two voices do not move, however, when such a passage is played on a piano, it sounds often too harsh to be considered classic, so it is to be avoided, due to pianoforte restrictions.
The same - a little bit altered - applies to octaves and fifths. Should two voices move to a fifth or octave while the others do not move may, even in choral four-part harmony, sound a little bit empty, however, when played on a pianoforte, the result is usually very "cold", so, again, it should be, in general, avoided.
Several other passages, such as thrids and sixths are allright to be used while no other voice is moving.
In general, while parallel fourths are not entirely forbidden, many times they do sound really intense and harsh, which makes them not a nice choice.
Except for parallel fifths and octaves, there are also their counter-parallel cousins. So, for instance, having Basso and Soprano moving from a perfect fifth to an octave (or another perfect fifth) with contrary move is also forbidden.

After all, what you are being examined to is music and it should remains so; if you write something that on the piano sounds nicely and is in context should be OK. For instance, I was taught that after a dominant (V) there should follow a tonic (I), however, I've used several times variations of an idea borrowed from the baroque - Haendel, specifically - that after (V6) one could have a (IV64) with a very pleasing result. So, despite all these rules, feel free to express yourself, as long as the given theme lets you do so
Answer: All the rules regarding voice leading in a four-part harmony are too many to put in a post.  They take a couple of chapters in a theory book, and I take about 8-10 classes to teach the basic rules to my theory class.  There's no way to address them all, but I'd say the two most important are: avoid parallel fifth and octave movement between any two voices, and do not space soprano/alto or alto/tenor greater than an octave.


Delete multiple files based on partial names list

Question: I have a folder one my Red Hat server with approx. 500k files from various extensions.
The name convention for those files is based on a number, for example:

a123456.csv
z123456.jpg
123456.exe
a234.jpg
234.exe

I designed a query which produce a list of all the numbers that should be deleted.
Assuming i export this list daily/weekly into a txt file, what would be the most efficient way to delete all the files from the folders which appears in the list?
Running a for loop on every folder would take too long since there are too many files. I managed to produce a list of all the numbers to delete which have files in this folder using:
join <(cat list.txt | sort) <(ls /folder/with/0.5Mfiles | grep -v html$ | sed 's/[a-zA-Z.]*//g' | sort)

but that way I lose the original file name (e.g. z123456.jpg)
What could be the most efficient way to do it?
Comment: This sounds like an XY problem. What's in list.txt? Is that a list of filenames or a list of numbers?
Comment: It is a list of numbers.
Answer: How about
while read -r number; do
    echo rm /path/to/folder/*"$number"*
done < lists.txt

Remove "echo" if it looks OK

Yes, when number=1234 then the pattern will match a12345.jpg. Let's try this:
$ shopt -s extglob nullglob
$ touch 1234 a1234 1234b c1234d 12345 a12345 12345b c12345d
$ number=1234
$ echo ?(*[^0-9])"$number"?([^0-9]*)
1234 1234b a1234 c1234d

the ?(...) form optionally matches the contained pattern, and we use *[^0-9] and [^0-9]* to add a "number boundary" -- the preceding/following character must be a non-digit. So ?(*[^0-9]) matches either an empty string or a sequence of chars ending with a non-digit.
Comment: In case 1234 will be in lists.txt - 12345.jpg will also be deleted
Comment: Using a while is way too slow when dealing with some many files, I'm trying to come up with a solution using xargs
Comment: that would be `printf "%s\0" ?(*[^0-9])"$number"?([^0-9]*) | xargs -0 rm`


Navbar dropdown doesn't appear

Question: In my website I have created a NavBar file and I include it, with php, in every other php file I want. Now my navbar file has a dropdown inside:

.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: white;
  min-width: 160px;
  box-shadow: white;
  z-index: 1;
  cursor: pointer;
}

.dropdown-inbuttons {
  border: none;
  padding: 6px 12px;
  text-decoration: none;
  display: inline-block;
  cursor: pointer;
  background-color: white;
  color: black;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  right: 0;
  background-color: white;
  min-width: 160px;
  box-shadow: white;
  z-index: 1;
  cursor: pointer;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown:hover .dropdown-content {
  display: block;
}
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    //.....other code....//

      <button class="dropbtn">

            </button>

        Link 1
        Link 2
        Log Out

When I put my mouse up to the dropbtn it shows me this:

I know why this happen because the dropdown content is inside the navbar and in the code navbar height = 58px and doesn't fit. So How to make my dropdown visible front of the other html files?
I import the navbar in other php files with this way:

    <?php
    session_start();

    if(!isset($_SESSION['u_id'])){
    header("Location: ../../login.php");
    }
    include '../../_includes/server.php';
    $userid = $_SESSION['u_id'];
    $usersql = "SELECT * FROM `users` WHERE id='$userid'";
    $result = mysqli_query($conn, $usersql);
    if($row = mysqli_fetch_assoc($result))
    {
        $_SESSION['first_name'] = $row['first_name'];
        $_SESSION['last_name'] = $row['last_name'];
        include('../../../navBar/navBarConnected.php');
    }
    ...
    ...

Comment: Remove `overflow:hidden` on `.w3-bar`
Answer: First approach: Override overflow:hidden of .w3-bar by overflow:visible.
Second approach: Change position: relative of .dropdown class to position: static and wrap the
...
 to another div and add position: relative to that.
Both of them will work. Choose whatever suits you.
Answer:

.dropbtn {
    background-color: transparent;
    color: #fff;
    padding: 16px;
    font-size: 16px;
    border: none;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}
.bar {
    background: black;
    color: #fff;
}

.dropdown-content a:hover {background-color: #ddd;}

.dropdown:hover .dropdown-content {display: block;}

.dropdown:hover .dropbtn {background-color: transparent;}
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  //.....other code....//

  <button class="dropbtn"></button>

    Link 1
    Link 2
    Link 3

Navbar dropdown doesn't appear


ASP Application on IIS crash

Question: ASP application always hangs and didn't work on IIS during rush hours connections
Also other scripts like PHP are working properly on IIS. The problem only with ASP.
I'm receiving this error when i'm trying to open the ASP script.
<code>================================================================
Server Error in '/' Application.

Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +404
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1363
   System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +58
   System.Data.SqlClient.SqlDataReader.get_MetaData() +118
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6312385
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +6313986
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +538
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +28
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +256
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +19
   System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +968
   System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207
   System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500
   System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50
   System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383
   website.Controls.Homepage.website_Column.BindData() +2671
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Control.LoadRecursive() +190
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
</code>
Answer: The application is timing out while trying to connect to the database. You can either

Extend the timeout parameter on the database connection.
Fix your database so it can handle the load you're throwing at it. Also, do some capacity management.
Comment: I'm a windows beginner, How can i extend the timeout on the db connection .? and How can i disable the timeout so it didn't loose the connection.
Comment: You adjust the `ConnectionTimeout` property on the `SqlConnection` object in your code (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx). But the default is 30 seconds, so if it's taking longer than 30s to even connect to your database, you've got database problems. Disabling the timeout is, I believe, impossible. At some point, synchronous tasks have to timeout, otherwise they'll just wait forever.

ASP Application on IIS crash


If chars are randomly inserted into a string with a prob $p$, what does $p$ need to be for the number of insertions on average to be $x$?

Question: So let's say I have a string = "taco" and I want to randomly insert 4 characters into this string. So at index=1 or at 't' I have a probability $p$ of inserting a random character and this process is run for all the letters so [t,a,c,o] all have $p$ of having a character inserted to the right of it. But I want $p$ to be defined in a way s.t. the expectation for the number of inserted characters will be 4.
The number of inserted characters can be 1-7 so that means I can insert 7 characters in "taco."
Is there a way of calculating $p$ s.t. the expectation for characters inserted equals some integer $x$?
Comment: Do you mean expected value, or the most likely value?
Answer: There are $4$ characters in "taco", so the expected number of characters you add to "taco" is $4p$ (can you explain why?).
To make this equal $x$, we need $4p=x$, that is, $p=x/4$.


Taylor's Theorem Error Term Upper Bound

Question: Use the error term in Taylor's theorem to given an upper bound for $|\cos(x) - f(x)|$ over the interval $[-\pi/2, \pi/2]$, using the worst case of $\varepsilon$, where $f(x)=1-(x^2/2)$.
(A lot of what I see already posted has some degree which I am not provided so I am confused how to solve this).
Edit: Is it fair to say this problem is degree 2 since it is $x^2$?
Answer: Let $g(x)= \cos x$. Then , by Taylor, if $ x \in [-\pi/2, \pi/2]:$
$$|\cos(x) - f(x)|= |\frac{g'''(t)}{3!}x^3|$$
for some $t$ between $0$ and $x$.
Can you proceed ?
Comment: This was extremely helpful and I was just able to solve it out. Thank you so much for your help!
Comment: Actually, $\cos x - f(x) = \frac{{x^3 }}{{3!}}g'''(0) + \frac{{x^4 }}{{4!}}g^{(4)} (t) = \frac{{x^4 }}{{4!}}g^{(4)} (t) = \frac{{x^4 }}{24}\cos t$, which provide you with a better estimate.

Taylor's Theorem Error Term Upper Bound


Probability of having all $4$ Ace in a player?

Question:
From all $52$ playcards, now a person picks $13$ cards. What is the probability of having all $4$ Ace in his hand ?

Edit:
Many thanks for @Balajisb rather helpful reply first.
I've googled before and seen quite a few answers on Internet, one of them is Balaji sb's answer$\frac{\binom{48}{9}}{\binom{52}{13}}$, but not sure which one is correct.
I guess this ans means no. of favorable outcomes divided by no. of total possible outcomes.
Since $4$ out of $13$ cards must be the $4$ Ace, the varying part is the remaining $9$ cards on hand.
So no. of favorable outcomes = no. of combination of remaining 9 cards = $\binom{52-4}{9} = \binom{48}{9}$, which is the numerator.
The denominator is no. of total possible outcomes, which is simply take any $13$ cards from $52$, which is$ \binom{52}{13}$.
But Some things that I don't understand about Balaji sb's answer are:

Why just calculated as $$P(\text{get all 4 Ace}) = \frac{1}{52} \times\frac{1}{51}\times\frac{1}{50} \times\frac{1}{49} ~~~?$$  Why this thought is wrong ?

What is the difference between my wrong thought (point $1$) and Balaji sb's answer $\frac{\binom{48}{9}}{\binom{52}{13}}$ ?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: If you want to use SE you should understand why users here did not like the original question and the answer to it. This is not "solve homework for a cheater" site.
Answer: The answer you proposed ($1/52\cdot 1/51 \cdot 1/50 \cdot 1/49$) does not take into account that you that you draw 13 cards; it assumes that 4 cards are drawn. Also, it assumes ordering of kings (say king of hearts followed by king of diamonds followed by ..). The correct answer to the question, as you noticed, is number of favorable outcomes divided by the number of total outcomes.
Answer: First, the number of ways to select $4$ cards from $52$ is given by the combination $\binom{52}{4} = 270725$. This is the total number of possible $4$-card hands.
the number of hands that contain all four aces is $$4\times\binom{48}{1} = 4 \times48 = 192~.$$
the probability of a player being dealt all four aces is the ratio of the number of hands that contain all four aces to the total number of possible $4$-card hands:
$$P(\text{all four aces}) = \frac{192}{270725}$$
This simplifies to approximately $0.00071$, or about $1$ in $1409$. So the probability of a player being dealt all four aces is quite low.


$X$ is connected and $\mathcal{U}$ is a locally finite collection of precompact open sets that covers $X$; then $\mathcal{U}$ has a countable subcover

Question: I came to this question in the course of trying to prove that if $X$ is a paracompact locally Euclidean Hausdorff space with at most countably many components, then it is second countable. I was able to reach the hypothesis in the thread title, then got stuck. I know this problem in general has been addressed before, but I'm wondering if my approach is valid.
The following is what I'd like to clarify, I'm not sure if it's legitimate. Pick any $U_0 \in \mathcal{U}$. There are $n_1$ sets in $\mathcal{U}$ that intersect $U_0$, call them $U_1,...,U_{n_1}$. There are $n_2$ sets that intersect any of the $U_0,...,U_{n_1}$, call them $U_{n_1+1},...,U_{n_1+n_2}$. Proceed this way, letting the sets $U_{n_1+...+n_k+1},...,U_{n_1+...+n_k+n_{k+1}}$ be the $n_{k+1}$ sets that intersect any of the preceding $U_i$.
Now, I argue that the open set $U = \bigcup_{i}U_i$ = X. Suppose it does not. For any $x \in U^c$, there is some $U_x \in \mathcal{U}$ that contains $x$, and it must have failed to appear in the list $U_i$; in fact, by construction it must not intersect any of the $U_i$ so $x \in U_x \subset U^c$. Thus $U^c$ is open, so $X$ is the union of two disjoint open sets ($U$ and $U^c$) and thus disconnected, which is a contradiction.
Comment: My mistake, the hypothesis should also assume the sets of $\mathcal{U}$ are precompact. In that case each $U$ intersects only finitely many other sets of $\mathcal{U}$.
Comment: Yes sorry, edited the title.
Answer: Local finiteness of $\mathscr{U}$ does not ensure that each member of $\mathscr{U}$ intersects only finitely many other members of $\mathscr{U}$: that's a stronger property.
However, you know that your space is locally separable, so it has a locally finite open cover $\mathscr{U}$ whose members are separable. Let $W$ be any separable open set, and let $D$ be a countable dense subset of $W$. For each $x\in D$ the set $\operatorname{ST}(x,\mathscr{U})=\{U\in\mathscr{U}:x\in U\}$ is finite, and
$$\{U\in\mathscr{U}:U\cap W\ne\varnothing\}=\bigcup_{x\in D}\operatorname{ST}(x,\mathscr{U})\;,$$
so $W$ intersects only countably many members of $\mathscr{U}$. Let
$$\operatorname{st}(W,\mathscr{U})=\bigcup\{U\in\mathscr{U}:U\cap W\ne\varnothing\}\;;$$
$\operatorname{st}(W,\mathscr{U})$ is the union of countably many separable sets, so it is also separable. Now fix $U_0\in\mathscr{U}$; $U_0$ is separable. Given a separable open set $U_n$ for some $n\in\Bbb N$, let $U_{n+1}=\operatorname{st}(U_n,\mathscr{U})$; then $U_{n+1}$ is also a separable open set. Let $W(U_0)=\bigcup_{n\in\Bbb N}U_n$; $W$ is a separable open set.

Show that $\{W(U):U\in\mathscr{U}\}$ is a partition of $X$ into open subsets, and conclude that $X=W(U)$ for each $U\in\mathscr{U}$.
Further deduce that $X$ is the union of countably many members of $\mathscr{U}$.
Finally, note that we could have assumed additionally that each $U\in\mathscr{U}$ was metrizable and hence Lindelöf, and deduce that $X$ is Lindelöf.


Finding global extrema of $a\left(\frac{1}{2}-b\frac{\sin(cx)}{x} \right) - b(1-\cos(cx))$, for $x\geq 0$

Question:
I have the following equation:
  \begin{equation}
f(x) = a\left(\frac{1}{2}-b\frac{\sin(cx)}{x} \right) - b(1-\cos(cx)), \quad x\geq0,
\end{equation}
  where a, b and c are strictly positive constants.

When I plug this into WolframAlpha to solve for min/max of $f(x)$ for $x>0$, it returns no global min/max is found. However, from all of the figures that it provides, the global min and max appears to be after to be within the first "cycle" - see figure. The numeric also confirms this, but I am struggling to find out how to prove that it is the case (if it is).
Any hint would be much appreciated. Here is the link for the numerical approximations of those peaks.
Comment: @saulspatz I have added the description that they are positive constants.
Answer: Plugging in $a, b, c = 1$ gives the equation $$-0.5-\frac{\sin(x)}{x}+\cos(x)$$Simplifying the derivative of this equation and setting it equal to zero yields $$(1-x^2)\sin(x)-x\cos(x)=0$$ Which although I cannot solve, Wolfram Alpha can, yielding the first positive solutions corresponding to local maxima to be x = 6.11676 and x = 12.48594. Plugging in these values back into the original equation yields y = 0.513 and y = 0.503, proving the conjecture false. Why, you may ask? I don't have a rigid proof, but since the factor of sin(x) is being divided by x, it's average value decreases over time, so the maxima values cannot be constant. The only possibility is if the sin term is zero for each maxima, so I do believe that you can construct a function that does follow your hypothesis but clearly not all functions do.
Whoops, I misread the question a bit. Simplifying the equation and removing unhelpful constants leads to the equation $$b(-a\frac{\sin(cx)}{x}+\cos(cx))$$ where we can effectively ignore $b$. As we take the limit of $x$ to infinity, the maxima occur near $x=\frac{2\pi}{c}k$. How much larger is the maxima of the whole function than the maxima of $\cos(cx)$? Comparing slopes of $-a\frac{\sin(cx)}{x}$ near $x=\frac{2\pi}{c}k$, gives $\frac{-abc^2}{2\pi k}$, or a decreasing magnitude when x increases. Since the magnitude is larger near zero, the maxima where the slopes of $-a\frac{\sin(cx)}{x}$ and $\cos(cx)$ are equal is larger when x is closer to zero. This is not a very rigorous proof, but it is an idea that does prove decreasing maximas for large enough x.
Comment: Since the first peak is larger than the second peak in your example, this would numerically support my conjecture that there exists a global maximum.
Comment: Oh, I'm sorry I misread what you claimed. I thought you said the opposite. So yeah, you're right, all data does seem to correspond with the claim. I did have a soft answer as to why that happens but when it comes to a rigorous proof, I will try to work on one.
Comment: Thank you! I have a small question. How do you find that the maximum occurs at $x=2 \pi/c$? I tried the function $\cos(2x) - sin(2x)/c$ and find that the maximum occurs at about $x=2.97018$ whereas $2\pi/c$ would give me at least $\pi \approx 3.14$.
Comment: It doesn't. It only approximates x = 2pi/c because the sin goes to zero as the function approaches infinity. So the maxima of only the cosine function is x = 2pi/c. That's why my proof is not rigorous, but it does show some insight into why.


Can someone help to explain the difference between independent and random?

Question: In statistics, does independent and random describe the same characteristics? What's the difference between them? We often come across the description like "two independent random variables" or "random sampling". I am wondering what's the exact difference between them. Can someone explain this and give some examples? for instance non-independent but random process?
Comment: This is a strange question, because if you were to consult formal definitions of "random variable" and "independent"--which is what "in statistics" would seem to suggest--you would find they have little in common.
Comment: Please do not confuse the heuristic explanation at the beginning of any Wikipedia entry with a definition. The definition is given under the heading "definition" [in the same article](https://en.wikipedia.org/wiki/Independence_(probability_theory)#For_events).  It is the one offered in Tim's answer here.
Comment: If we check the definition of independence from wiki: "In probability theory, two events are independent, statistically independent, or stochastically independent if the occurrence of one does not affect the probability of the other.", the dependency of two observations should be based on how they are generated/selected, rather than how they look like in the data. Then the two identical observations in the case I mentioned above should still be independent.
Comment: Here is two distinct (on a not very deep level) concepts merged. "Independent" in the sense independently generated observations, and "independent variables" wrt their distributions.
Comment: @ttnphns, Yes, I guess I was more confused about the term "independently generated observations" with "randomly generated". In sampling, we often hear (simple) random sampling, which makes me feel like independent samples. I guess if we really want to combine both characteristics in describing a sampling method, it should be: the selection of observations is not dependent on each other (=independently) and the probability of selection an observation is known (=randomly)?
Comment: Another issue is that I wonder why the term "independent sampling" is not often mentioned? Could it happen that two observations are independently selected however they are dependent? For instance in a simple random sampling with replacement, I would independently select observations, but 2 identical observations are selected due to sampling with replacement. Does this mean that these two observations are dependent?
Comment: However, when we apply mixed models to nested data, we often state that some observations are not-independent, just based on the data structure. But if these observations are indeed independently selected, how come they become non-independent? or the non-independence here refers to the random variable that we want to estimate in the model?
Answer: I'll try to explain it in non-technical terms: A random variable describes an outcome of an experiment; you can not know in advance what the exact outcome will be but you have some information: you know which outcomes are possible and you know, for each outcome, its probability.
For example, if you toss a fair coin then you do not know in advance whether you will get head or tail, but you know that these are the possible outcomes and you know that each has 50% chance of occurrence.
To explain independence you have to toss two fair coins. After tossing the first coin you know that for the second toss the probabilities of head is still 50% and for tail also. If the first toss has no influence on the probabilities of the second one then both tosses are independent. If the first toss has an influence on the probabilities of the second toss then they are dependent.
An example of dependent tosses is when you glue the two coins together.
Comment: Another pair of dependent variables would be "whether you got heads" and "whether you got tails". Both are random but they are not independent of each other.
Comment: @immibis Or roll a fair dice, write down the value. then roll it once more and multiply the value with the value written down. This value is random, but dependent on the first roll.
Answer: Random relates to random variable, and independent relates to probabilistic independence. By independence we mean that observing one variable does not tell us anything about the another, or in more formal terms, if $X$ and $Y$ are two random variables, then we say that they are independent if
$$ p_{X,Y}(x, y) = p_X(x)\,p_Y(y) $$
moreover
$$ E(XY) = E(X)E(Y) $$
and their covariance is zero. Random variable $Y$ is dependent on $X$ if it can be written as a function of $X$
$$ Y = f(X) $$
So in this case $Y$ is random and dependent on $X$.
Calling process "non-independent" is pretty misleading - independent of what? I guess you meant that there are some $X_1,\dots,X_k$ independent and identically distributed random variables (check here, or here) that come from some process. By independent we would mean in here that they are independent of each other. There are processes producing dependent random variables, e.g.
$$ X_i = X_{i-1} + \varepsilon $$
where $\varepsilon$ is some random noise. Obviously in such case $X_i$ is dependent on $X_{i-1}$, but it is also random.
Comment: @tiantianchen the other way around: if you have iid random variables, then you can construct likelihood function by multiplying the individual pdf's *because* they are independent.
Comment: @m_t_ this is splitting hair, see http://stats.stackexchange.com/questions/16321/are-the-random-variables-x-and-fx-dependent or http://www.math.ucsd.edu/~napkaria/crypto/handouts/IndepDepRV.pdf
Comment: What does $P(X)$ mean if X is a random variable? I think you're confusing RVs and events: two RVs X and Y are independent if the *events* $P(X\leq r)$ and $P(Y\leq s)$ are independent for all r,s
Comment: Then any two continuous random variables are independent.
Comment: @m_t_ I really do not think that discussing the notation leads anywhere (see e.g. https://en.wikipedia.org/wiki/Independence_(probability_theory)#For_random_variables )
Comment: That's better, but the statement with f isn't right: if f is constant then so is Y= f(X), so Y is independent of X, not dependent on X.
Comment: Can I interpret the definition of independence p(x,y) using likelihood function as an example? If I have a dataset each observation is independent and each observation follows a pdf(randomness). The likelihood of observing such data would be a multiplication of the pdfs, which combines the independence and randomness of a sampled data into one formula
Comment: Thanks @Tim. Your answers are very clear to me. One last question: does the concept of independence only applies to random variables? We often make such statement: observation A and B are independent. So this actually refers to: the probability of observing A and probability of observing B are independent?
Comment: @tiantianchen I'm afraid your example is to vague to comment it, but *everything* we deal with in statistics are random variables, so if the statement is in context of statistics, then yes -- it's either about independent events, or independent random variables.
Answer: The notion of independence is relative, while you can be random  by yourself. In your example, you have "two independent random variables", and do not need to talk about several "random sampling".
Suppose you cast a perfect die several times. The outcome $6,5,3,5, 4\ldots$ is a priori random. Knowing the past, you cannot predict the number following 4. Suppose I generate a sequence from the other side of the die: $6\to1$, $3\to4$. I get $1,2,4,2, 3\ldots$. It is as random as the first one. You cannot guess what comes after $3$. But the two sequences are completely dependent.
If one casts two dice in parallel (without interactions between they), their respective sequences will be random and  independent.
Comment: This may be a little technical given the level of the OP, but regarding your statement "You cannot be independent (of something) alone (as a process, a sequence)" consider the following: Any random variable X, which equals a constant c with probability one, is independent of "everything", including itself.  I.e., for such an X, X is independent of X. You can easily check that per the definition of independence.
Comment: @Mark L. Stone I shall correct this false statement. By alone I meant "in itself". In your definition, are you allowed to say: $X$ is independent, or $X$ and $X$ are independent?
Comment: X is independent of itself. I.e., X is independent of X.
Answer: Variables are used in all fields of mathematics.  The definitions for independence and randomness of a variable are applied unilaterally to all forms of mathematics, not just to statistics.
For example, the X and Y axes in 2-dimensional Euclidean geometry represent independent variables, however, their values are not (usually) assigned at random.
Two given variables can be random, or independent (of one another), or both, or neither.  Statistics tends to focus on the randomness (more correctly, on probability), and whether or not two variables are independent can have many implications for the probabilities of given outcomes being observed.
You tend to see these two properties (independence and randomness) described together when studying statistics, because both are important to know, and can influence the answer to the question at hand.  However, these properties are not synonymous, and in other fields of mathematics they do not necessarily occur together.
Comment: This is a non-statistical answer that addresses a different sense of "independent" than the one used in the question.  It also confuses two senses of "variable": one is the mathematical one and the other is the statistical definition of *random variable* (which definitely is *not* the same as variables on geometric axes).
Comment: Thanks. Can you explain more about "whether two variables are independent can have many implications for the probabilities of given outcomes being observed."
Answer: When you have a pair of values when the first is randomly generated and the second has any dependence on the first one. e.g. height and weight of a man. There is correlation between them. But they are both random.
Comment: Although this post uses the words "random" and "dependent," it doesn't define them or clearly distinguish them.  Indeed, it seems to suggest that "random=dependent"!
Answer: David Bohm in his work Causality and Chance in Modern Physics (London: Routledge, 1957/1984) describes causality, chance, randomness, and independence:
"In nature nothing remains constant. Everything is in a perpetual state of transformation, motion, and change. However, we discover that nothing simply surges up out of nothing without having antecedents that existed before. Likewise, nothing ever disappears without a trace, in the sense that it gives rise to absolutley nothing existing at later times. .... everything comes from other things and gives rise to other things. This principle is not yet a statement of the existence of causality in nature. To come to causality, the next step is then to note that as we study processes taking place under a wide range of conditions, we discover that inside all of the complexity of change and transformation there are relationships that remain effectively constant. .... At this point, however, we meet a new problem. For the necessity of a causal law is never absolute. Thus, we see that one must conceive of the law of nature as necessary only if one abstracts from contingencies, representing essentially independent factors which may exist outside the scope of things that can be treated by the laws under consideration, and which do not follow necessarily from anything that may be specified under the context of these laws. Such contingencies lead to chance." (pp.1-2)
"The tendency for contingencies lying outside a given context to fluctuate independently of happenings inside that context has demonstrated itself to be so widespread that one may enunciate it as a principle; namely, the principle of randomness. By randomness we mean just that this independence leads to fluctuation of these contingencies in a very complicated way over a wide range of possibliities, but in such a manner that statistical averages have a regular and approximately predictable behaviour."
(p.22)
Comment: I believe part of the difficulty we are having in communicating is that you appear to be thinking of "independent" in the sense of an *independent variable in regression.* Although some elements of the question might suggest that, the phrases "two independent random variables" and "random sampling" indicate otherwise.
Comment: Your definition of "random" seems unusual.  It appears to be intimately connected with concepts of "predictability" and "pattern"--but what exactly do those mean?  For instance, if an experiment that potentially could yield any number between $0$ and $1$ were consistently observed to yield values of either $1/3$ or $4/7$, that would seem to be a "pattern" and--to the extent it differs from the original infinite set of possible values--is at least partially "predictable." Where you write "if you plot..." it seems you are claiming that *no* univariate variable can be random!
Comment: You seem to be discussing *stochastic processes* (in time) rather than randomness and random variables.
Comment: I cannot even tell what your understanding is, because your answer provides no definitions.  I'm having to guess what you're trying to say from the examples and descriptions you give.  They appear to differ from the senses of "random" and "independent" in the ways I have described in previous comments.
Comment: I'd add to @whuber comments that your definition mentioning random variables **influencing** each other may be misleading. "Influence" is a very strong term implicating some kind of causality etc. while the formal definition of independence does not require any causality or influence but it is simply about relations of joint vs individual probabilities.
Comment: Second paragraph, you bolded it.
Comment: Your last edit with the example of blue sky and rain actually illustrates mine and @whuber's doubts: you are not talking here about probabilistic independence. Even if those two events are *caused* by an external factor and do not "depend" directly on each other, though they co-occur more often then by chance, so $p(x,y) \ne p(x)p(y)$, i.e. they are not independent by definition. You call independence "assumption", while it is rather a property of events of random variables. Even if you are talking about "dependent" and "independent" variables as understood in regression, then this needs to
Comment: @Tim Thanks! It took me a while to understand that my misunderstanding was on a very basic level.
Comment: @whuber When any event in a sequence of events cannot be inferred from the previous events, the sequence is random. A pattern has different motifs that are repeated. For example, the squares of a square wave. If one motif is omitted, it can be said to be a pattern if the pattern predicts completion for the omitted motif. By *pattern* I mean the sequential pattern of the variable. By *prediction*, I did not intend the outcome of the variable at time point $t$ given an expected value *range(0.0, 1.0)*, but how an arbitrary point $t_n$ cannot be predicted based on $t_n-m$ for all negative $m$s.
Comment: @whuber I fail to see how $t$ does not generalize to $x$.
Comment: @whuber How is your understanding of independent different from mine? Random sampling is different from conditional sampling - consider a hypergeometric distribution resulting from sampling without replacement. The samples can be drawn randomly, but the population is given a priori. The order of the sampling provides x. Perhaps it is the distinction between "random effect" and fixed effect that confuses. I don't know.
Comment: @whuber Described independent, you have not.
Comment: I am sorry that I have been of no help in getting your answer clarified.  Might I suggest taking a look at [Tim's answer](http://stats.stackexchange.com/posts/231432/edit) for a rigorous definition?
Comment: @whuber I do not think you have read my answer properly.
Comment: @Tim Where do I state that random vars influence each other?
Comment: @Tim That's not what I said.
Comment: be stated in your answer directly, because otherwise your answer is misleading. Independent variable in regression is something really different then independent random variables.
Comment: @whuber Tim made it clear to me that I was wrong. Thanks for your patience.
Comment: @noumenal could you consider either editing or deleting your answer? As it stands we have an answer, now sitting here untouched for half a year essentially saying "ignore this while I think about it"...
Comment: @Glen_b Sorry, I forgot about this question. I will let David Bohm answer this one.
Answer: The coin example is a great illustration of a random and independent variable, a good good way to think of a random but dependent variable would be the next card drawn from a seven deck shoe of playing cards, the -likelihood- of any specific numerical outcome changes depending on the cards previously dealt, but until only one value of card remains in the shoe, the value of the card to come next will remain random.
Comment: Probably worth replacing the word "likelihood" by "probability" here, since [likelihood has a separate technical definition in statistics](https://en.wikipedia.org/wiki/Likelihood_function)
Comment: A probability that depends on other events (often previous events, but sometimes based on knowledge of future or simultaneous events - there actually is no temporal direction to this) is called a *conditional* probability. The word *likelihood* is used to refer to a kind of "probability in reverse" (or in the continuous case, a probability density) - that is, one calculates the probability of an outcome (e.g. your data) conditional on your model parameter(s), but if we think of this the other way round, it's the likelihood *of that parameter, given your data*.
Comment: Unless you're calculating the likelihood of a parameter, it's best to avoid the word "likelihood" in statistics, even where in normal English one would use "likelihood" as a synonym for the probability of an event (e.g. "rolling ten sixes in a row in a game of dice has a very low likelihood" is fine for colloquial English, but isn't using the word correctly in a statistical sense). "Let $π$ be a parameter denoting the probability that a biased die rolls a six; calculate the likelihood that $π=1/6$ given that ten rolls of the die were all sixes" is statistically correct but jargony


In R, what does sample(..., replace=TRUE, ...) do?

Question: After reading R's documentation on the function sample, I still do not understand what does the option replace do.

data <- sample(x=c(0, 1), size=n, replace=TRUE)
data <- sample(x=c(0, 1), size=n, replace=FALSE)

How to understand this?
Comment: The underlying statistical issue of the difference between sampling with (`replace = TRUE`) and without replacement (`replace = FALSE`) is covered on this site, for example [here](https://stats.stackexchange.com/q/49480/28500). Please read what's available on this site about this issue and, if you still have questions about this difference in sampling approaches, edit the question to focus on your remaining questions.
Answer: It's related to sampling techniques. When you sample replace = False, first element/number picked for sampling will not kept back in entire population to be picked again in same sample.
read this article -
https://www.ma.utexas.edu/users/parker/sampling/repl.htm
It's not related to R as such but to- ways of sampling. Also do good research before posting any question. Big guys here will give you -1 for this. :P :P
Comment: considering one is taking one element at a time in sampling.


Fixed effects model for surface growth

Question: I am trying to fully understand and reproduce the paper Normative brain size variation and brain shape diversity in humans, in which the authors have used brain surface measurements from many different subjects with different brain sizes to compute a scaling factor for each vertex on the brain mesh that describes the increase/decrease in surface area at that anatomical location relative to a given increase in the whole brain surface.
In the Methods section, which is available in the Supplementary Materials, p4, the authors write:

Vertex-wise areal scaling with total cortical area was estimated using
  a semi-parametric  spline  regression  model  that  simultaneously
  incorporated  effects  of  age  and sex  on  vertex  area  (41, 42).
  The  scaling  relationships  presented  in  our  results,  were
  estimated using the following fixed-effects model:
Log10(vertex_area) ~ s(age, by=sex) + ß1[log10(total_area)],     [1]
where s(age, by=sex) denotes a fixed-effect thin plate spline basis
  estimated for each  sex. [...] The ß1 coefficient from model [1] provides > an estimate of how area at each cortical vertex scales with total
  cortical size.

I would like to implement that model (preferably in Python, Matlab or GNU R), but I am struggling with the part s(age, by=sex) denotes a fixed-effect thin plate spline basis estimated for each sex.
How could I compute such a fixed-effect thin plate spline basis, given observations of the position of the respective surface point for a number of subjects (and their age+sex)?
Answer: The mgcv package in R has a gamm function which will provide what you need as it can incorporate so-called factor smooth interactions, which allow the smooth, nonlinear effect of one continuous variable such as age to be different across the levels of a categorical variable such as sex. See for example:
https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/smooth.construct.fs.smooth.spec.html
https://www.fromthebottomoftheheap.net/2017/10/10/difference-splines-i/
and especially
http://www.sfs.uni-tuebingen.de/~jvanrij/Tutorial/GAMM.html.
You'll probably need to specify your model along these lines:
gamm(log10(vertex_area) ~ s(age, by = sex, bs = "ts") +
                          log10(total_area),
                          data = YourData)

In fact, you could also use the bam() function of mgcv instead of the gamm() function, which is suitable for large data sets, as illustrated in the last of the 3 links I provided.
Comment: Thanks, the R functions and the links helped me to get started and let me into the right direction.
Comment: You're welcome, @spirit!
Comment: @spirit: Please check out this awesome, hot-off-the-press pre-print by Gavin Simpson and his colleagues: https://peerj.com/preprints/27320.pdf. It's an excellent resource!

Fixed effects model for surface growth


How can delta (Δ) R² for a term be larger than R² for that term?

Question: I am testing whether a variable predicts an outcome - firstly on its own, and then after controlling for various covariates. Since the outcome is continuous, I want to report R² as an effect size metric.
For that, I was planning to report

R² for the DV ~ IV model, and
ΔR² comparing DV ~ IV + CV minus DV ~ CV.

In some instances, the resulting ΔR² is larger than the corresponding R² - which does not seem to be possible with my understanding of what R2 indicates. How can a variable explain a greater incremental than total share of variance? I'd be very grateful for any pointers.
Comment: Do you include intercept terms in these models or not?  Regardless, consider the case where the DV is a linear combination of CV and IV but CV is orthogonal to DV: your $\Delta R^2$ would be 100%. Here's an example with four observations: IV = (-1,0,1,0); CV=(-0.9,-0.1,1.1,-0.1), and DV=(0.9,-1.01,0.98,-1.08).  The R^2 for DV~IV is 0.00; the difference in R^2 for DV~CV and DV~IV+CV is 0.97.  (All models include intercepts.)
Comment: You cannot decompose the total variance into variance components uniquely unless the explanatory variables are uncorrelated.  The (strong) correlation among IV and CV in the examples is what makes them work.
Comment: Is $\Delta R^2$ the difference in $R^2$ between the larger and the smaller model?
Comment: Yes - I clarified that in the question.
Comment: Yes, I include intercepts. Thanks for that example, very helpful. So far, I've always been thinking about shared variance that is then parcelled out - and my intuition for this case is still not clear; some more thinking to do.
Answer: First, to get this nitpick out of the way: you are not predicting, you are fitting and explaining variance. These two are very much not the same. One model might explain much more variance (and even have a higher adjusted $R^2$) but yield worse predictions than a different model. In-sample fit is a notoriously bad guide to out-of-sample predictive power. Analyzing model fit and calling it "prediction" confuses two very different things, and every time I see a psych paper discussing "prediction", I am sorely tempted to ask them to actually do predict something and compare these predictions to a much simpler model on a true holdout sample. They would usually be shocked how little their statistically significant findings actually improve predictive power.

Now, this is just a situation where your intuition (that a variable should not explain more variance in the presence of a covariate than without that covariate) is off. There is simply no reason for this to be true.
You can simulate simple cases like this multiple times, playing around with your simulation parameters, and check whether the property your intuition calls for holds. Here is a simple case with $n=20$ data points, a numerical IV and a two-level factor CV where it doesn't:

Regressing DV on IV alone gives $R^2=0.01628121$. A model with DV and CV gives $R^2=0.4843284$, and one with only CV gives $R^2=0.4656828$, so
$$\Delta R^2 = 0.4656828-0.4843284 = 0.01864566, $$
larger than the single-predictor $R^2$.
Note that we are analyzing a correctly specified model with the two main effects. You could probably create more counterexamples with misspecification. In this case, the issue is that CV already explains a lot of variance, so when we regress only on the IV, we incorrectly believe we can explain some variance that is actually driven by CV - and in comparing the two competing models, this variance is correctly already explained by CV.
R code:
nn <- 20
set.seed(1)
IV <- runif(nn)
CV <- as.factor(rep(c("A","B"),each=nn/2))
DV <- 1*IV+2*as.numeric(CV)-0.0*IV*as.numeric(CV)+rnorm(nn,0,1)

plot(IV,DV,col=CV,pch=19+as.numeric(CV),las=1)

summary(lm(DV~IV))$r.squared
summary(lm(DV~IV+CV))$r.squared
summary(lm(DV~CV))$r.squared
summary(lm(DV~IV+CV))$r.squared-summary(lm(DV~CV))$r.squared

Comment: Thank you - I am indeed a social psychologist and trying to get over the 'prediction' language, so that is a helpful reminder. However, I still don't get *why* this numerical result can be obtained - I don't doubt that it can be, since it arises from my data. Your description "when we regress on the IV, we incorrectly believe that we can explain some variance that is actually driven by the CV" would seem to imply that R2 is too large and thus larger than delta R2?
Comment: I would not call it "too large". It's simply that there is no reason for $R^2$ to behave as your intuition would like it to do. Also, I don't see a quick-and-easy way of classifying situations where intuition misleads us here (although there may well be such a classification). [whuber's comment is also very nice.](https://stats.stackexchange.com/questions/597361/how-can-delta-%ce%94-r%c2%b2-for-a-term-be-larger-than-r%c2%b2-for-that-term/597364?noredirect=1#comment1105776_597361)
Answer: Stephan Kolassa has an important point and provided a good example for this being a common phenomenon but i think, that i can actually explain it. Namely this is a kind of weak Simpsons Paradox(https://en.wikipedia.org/wiki/Simpson's_paradox), which is a) not limited to subgroups and b) only suppresses the "effect" not wholly inverts it.
Consider the classic example of grad school admission(DV) at Berkeley in the 70s, where being a women(IV) was correlated with being in a more competitive Department(CV). Now the correlation between DV ad IV was negative , but once adjusted for the departments it actually changes into being positive. However if the correlation between IV and CV or the adjusted Correlation CV and DV had been smaller we might have seen no unadjusted(marginal) Correlation between IV and DV. This would translate to $R^2 = 0$ and then obviously $\Delta R^2 > R^2$.
In the example from Stephan Kolassa the adjusted effects are both positive and the correlation between IV, CV is (purely by chance) negative, which means that the marginal effect of IV on DV is suppressed by there being fewer CV = B for high IV values. If we simulate the setup 1000 times this becomes apparent:
nn <- 20
res <- replicate(1000, {
  IV <- runif(nn)
  CV <- as.factor(rep(c("A","B"),each=nn/2))
  DV <- 1*IV+2*as.numeric(CV)-0.0*IV*as.numeric(CV)+rnorm(nn,0,1)
  c(cor(as.numeric(CV), IV), (summary(lm(DV~IV+CV))$r.squared-summary(lm(DV~CV))$r.squared) - summary(lm(DV~IV))$r.squared)
})

plot(res[1, ], res[2, ], xlab = "Cor(IV, CV)", ylab = "deltaR2 - R2")
abline(h = 0, v = 0)

$\Delta R^2 - R^2$ is negatively correlated with Cor(IV, CV)" />
Now this is messy, because the $\hat{\beta}$s  have a high variance and if the sign of one of the betas changes then so does the effect. We can however see, that if IV and CV are uncorrelated, the $\Delta R^2 - R^2 = 0$ which, if you have a strong intuition about the geometry of a linear model, follows from Pythagorean Theorem.
If we increase the signal to noise ratio by using a smaller $\sigma$ the picture is much clearer
nn <- 20
res <- replicate(1000, {
  IV <- runif(nn)
  CV <- as.factor(rep(c("A","B"),each=nn/2))
  DV <- 4*IV+2*as.numeric(CV)-0.0*IV*as.numeric(CV)+rnorm(nn,0, 0.2)
  c(cor(as.numeric(CV), IV), (summary(lm(DV~IV+CV))$r.squared-summary(lm(DV~CV))$r.squared) - summary(lm(DV~IV))$r.squared)
})

plot(res[1, ], res[2, ], xlab = "Cor(IV, CV)", ylab = "deltaR2 - R2")
abline(h = 0, v = 0)

$\Delta R^2 - R^2$ is strongly negatively correlated with Cor(IV, CV). Its almost a straight line." />
In conclusion: Looking at DV ~ IV only tells you about the sum of the direct effect from IV to DV and the indirect effect from IV to CV and then to DV. This indirect effect can be in the same direction ($\Delta R^2 < R^2$),  opposite direction but of moderate size ($\Delta R^2 > R^2$) or outright overpower the direct effect like with Berkley in which case $R^2$ is not a very sensible metric. The indirect effect is basically the product of IV -> CV and the direct effect from CV to DV, so it's positive if both of those have the same sign and negative if they don't. Please consult causal theory to figure out, if marginal effects or adjusted effects are right for you. After all cigarettes are perfectly healthy if you adjust on the state of peoples lunges.
P.S. I've used the term direct effect which should be read as adjusted and effects are of course just correlations not causations.
Comment: Thank you for such a clear and comprehensive explanation - very helpful!


Search for a value on a database column splitting the value where there is a blank space

Question: I have a table on my database named leads. Inside that table there are several columns containing the name, telephone, address, postal code etc, etc... of the leads.
The column that contains the name of the leads is called clientName.   As an example we have Loyalty Logistics.
I have an input type text inside a form where users search for a specific client name and shows the results on a Popup.   Right now I am using a WHERE clause
<code>....WHERE leads.clientName LIKE "%'.$_POST["keyword"].'%"
</code>
The way it is right now it will only show up the client Loyalty Logistics
if the user type Loyalty or Logistics or Loyalty Logistics, but in the case the user made a mistake and typed Loyalti Logistics I would also like to be able to show on the results all the clients that contained Logistics on its name.
Comment: Just type it correctly!
Comment: If I would be the only user I wouldn't have this problem but the users that are using my program are old and make lots of mistakes.
Comment: Could you construct some kind of autosuggest in that case?
Answer: You can make the split with your server side language (PHP, Python, JS ...) and obtain a list of keywords and make your sql request with it.
<code>keywords = split(keyword)
for key in keywords
    ....WHERE leads.clientName LIKE "%'.$_POST["key"].'%"
</code>
I hope it will be helpful.
Comment: Good idea.   I am a PHP developer.  Thanks a lot.


Further Trigonometry

Question:
Does anyone knows how to do $12(ii)~?$ Thanks in advance!
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to write up your questions here, rather than attaching a link or a picture. Also, please explain what you have tried and are stuck on.
Answer: $s^2=2+4$sin$^2θ  +4$sin$θ$cos$θ=2+4$sin$^2θ  +2$sin$2θ  =2+4(1-$cos$2 θ )/2+2$sin$2θ  =2+2(1-$cos$2 θ )+2$sin$2 θ =4-(2/\sqrt{2})(-\sqrt{2}$cos$2θ +\sqrt{2}$sin$2θ )=4-(2/\sqrt{2})[(-2$cos$2θ )(\sqrt{2}/2)+(2$sin$2θ )(2/\sqrt{2})]=4-(2/\sqrt{2})(-2$cos$(2θ +π /4))=4-4/\sqrt{2}($cos$(2θ +π/4))$

Further Trigonometry


PHP json_encode com valores boolean e decimais

Question: Possuo uma função PHP que obtém dados do banco de dados e me retorna uma array com os resultados. Essa array, por padrão, possui todos os dados como tipo string, porém alguns campos devem ser tratados como boolean enquanto outros devem ser tratados como valores (dinheiro) e são do tipo decimal.
Posteriormente eu faço uso desses dados na página HTML para executar algumas funções ou exibição de dados. Por exemplo:

valor - tipo _decimal(10,2) - Usado para exibir o valor de um produto.
ativo - tipo tinyint - Usado para marcar ou não um checkbox.

A array de dados que eu obtenho são geradas através de uma consulta (SELECT) ao banco de dados, com isso o retorno vem com todos os campos em string. Isso "resolve" uma parte do problema, pois mantém o campo valor com as casas decimais. O problema começa quando eu tento a conversão, usando flags no json_encode, transformar os valores de volta para boolean (ou int), e então tenho esses 2 casos:
Caso 1: Quando utilizo json_encode($resposta,JSON_NUMERIC_CHECK) a coluna valor perde seus decimais e é arredondada. Ex.: 9.90(string) -> 10(int)
Caso 2: Quando utilizo json_encode($resposta,JSON_PRESERVE_ZERO_FRACTION ) a coluna ativo vem como string e com isso não consigo controlar o checkbox.
Existe algum modo de contornar essa situação?
Comment: Estranho acabei de testar, http://ideone.com/EPzTTv , não perdeu as casas decimais, e não coloquei parametros a mais no `json_encode`
Comment: @DaniloMiguel acho que isso não vai interferir no resultado, seria apenas uma mudança estrutural. Por sinal, diversas questões que li no SO inglês inclusive não recomendam enum, e sim tinyint ou bit. Como o banco já possui essa estrutura, preferi manter. Mas acho que não vem ao caso.
Comment: Tem como postar um trecho do código e um var_dump() do retorno, inclusive após o json_encode?
Comment: @Miguel mas aqui você está gerando uma array manualmente, o que eu faço é uma requisição sql ao banco de dados, onde os valores iniciais retornados estão todos em string. O que resolve o caso dos valores decimais, pois mantém as casas. Porém eu necessito converter para poder utilizar os valores do tipo boolean, é nessa conversão que eu perco as casas decimais.
Comment: No "ativo" por que usar tinyint ao invés de "enum"?
Comment: `abs()` ou `(bool)` na coluna `ativo` antes de mandar pro json_encode não resolveria no segundo caso? JSON_NUMERIC_CHECK está transformando suas strings em ints mas se vc transformar antes JSON_PRESERVE_ZERO_FRACTION não deve interferir nisso.
Comment: Celsom, veja esta possível solução, http://ideone.com/EPzTTv , aqui converte manualmente o valor para float e o ativo para int
Comment: @RicardoMoraleida consegues um exemplo mais prático de como eu poderia fazer isso?
Comment: @Miguel mas nesse caso, se houver um json_encode depois não iria "resetar" e converter de volta para string? Pois eu pensei em usar um foreach como alternativa, mas acho que o problema está acontecendo depois, na hora de usar o json_encode. Como eu uso os dados em javascript posteriormente, essa etapa é necessária.
Comment: @CelsomTrindade algo assim, não otimizei: https://eval.in/673597
Comment: @RicardoMoraleida isso mesmo! É por ai. A única diferença é que ao invés de usar JSON_NUMERIC_CHECK eu tive que usar JSON_PRESERVE_ZERO_FRACTION assim me retornou valor(string) e ativo(int) como eu precisava. Uma dúvida a respeito disso.. Existe um método de mudar o campo valor ao invés do ativo? ex.:  `string($produto['valor'])`. Assim eu posso manter o id (ou outros campos de int) como int também e só o valor como string.
Answer: Trazendo pra cá o código que linquei nos comentários. Uma solução mais simples do que tentar coordenar as flags de json_encode() é tratar os valores antes de passar para a função.
Nesse caso, se ativo deve ser um intou bool e valor deve ser uma string, só é preciso tratar o ativo e não é necessária nenhuma flag, já que na saída do seu SQL todos os valores vem como string:
$produtos = array(
    array(
        'valor'=> "1.95",
        'ativo'=> '1'
    ),
    array(
        'valor' => '9.90',
        'ativo' => '0'
    ),
);

foreach( $produtos as $produto ) {
    $produto['ativo'] = abs($produto['ativo']);
    $resposta[] = $produto;
}

echo json_encode( $resposta );

Resultado:
[{"valor":"1.95","ativo":1},{"valor":"9.90","ativo":0}]

Se precisasse converter um valor para string poderia também usar 'valor' => (string) 1.95 por exemplo.
Comment: Isso ai resolve o problema, perfeito! Mas uma dúvida.. Caso eu queira converter de int para string, ou manter apenas 1 campo como string. Digamos que eu tenha varios campos do tipo int e somente o valor do tipo string, seria mais fácil converter apenas o valor para string, porém se eu usar `(string)$produto['valor']` ao fazer o JSON_NUMERIC_CHECK ele perde o tipo string, se não usar essa flag, os demais não retornam como int, e sim como string. Tem como resolver isso? Se é que eu expliquei corretamente...
Answer: Fiz um teste pra demonstrar que não há dificuldde com decimais ou booleanos ao converter para o formato json.
<?php

$x = array(9.9, 0);

$j = json_encode($x);
?>

A sua pergunta não deixa claro onde e como faz as comparações de valores booleanos, mas pelos comentários parece ser com JavaScript.
Para o JavaScript o valor 1 é true e valor 0 é false quando são valores numéricos. Se for do tipo string v = '0', por exemplo, v será tido como true.
Para "driblar" isso pode resolver com a função parseInt().
<?php

$x = array(9.9, '0');

$j = json_encode($x);
?>

Quanto ao valor decimal, pode vir como string do banco de dados que não fará diferença.
No entanto, para prover consistência com operações matemáticas no JavaScript, converta com a função parseFloat() quando necessitar fazer operações matemáticas.
a = '9.9';
b = 3;
document.write(parseFloat(a) + b);

Apenas por curiosidade, para o PHP é semelhante. Apenas muda o nome das funções. Seria intval() e floatval().
E claro, desconsiderei a comparação que verifica o tipo da variável.
if (v === true) {, por exemplo, necessita de um outro tratamento mais adequado. Mas o importante é que não precisa mexer em nada no json_encode() para ambos os casos.