Elegant proof that $L^2([a,b])$ is separable

Question: Is anybody aware of, or can provide at least an outline, of a proof that the Hilbert space of Lebesgue functions square-integrable on the closed real interval [a,b], equipped with the $L^2$ norm, is separable?
I've seen an ugly proof involving truncated functions so I'm not desperate, but would really like to use something nice. By the way, if you refer to a particular dense countable subset, could you please explain why it is dense and countable even if you consider it to be a fairly 'high-profile' set?
Thanks
Comment: polynomials with rational coefficients
Answer: The sub-$\mathbb Q$-vector space generated by the characteristic functions of intervals with rational end-points is countable and dense.
Comment: @Qiaochu: I could rephrase my question as follows: given that $\mathbb Q$ is dense in $\mathbb R$, how do you conclude that the step (simple) functions with endpoints in $\mathbb Q$ are dense in the step functions with endpoints in $\mathbb R$. But I can see now that it may be so because - unlike my arbitrary function $f$ above, a step function in $\mathbb R$ cannot escape because it has finitely many values. (I hope this makes sense to someone other than me, but it makes me happy anyway ;) )
Comment: Very good answer: simple, elegant and almost trivial after observing this fact in the first place. :-) (the upvote wasn't enough.)
Comment: Thank you. Could you please explain a bit about the endpoints? In particular, if $a$ is irrational then any simple function $\phi$ will vanish at $a+\delta$, leaving a set of positive measure on which $|f-\phi|=|f|$. Now $\delta$ tends to zero, but why doesn't $f$ escape fast enough for convergence in $L^2$ to be avoided?
Comment: @Josef: I'm not sure I understand your question. The subspace Mariano describes approximates the space of all step functions since $\mathbb{Q}$ is dense in $\mathbb{R}$, and the step functions are dense in $L^2$ by the standard argument.
Comment: The $L^2$ distance between the characteristic function of $[a,b]$ and $[p,q]$, where $p$ and $q$ are rational approximations for $a$ and $b$, is $\sqrt{|a-p|+|b-q|}$. Clearly you can make this arbitrarily small.
Comment: I was talking about step functions though.
Comment: Step functions are just (finite) linear combinations of characteristic functions of intervals...
Comment: @R. Thank you. I am not sure whether you aim to agree or disagree with the comment I addressed to Qiaochu above where I refer to step functions. I don't feel the need to decompose the argument beyond this to indicator functions unless there is something wrong in my conclusion.
Comment: I don't aim to disagree with your comment, just to show a simple line of reasoning why it follows from the density of $\mathbb{Q}$ in $\mathbb{R}$ that the step functions with rational endpoints will be dense in $L^2$.
Comment: @josef, but to go from one of those facts to the next in order to get a detailed proof should be easy for anyone familiar enough with measure theory to understand your question!
Comment: Sorry, I fail to see what the argument is that either of you have in your minds. What comes across on the page is just mathematical facts (eg denseness of $\mathbb Q$ in $\mathbb R$, that the difference betweeen two indicator functions can be made arbitrarily small), which I do not disagree with but whose consequences to the present context are not made evident in your text.
Comment: Well: a corollary of my last comment is that you should think about this for a while and find yourself a way of actually filling in the details. That I, or others, do it for you will help significantly less than that.
Comment: I have done a first course in Measure Theory and in Functional Analysis. I think the follow-on thinking from the above is easy, but I am taking my first steps in a complex field and feel the need for validation of even simple conclusions in order to grow in confidence. (By the way, the last comment wasn't in relation to you proof, Mariano.)
Comment: If/when you post a new question giving the result of you completing the details of the argument and asking for validation, I and others will probably do just that. :)
Answer: The set of functions $\{e_n\colon n\in\mathbb{Z}\}$ given by $$e_n(x) = \exp\left(2\pi in\frac{x-a}{b-a}\right)$$ is dense in $C[a,b]$ by the Stone-Weierstrass Theorem.*  Since $C[a,b]$ is dense in $L^2[a,b]$, it follows that $\{e_n\colon n \in \mathbb{Z}\}$ is dense in $L^2[a,b]$.
*Technically speaking, they're dense in the space of continuous functions normalized so that $f(a) = f(b) = 1$.  However, this doesn't really matter as we can always look at $[a-\epsilon, b+\epsilon]$ instead.
Comment: To complete the argument you need to use the fact that the uniform norm (or the $L^\infty$ norm) is stronger than the $L^2$ norm. More precisely, if a sequence of function on $[a,b]$ converges uniformly it will also converge in $L^2$ to the same limit.
Comment: One needs to be slightly careful. Stone-Weierstrass Theorem gives that the trig polynomials are dense in $C[a,b]$ in the topology given by uniform convergence of functions, while $C[a,b]$ is dense in $L^2$ in the Hilbert space topology of $L^2$. So just this is not enough to guarantee that the trignometric polynomials are dense in $L^2$. This is the distinction [I wrote about in my answer](http://math.stackexchange.com/questions/33645/) to another question.
Comment: Can someone verify (or argue against) my comment after the asterisk?  It's late where I am, and I can never be 100% sure of myself at this hour...
Comment: It's not the set of functions but the vector space generated by these functions, and after the asterisk the condition is just $f(a)=f(b)$.
Comment: Thanks Jesse. Where did you find these functions?
Comment: @Josef K.: http://en.wikipedia.org/wiki/Fourier_series
Answer: The set of continuous functions $C^0$ forms a dense subset of $L^2$ (Principles of Mathematical Analysis. W.Rudin. Theorem 10.38), the set of all polynomials with rational coefficients is clearly a countable set contained in $C^0$ and so it is a dense subset of $L^2$.


How to initialize some class, which is not a Servlet on glassfish4?

Question: I have web application in Java code, which uses servlets. My question is how to initialize some java class, which is not servlet. I understand that if the client connects - the servlet then prints the output. But only "if client connects".
Is it possible to run some threads before any connections are made?
EDIT:
Thanks to answers, right now I'm trying to do it this way:
the class:
package com.xsistema.filemanager.application;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 *
 * @author Ernestas Gruodis
 */
public class ServerInit implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Initialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Destroyed");
    }
}

And the glassfish-web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
    <context-root>/file-manager</context-root>
    <class-loader delegate="true"/>
    <jsp-config>
        <property name="keepgenerated" value="true">
            <description>Keep a copy of the generated servlet class' java code.</description>
        </property>
    </jsp-config>

    <listener>
        <listener-class>
            com.xsistema.filemanager.application.ServerInit
        </listener-class>
    </listener>

</glassfish-web-app>

And I getting this error while deploying the application:

Warning:   Unsupported deployment descriptors element listener-class
  value com.xsistema.filemanager.application.ServerInit.

What's wrong here?
EDIT2:
Can not delete this question, appeared to be duplicate (it has the answers already). But I found the solution:
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.servlet.ServletContextEvent;

@Startup
@Singleton
public class Config {

    @PostConstruct
    public void init() {
        // Do stuff during webapp's startup.
    }

    @PreDestroy
    public void destroy() {
        // Do stuff during webapp's shutdown.
    }
}

Very nice and easy, and working :)
Answer: The preferred way to do this is to install a ServletContextListener.
These get a chance to run code when the container starts up and shuts down.
If the code affects only a single servlet (or needs to initialize something private to that servlet object), you could also do the work in the init method of the servlet and make sure that the servlet is loaded even before a request is made (via the load-on-startup parameter).
Comment: I got this warning on glassfish4: "Warning:   Unsupported deployment descriptors element listener-class value path.path..."
Comment: Seems that glassfish4 can not find the specified file..
Comment: Do you have to use the glassfish-web.xml? Maybe it does not support this. Cannot you use the standard web.xml? Or try the `@WebListener` annotation.
Answer: You may run your code that initializes the other classes in the init() method of one of your servlets.
Comment: But that means I have to add the same code on all servlets, or do some filter.. Not good.
Comment: if it's something you need to perform before any of you servlets is called, then yes. In that case, I'd let all servlets extend one base servlet class with such a logic.
Comment: Ok, ServletContextListener is more appropriate here, if it's an application-wide initialization. I'm upvoting the other answer :)
Comment: " I have to add the same code on all servlets,". Well, not really, depends on what that code does. While ServletContextListener is probably the cleaner way, it is functionally almost equivalent to putting the same code into a single Servlet and loading that on startup. That's what people did before there were ServletContextListeners. The effect (how it impacts this and other servlets) is the same either way.


Como ler várias linhas de um arquivo de texto (.txt) e armazená-las numa mesma variável?

Question: Alguém tem uma ideia para me ajudar a extrair as linhas abaixo e que sempre se apresentam neste padrão?
Palavra1 (é sempre igual)
Linha a ser extraida, de tamanho variavel
Linha a ser extraida, de tamanho variavel
Linha a ser extraida, de tamanho variavel
Palavra2 (é sempre igual)

bla bla bla
bla bla bla

Palavra1 (é sempre igual)
Linha a ser extraida, de tamanho variavel
Linha a ser extraida, de tamanho variavel
Linha a ser extraida, de tamanho variavel
Palavra2 (é sempre igual)

As 3 linhas são partes da mesma informação que eu devo guardar em uma única variável e exibir ao usuário, mas que, na hora da conversão do arquivo, acabaram sendo jogadas em 2, 3 ou 4 linhas.
Segue o código que eu imaginei até aqui:
StringBuilder sb = new StringBuilder();
if(linha.startsWith("palavra1")){
    linha = arquivoEntrada.readLine() + 1; //pula a linha
    if(!linha.startsWith("palavra2")){ //minha condição de parada
        sb.append(linha + " "); //StringBuffer pra ir armazenando as linhas lidas
                                //como fazer o sistema pular a linha agora??????
    } else {

    }
    variavelQualquer = sb.toString();
}

Com esse código, eu só consigo pegar a primeira linha. Tentei com while em vez do segundo if, mas não funcionou.
Qualquer ajuda seria bem-vinda.
Comment: Você pode postar mais algum trecho do código? Acho que ajudaria entender o que está fazendo e propor algo mais próximo do que você precisa.
Comment: Resumidamente, eu tinha um arquivo PDF que foi convertido em txt. Meu trabalho é manipular via substring certas informações deste TXT gerado e, por fim, criar outro arquivo TXT final exibindo apenas as informações manipuladas. No caso, essas 3 ou mais linhas que eu ilustrei deveriam estar numa única linha (ou seja, elas são a informação que eu preciso), mas o conversor PDF p/ TXT acabou quebrando e jogando em várias linhas. Preciso agora, então, reuni-las novamente e jogar no TXT final como uma linha única. Espero que tenha ficado mais claro agora.
Comment: A ausência de pelo menos um ciclo me faz ver que só deverá mesmo ler a primeira linha.
Comment: @Cold, eu tentei usar o while, mas deu estouro de memória. De todo modo, o if deveria funcionar se minha lógica estivesse correta.
Comment: @bigown Minha lógica foi tentar trabalhar com a regularidade que me permite identificar o bloco de linhas de que eu preciso, e essa regularidade é a existência de uma mesma palavra antes dessas linhas e outra palavra depois dessas linhas. Quer dizer, as linhas que eu preciso estão sempre num bloco delimitado por 2 palavras que são sempre iguais.
Answer: Sugiro o seguinte:
...
StringBuilder sb = new StringBuilder();
linha = arquivoEntrada.readLine();
do
{
    if (linha.startsWith("Palavra1"))//verifica se começa pela Palavra e não
    {
        String linhaAux = arquivoEntrada.readLine();
        while (linhaAux != null && !linhaAux.startsWith("Palavra2"))
        {
            sb.append(linhaAux + " ");
            linhaAux = arquivoEntrada.readLine();
        }
    }
    linha = arquivoEntrada.readLine();
} while (linha != null)
...

Comment: sua ideia funcionou mais ou menos, mas o suficiente para que eu possa tentar caminhar sozinho. Não consigo dar upvote porque não tenho 15 pontos de reputação. De qualquer maneira, agradeço muito.
Comment: Sem makas. Me diz o que significa mais ou menos :) ?
Comment: Hehe, na verdade, funcionou. Ele concatenou as linhas como eu precisava. O "mais ou menos" fica por conta de ele ter retornado não apenas as linhas concatenadas, mas ter gerado várias linhas em branco entre cada uma das linhas concatenadas. Ainda tô tentando entender o porquê disso e eliminar essas linhas em branco. De qualquer maneira, as linhas que importam estão concatenadas e eu novamente lhe agradeço muito.
Comment: Linhas em branco? Hum. Não vejo como, ainda.


Can KafkaListenerEndpointRegistry be used for re-uploading all the clients configs?

Question: Can I call stop() on the KafkaListenerEndpointRegistry and after that start() to reload all the kafka client configs?
Answer: Short answer is yes.
But I would suggest to just do a pause and resume instead of start and stop. Because if you are working with multiple partitions then stop/start will trigger rebalancing of consumers while pause/resume maintain the original config i.e. consumer will consume from same partition as before


Does this gradient descent make sense?

Question: I am trying to maximize a function $f(x)$ of a vector of reals $x=<x_1, x_2, ...x_n>$. In my practical application, I have no expression for $f$ whatsoever, all I can do is given a vector $x$, calculate $f(x)$ via a deterministic experiment.
So, instead of having to set a step size $\alpha$, calculate derivatives, etc, just see whether the move $x_1 ->x_1(1+\alpha)$ increases $f$, or $x_1 ->x_1(1-\alpha)$ increases it, transform $x_1$ accordingly, and then iterate over all coordinates in this manner until some termination criterium is met. Here $\alpha$ is a small positive number like $0.05$.
This is more practical for me than a standard gradient descent, because the value of $f$ is completely different order of magnitude of the $x_i$s, as well its derivative, so it will be harder to choose appropriate step size in a classical text book gradient descent manner.
Does this approach make sense? Does it have a specific name?
Answer: This is called coordinate descent.  It is slow, but it works if the function is smooth. You might also consider adaptive coordinate descent, which tries to find a transformation which uncorrelates the descent coordinates in order to speed up convergence (avoiding zig-zags).
A note on step size:
Generally for gradient descent type algorithms, you want to choose an additive step size which decreases to zero as the optimization proceeds. That is, if moving in the positive direction, set
$$x_1\gets x_1 + \mu(1-\epsilon)^n,$$
 where $\mu$ is your initial step size, and $\epsilon \ll 1$ is the decay. As $n$ gets large, your algorithm will converge to a specific value of $x_1$.
 In your post you use a multiplicative step size, which can be dangerous especially if $\alpha$ is not adaptive. For example, suppose that your function is a Gaussian with mean 100, and you initialize $x = 1$ with $\alpha = 0.2$. Then your algorithm will dance around the optimum, like this:

Note the much better performance of an additive step with decay (in orange)
Comment: Thanks. But I thought in coordinate descent, you have a fixed grid of values you are iterating over for each coordinate, is that not right? Or you actually shifting the grid as you find better and better solutions?
Basically, I am asking how do you come up with coordinate candidates.
And also, is there a way to dynamically size alpha along the way.
Comment: Coordinate descent I think simply refers to breaking the optimization problem into $n$ smaller, single-variable optimization problems.  You don't need a grid, meaning the step size $\delta$ could be decreasing as time goes on. I think using a multiplicative step as in your post will give you some unstable behavior, especially if one of the optima has a large coordinate value.
Comment: Thanks. Any practical references you can recommend? I am more interested in implementation than theory.
Comment: I think google is your friend here - gradient descent approaches are the workhorse for most neural networks these days, and there are many people writing about them. Adding [momentum](http://distill.pub/2017/momentum/) to your updates might help too (distill also has been putting out some quality work, so check out the rest of their site).
Comment: Distill? Can you please send me a specific link?
Comment: Follow the momentum link above

Does this gradient descent make sense?


How to use $variables from theme setting in main menu

Question: I make some field in theme setting and can use them normali in block, page, but when I want to use them in main menu its dont work.
function saka_theme_preprocess_menu__main (&$variables, $hook) {

    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');

}

and in menu--main.html.twig I write this..
{% for item in items %}

                     {{ item.title }}

        {% endfor %}

Answer: You can't use name suggestions with double underscore in preprocess function names.
You have to replace this with an if statement in code:
function saka_theme_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');
  }
}


UINavigationBar appearance error in IOS 5

Question: I want to make a custom UINavigationBar with a drop shadow.
Doing so:
UIImage *barImage = [[UIImage imageNamed:@"navbar2.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]; // OK
[[UINavigationBar appearance] setBackgroundImage:barImage forBarMetrics:UIBarMetricsDefault];  // OK

[[UINavigationBar appearance] setShadowColor:[UIColor blackColor]]; // Error

What is wrong?
Can I do this thing with "appearance"?
Thanx!
Comment: You might have to subclass UINavigationbar to add shadow. I am not sure if it has setShadowColor property.
Answer: UINavigationBar doesn't have a shadow color. It has a shadow image or if you want to set the text shadow, use titleTextAttributes.
Comment: [[UINavigationBar appearance] setShadowImage:[UIImage imageNamed:@"navbar2.png"]]; ERROR - [_UIAppearance setShadowImage:]: unrecognized selector sent to instance 0x8839c40
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIAppearance setShadowImage:]: unrecognized selector sent to instance 0x8839c40'
Comment: like I said. there is no shadow image to set.


Resultado - .find() - Diferente do esperado

Question: Quando eu rodo esse código:
fname = input('File name: ')
fhand = open(fname)
count = 0
for line in fhand:
    if line.find('Subject:'):
        count = count + 1
print('There were', count, 'subjects lines in ', fname)

Com o input: mbox-short.txt (Link abaixo)
Output correto: 27
Output atual: 1883
Não faço a mínima ideia do porque.
link do arquivo txt
py version: 3.8.3 - Nem sei porque estou usando essa versão, se você tiver alguma opnião sobre isso por favor, comente
Comment: Quanto a versão do Python: 3.8.3 é bem atual, e é a indicada pra usar. Há poucos dias saiu a versão 3.9.0  - quando quiser, e principalmente se for começar um novo projeto, pode fazer a atualização para a série 3.9
Answer: O método str.find retorna a posição da primeira ocorrência da string desejada ou -1 quando não encontrada.
O problema principal é que você fez apenas if line.find('Subject:'). Quando não encontrado, o retorno é -1, que é avaliado como True no Python. Apenas o número zero é avaliado como False. Ou seja, para todas as linhas que ele não encontrar a string irá contabilizar na sua variável; e se encontrar, mas for no início, o retorno será 0 e não contabilizará.
Basta, então, corrigir a sua condição para:
if line.find('Subject:') >= 0:
    count = count + 1


Expressing an ellipse with polar coordinates

Question: We have the following ellipse:
$2(x+1)^2+(y+1)^2 \le 16$
So the polar coordinates will be:
$x = -1 + A\cos(\phi)$
$y = -1 + r\sin(\phi)$
Where $0 \le r \le 4$ and $0 \le \phi \le 2\pi$.
This is pretty easy, however I have trouble determining the coefficient for $x$, $A$ since we get $\frac{2(x+1)^2}{4}$. How do we determine the coefficient so that it is true when $0 \le r \le 4$?
Answer: Since$$2(x+1)^2+(y+1)^2\leqslant16\iff\frac{(x+1)^2}8+\frac{(y+1)^2}{16}\leqslant1,$$the expression of the ellipse in polar coordinates is $x=2\sqrt2r\cos\phi$ and $y=4r\sin\phi$, with $0\leqslant r\leqslant1$ and $0\leqslant\phi\leqslant2\pi$.
Comment: @osk Yes, that's it. I should have expressed my answer with $0\leqslant r\leqslant 4$, since tha't what you wanted.
Comment: Thank you and then if I want it on the form $0 \le r \le 4$ I just divide by $4$ and get $x=r/\sqrt2cos\phi$


JAX-WS Dispatch client was working fine until wlfullclient.jar was added

Question: I have a standalone batch program which runs on jdk1.6.0_31. This standalone program has JAX-WS client and EJB client. JAX-WS client was working fine without adding any jars until I added wlfullclient.jar for EJB client. Now with wlfullclient.jar in classpath I am getting the below exception. Please let me know how to resolve this. Appreciate your help.
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/xml/ws /spi/ProviderImpl
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at javax.xml.ws.spi.FactoryFinder.safeLoadClass(FactoryFinder.java:150)
at javax.xml.ws.spi.FactoryFinder.newInstance(FactoryFinder.java:30)
at javax.xml.ws.spi.FactoryFinder.find(FactoryFinder.java:90)
at javax.xml.ws.spi.Provider.provider(Provider.java:83)
at javax.xml.ws.Service.<init>(Service.java:56)
at javax.xml.ws.Service.create(Service.java:691)

Answer: We had the same problem, after researching and finding this question, I followed a hunch and looked into the documentation for the Weblogic Server.
I was looking for alternative Clients.
There are basically three client jars:

wlclient.jar - for IIOP clients
wlfullclient.jar - for everything in one jar (massive size ~50MB)
wlthint3client.jar - for a very thin t3 client

The last option is a slimmed down version of the client which has support for Weblogics proprietary t3 protocol. It has some drawback in terms of functionality, but if all you need to do is talk to an ejb on the server: it's all there.
After switching form wlfullclient.jar to wlthint3client.jar, all NoClassDefFoundError were gone.
Here a link to the Weblogic Documentation.
Comment: Yes, replacing wlfullclient with wlthint3client.jar would fix this issue
Answer: Did you have any luck with this? I am running into exactly the same issue running on JetSpeed 2.2.2 (portal server based on tomcat). Before I include wlfullclient.jar in the server's lib folder my web service works fine. After inclusion it blows up on instantiation with exactly the stack trace you include above.
My thinking (theoretical at this stage) is as follows:
wlfullclient.jar has a class that has the same name and package as a class already in Metro web services stack. This class is getting loaded ahead of the Metro class and then directing classloading down a pathway of loading web logic implementations instead of metro implementations. The web logic implementations do not exist (it's not like we have gone to the effort to include them as we want to use standard java) and this explains the NoClassDefFound.
It is worth noting I have not found this supposed class with the same name and package in both Metro and wlfullclient.jar. In this sense the class is akin to the Higgs boson at at the moment. Then presuming it exists, what to do about it?
I'd be keen to know if you have found a solution.
Also I should add:
I need to include wlfullclient.jar as it is used by other portlets running on the same server. I cannot remove it but am not using it myself.
Comment: Likewise to you :) No solution as yet. I have been working on other projects but will certainly resume trying to solve this issue when I am back in that space.


Correspondance between section of covering space and points in the preimage

Question: Let $p:\tilde{X}\to X$ be a covering map (where $X$ is path conncetd and locally path connected). We call a continuous map $s:X\to\tilde{X}$ a section if $p\circ s=id_X$. Fix a point $x_0\in X$. Prove that there exists a bijective correspondance between the set of points $y\in p^{-1}(x_0)$ such that every loop $f$ with base point $x_0$ lifts to a loop $\tilde{f}$ with basepoint $y$ and the sections of $p$.
Attempt: I defined a map $s_y:X\to\tilde{X}$ with $s_y(x)=\tilde{f}(1)$ where $f$ is a path with $f(0)=x_0,f(1)=x$ and $\tilde{f}(0)=y$. Can we prove this correspondance is onto?
Answer: Let $L(x_0)$ denote the set of points $y\in p^{-1}(x_0)$ such that every loop $f$ with basepoint $x_0$ lifts to a loop $\tilde{f}$ with basepoint $y$. Note that the latter means that the unique lift $\tilde{f}$ of $f$ with $\tilde{f}(0) = y$ has the property $\tilde{f}(1) = y$.
Let $S$ denote the set of sections $s : X \to \tilde X$ and define $\phi : S \to p^{-1}(x_0), \phi(s) = s(x_0)$.

$\phi$ is injective: Each section $s$ is a lift of $id_X$, thus $s$ is uniquely determined by the value $s(x_0)$. Here we use the fact that $X$ is connected.

$\phi(S) \subset L(x_0)$: For any loop $f$ with basepoint $x_0$ the loop $s \circ f$ is a lift of $f$ with basepoint $y$.

It remains to show that each $y \in L(x_0)$ is in the image of $\phi$. We need some preprations.

For each path component $C$ of $\tilde X$, the restriction $p\mid_C : C \to X$ is a covering map.
i) $p \mid_C$ is surjective: Let $x \in X$.  Pick $c_0 \in C$ and choose a path $u : I \to X$ such that $u(0) = p(c_0)$ and $u(1) = x$. There exists a lift $\tilde u$ of $u$ such that $\tilde u (0) = c_0$. Then $\tilde u(1) \in C$ and $p(\tilde u(1)) = u(1) = x$ which shows that $x \in p(C)$.
ii) Let $x \in X$. Choose a path connected open neigborhood $U$ of $x$ which is evenly covered by $p$. Then $p^{-1}(U) = \bigcup_{\alpha \in A} V_\alpha$ with pairwise disjoint open $V_\alpha \subset \tilde X$ which are mapped by $p$ homeomorphically onto $U$. Thus each $V_\alpha$ is path connected and therefore contained in some path component of $\tilde X$. Hence $(p \mid_C)^{-1}(U) = \bigcup_{\alpha \in A_C} V_\alpha$ for a suitable nonempty subset $A_C \subset A$. This means that $U$ is evenly covered by $p \mid_C$.

The cardinality of $(p \mid_C)^{-1}(x_0)$ is the number of sheets of $p \mid_C$. Let $y \in p^{-1}(x_0)$ and $C$ its path component. We claim that
(a) If $p \mid_C$ has one sheet, then $y \in \phi(S) \subset L(x_0)$.
(b) If $p \mid_C$ has more than one sheet, then $y \notin L(x_0)$.
This clearly proves $\phi(S) = L(x_0)$.
(a) In this case $p \mid_C$ is an open bijection, i.e. a homeomorphism. Thus $s = (p \mid_C)^{-1} : X \to C \hookrightarrow \tilde X$ is a section such that $s(x_0) = y$ which means $y \in \phi(S)$.
(b) In this case there exists a point $y' \in C$ other than $y$ such that $p(y') = x_0$. There is a path $\tilde f$ in $C$ from $y$ to $y'$; it is no loop. On the other hand f = $p \circ \tilde f$ is a loop based at $x_0$. But since $\tilde f$ is the unique lift of $f$ with $\tilde f(0) = y$, we see that $y \notin L(x_0)$.

Update:
Instead of steps 3. and 4. we can invoke the following two well-known theorems:
(1) Let $p:\tilde{X}\to X$ be a covering map, $x_0 \in X$ and $y \in p^{-1}(x_0)$. The induced homomorphism $p_* : \pi_1(\tilde X,y) \to \pi_1(X,x_0)$ is injective. The image subgroup $p_*(\pi_1(\tilde X,y)) \subset \pi_1(X,x_0)$ consists of the homotopy classes of loops in $X$ based at $x_0$ whose lifts to $\tilde X$ starting at $y$ are loops.
(2) Lifting theorem. Let $p:\tilde{X}\to X$ be a covering map, $x_0 \in X$ and $y \in p^{-1}(x_0)$ and $g : (Z, z_0) \to (X,x_0)$ be a map  with $Z$ path-connected and locally path connected. Then a lift $\tilde g : (Z, z_0) \to (\tilde X, y)$ of $g$ exists if and only if $g_*(\pi_1((Y, y_0)) \subset p_*(\pi_1(\tilde X,y))$.
Now (1) says that $y \in L(x_0)$ if and only if $p_*(\pi_1(\tilde X,y)) = \pi_1(X,x_0)$ and (2) says that the identity $id_X : (X,x_0) \to (X,x_0)$ has a lift $s : (X,x_0) \to (\tilde X,y)$ (which is nothing else than a section of $p$ with $\phi(s) =y$) if and only if $\pi_1(X,x_0) = (id_X)_*(\pi_1((X, x_0)) \subset p_*(\pi_1(\tilde X,y))$. The latter condition means $\pi_1(X,x_0) = p_*(\pi_1(\tilde X,y))$. This shows $L(x_0) = \phi(S)$.
Comment: I thought I settled those cases but I might have made a mistake somewhere. I think 4. only needs case a) since $s$ is an isomorphism of the covering maps $p:\tilde{X}\to X$ and $id_X$ and thus it exists iff $\pi_1(\tilde{X},\tilde{x_0})=\pi_1(X,x_0) \iff p^{-1}(x_0)=1$
Comment: @idocomb You need some kind of proof. My access is completely elementary, but I updated my answer to give an alternative proof. Note that the proof of the lifting theorem includes the steps mentioned in my comment to Sam Freedman's answer: That $s_y(x)$ does not depend on the choice of $f$ and that $s_y$ is continuous.
Answer: Hints:
To show that the correspondence is onto, start with an arbitrary section $s'$. Your goal is to find a point in $p^{-1}(x_0)$ with correct lift-looping behavior that maps to $s$ under your correspondence $y \mapsto s_y$.
Since $s'(x_0)$ is in the fiber over $x_0$, and $s'(x_0)$ does have correct lift looping (why?), it remains to show that this point maps to $s'$ under the correspondence. That is, you want to show $s_{s(x_0)} = s'$. How can you use properties of covering spaces to show this?
Comment: There is still of lot of work to be done: You must show that $s_y(x)$ does not depend on the choice of $f$ and that $s_y$ is continuous. The proof must involve the condition that $X$ is  locally path connected,
Comment: I assume correct loop lifting is simply because $f(0)=f(1) \implies s'\circ f(0)=s'\circ f(1)$ ?
Comment: Yes that's right— you're pushing $f$ upstairs with the section $s'$
Comment: I am thinking of composing a path $f$ with $f(0)=x_0, f(1)=x$ with the identity giving me: $p\circ s_{s(x_0)}\circ f=p\circ s'\circ f$ which will give me then $s_{s(x_0)}\circ f = s'\circ f$ since $s_{s(x_0)}\circ f(0)= s'\circ f(0)=s'(x_0)$. Then $s_{s(x_0)}\circ f (1)= s'\circ f(1) \implies s_{s(x_0)}(x)=s'(x)$. Am I correct?
Comment: Yes, also looks good to me—you are using uniqueness of path-lifting to show the two sections agree.
Comment: exactly, is this what you had in mind or is there a more direct approach?
Comment: This is the approach I thought of, but there certainly could be a better one out there


Windows Server 2012 R2 port 443 open, stopping IIS doesn't work

Question: Sorry for the bad wording in the title, 'doesn't help' is not allowed as a title, I am definitely able to stop IIS.
While trying to install VisualSVN I ran into the problem that port 443 was already open. After looking through dozens of forum entries and checking netstat (screengrab) I was only able to find out that PID 4 caused the issue, and Process Explorer confirmed the port being listened in the properties window (screengrab).
Now in all those posts Process Explorer was referred to for finding out which service is the culprit, but I cannot really figure out which service in particular opened the port, all I can really see is the listing under TCP/IP. Now I do have IIS installed and plan on setting up websites in the future, for now there is only the default site installed. When I stop the website the listing for port :http and :80 disappear from netstat and Process Explorer, 433 is still there though. Same goes for stopping the entire IIS server in the Manager window or just stopping the IIS service(s).
Is there anything I am doing wrong? Any ideas?
Answer: Do you have routing and remote access service installed? If yes, try to disable it (RRAS uses SSTP by default and it listens for 443 port and lsas.exe process which is using port in your situation is used for IPSEC also).
Comment: Yes! Finally, that's it, now how can I change the RRAS port from 443 to something else?
Comment: Also, do you by any chance have an idea how I can fix the VPN Status page just showing Unavailable at every entry?
Comment: If you don't want to remove RRAS role (in case you really need it), disable SSTP port. Go to Routing and Remote access management, choose ports and change available port quantity for SSTP protocol from 128 (default) to 0
Comment: @nO_OnE_910 about VPN Status page: I didn't get you full, can you send link to screenshot please?
Comment: http://i.stack.imgur.com/Rh1y6.jpg I dont even have remote access enabled, I just really need the VPN, and it only comes with the remote access.
Comment: @nO_OnE_910 that's a different control. That one called Remote Access Management Console but what you need called Routing and Remote access (placed also in tools). Unfortunately I don't have now test server with VPN installed to show, so here is step by step guide https://technet.microsoft.com/en-us/library/dd458965.aspx?f=255&MSPPError=-2147217396 (remember, you need set SSTP port to 0).
Comment: Ah yes, it was the wrong config window, that's why I didnt find the port properties. Thanks!
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39145/discussion-between-senator14-and-no-one-910).
Comment: I cannot set the number to 0. Also I've joined the chat now.
Answer: I think you're going to run into major issues running both IIS and VisualSVN, which installs and runs on Apache, on the exact same server.  If I were you, I'd separate them out and give each web server their own VM.  I know this doesn't directly answer your question but I'm wondering if your original posted problem is not a symptom of trying to run both web servers on the same VM.
Comment: well, what problems would that be? All seems to work fine now.
Comment: Well I based my original response on the fact that your issue is not a typical experience when installing VisualSVN.  The fact that you've had to do some workarounds or troubleshooting means you have conflicts that are not standard.  It isn't a stretch to think you won't see other issues down the road as well.

Personally, I've just never been a fan of monolithic servers like that which run multiple services.  I have all my IIS VMs separate from all my Apache VMs.  Also, I would be very concerned about Apache vulnerabilities now exposing threats to your sites that run on IIS and vice versa.


Não consigo definir margin-top/bottom/right para elemento block, por quê?

Question: Tenho um elemento
 dentro de uma
, dessa forma:
HTML

texto

CSS
div {
  width: 30px;
  height:30px;
  background-color: green;
}

p {
  width: 30px;
  height:30px;
  background-color: red;
  margin: 10px 10px 10px 10px;
}

Quando eu aplico margin-left funciona normalmente, o elemento
 se distancia 10px da esquerda, porém quando eu aplico margin-top, margin-bottom ou margin-right nada é alterado, o elemento
 permanece na mesma posição. Eu não entendi o por quê, alguém sabe explicar este comportamento ?
Ver exemplo no JSBin
Answer: Temos um grande problema aí. Os dois elementos têm as mesmas dimensões e você está tentando ganhar mais espaço.
A margin do p está para fora da div, como é possível ver usando um web inspector:

Olhando a posição do p, ele está saindo de dentro da div:

Para isso funcionar dessa maneira, precisaria de um overflow: hidden na div (para evitar que a margin colapse) e de 50px de altura e largura (30px das dimensões + 20px de margin, 10px de cada um dos lados).
<!DOCTYPE html>

  <meta charset=utf-8 />

div {
  width: 50px;
  height: 50px;
  background-color: green;
  overflow: hidden;
}

p {
  width: 30px;
  height:30px;
  margin: 10px;
  background-color: red;
}

http://jsbin.com/IXInADEg/1/edit
Considere usar padding na div no lugar da margin no p. E, dependendo do conteúdo, usar inline-block em ambos os elementos pode ser mais útil.
Comment: Muito obrigado ! Dúvida esclarecida.
Answer: A margem superior está sim sendo aplicada, o problema é que ela colapsa com a margem da div externa, e acaba sendo aplicada entre a div externa e o topo da página.
Você pode ver uma descrição detalhada de como isso funciona nesta minha outra resposta, mas a explicação bem resumida neste caso é a seguinte: quando você tem vários blocos aninhados, e somente o mais interno tem margem superior, essa margem acaba colapsando com a dos blocos ancestrais, e termina aplicada entre o mais externo e seu pai (aqui, o body).
Como isso só ocorre com blocos, a solução mais simples é transformar seu parágrafo em um inline-block:
p {
  width: 30px;
  height:30px;
  background-color: red;
  margin: 10px 10px 10px 10px;
  display: inline-block;
}

Demo no jsbin
Comment: Bfavaretto, segue um exemplo: http://jsfiddle.net/rLk36/.
Comment: Outra forma simples de corrigir o problema é overflow:hidden.
Comment: Cleiton, fiz um teste com `overflow:hidden`, mas não resolveu.
Comment: @Cleiton Ah, é que o div externo da pergunta tem dimensões fixas. Aí o overflow:hidden corta o conteúdo.
Comment: Muito obrigado @bfavaretto! Realmente, sua resposta com a citação da documentação esclareceu muitas das minhas dúvidas (:


Underlining text using transition on page load with a delay

Question: I've been at this for a while now, and so far I haven't gotten very far. I have this code (CSS) and I want to underline specific text (from middle to out) after about 8 seconds after the page load, I can only figure out the :hover part (I want the underline to appear 8s after the page has loaded in, without having to hover over the element):
#sec {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}
#sec:after {
  content: '';
  display: block;
  margin: auto;
  height: 3px;
  width: 0px;
  background: transparent;
  transition: width .5s ease, background-color .5s ease;
}
#sec:hover:after {
  width: 100%;
  background: blue;
}

and the HTML:

our clone site is currently down. click here for updates on the status of each site

I am trying to get the
 to underline 8s[econds] after the page has loaded.
Comment: you need a Jquery for this because it use a `.Ready()` function which detect when the page loaded and do your code
Comment: So you're saying add the Jquery at the end of...
Answer: How about using animation (keyframes), check snippet
PS: Run snippet and wait for 8 seconds.

#sec {
  display: inline-block;
  position: relative;
  padding-bottom: 3px;
}
@-webkit-keyframes border {
     from {width: 0px;}
     to {width:100%}
}

#sec:after {
  content: '';
  display: block;
  margin: auto;
  height: 3px;
  width: 0px;
  background: blue;
  -webkit-animation-name: border; /* Safari 4.0 - 8.0 */
  -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
  -webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */
  animation-name: border;
  animation-duration: 1s;
  animation-delay: 8s;
  animation-fill-mode: forwards;
}

our clone site is currently down. click here for updates on the status of each site

Comment: change the `height`
Comment: This has helped a lot, but I need the underline to stay visible after it being displayed, is there a way for that?
Comment: Is there a way to change the thickness of the line?


Union of Two Subspaces

Question:
Q. Say $U$ and $W$ are subspaces of a a finite dimensional vector space $V$ (over  the field of real numbers). Let $S$ be the set-theoretical union of $U$ and $W$. Which of the following statements is true:
a) Set $S$ is always a subspace of $V$
b) Set $S$ is never a subspace of $V$
c) Set $S$ is a subspace of $V$ if and only if $U=W$
d) None of the above

I've researched on this question and found a proof that says set $S$ is not always subspace of $V$ (Is it true?).
If $U=W$ then $S$ is a subspace of $V$ since $U$ and $W$ are closed under addition hence $U \cup W = U$ (or $W$). So can I say that $S$ is a subspace of $V$ if and only if $U = W$?
Also, please can you give an example of how to calculate union of two vector spaces? So what would be the union of vector spaces $\begin{pmatrix} a&  0  &0\end{pmatrix} \cup \begin{pmatrix}0&  b&  0\end{pmatrix}$ ?
Thanks
Comment: The union of  $U$ and $W$ is a subspace of $V$ if and only if either $U\subseteq W$ or $W\subseteq U$.  For a proof, suppose that neither subset relation holds.  Let $x$ be in $U$ but not in $W$ and let $y$ be in $W$ but not in $U$. Show that $x+y$ is not in the union of $U$ and $W$.
Comment: It is true if the underline field is $\mathbb{R}$... as a consequence of Baire category theory... other wise it may not be true...for an example if you consider the underline field as $|mathbb{Z_2}$ then you can find some counter example
Comment: have a look in this link http://mathoverflow.net/questions/26/can-a-vector-space-over-an-infinite-field-be-a-finite-union-of-proper-subspaces
Comment: Does this answer your question? [Union of two vector subspaces not a subspace?](https://math.stackexchange.com/questions/71872/union-of-two-vector-subspaces-not-a-subspace)
Answer: If $U \subset W$ (or vice versa) then $U \cup W = W $ so if W is a subspace so is the union.
Otherwise there is $a \in U ,\ a \notin W$ and  $b \in W,\ b \notin U$
So, $a, b \in U \cup W$.
But $a + b \notin U$ otherwise with $(-a) \in U$ then $(-a) + a + b \in U \implies b \in U$
And similarly $a + b \notin W$
Therefore $a + b  \notin U \cup W$, i.e. there are vectors $a, b$ in $U \cup W$ whose linear combination is not in $U \cup W$, so $U \cup W$ is not closed.

Union of Two Subspaces


How to get faster code than numpy.dot for matrix multiplication?

Question: Here Matrix multiplication using hdf5 I use hdf5 (pytables) for big matrix multiplication, but I was suprised because using hdf5 it works even faster then using plain numpy.dot and store matrices in RAM, what is the reason of this behavior?
And maybe there is some faster function for matrix multiplication in python, because I still use numpy.dot for small block matrix multiplication.
here is some code:
Assume matrices can fit in RAM: test on matrix 10*1000 x 1000.
Using default numpy(I think no BLAS lib).
Plain numpy arrays are in RAM: time 9.48
If A,B in RAM, C on disk: time 1.48
If A,B,C on disk: time 372.25
If I use numpy with MKL results are: 0.15,0.45,43.5.
Results looks reasonable, but I still don't understand why in 1st case block multiplication is faster(when we store A,B in RAM).
n_row=1000
n_col=1000
n_batch=10

def test_plain_numpy():
    A=np.random.rand(n_row,n_col)# float by default?
    B=np.random.rand(n_col,n_row)
    t0= time.time()
    res= np.dot(A,B)
    print (time.time()-t0)

#A,B in RAM, C on disk
def test_hdf5_ram():
    rows = n_row
    cols = n_col
    batches = n_batch

    #using numpy array
    A=np.random.rand(n_row,n_col)
    B=np.random.rand(n_col,n_row)

    #settings for all hdf5 files
    atom = tables.Float32Atom() #if store uint8 less memory?
    filters = tables.Filters(complevel=9, complib='blosc') # tune parameters
    Nchunk = 128  # ?
    chunkshape = (Nchunk, Nchunk)
    chunk_multiple = 1
    block_size = chunk_multiple * Nchunk

    #using hdf5
    fileName_C = 'CArray_C.h5'
    shape = (A.shape[0], B.shape[1])

    h5f_C = tables.open_file(fileName_C, 'w')
    C = h5f_C.create_carray(h5f_C.root, 'CArray', atom, shape, chunkshape=chunkshape, filters=filters)

    sz= block_size

    t0= time.time()
    for i in range(0, A.shape[0], sz):
        for j in range(0, B.shape[1], sz):
            for k in range(0, A.shape[1], sz):
                C[i:i+sz,j:j+sz] += np.dot(A[i:i+sz,k:k+sz],B[k:k+sz,j:j+sz])
    print (time.time()-t0)

    h5f_C.close()
def test_hdf5_disk():
    rows = n_row
    cols = n_col
    batches = n_batch

    #settings for all hdf5 files
    atom = tables.Float32Atom() #if store uint8 less memory?
    filters = tables.Filters(complevel=9, complib='blosc') # tune parameters
    Nchunk = 128  # ?
    chunkshape = (Nchunk, Nchunk)
    chunk_multiple = 1
    block_size = chunk_multiple * Nchunk

    fileName_A = 'carray_A.h5'
    shape_A = (n_row*n_batch, n_col)  # predefined size

    h5f_A = tables.open_file(fileName_A, 'w')
    A = h5f_A.create_carray(h5f_A.root, 'CArray', atom, shape_A, chunkshape=chunkshape, filters=filters)

    for i in range(batches):
        data = np.random.rand(n_row, n_col)
        A[i*n_row:(i+1)*n_row]= data[:]

    rows = n_col
    cols = n_row
    batches = n_batch

    fileName_B = 'carray_B.h5'
    shape_B = (rows, cols*batches)  # predefined size

    h5f_B = tables.open_file(fileName_B, 'w')
    B = h5f_B.create_carray(h5f_B.root, 'CArray', atom, shape_B, chunkshape=chunkshape, filters=filters)

    sz= rows/batches
    for i in range(batches):
        data = np.random.rand(sz, cols*batches)
        B[i*sz:(i+1)*sz]= data[:]

    fileName_C = 'CArray_C.h5'
    shape = (A.shape[0], B.shape[1])

    h5f_C = tables.open_file(fileName_C, 'w')
    C = h5f_C.create_carray(h5f_C.root, 'CArray', atom, shape, chunkshape=chunkshape, filters=filters)

    sz= block_size

    t0= time.time()
    for i in range(0, A.shape[0], sz):
        for j in range(0, B.shape[1], sz):
            for k in range(0, A.shape[1], sz):
                C[i:i+sz,j:j+sz] += np.dot(A[i:i+sz,k:k+sz],B[k:k+sz,j:j+sz])
    print (time.time()-t0)

    h5f_A.close()
    h5f_B.close()
    h5f_C.close()

Comment: That linked question compares `np.dot` working on chunks (via `hdf5`) with a single call to `np.dot`.  So isn't a test of `np.dot` versus something else, but a test of memory handling for large arrays.
Comment: First what is your numpy BLAS linked to? In the `np.dot` scenario are you running out of memory and using virtual memory? If you could post a small discrete example so that we can reproduce the difference it will be very beneficial.
Comment: General question was why block matrix multiplication using hdf5 was faster then naive matrix multiplication using numpy, but second questions was there is something faster then numpy.dot. In code there are 3 cases how to store matrices in RAM or on disk.
Answer: np.dot dispatches to BLAS when

NumPy has been compiled to use BLAS,
a BLAS implementation is available at run-time,
your data has one of the dtypes float32, float64, complex32 or complex64, and
the data is suitably aligned in memory.

Otherwise, it defaults to using its own, slow, matrix multiplication routine.
Checking your BLAS linkage is described here. In short, check whether there's a file _dotblas.so or similar in your NumPy installation. When there is, check which BLAS library it's linked against; the reference BLAS is slow, ATLAS is fast, OpenBLAS and vendor-specific versions such as Intel MKL are even faster. Watch out with multithreaded BLAS implementations as they don't play nicely with Python's multiprocessing.
Next, check your data alignment by inspecting the flags of your arrays. In versions of NumPy before 1.7.2, both arguments to np.dot should be C-ordered. In NumPy >= 1.7.2, this doesn't matter as much anymore as special cases for Fortran arrays have been introduced.
>>> X = np.random.randn(10, 4)
>>> Y = np.random.randn(7, 4).T
>>> X.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
>>> Y.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

If your NumPy is not linked against BLAS, either (easy) re-install it, or (hard) use the BLAS gemm (generalized matrix multiply) function from SciPy:
>>> from scipy.linalg import get_blas_funcs
>>> gemm = get_blas_funcs("gemm", [X, Y])
>>> np.all(gemm(1, X, Y) == np.dot(X, Y))
True

This looks easy, but it does hardly any error checking, so you must really know what you're doing.
Comment: Because of numerical implementation issue the comparison line should be better ```np.allclose(gemm(1, X, Y),np.dot(X, Y))```
Comment: Good answer, maybe also you can aswer about big matrix multiplication stored on disk and how to optimize chunk size and other parameters for particular PC?
Comment: I just tried the `get_blas_funcs` approach and it turned out to be about 6 times slower than `np.dot`. Is this what you would expect?
Comment: I confirm @satoru 's finding above: 10.3 µs ± 238 VS. 768 ns ± 14.3 ns


Hint Taylor Series $x^{2}\ln(x)$ about $a=1$

Question: Find the taylor series of $g(x):= x^{2}\ln(x)$ about $a=1$
Idea: I would have thought we should find the Taylor series of $\ln(x)$ about $a=1$, which is
$\sum^{\infty}_{k=1}\frac{(-1)^{k+1}}{k!}(x-1)^{k}$ and then I would just multiply that with $x^{2}$. So, we'd get:
$\sum^{\infty}_{k=1}\frac{(-1)^{k+1}}{k!}(x-1)^{k}x^2$
This cannot be simplified can it? Surely there must be a better without having to calculate the $n$-th derivative of $x^2\ln(x)$
Comment: The product of two Taylor series is the Taylor series of the product. What you wrote is still not the Taylor series at $a=1$, since the taylor series of $x^2$ at $a=1$ is not $x^2$.
Comment: You might do better if you let $y=x-1$ and found the Taylor series of $h(y)=(1+y)^2 \log_e(1+y)$ about $b=0$
Comment: @Henry Does it always hold that we rewrite the taylor series about $b=0$ and then are we **ALWAYS**  allowed to use the "plugging in", for example the taylor polynomial of $e^{x^{2}+2x}$ is simply $\sum\frac{(x^2+2x)^n}{n!}$ about $0$
Comment: Not *always* - that will not work with the series at $x=\pm\infty$.  But otherwise, I suspect it should work: you want the expansion at $c$ to be in terms based on of $(x-c)$
Answer: Your answer  is  no completely correct. As you would like the expansion around $a=1$, you should also expand $x^2$ around this point. In fact, you can easily show that
$$x^2 = 1 +2 (x-1) + (x-1)^2\;.$$
As a result, we have that
$$x^2 \ln x = \Bigl[1 +2 (x-1) + (x-1)^2 \Bigr] \sum_{k=1}^\infty \frac{(-1)^{k+1}}k (x-1)^k\;.$$
Or, after expanding
$$x^2 \ln x = \sum_{k=1}^\infty \frac{(-1)^{k+1}}k (x-1)^k + 2 \sum_{k=1}^\infty \frac{(-1)^{k+1}}k (x-1)^{k+1} + \sum_{k=1}^\infty \frac{(-1)^{k+1}}k (x-1)^{k+2}\\
= \sum_{k=1}^\infty \frac{(-1)^{k+1}}k (x-1)^k + 2 \sum_{k=2}^\infty \frac{(-1)^{k}}{k-1} (x-1)^{k} + \sum_{k=3}^\infty \frac{(-1)^{k+1}}{k-2} (x-1)^{k}\\
= (x-1) + \frac32 (x-1)^2 +\sum_{k=3}^\infty  (-1)^{k+1}\left[\frac{1}{k} - \frac{2}{k-1} + \frac{1}{k-2} \right] (x-1)^k.$$


How to get a variable from FieldWidget in the same modules Template

Question: I have module that is currently setup like this
module
  -signature.module
  -signature.info.yml
  -src
    -Plugin
      -Field
        -FieldWiget
          -SignatureWidget.php
  -templates
    -signature.html.twig

Everything in the module works correctly as is. I'm trying to pass a variable $field_name = $items->getName(); from SignatureWidget.php to signature.html.twig (or signature.module so that I can then pass it to signature.html.twig). I'm trying to do this in order to apply ids generated from a variable in the widget to some of the markup in the template. How would one do this?
I understand how to do this from the .module file (Use a twig template instead of a render array in a custom module admin page), but can't seem to figure it out when it comes to plugin variables.
The hook_theme in module associated with the widget looks like this.
function signature_theme() {

  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => array('sign_src' => ''),
  ];
  return $theme;
}

The widget code from SignatureWidget.php looks like this
<?php

namespace Drupal\signature\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_widget",
 *   module = "signature",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $file_upload_help = array(
        '#theme' => 'signature',
        '#sign_src' => $value,
      );
     $sign_thumb = array( '#type'   => 'html_tag',
                          '#tag' => 'img',
                          '#attributes' => array('src' => '', 'id' => 'signature_thumb', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

$field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

$text_area_id = 'signature_field_' . $field_name;

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array('signature_data'),
                        ),
      '#attached' => array(
        'library' => array('signature/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    $element['#suffix'] = \Drupal::service('renderer')->renderPlain($sign_thumb);

    return array('value' => $element);
  }

}

The template from signature.html.twig looks like this.

    <canvas width="450" height="200" class="sign-canvas">SIGNATURE CANVAS</canvas>
{% if(sign_src != '') %}

{% endif %}
     <button type="button" id="clear-sign" class="button clear" data-action="clear">Clear</button>

I'm trying to return the string value from $text_area_id in SignatureWidget.php from within signature.html.twig
Comment: It's still not completely clear to me what you're trying to do. What is your template used for? Is it used as theming wrapper for your widget form? Please add your relevant hook_theme() part, how you try to wrap your form, and probably your relevant template parts. This would make it easier to understand what you want to do and giving you a to-the-point answer without having to read through other questions/answers you posted as reference.
Comment: Thanks for letting me know! I have updated the question with what I'm hoping is all pertinent information. If you need anything else please let me know. I really appreciate your time.
Comment: That made it far easier to understand. Please see my answer below.
Answer: You already pass the template variable sign_src to your template. Now you want to pass an additional variable. You can easily do this by extending your hook_theme implementation:
/**
 * Implements hook_theme().
 */
function signature_theme() {
  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => [
      'sign_src' => NULL,
      'text_area_id' => NULL,
    ],
  ];
  return $theme;
}

Then pass the ID into your template like this:
$value = $items[$delta]->value ?: '';
$text_area_id = 'signature_field_' . $items->getName();

$file_upload_help = [
  '#theme' => 'signature',
  '#sign_src' => $value,
  '#text_area_id' => $text_area_id,
];

And use it in your template like this:
{{ text_area_id }}

Edit: Some further suggestions for your code snippets:
Wherever possible, you should leave rendering to the theming engine and avoid manually calling the \Drupal::service('renderer')->renderPlain() method. Your description will do just fine with the render array. Your #suffix can be changed to a distinct child element of your widget element (note: there is no hash before):
$element['#description'] = $file_upload_help;
$element['suffix'] = $sign_thumb;

In your template, you can change the empty check to
{% if sign_src %}

{% endif %}

And should wrap the src URL into quotes.
A final note about the URL itself: It seems to be a user given value. If so, consider using UrlHelper::stripDangerousProtocols before you pass it into the template.
Comment: Thank you Mario. That makes perfect sense. I had thought I had tried something just like that. Your setup works perfectly many thanks.


In C#, why is String a reference type that behaves like a value type?

Question: A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object.
Why isn't string just a value type then?
Comment: Since for immutable types the distinction is mostly an implementation-detail (leaving `is` tests aside), the answer is probably "for historical reasons". Performance of copying cannot be the reason since there's no need to physically copy immutable objects. Now it's impossible to change without breaking code that actually uses `is` checks (or similar constraints).
Comment: BTW this is the same answer for C++ (although the distinction between value and reference types is not explicit in the language), the decision to make `std::string` behave like a collection is an old mistake that cannot be fixed now.
Answer: Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...
(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)
Comment: I'm nitpicking here, but only because it gives me an opportunity to link to an blog post relevant to the question: value types are not necessarily stored on the stack. It's most often true in ms.net, but not at all specified by the CLI specification. The main difference between value and reference types is, that reference types follow copy-by-value semantics. See https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-stack-is-an-implementation-detail-part-one and https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-stack-is-an-implementation-detail-part-two
Comment: @Qwertie: `String` is not variable size. When you add to it, you are actually creating another `String` object, allocating new memory for it.
Comment: @codekaizen Qwertie is right but I think the wording was confusing. One string may be a different size than another string and thus, unlike a true value type, the compiler could not know beforehand how much space to allocate to store the string value. For instance, an `Int32` is always 4 bytes, thus the compiler allocates 4 bytes any time you define a string variable. How much memory should the compiler allocate when it encounters an `int` variable (if it were a value type)? Understand that the value has not been assigned yet at that time.
Comment: That said, a string could, in theory, have been a value type (a struct), but the "value" would have been nothing more than a reference to the string. The .NET designers naturally decided to cut out the middleman (struct handling was inefficient in .NET 1.0, and it was natural to follow Java, in which strings were already defined as a reference, rather than primitive, type. Plus, if string were a value type then converting it to object would require it to be boxed, a needless inefficiency).
Comment: Sorry, a typo in my comment that I cannot fix now; that should have been.... For instance, an `Int32` is always 4 bytes, thus the compiler allocates 4 bytes any time you define an `int` variable. How much memory should the compiler allocate when it encounters a `string` variable (if it were a value type)? Understand that the value has not been assigned yet at that time.
Comment: @BenSchwehn You say: *reference types follow copy-by-value semantics.* Are you sure about that or do you mean *value types follow copy-by-value semantics*?
Comment: @Qwertie: A variable doesn't have a size (except if you are talking about the size of the reference, but even if you are, it is always the same). What actually takes up the memory is the object.
Comment: @KevinBrock - first, the compiler doesn't manage stack space, the runtime does. This means you can dynamically allocate stack space. You can stackallocate arrays with a size not known until runtime for example. Given this, and that string instances are immutable and the size doesn't change after allocation (even though the size may not be known until runtime), it is conceivable that strings could be stack allocated and therefore be value types.
Comment: @codekaizen As far as I know you can do this only in an unsafe context and the stack allocated array is fixed size. Yes the runtime can choose to rearrange things but the compiler defines how big the allocation on the stack is, thus a value type string must have a known size or use unsafe pointer management (for dynamically sized stack allocation). Are you proposing then that strings should be unsafe?
Comment: @codekaizen The stack allocation for value-type variables is independent of their assignment. Space is allocated for a stack frame when the method begins, not when the method is actually running, so I'm not sure how this dynamic allocation idea would pan out.
Comment: @codekaizen: and how would this work for strings that are members of classes? If a string member was reassigned, would the entire object be resized? It's unmanageable.
Comment: Not to mention, strings are variable-size, so they can't be value types (as value types are stored directly wherever you declare them). When you declare a string inside a class, how could the class hold the string directly, given that one can change the string to another string of different length at any time? No, there would have to be a REFERENCE to the string because it is variable-size.
Comment: @codekaizen: String *variables* are mutable and therefore variable-size.
Comment: @codekaizon Of course the compiler could do special things for such a string and then it would not have to be unsafe, but then you are proposing a special kind of value type for string (not what `struct` is today) which would be another reason for defining string as a `class` - it can use one of the two main types of definition (struct or class) already defined in the language with out more "magic" (already plenty of that in the compiler for the existing `string` class).
Comment: @KevinBrock - my point is that the language doesn't even need to expose the workings in our hypothetical case, which you seem to realize in your second post. The compiler does special things with special types all the time, and strings would just be another case if they were value types. However, if they were value types, the runtime would need to change drastically, as my answer above enumerates. My point in debating this is to show that Qwertie's statements about strings continue to be inaccurate, even under your interpretation.
Comment: "You couldn't intern strings" , `String.Intern()` ??
Comment: @I'mBlueDaBaDee - right; this method would not work if System.String were a System.ValueType, since it would not be possible to track a single instance, as any reference to the instance would copy it.
Comment: @BenSchwehn According to the article you linked:

Surely the most relevant fact about value types is not the implementation detail of how they are allocated, but rather the by-design semantic meaning of "value type", namely that they are always copied "by value".
Answer: It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.
It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if
string s = "hello";
string t = "hello";
bool b = (s == t);

set b to be false? Imagine how difficult coding just about any application would be.
Comment: Java is not known for being pithy.
Comment: @Juri: Actually i think it's never desirable to check the references, since sometimes `new String("foo");` and another `new String("foo")` can evaluate in the same reference, which kind of is not what you would expect a `new` operator to do. (Or can you tell me a case where I would want to compare the references?)
Comment: @Matt: exactly. When I switched over to C# this was kind of confusing, since I always used (an do still sometimes) .equals(..) for comparing strings while my teammates just used "==". I never understood why they didn't leave the "==" to compare the references, although if you think, 90% of the time you'll probably want to compare the content not the references for strings.
Comment: @Michael Well, you have to include a reference comparison in all comparisons to catch comparison with null. Another good place to compare references with strings, is when comparing rather than equality-comparing. Two equivalent strings, when compared should return 0. Checking for this case though takes as long as running through the whole comparison anyway, so is not a useful short-cut. Checking for `ReferenceEquals(x, y)` is a fast test and you can return 0 immediately, and when mixed in with your null-test doesn't even add any more work.
Comment: ...having strings be a value type of of that style rather than being a class type would mean the default value of a `string` could behave as an empty string (as it was in pre-.net systems) rather than as a null reference.  Actually, my own preference would be to have a value type `String` which contained a reference-type `NullableString`, with the former having a default value equivalent to `String.Empty` and the latter having a default of `null`, and with special boxing/unboxing rules (such that boxing a default-valued `NullableString` would yield a reference to `String.Empty`).
Comment: @Jason: If `string` were implemented as a value type with a single field of type `char[]` or `PrivateStringData` (the latter being a class type which was private to the module which defined the structure), most things would work as they do now; the difference would be that unless strings had special boxing rules, a boxed string would be mutable (note that all boxed structs, even supposedly "immutable" structs--are nullable*), though mutating a boxed string would cause it to reference a different heap object internally, rather than mutating the heap object itself).  On the other hand, ...
Comment: @Jon Hanna a reference comparison speeds up the case where the strings are equal and happen to be the same object (so it is an improvement). i expect the .net guys to be smart enough to have used this, when implementing the "==" operator for strings.
Comment: @symbiont it does, and strings to tend generally to be a case where this benefits. More generally, the benefit depends on how likely comparison with self is to happen, though the fact that most more detailed comparisons would fail on null meaning a check for the possibility of `x == null && y == null` has to be in there somewhere if test for `ReferenceEquals(x, y)` has not already been done, means there's little downside to doing a reference-equals test for all such types. I was talking about the generalisation of this, which is that for ordered comparisons (`.CompareTo()` and `.Compare()`...
Comment: @symbiont ... then the shortcut `if(ReferenceEquals(x, y)) return 0;` is also always valid, and sometimes useful, not only does identity entail equality (why `if(ReferenceEquals(x, y)) return true;` works for `.Equals()`) but also equality entails equivalence for most orderings, and identity entails equivalence for all of them. The built-in string comparisons will use this short-cut some of the time, but not all.
Comment: do you mean that b evauates "=" to false ? b is true because the reference of the two variables are the same
Comment: Literals are interned so that should be true.
Answer: A string is a reference type with value semantics. This design is a tradeoff which allows certain performance optimizations.
The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on assignments and method calls (if the data size is larger than a pointer), because the whole object is copied in memory rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Furthermore the size of a value type must be known at compile time, which is not always the case for strings.
But strings have value semantics which means they are immutable and compared by value (i.e. character by character for a string), not by comparing references. This allows certain optimizations:
Interning means that if multiple strings are known to be equal, the compiler can just use a single string, thereby saving memory. This optimization only works if strings are immutable, otherwise changing one string would have unpredictable results on other strings.
String literals (which are known at compile time) can be interned and stored in a special static area of memory by the compiler. This saves time at runtime since they don't need to be allocated and garbage collected.
Immutable strings does increase the cost for certain operations. For example you can't replace a single character in-place, you have to allocate a new string for any change. But this is a small cost compared to the benefit of the optimizations.
Value semantics effectively hides the distinction between reference type and value types for the user. If a type has value semantics, it doesn't matter for the user if the type is a value type or reference type - it can be considered an implementation detail.
Comment: Once you have created an array it's size is constant, but all arrays in the entire world are not all of exactly the same size.  That's my point.  For a string to be a value type all strings in existence would need to all be exactly the same size, because that's how value types are designed in .NET.  It needs to be able to reserve storage space for such value types *before actually having a value*, so the size must be know *at compile time*.  Such a `string` type would need to have a char buffer of some fixed size, which would be both restrictive and highly inefficient.
Comment: @Sevy: The size of a string *is* constant.
Comment: The distinction between value types and reference types isn't really about performance at all.  It's about whether a variable contains an actual object or a reference to an object.  A string could never possibly be a value type because the size of a string is variable; it would need to be constant to be a value type; performance has almost nothing to do with it.  Reference types are also not expensive to create at all.
Comment: Because it just contains a reference to a character array, which is of variable size.  Having a value type who's only real "value" was a reference type would just be all the more confusing, as it would still have reference semantics for all intensive purposes.
Comment: @Sevy: The size of an array is constant.
Comment: Ah, now I get what you are saying. Yes, the size of a string is not necessarily known at compile time. And .net does not support dynamically typed arrays on the stack.
Comment: The size of a reference to an array is constant.  The size of an array itself is dependent on the number of items in the array and the size of the type the array holds.
Answer: This is a late answer to an old question, but all other answers are missing the point, which is that .NET did not have generics until .NET 2.0 in 2005.
String is a reference type instead of a value type because it was of crucial importance for Microsoft to ensure that strings could be stored in the most efficient way in non-generic collections, such as System.Collections.ArrayList.
Storing a value-type in a non-generic collection requires a special conversion to the type object which is called boxing. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.
Reading the value from the collection requires the inverse operation which is called unboxing.
Both boxing and unboxing have non-negligible cost: boxing requires an additional allocation, unboxing requires type checking.
Some answers claim incorrectly that string could never have been implemented as a value type because its size is variable. Actually it is easy to implement string as a fixed-length data structure containing two fields: an integer for the length of the string, and a pointer to a char array. You can also use a Small String Optimization strategy on top of that.
If generics had existed from day one I guess having string as a value type would probably have been a better solution, with simpler semantics, better memory usage and better cache locality. A List<string> containing only small strings could have been a single contiguous block of memory.
Comment: My, thanks for this answer! I've been looking at all the other answers saying things about heap and stack allocations, while [stack is an implementation detail](https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/). After all, `string` contains only its size and a pointer to the `char` array anyway, so it wouldn't be a "huge value type". But this is a simple, relevant reason for this design decision. Thanks!
Comment: @V0ldek: This is not true though, a string object in .net does not contain a pointer to a separately allocated character array. The size and the characters are stored in the same place.
Comment: @JacquesB I was judging that by the [type definition in the BCL](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/String.cs). It just has the size and the first char. I might be wrong though, that entire class is just some magic native interop.
Comment: @V0ldek: Notice the `_firstChar` field is not a pointer, it is a char. The rest of the chars (if any) are located directly after. But yes, lots of magic going on.
Answer: Not only strings are immutable reference types.
Multi-cast delegates too.
That is why it is safe to write
protected void OnMyEventHandler()
{
     delegate handler = this.MyEventHandler;
     if (null != handler)
     {
        handler(this, new EventArgs());
     }
}

I suppose that strings are immutable because this is the most safe method to work with them and allocate memory.
Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define
string s1 = "my string";
//some code here
string s2 = "my string";

Chances are that both instances of "my string" constant will be allocated in your assembly only once.
If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.
If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.
Comment: Re the last point: StringBuilder doesn't help if you trying to *pass* a large string (since it is actually implemented as a string anyway) - StringBuilder is useful for **manipulating** a string multiple times.
Comment: There are plenty of examples of immutable reference-types. And re the string example, that is indeed pretty-much guaranteed under the current implementations - *technically* it is is per *module* (not per-assembly) - but that is almost always the same thing...
Answer: In a very simple words any value which has a definite size can be treated as a value type.
Comment: easier to understand for ppl new to c#
Comment: This should be a comment
Answer: Also, the way strings are implemented (different for each platform) and when you start stitching them together.  Like using a StringBuilder.  It allocats a buffer for you to copy into, once you reach the end, it allocates even more memory for you, in the hopes that if you do a large concatenation performance won't be hindered.
Maybe Jon Skeet can help up out here?
Answer: It is mainly a performance issue.
Having strings behave LIKE value type helps when writing code, but having it BE a value type would make a huge performance hit.
For an in-depth look, take a peek at a nice article on strings in the .net framework.
Answer: How can you tell string is a reference type? I'm not sure that it matters how it is implemented. Strings in C# are immutable precisely so that you don't have to worry about this issue.
Comment: It's a reference type (I believe) because it doesn't derives from System.ValueType   From MSDN Remarks on System.ValueType:
Data types are separated into value types and reference types. Value types are either stack-allocated or allocated inline in a structure. Reference types are heap-allocated.
Comment: Both reference and value types are derived from the ultimate base class Object. In cases where it is necessary for a value type to behave like an object, a wrapper that makes the value type look like a reference object is allocated on the heap, and the value type's value is copied into it.
Comment: The wrapper is marked so the system knows that it contains a value type. This process is known as boxing, and the reverse process is known as unboxing. Boxing and unboxing allow any type to be treated as an object. (In hind site, probably should've just linked to the article.)
Answer: Actually strings have very few resemblances to value types. For starters, not all value types are immutable, you can change the value of an Int32 all you want and it it would still be the same address on the stack.
Strings are immutable for a very good reason, it has nothing to do with it being a reference type, but has a lot to do with memory management. It's just more efficient to create a new object when string size changes than to shift things around on the managed heap. I think you're mixing together value/reference types and immutable objects concepts.
As far as "==": Like you said "==" is an operator overload, and again it was implemented for a very good reason to make framework more useful when working with strings.
Comment: Somehow, in "int n = 4; n = 9;", it's not that your int variable is "immutable", in the sense of "constant"; it's that the value 4 is immutable, it doesn't change to 9. Your int variable "n" first has a value of 4 and then a different value, 9; but the values themselves are immutable. Frankly, to me this is very close to wtf.
Comment: @WebMatrix, @Davy8: The primitive types (int, double, bool, ...) are immutable.
Comment: @Jason, I thought immutable term mostly apply to objects (reference types) which can not change after initialization, like strings when strings value changes, internally a new instance of a string is created, and original object remains unchanged. How does this apply to value types?
Comment: +1. I'm sick of hearing this "strings are like value types" when they quite simply aren't.
Comment: I realize that value types aren't by definition immutable, but most best practice seems to suggest that they should be when creating your own. I said characteristics, not properties of value types, which to me means that often value types exhibit these, but not necessarily by definition
Comment: Good information, but I think a misinterpretation of the question
Comment: @Davy8: Value types inherit mutability, or lack thereof, from the location in which they're stored.  If a value type has any fields--public or private--that can ever take on a non-default value, those fields will be mutable for instances stored in mutable locations, and immutable for instances stored in immutable locations.  Some so-called "immutable" value types may require one to rewrite all fields whenever one rewrites any, but that doesn't make them immutable.
Answer: The fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.
Floating-point primitive types are handled by the FPU, which is 80 bits wide.
This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.
Answer: Isn't just as simple as Strings are made up of characters arrays. I look at strings as character arrays[]. Therefore they are on the heap because the reference memory location is stored on the stack and points to the beginning of the array's memory location on the heap. The string size is not known before it is allocated ...perfect for the heap.
That is why a string is really immutable because when you change it even if it is of the same size the compiler doesn't know that and has to allocate a new array and assign characters to the positions in the array. It makes sense if you think of strings as a way that languages protect you from having to allocate memory on the fly (read C like programming)
Comment: "string size is not known before it is allocated " - this is incorrect in the CLR.


Boolean law on predicate logic

Question: I have a doubt, in boolean algebra $$p \Rightarrow b \equiv \neg\: b \Rightarrow \neg\: p$$ Can I apply the same rule in predicate logic for example : $$((\forall x| \neg A : \neg E) \Rightarrow (\forall x | \neg A : \neg Q)) \equiv (\neg (\forall x| \neg A : \neg Q) \Rightarrow \neg (\forall x | \neg A : \neg E))$$ or do I need to transform the quantifiers and their expressions.
Thank you!
Comment: I'm unfamiliar with your notation for predicate logic, but yes, a propositional tautology with statements of predicate logic substituted in is a logically valid statement.
Answer: Yes. The whole point of propositional logic is to show certain logical relationships hold between sentences without having to know what those sentences are.
As such, when we find that $p \rightarrow b \Leftrightarrow \neg b \rightarrow \neg p$, we know that this is true for any sentences $p$ and $b$ ... and this includes sentences from predicate logic.

Boolean law on predicate logic


How do I run code before user leaves the page?

Question: Nothing I've tried does work. I need to run some code before the user leaves the page all:
window.onbeforeunload = function(){
   alert(1);
}

window.addEventListener("beforeunload", function(e){
   alert(2);
});

    window.addEventListener('unload', function(e) { alert(3); })

How am I supposed to do that nowadays? if matter, in the real application i'm using react and nextjs.
Comment: It depends what you're trying to do when the user leaves the page. If you want to send information to your server side, then use a [Beacon](https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API). If you want to ask the user if they are sure they want to leave the page, then return a value from the event handler. If you want to do *anything* else, then it will not be possible. The unload event has been heavily restricted to prevent user-unfriendly or even malicious intent.
Comment: https://stackoverflow.com/a/58732877/519413
Comment: @RoryMcCrossan How can I use Beacon to archive that? my goal here is to call `navigator.sendBeacon()` before the user leaves the page but I can't find the proper event to do that[
Comment: @RoryMcCrossan thank you for the help. I'll call `navigator.sendBeacon()` on `mouseout` event.
Answer: As an alternative to sending beacons (which my browser blocks by the way) you can catch the user as they move the mouse cursor out of the window and before they can kill the tab via...
window.addEventListener('mouseout', (event) => {

// do something here

});

Of course, the user may not necessarily kill the tab on leaving the window but there's no harm in updating something when they do move away.
Comment: It's easy to close a tab without moving the mouse?!
Comment: I'll rather use this one. unload and whatnot seems rather problematic.
Comment: Wise choice… beacons are often used maliciously and the paranoid community (myself included) block them vigorously.
Comment: I just saw browsers like brave seems to block those automatically
Comment: Too bad... there are no perfect solutions.


True/false : If $f_n(x)\to 0$ almost everywhere , then $\int_{a}^{b}f_n(x)dx \to 0$

Question: Is the following sttaement is true/false ?

let {$f_n$} be sequence of integrable functions defined on an interval $[a,b]$.
If $f_n(x)\to 0$ almost everywhere , then $\int_{a}^{b}f_n(x)dx \to 0$

My attempt : i know that $m(\mathbb{Q}) = 0$  and $f(\mathbb{Q}) =0$  is almost everywhere because the  $f$ is not going to $0$ and measure is $0$ in $[0,1]$
Now consider the function $f_n(x)$, on the interval $[0,1]$. Let $\{r_1, r_2, \dots\}
$ is the enumerarion of rationals on $[0,1]$.
$$f_n(x) = \begin{cases} 1 & \text{x = $r_1, r_2, \dots r_n$} \\ 0 & \text{elsewhere} \end{cases}$$
Thus $f_n(x) \rightarrow f(x)$, which is $0$ almost everywhere
$$f(x) = \begin{cases}1 & x \in \mathbb{Q}\cap [0,1] \\0 & x \in [0,1] - \mathbb{Q}\cap [0,1]\end{cases}$$
But $\int_0^1 f(x)$ does not exists.
so the given statement is false
Is its true ?
Comment: Why do you say $\int_0^1 f(x) \, dx$ does not exist?
Comment: https://en.wikipedia.org/wiki/Dominated_convergence_theorem
Answer: The usual counterexample is something like $$f_n(x) = \begin{cases}n & x \in (0, 1/n] \\ 0 & \text{otherwise}\end{cases}$$
Comment: @jasmine No, $f_n(x) \to 0$. For example, if $x=0.1$, then $f_n(x) = 0$ for any $n > 10$.
Comment: ur $f_n(x)  \rightarrow  \infty $???? @angryavian,,,,,my question is $f_n(x) \rightarrow 0$ read question again
Answer: Take for instance the sequence $f_n=n1_{[0,\frac{1}{n}]}$ on $[0,1]$
Answer: If you want smooth functions as a counterexample, try $f_n(x)=nx^n$ on $[0,1].$
Comment: @jasmine, read ur own question again: it says that $f_n\to 0$ _almost everywhere_.
Comment: im little bit confused @zhw  at $x= 1$ ur $f_n(x)$ does not tend to $0$


Key key = new SecretKeySpec(keyValue, "AES"); in Objective C

Question: I have this code in Java:
Key key = new SecretKeySpec(keyValue, "AES");

I want to port this code to objective-c?
Comment: I don't understand mutch about objective c but I found this code that generates an AES key give it a try http://stackoverflow.com/a/23534490/5467727
Comment: If the given answer solved your problem, you may [accept](http://meta.stackexchange.com/q/5234/266187) it. If it didn't, then please expand on what is wrong.
Answer: Key and SecretKeySpec are simple container types for Java's jce. They don't have corresponding types in Objective-C (CommonCrypto). keyValue is a simple byte[] that corresponds to a byte array in Objective-C which you can use there.