Mathematical manipulations with partial derivatives

Question: Hello dear mathematical community.
I was wondering if anybody could help me, please, with the following question. (I apologize in advance in case my question reveals unawareness of mathematical basics).
I have a first order partial differential equation:
$$\frac{\partial (A·V)}{\partial x} = -\frac{\partial A}{\partial t}$$
Here:
$A=f(x,t)$ - field of property $A$ as a function of spatial coordinate $x$ and time coordinate $t$
$V=f(x,t)$ - field of property $V$ as a function of spatial coordinate $x$ and time coordinate $t$
I did the following mathematical manipulations with it:
$$\frac{\partial (A·V)}{\partial A} = -\frac{\partial x}{\partial t}$$
MY QUESTION IS: whether I can do such mathematical manipulation with partials or not? 1) If not then why? 2) If conditional yes, then what are the conditions? 3) If yes, how can it be physically/mathematically explained and what theorem/rule does allow me to do it?
Thank you in advance.
CLARIFICATIONS REQUIRED BY  @Raskolnikov, @user7530, @MarsPlastic, @Shogun, @ParclyTaxel:
My question is pretty obvious: can I work with partial derivatives as if they were mere division operations. Like in my example: can I bring the numerator of the right hand side to the denominator of the left hand side. And in turn, denominator of the left hand side to the numerator of the right hand side.
So, I am interested if there exist mathematically proven rules prescribing allowed manipulations with derivatives. Basically, that's it - can I work with derivatives as with regular division operations? If yes - what theorem allows me to do it. If not - what theorem doesn't allow me to do it.
The answer of Hans Lundmark doesn't satisfy me - I explained the reason in my answer. Briefly, he states that $\frac{\partial x}{\partial t}$ must be zero. I explained why it is not necessarily zero. He also states that $\partial/\partial A$ doesn't mean anything. I explained its meaning.
CLARIFICATION OF THE REASON OF MY QUESTION:
Obviously, my equation is one equation with two unknowns. I want an extremely simple thing - I want to express one unknown through the other unknown. That's it. This is what we do without hesitation with any algebraic equations, e.g.: $x + y = 5 \Rightarrow x = 5 - y$. Why can I do it? Because rules of work with addition and subtraction are determined. How can I do the same thing with derivatives? Literature is full of solution methods for PDEs. But what if I don't need to solve it - instead, I want to express one variable through another one? What should I do in this case?
SUGGESTED CORRECTIONS:
1) $x$ and $t$ are independent variables, since I am considering two fields.
2) I can't tell what becomes a constant and what becomes a variable when I move $\partial A$ to the left hand side. This can be treated as a part of my question: whether or not I can make such manipulation and what does it mean.
3) One may treat $V$ as a one dimensional velocity field of a pipe fluid flow. Since it is one dimensional, then its $x$ component equals to its magnitude at every point. Therefore, right hand side of the second expression might be considered equal to $-V$ at every point.
4) In the first expression, $A$ and $V$ are allowed to vary with time and space. In the first expression on the right hand side, $x$ is held constant, on the left hand side $t$ is held constant. In the second expression on the left hand side - it seems that I begin considering $A$ and $V$ as the functions of each other. But I am not sure about it. It's my question. Right hand side of the second equation seems strange, since $x$ and $t$ are independent variables. But to my opinion, right hand side can be treated as an $x$ component of velocity field by analogy to the way we derive acceleration expression for a flow field.
5) One's first thought can apparently be that the solution of the equation should be $A = f(x,t)$ and $V = f(x,t)$. But I don't imply such limitation when I am asking the question. Yes, there are two functions in my equation and, therefore, it is obvious that my equation is a part of a system of PDEs. But it's not important now. I would be satisfied if I could only use my equation to express one function through another, for instance: $A$ through $V$, or vice versa.
6) Apart from all, I am interested in pure math: what mathematical manipulations are allowed for numerators and denominators of partial derivatives. In other words: am I allowed to freely manipulate with numerators and denominators of a partial derivative as if it were not a derivative but a division defined at a point.
RESPONSE TO THE @HansLundmark ANSWER AND @user7530 COMMENTS:
Dear @user7530 and @HansLundmark.
Thank you for the responds. You hinted me where to look at.
Regarding your comments I have only to say the following so far.
1) I already thought about $-\frac{\partial x}{\partial t}$. It can have some value other then zero. To my mind (I might be absolutely wrong), it is similar to the way, we derive an acceleration equation for fluid flows. Let me introduce this example for better understanding of what I mean.
\EXAMPLE
Assume, we have a velocity field of some transient 3D flow: $$v = f(x,y,z,t)$$ Let's take its differential (v is obviously a vector): $$dv = \frac{\partial v}{\partial x}dx+\frac{\partial v}{\partial y}dy+\frac{\partial v}{\partial z}dz+\frac{\partial v}{\partial t}dt$$ Now, let's divide both sides by $dt$. We'll get:
$$\frac{dv}{dt} = \frac{\partial v}{\partial x} \frac{dx}{dt}+\frac{\partial v}{\partial y} \frac{dy}{dt}+\frac{\partial v}{\partial z} \frac{dz}{dt}+\frac{\partial v}{\partial t}$$ Then we say that:
$\frac{dv}{dt} = a$ - is acceleration
$\frac{dx}{dt} = u$ - is x component of velocity
$\frac{dy}{dt} = v$ - is y component of velocity
$\frac{dz}{dt} = w$ - is z component of velocity
And we get that flow acceleration at every point in the flow field is:
$$a = u\frac{\partial v}{\partial x} + v\frac{\partial v}{\partial y} + w\frac{\partial v}{\partial z} + \frac{\partial v}{\partial t}$$
Now why do people say that $\frac{dx}{dt} = u$, $\frac{dy}{dt} = v$, $\frac{dz}{dt} = w$? We know that $x$, $y$, $z$, $t$ are independent variables. Therefore, these derivatives should equal zero. But they are not. They equal to the corresponding velocity components. Why? To my opinion, because, if for a moment we cease considering field where coordinates are fixed and instead consider a real fluid particle at some point in the flow field, then we'll see that magnitudes of its velocity components can be written as $\frac{dx}{dt} = u$, $\frac{dy}{dt} = v$, $\frac{dz}{dt} = w$. But in this case, $x$, $y$, $z$ are corresponding components of its radius-vector. Hence in the field equation for acceleration, the terms $\frac{dx}{dt} = u$, $\frac{dy}{dt} = v$, $\frac{dz}{dt} = w$ mean nothing. But they mathematically equal to the velocity components of a real fluid particle. Therefore, we plug the velocity components into the equation.
\END OF THE EXAMPLE
That is why, I think that in my equation the term $-\frac{\partial x}{\partial t}$ can be treated the same way and can be substituted with an $x$ component of velocity of the flow (because my equation is written for a 1D flow originally).
I apologize that I didn't mention it at once.
2) Now about what $\partial/\partial A$ means. I though of it. It apparently seems to me, that when I do my manipulation I automatically begin considering $A$ and $V$ as functions of $A$ on the left hand side (physically, it is possible due to the nature of my equation). Since, $A$ cannot be a function of itself, then I am left with only $V$ as a function of $A$ on the left hand side. Which allows me to move from partial derivatives to the total ones and solve the equation getting as a result $V = f(A)$.
I would be really grateful to you if you could provide any of you thoughts regarding my reasoning.
I am an engineer - not a mathematician. So, I apologize if the way I work with equations seems barbarian to you.
Thank you in advance.
Comment: $A$ and $V$ are scalar functions.
Comment: What does $\frac{\partial x}{\partial t}$ even *mean*, if these are both independent variables?
Comment: @user7530: If $f(x,t)=x$, then $\partial f/\partial t=0$, so a reasonable interpretation is that $\partial x/\partial t=0$. The real mystery is what the *left-hand* side with $\partial/\partial A$ is supposed to mean...
Comment: @HansLundmark I assume Ivan is defining $g(y, x, t) = y V(x,t)$ and the left-hand side is $\frac{\partial g}{\partial y}.$ Ivan if you want us to help you, please reformulate your question, explaining better which quantities you're varying and which you're holding fixed in each of your expressions...
Answer: You certainly cannot!
First of all, it's not really clear what the operation $\partial/\partial A$ even means. (What quantity is supposed to be held constant as $A$ varies?)
Secondly, the right-hand side of the new equation, $-\partial x/\partial t$, is identically zero (if $\partial/\partial t$ has the same meaning as in the term $\partial A/\partial t$ in the original equation, namely that $x$ is held constant as $t$ varies), and whatever the left-hand side $\partial (A \cdot V)/\partial A$ means, it's not reasonable that it should be unconditionally equal to zero.


Bootstrapping ordinal correlations? How to deal with the effect of duplicated observations?

Question: When dealing with ordinal correlations (e.g. Spearman's Rho, Kendall's Tau), one can non-parametrically test the null hypothesis of no correlation by a random permutation test (shuffling one of the two variables).
However, if we have a significantly non-zero correlation and we'd like to obtain a confidence interval for the correlation coefficient we need a standard error estimate that doesn't rely on the null hypothesis.
Bootstrapping seems to the way to go, but then comes the problem of duplicated observations. The bootstrapped samples contain duplicated observations due to resampling with replacement, and these duplicates generate ties that affect the ordinal correlations measures. For example, if one uses Kendall's Tau a, these spurious ties will decrease the correlation coefficient (i.e., introduce a negative bias).
How to deal with this problem? will a BCA (bias corrected and accelerated) confidence interval be appropriate here ? or alternatively, should we use a different resampling approach (e.g., jackknifing) instead?
Answer: I found a paper that addresses your issue. The answer will depend on how correlated your data is. To summarise the paper, the Spearman correlation (r_s) is used to test the null hypothesis, but you are right to worry that we don't want the traditional Spearman test. The Fisher transform is z_r= arctanh(r_s). With this transform we can define a confidence interval =
tanh[z_r±((N-3)^(-1/2)+z_CL)]

z_CL "is the percentile point of standard normal distribution below the which the subscripted portion of scores lies[sic]. For example, constructing a 95% CI for r=.5 and N=50 would proceed as follows: z_r = arctanh(.5) z_CL=z_.025=1.96, and CI=tanh(.5493 ± .1459 × 1.96)

To be honest, I don't understand the z_CL calculation, but if you want 95% then just use 1.96. Note that this method uses deviation from the theoretical "usual estimate" around Var(z_r)=(N-3)^(-1/2). It is possible that domain knowledge would suggest that this is not a good starting estimate.
I would try this initial estimate first, and if it does not give you reasonable CI then you can read on in the paper. I can also develop my answer more if need be.
In short, you may be able to avoid the bootstrapping issue.
In the case of making CI for Kendall's Tau there is already a cross validated question for this.
Comment: Thank you for your answer. This indeed might be useful for Spearman. However, I'd like to know how should one generally approach this problem of bootstrapping ordinal correlations. In particular, I'd like to estimate confidence intervals to different variants of Kendall's Tau.
Comment: @Trisoloriansunscreen updated to reference a prior question on Kendall's Tau


Python code for curve fitting by convolution of a gausian and multi exponential decay

Question: I'm developing a code for fitting a data with a model which is convolution of two functions (Gaussian with multi exponential decay exp(Ax)+exp(Bx)+...). basically the fitting with only Gaussian and/or Gaussian modified https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution is working perfectly fine in Lmfit but using the builtin convolution (i.e if np.convolve of two functions is used Lmfit doesn't work.
I have tried many examples on internet, so far I realized that my functions returns inf or nan values and also data is not equally spaced for being used in convolution. I found a detour for the issue by using the mathematical expression of convolution and by using scipy.optimize.curve_fit .But it is a very clumsy and time consuming, I would like to find a way to making it more sophisticated and general by using a convolution of two functions and using lmfit where I can control the parameters a lot easier.
The data set is also included in comments as your reference.
w=0.1 # is constant
def CONVSum(x,w,*p):
    n=np.int(len(p)/3)
    A=p[:n]
    B=p[n:2*n]
    C=p[2*n:3*n]
# =======================================================================
#     below formula is derived as mathematical expression of convoluted multi exponential components with a gaussian distribution based on the instruction given in http://www.np.ph.bham.ac.uk/research_resources/programs/halflife/gauss_exp_conv.pdf
# ======================================================================
    fnct=sum(np.float64([A[i]*np.exp(-B[i]*((x-C[i])-(0.5*np.square(w)*B[i])))*(1+scipy.special.erf(((x-C[i])-(np.square(w)*B[i]))/(np.sqrt(2)*w))) for i in range(n)]))
    fnct[np.isnan(fnct)]=0
    fnct[fnct<1e-12]=0
    return fnct
N=4 #number of exponential functions to be fitted
params = np.linspace(1, 0.0001, N*3); #parameters for a multiple exponential
popt,pcov = curve_fit(CONVSum,x,y,p0=params,
    bounds=((0,0,0,0,-np.inf,-np.inf,-np.inf,-np.inf,-3,-3,-3,-3),
           (1,1,1,1, np.inf, np.inf, np.inf, np.inf, 3, 3, 3, 3)),
           maxfev = 1000000)

fitted data with curve fitt
Any help or hint regarding the fitting with convolution of Gaussian and  multiple exponential decay is highly appreciated, I prefer using lmfit since I can identify parameters very nicely and also to relate them to each other.
Ideally I want to fit my data with the parameters where some of them are shared among the data sets, some are delayed (+off_set).
Comment: here is my sample data file https://drive.google.com/open?id=1qq_01Eg1VYrQLQU_dtTbvHtOCZEd5huA
Answer: Well, your script is a bit hard to read and follow closely with lots of stuff that is not related to your question.   Your exgauss function is not guarding against infinities.  np.exp(x) for x>~ 710 will give Inf, and the fit will not be able to proceed.
Comment: Dear @M Newville thanks for your time to reply, the issue was resolved by using np.isnan() to eliminate nan and inf, but the fitting os still not working. I did find the way to edite my question but I  changed it a bit.
Answer: Here is the equvalent of the cure fitting code given in question. I managed to creat this by using very great instruction and infromation in here and here. But still it needs to be developed.
    # =============================================================================
    #     below formula is drived as mathematical expresion of convoluted multi exponential components with a gausian distribution based on the instruction given in http://www.np.ph.bham.ac.uk/research_resources/programs/halflife/gauss_exp_conv.pdf
    # =============================================================================

def CONVSum(x,params):
    fnct=sum(
            np.float64([
                    (params['amp%s_%s'%(n,i)].value)*np.exp(-(params['dec%s_%s'%(n,i)].value)*((x-(params['cen%s_%s'%(n,i)].value))-
                     (0.5*np.square((params['sig%s_%s'%(n,i)].value))*(params['dec%s_%s'%(n,i)].value))))*
                    (1+scipy.special.erf(((x-(params['cen%s_%s'%(n,i)].value))-(np.square((params['sig%s_%s'%(n,i)].value))*
                    (params['dec%s_%s'%(n,i)].value)))/(np.sqrt(2)*(params['sig%s_%s'%(n,i)].value)))) for n in range(N) for i in wav
                    ])
            )
    fnct=fnct/fnct.max()
    return fnct
    # =============================================================================
    #  this global fit were adapted from  https://stackoverflow.com/questions/20339234/python-and-lmfit-how-to-fit-multiple-datasets-with-shared-parameters/20341726#20341726

    # it is of very important thet we can identify the shared parameteres for datasets
    # =============================================================================

def objective(params, x, data):
    """ calculate total residual for fits to several data sets"""
    ndata = data.shape[0]
    resid = 0.0*data[:]
    # make residual per data set
    resid = data- CONVSum(x,params)
    # now flatten this to a 1D array, as minimize() needs
    return resid.flatten()

# selec datasets
x  = df[949].index
data =df[949].values

# create required sets of parameters, one per data set
N=4 #number of exponential decays
wav=[949]  #the desired data to be fitted
fit_params = Parameters()
for i in wav:
        for n in range(N):
            fit_params.add( 'amp%s_%s'%(n,i), value=1, min=0.0,  max=1)
            fit_params.add( 'dec%s_%s'%(n,i), value=0.5, min=-1e10,  max=1e10)
            fit_params.add( 'cen%s_%s'%(n,i), value=0.1, min=-3.0,  max=1000)
            fit_params.add( 'sig%s_%s'%(n,i), value=0.1, min=0.05, max=0.5)

# now we constrain some values to have the same value
# for example assigning sig_2, sig_3, .. sig_5 to be equal to sig_1
for i in wav:
        for n in (1,2,3):
            print(n,i)
            fit_params['sig%s_%s'%(n,i)].expr='sig0_949'
            fit_params['cen%s_%s'%(n,i)].expr='cen0_949'

# it will run the global fit to all the data sets
result = minimize(objective, fit_params, args=(x,data))
report_fit(result.params)

# plot the data sets and fits
plt.close('all')
plt.figure()
for i in wav:
    y_fit = CONVSum(x,result.params)
    plt.plot(x, data, 'o-', x, y_fit, '-')
    plt.xscale('symlog')
plt.show()

fitted data with convolution of multi exponential and gausian
unfortunately the fitted results are not very satisfying, I am still looking for some advice to improve this.
Comment: That is very hard to read and obviously incomplete... If you would like help cleaning it up and understanding how to make it better, post a COMPLETE example, including imports and reading of the data.  As it is, it is essentially impossible to know what you are doing... That's not helping anyone.


Informações extras no login de um usuário

Question: Meu cenário é o seguinte:
O usuário vai logar no sistema. Então vai ser exibido uma lista de itens e ele vai escolher um.
Preciso então que o sistema armazene o usuário logado e o item que ele escolheu.
Não sei como posso estar fazendo isso e desconheço as tecnologias que posso estar utilizando.
Atualmente para autenticação de meus projetos utilizo FormsAuthentication, porém o mesmo não consigo armazenar mais de um valor (pelo menos eu não sei).
Achei a seguinte alternativa:
Forms.SetAuthCookie (UserName + "|" + UserId, true);

if (HttpContext.Current.Request.IsAuthenticated)
{
    userId = Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('|')[1]);
}

Pensei também na utilização de Session, mas acho que existe uma tecnologia mais apropriada.
Comment: Penso que deves rever a tua questão... Não parece ter qualquer tipo de esforço de pesquisa
Comment: @CesarMiguel, editei minha pergunta, porém não sei mais o que colocar.
Comment: Por quanto tempo você precisa armazenar essa informação? Por alguns minutos? Meses? Pra sempre? Esse armazenamento é só para conveniência do usuário voltar ao site e rever as coisas como as selecionou da última vez, ou você vai fazer alguma análise ou processamento do seu lado?
Comment: @Renan, por um tempo curto... O tempo que dura o FormsAuthentication....
Comment: Isso meio que não fez sentido. Acho que se você disser o que vai fazer com essas informações fica mais fácil. Mas vou arriscar uma resposta.
Answer: Se tudo que você quer é ter esses valores para usar enquanto o usuário estiver logado - ou se quiser usar esses valores apenas na próxima requisição - você pode usar a sessão do usuário.
A sessão é um objeto que é único por usuário. Ela é criada quando o usuário autentica, e destruída quando ele é desconectado. Assim ela sobrevive, por exemplo, de uma requisição para outra. Ela fica no servidor, então pode continuar viva mesmo que o usuário mude de máquina ou ponto de acesso.
Um exemplo de uso comum de sessões é pra guardar "carrinhos de supermercado" dos usuários.
Para jogar valores na sessão:
Session[nomeDaVariavel] = foo;

Onde nomeDaVariavel é uma string arbitrária, e foo é um valor que você quer guardar apenas enquanto o usuário está logado.
Pra ler os valores, supondo que sejam strings:
string valor = (string)Session[nomeDaVariavel];

Se o valor não tiver sido armazenado, virá nulo.
Isso deve ser tudo que você precisa. Boa sorte, e se isso ajudou, não esqueça de fazer uma leitura aprofundada da documentação oficial, que também sugere outras alternativas ;)
Answer: Pensei também na utilização de Session, mas acho que existe uma tecnologia mais apropriada.
Existe. É a tecnologia de Profiles.
Use uma implementação sua de ProfileBase para guardar as opções de cada usuário.
Use ProfileManager para gerenciar os perfis dos seus usuários.
Respondi recentemente algumas perguntas sobre isso que podem ser do seu interesse:

Criar Objeto ProfileCommon em Asp.Net Membership
Persistir dados no ProfileCommon


why does NSManagedObjectContext Queue execute on main thread?

Question: When I send a performBlock message to my MOC of type NSPrivateQueueConcurrencyType, like this:
[self.privateManagedObjectContext performBlockAndWait:^{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"executing on the main thread!!");
    }
    …
}];

I find that, by default, this executes on the main thread. The conditional in the above code triggers, and the Issue Navigator indicates that execution is occurring on Thread 1 in the NSManagedObject Queue.
This is very puzzling to me, because Apple tells us that "each thread must have its own entirely private managed object context." Given that an MOC of type NSMainQueueConcurrencyType will use the main thread, doesn't it violate thread confinement for an MOC of type NSPrivateQueueConcurrencyType to use the main thread?
Is the execution of my code on the main thread normal? Have I misunderstood thread confinement? I understand that a queue is not necessarily tied to a particular thread, but in this case it seems the private MOC queue should at a minimum avoid the main thread, if not have a single go-to thread. I'm having some weird bugs, so I need to figure out what's going on. Thanks!
Answer: This optimization is possible because performBlockAndWait: executes the block
synchronously, i.e. the method does not return until the block has finished.
Therefore the block will not be executed in parallel with other operations on
the main thread.
(For the same reason, dispatch_sync(queue, ...) may execute a block on the main thread
instead of a separate thread.)
Comment: @Chengjiong: NSPrivateQueueConcurrencyType specifies that the context is associated with a private dispatch *queue*. A queue is not bound to a fixed *thread*. GCD can choose to execute blocks from a non-main queue on the main thread here, because there is no possibility that any other code executes on the main thread simultaneously. It is an optimization to reduce the number of thread switches.
Comment: Cool, you cleared my doubt. I have another question, wish you can help me:). The question is, I create a context with type NSPrivateQueueConcurrencyType in the main thread, from Apple's doc, is this mean that I can only use the context and NSManagedObjects managed by it in main thread only?
Comment: Yes, what this post describes is right, but does it give the question an answer?
Comment: @Chengjiong: I think I have answered the question. What do you think is missing?
Comment: you explained why the block in performBlockAndWait: was performed in main thread, but as I saw in the question, mkc842 wants to know why a NSPrivateQueueConcurrencyType context can run on main thread, does this violate Apple's rule, also these are what I want to know.


Understanding an exercise about gradients and vector fields

Question: In John M. Lee's Introduction to Smooth Manifolds, exercise 11.17 goes as follows:

Let $f(x,y)=x^2$ on $\mathbb R^2$, and let $X$ be the vector field $$X=\operatorname{grad} f=2x\frac\partial{\partial x}.$$ Compute the coordinate expression for $X$ in polar coordinates (on some open subset on which they are defined) and show that it is not equal to $$\frac{\partial f}{\partial r}\frac{\partial }{\partial r}+\frac{\partial f}{\partial \theta}\frac{\partial}{\partial\theta}.\tag{*}$$

I am not sure, what I am supposed to do here, but this is what I thought: Considering the change of coordinates $(x,y)=(r\cos\theta,r\sin\theta)$ we can compute the change of bases of tangent spaces:
$$
\begin{align}
\frac{\partial}{\partial r}
&=\cos\theta\frac{\partial}{\partial x}+\sin\theta\frac{\partial}{\partial y}\\
\frac{\partial}{\partial\theta}
&=-r\sin\theta\frac{\partial}{\partial x}+r\cos\theta\frac{\partial}{\partial y}
\end{align}
$$
and then since $f(r,\theta)=r^2\cos^2\theta$ we have
$$
\begin{align}
\frac{\partial f}{\partial r}&=2r\cos^2\theta\\
\frac{\partial f}{\partial\theta}&=-2r^2\cos\theta\sin\theta
\end{align}
$$
we see that the coefficient of $\dfrac{\partial}{\partial y}$ in $(*)$ becomes
$$
2r\cos^2\theta\sin\theta-2r^3\cos^2\theta\sin\theta\neq 0
$$
but to equal $X$, this coefficient should have been identical zero. I chose to use $(x,y)=(r\cos\theta,r\sin\theta)$ instead of $(r,\theta)=(\sqrt{x^2+y^2},\tan^{-1}(y/x))$ which is limited to $x>0$ and more heavy to work with.
But I would like to know, if what I write here even makes sense, or if I am way off.
Comment: What you're done is correct, but the exercise also asks you compute $X$ is polar coordinates. You don't need to use the chain rule again, you just have to invert the matrix in your system, ra
Comment: @Michael: Hi Michael! Yes, that was me :) Great to hear from you. I left that site when they gave it "an extreme makeover" so that noone could find anything anymore ;) And this site has the MathJaX-advantage ...
Comment: @ArturAraujo: Thank you! I will do that and return to it later.
Answer: One mistake in your computation:
$$\frac{\partial f}{\partial \theta}=-2r^2\sin{\theta}\cos{\theta}$$
The others look correct to me. However in the problem, I understand $X=\nabla f$. But then what does $2x\frac{\partial }{\partial x}$ mean?
Comment: Because $2x{\partial_x}\bigg|_{(x,y)}$ then is a tangent vector at $(x,y)\in\mathbb{R}^2$. The coordinate function $2x$ (which maps $(x,y)\mapsto 2x$) is smooth, therefore $X$ is a section in the tangent bundle, i.e. by definition a vector field.
Comment: Thank you for pointing out that I missed the the derivative of the inner function there! The tangent space consists of derivations in this abstract setup. So here $2x\dfrac{\partial}{\partial x}$ is a derivation that for a given smooth function $g$ defined on our manifold $\mathbb R^2$ can assign a number in $\mathbb R$. Furthermore, a derivation $v:C^{\infty}(\mathbb R^2)\rightarrow\mathbb R$ must satisfy the Leibniz (product) rule $v(gh)=v(g)h+g v(h)$, which in particular the differential operator $\frac{\partial}{\partial x}$ does. At least that is how I have understood it this far.
Comment: Thanks for explaining. Why is $X$ a vector field then, if $2x\frac{\partial}{\partial x}$ is a derivation that assigns $g$ a number in $\mathbb{R}$?


O que é assíntota?

Question: Em uma resposta veio o termo assintótica. Em comentário veio uma definição.
Acho que seria ter aqui uma definição mais completa. Mas o foco da pergunta é até mais simples:
Em português claro, ainda que impreciso, o que isso quer dizer para o programador que não tem uma boa base matemática? Por que isso importa para ele?
Para o programador médio isto não é claro e o que isto importa:

Em matemática, uma assíntota/assímptota de uma curva C é um ponto ou uma curva de onde os pontos de C se aproximam à medida que se percorre C Quando C é o gráfico de uma função, em geral o termo assímptota refere-se a uma reta.
Comment: @Fernando não sei se é o foco, mas é uma sugestão para quem for responder.
Comment: E nada claro :D
Comment: @Fernando essa pergunta fornece exemplos de assíntotas para a complexidade temporal de um algoritmo, e as respostas tratam de outros algoritmos também: https://pt.stackoverflow.com/q/236960/64969
Comment: `lim x-> N F(x)/G(x) = k` para `N pertencente R + { -infinito , +infinito }` e `k pertencente a R*` implica que `G` é assíntota da função `F` no ponto `N` (ou nos infinitos). Não está totalmente certo mas é bem próximo
Comment: [A assíntota de Aquiles é a tartaruga](https://en.wikipedia.org/wiki/Zeno's_paradoxes?wprov=sfti1https://en.wikipedia.org/wiki/Zeno's_paradoxes?wprov=sfti1)
Comment: Cada vez menos claro :D :D :D
Comment: Há como adicionar um exemplo para essa sua definição ? @Maniero
Comment: Esse termo foi empregado nessa nota: Note aqui mais uma propriedade matemática que afasta as possibilidades reais da teoria, obrigando o sujeito que usa a
estatística gaussiana a platonificar. CONTINUA...
Comment: No mundo real, por limite de tempo, recursos ou disponibilidade de dados, somos quase
sempre obrigados a trabalhar com tamanhos pequenos de amostras, bem longe de serem considerados razoáveis para boas
aproximações, no sentido da "Lei dos Grandes Números" e do "Teorema Central do Limite". CONTINUA ...
Comment: Ou seja, não vivemos na
`assíntota`. Frequentemente, em cursos de estatística, os professores estipulam um número mágico, como n=30, como sendo
suficientemente grande para permitir boas aproximações. É claro que isto só faz sentido se algumas fortes hipóteses sobre a
natureza das variáveis forem feitas a priori, como crer que elas têm comportamento de Mediocristão (muitas vezes uma forte
Platonificação): uma "casca de banana" para cair na falácia lúdica.  http://www.econ.puc-rio.br/uploads/adm/trabalhos/files/Bruno_B_de_Oliveira.pdf
Answer: Um conto grego

A assíntota de Aquiles é a tartaruga

Corolário do Paradoxo de Zeno

Um dia, Aquiles, o Herói, e uma tartaruga discutiram. A tartaruga afirmou para Aquiles que, se ela começasse na frente, ela iria vencer uma corrida de qualquer distância contra o Herói. Curioso, Aquiles perguntou
-Por que disso? Se eu sou mais rápido que você, eu irei vencer.
Para então a tartaruga responder:
-Se eu começar na frente, você precisa primeiro alcançar a posição que eu estava. Mas até você chegar lá, eu terei andado, estarei mais adiante. Então, você deverá chegar a minha nova posição, e eu estarei na sua frente. Então você precisará de infinitos passos desses até chegar em mim, pois então para me ultrapassar precisará de mais do que infinitos passos.

Noção informal de assíntota
No paradoxo de Zeno, não importa quantas vezes Aquiles tente ultrapassar a tartaruga, ele nunca conseguirá. Pois, a cada passo, Aquiles está se aproximando da tartaruga. Aquiles se torna assintoticamente próximo da tartaruga.
Veja os seguinte infográfico, evolução das posições de Aquiles e da tartaruga:

Dá para perceber que Aquiles fica cada vez mais próximo da tartaruga a cada passagem de tempo. A esse tipo de comportamento nós chamamos de assíntota. Daí, a assíntota de Aquiles é a tartaruga.
Quando você quer saber o comportamento geral de uma função, você quer saber qual a assíntota da função. Por exemplo:

Ao infinito, essa função tende a ter o mesmo comportamento que x^2. Então podemos dizer que o comportamento de f(x) = (x^2 - x)/2 é assintoticamente x^2.
Isso tem aplicação prática?
Bem, isso quer dizer que o bubble sort piora tão rápido quando o insertion sort, e também que o merge sort será melhor em casos maiores. Mais tarde, na seção Por que isso importa para o programador?, eu detalharei mais.
Como identificar assíntotas?
De modo geral, você precisa de um "Aquiles" e de uma "tartaruga". A tartaruga será a assíntota de Aquiles.
A função dada como exemplo ela se aproxima de x^2, mas nunca chega nela.
Outro caso também, eu poderia pegar a função 1/x. No infinito positivo, ela tende a ser zero, mas nunca o é:

Note que quando x=10, a função vale 0.1. Quando x=80, a função por sua vez agora valeria 0.0125. Ficando cada vez mais próxima de 0, mas nunca de fato chegando lá.
Por que isso importa para o programador?
Em um mundo normal de aplicações corporativas que não se preocupam em calcular qual o desconto (em porcentual) que eu devo aplicar no preço de venda para que o valor com o ICMS-ST alcance o total de R$10,00 no preço final (dica: tem uma fórmula que condensa a soma infinita), assíntotas servem basicamente para descrever comportamentos de algoritmos.
Então, para o programador médio, o que importa é comportamento assintótico, normalmente associado à complexidade temporal/espacial de um algoritmo.
A seguir, uma lista de perguntas que flertam com esse conceito (o autor sabendo disso ou não):

Como provar a ordem assintótica de um algoritmo?
Existe algum algoritmo de ordenação que execute realmente em O(n)?
Consumo de tempo em código cúbico
Como melhorar o desempenho de meu código com "for"?
Nota especial: nessa pergunta, o autor acreditava que ter 3 for aninhados um dentro do outro era sinal de ineficiência, mas ele não havia percebido que estava no melhor possível matematicamente para iterar em uma coleção "cúbica" de dados
Complexidade temporal de algoritmo palíndromo recursivo
Qual a melhor implementação do 'Algoritmo MergeSort'?

Em todos os casos, se pede algo em relação ao comportamento assintótico (ou como parte da resposta, ou como parte da pergunta).
Também vale para o programador saber que comportamento assintótico nem sempre é tudo. As vezes temos constantes escondidas que, quando não se está "perseguindo tartarugas no infinito", se tornam muito mais importantes. Por exemplo, o quick sort possui o tempo de execução normalmente mais rápido do que o merge sort.
Como provar a ordem assintótica de um algoritmo?

Esta pergunta já tem uma resposta aqui:

Como provar a ordem assintótica de um algoritmo? 3 respostas

Formalmente, o que é uma assíntota?
Uma assíntota é um ponto ou curva para o qual uma função tende. Por exemplo, o centro é a assíntota para a seguinte função polar exponencial:

Ela é plotada assim:

Quanto maior o θ, mais próxima a função fica de (0,0). Então (0,0) é a assíntota de f(t) = e^(-0.1 t).
Uma curva pode interceptar sua assíntota. Por exemplo, f(x) = sen(10*x)/x + x tem como assíntota g(x) = x:

Nem toda assíntota precisa ser uma reta, mas pode ser uma curva. Como o caso de f(x) = |1/x| + x**2, cuja assíntota nos infinitos é g(x) = x**2:

Então, a assíntota A de uma função F é um valor (exemplo da espiral) ou função (outros dois exemplos) que, dada a evolução de F em termo de alguma variável, F se aproxima arbitrariamente próxima de A.
Como descobrir uma assíntota de uma função?
Eu normalmente uso os seguintes passos (para funções que usam coordenadas cartesianas, não polares) para descobrir a ordem da assíntota:

conjecture OA
divida* F/OA ou OA/F
se errou, repita

A divisão, entretanto, não pode ser feita de qualquer forma. Normalmente, se deseja saber qual o comportamento extremo da função, então a divisão é com o limite da variável indo ao infinito. Nesse caso de comportamento no infinito, OA é da mesma ordem da assíntota de F se elas forem co-dominantes conforme definida nesta resposta:

Também condensado nessa resposta do @Isac para a mesma pergunta (obs: com c != 0):

Descoberta a ordem, o valor obtido pela divisão é o coeficiente do maior termo. Isso significa que o termo mais significante da assíntota tem coeficiente conhecido, c. Agora, remova o termo mais significativa e calcule novamente. Como?
Bem, achamos OA a função co-dominante de F. Sabemos que F = OA * c + G, para c = lim OA/F. Então, agora, é achar o valor da assíntota de G e somar a c*OA, fazendo isso recursivamente até que, em algum momento, lim G = 0. Essa será a curva da assíntota de F.
Exemplo
Para f(x) = x + sen(10*x)/x. Vamos primeiro supor que a ordem da função assintótica OA é x**2:

Essa divisão dá 0, portanto OA domina f(x). Portanto, a primeira conjectura da ordem da função assintótica deu errado. Nesse caso, repitamos.
Vamos agora supor que a ordem da função assintótica OA é x:

Eles são co-dominantes, então a ordem assintótica é, realmente, OA. Para o próximo passo, precisamos remover c*OA de f(x) e verificar g(x):

Chegamos a conclusão que g(x) = sen(10 x)/x. Agora, precisamos de outro termo para definir a assíntota de g(x)?

Não, não precisamos. Portanto, A(x) = x é a assíntota para f(x) = x + sen(10*x)/x.
Existem outras assíntotas que não as do infinito?
Sim, existem. Normalmente, elas se encontram em pontos de descontinuidade.
Tome a hipérbole f(x) = 1/x:

Ela apresenta descontinuidade em x = 0. Portanto, o ponto x = 0 é um candidato a ser uma assíntota vertical da função. Para achar uma assíntota vertical no ponto x = a, é preciso atender um desses quatro critérios:

A função deve tender ao infinito (positivo ou negativo) quando x tender ao valor a, seja o limite pela esquerda ou o limite pela direita.
No caso da hipérbole, quando x -> 0 pela direita, f(x) -> +infinito. Isso já é o suficiente para considerar x = 0 hipérbole vertical de 1/x.

Fontes das imagens:

Testudo marginata (GPL): https://en.wikipedia.org/wiki/File:Nacht_006.jpg
O gif lide com isso, Aquiles portanto também deve ser usada sob a GPL
1 sobre x: https://en.wikipedia.org/wiki/File:Hyperbola_one_over_x.svg
Aquiles e a tartaruga: https://en.wikipedia.org/wiki/File:Zeno_Achilles_Paradox.png
Plotagem das funções obtidas de consultas ao WolframAlph:

f(t) = e^(-0.1 t)
f(x) = sin(10*x)/x + x vs g(x) = x
f(x) = |1/x| + x**2 vs g(x) = x**2
Comment: +1 pela historinha da tartaruga que elucidou!
Comment: E vem ele com as dissertações :) Amanhã eu leio, agora vou embarcar
Comment: Acho que alguém ganhará um *bounty*, mas só depois do carnaval, o povo tá de férias :)
Comment: Pra você: https://i.stack.imgur.com/k0UNy.gif , haha
Comment: @RafaelSalomão nunca mais olhará para tartarugas da mesma forma, haha
Answer: Vou ser o mais breve e o mais simples possível e me concentrar em responder:

O que isso quer dizer para o programador que não tem uma boa base matemática?
Este é o meu caso, não considero ter uma boa base matemática. Mas para mim, o conceito: assíntota me leva a pensar na Notação Assintótica tem relação com a análise de algoritmo e é usado como uma ferramenta de análise para o fim de realizar: Análise Assintótica. Desta forma, podemos assumir que:

Em geral, cada passo em uma descrição em pseudocódigo ou implementação em linguagem de alto nível corresponde a um pequeno número de oprações primitivas (exceto para chamadas de métodos, naturalmente). Assim, podemos realizar uma análise simplificada de um algoritmo escrito em pseudocódigo que estima o número de operações primitivas executadas, execeto por um fator constante, contando os passos do pseudocódigo (mas deve-se ter cuidado uma vez que uma linha de pseudocódigo pode denotar vários passos em alguns casos).[Goodrich, Michael; Tamassia, Roberto - 2007, 159 p.]

Para isso usamos a Notação Assintótica, um bom exemplo: Big-O (veja definição aqui: [Luiz Vieira - 56868], muito bem respondida por sinal), ômega: Ω e theta: θ são bem convenientes porque permitem a concentração nos aspectos gerais, em vez dos detalhes.
Por que isso importa para ele?
Quando assumimos o papel, isto é, usamos o "boné" de programador é muito importante, na análise de algoritmos concentrar-se na taxa de crescimento do tempo de execução.
E é importante sabermos diferenciar algoritmos eficientes e ineficientes, é natural fazer esta distinção entre os algoritmos que rodam em tempo polinominal e aqueles que requerem tempo exponencial respectivamente.

Ou seja, faz-se a distinção entre algoritmos que rodam em tempo O(nc) para alguma contante c > 1 e aquele cujo tempo de execução é O(bn) para alguma contante b > 1. ([Goodrich, Michael; Tamassia, Roberto - 2007]).

Com base nisso podemos usar o gráfico de complexidade abaixo para fazer a distinção visualmente.

Figura: Gráfico que apresenta a relação da Notação Big-O e suas complexidades
FONTE: [Maniero - 268308]
E é claro que é importante para o programador saber que:

Pode-se usar a Notação Assintótica O (Big-O) para ordenar classes de funções por seu crescimento assintótico.

Isto é, se uma função f(n) precede uma função g(n) na sequência conforme a tabela abaixo:

f(n) é O(g(n))

Tabela: sequência ordenada das classes de funções por seu crescimento assintótico
FONTE: Elaboradas pelo autor da resposta.

Nota1: quanto a base matemática, diremos que devemos manter o hábito de praticar, fazendo listas de exercícios, das funções (fatos matemáticos) aplicáveis na análise de algoritmo.
Nota2: Na tabela cima, assumi o critério de eficiente e ineficiente apenas por ser bem convenientes porque é para concentração nos aspectos gerais, em vez dos detalhes.

Referência:
[Goodrich, Michael; Tamassia, Roberto -  2007], 4 ed. - Porto Alegre: Bookman © 2007, Estrutura de dados e algoritmos em Java: 4 Edição.
[Maniero - 268308], Stack Overflow , Resposta: Como melhorar o desempenho de meu código com "for"?. Acesso em: 14 jan. 2018
[Luiz Vieira - 56868], Stack Overflow , Resposta: Definição da notação "Big O". Acesso em: 14 jan. 2018

O que é assíntota?


Wait for vuex to load before loading the component with vue-chartjs

Question:

I'm loading the data from vuex, how do I make the component to load AFTER the vuex store loads? It only shows the chart when click away from the page and going back to the page that contains this component. How do I re-render the chart? I don't know how to use watcher that watches vuex states
Answer: Use v-if in the parent to conditionally render this component only when the chart data is ready.  For example, if the data is stored in chartData:
Parent

  <ChartComponent v-if="chartData"></ChartComponent>

data() {
  return {
    chartData: null
  }
}

Imagine that chartData is the data eventually set by the Vuex dispatch.  Now the child chart component won't be rendered until that async call has completed and the data is ready.
Also: You could show a loading element while you wait if you like with v-else.  Here's a basic element but you could use an animated icon, placeholder, a completely different component, etc.:

  <ChartComponent v-if="chartData"></ChartComponent>

Loading...

Comment: Yes what @Dan just said, simple solution that cant go wrong! if your daily variables are the vuex data that you want then add in the parent component v-if="dailyXYChart && dailyXYChartYesterday"


How to define listTree so that it returns a list containing all the elements in order?

Question: listTree :: Tree a -> [a]
listTree = foldTree f z
    where
    f x y z  = x + y + z
    z = []

This is what I have so far, but my f is wrong because the expected type is Tree a -> [a] but the actual is Tree [a] -> [a]
data Tree a
   = Tip
   | Bin (Tree a) a (Tree a)
   deriving (Show, Eq)

foldTree :: (b -> a -> b -> b) -> b -> Tree a -> b
foldTree f z Tip         = z
foldTree f z (Bin l x r) = f (foldTree f z l) x (foldTree f z r)

This is fold and data type for tree.
Need help with defining f.
Answer: First of all, combining lists uses ++ in haskell. + is only used for adding numbers. Second, the variable y is of type a, not [a], so you cannot use ++ on it directly.
listTree :: Tree a -> [a]
listTree = foldTree f z
    where
    f x y z = x ++ [y] ++ z
    z = []


Populating ERB template with hash fails with symbol as array index

Question: I'm trying to populate a json string using a hash that is built in a chef recipe but keep hitting the error 'Symbol as array index'.  My searches on stackoverflow and google have lead me nowhere and am just curious what's going on here.  I'm not great with Ruby so please forgive me if the code is a bit off.
Attribute file:
node.default[:server][:sumologic][:sources][:apache] = Hash.new
node.default[:server][:sumologic][:sources][:apache][:type] = "LocalFile"
node.default[:server][:sumologic][:sources][:apache][:name] = "Apache Logs"
node.default[:server][:sumologic][:sources][:apache][:path_expression] = "/var/log/httpd/*.log"
node.default[:server][:sumologic][:sources][:apache][:blacklist] = Array.new
node.default[:server][:sumologic][:sources][:apache][:blacklist] << "/var/log/httpd/access.log*"
node.default[:server][:sumologic][:sources][:apache][:blacklist] << "/var/log/httpd/error.log*"
node.default[:server][:sumologic][:sources][:apache][:blacklist] << "/var/log/httpd/ssl_request_log"
node.default[:server][:sumologic][:sources][:apache][:blacklist] << "/var/log/httpd/access_log"
node.default[:server][:sumologic][:sources][:apache][:blacklist] << "/var/log/httpd/error_log"
node.default[:server][:sumologic][:sources][:apache][:category] = "test-httpd"

Template erb file:
{
  "api.version": "v1",
  "sources": [
    <% sources.each do |source| %>
    {
      "sourceType" : "<%= source[:type] %>",
      "name": "<%= source[:name] %>",
      "pathExpression": "<%= source[:path_expression] %>",
      <% if defined?(source[:blacklist]) %>
      "blacklist": [
        <% source[:blacklist].each do |listed, index| %>
        <%  if index < source[:blacklist].length - 1 %>
        "<%= listed %>",
        <%  else %>
        "<%= listed %>"
        <%  end %>
        <% end %>
      ],
      <% end %>
      "category": "<%= source[:category] %>"
    },
    <% end %>

...

Recipe Code:
template '/opt/SumoCollector/sources.json' do
  source 'sources.json.erb'
  variables({
      :sources => node[:server][:sumologic][:sources]
  })
end

Answer: Your usage of chef attributes is a bit wrong. They are not hashes, but smarter, so you don't have to initialize them as Hash. Remove the line:
node.default[:server][:sumologic][:sources][:apache] = Hash.new

Also it's better to initialize array attributes in 1 operation:
node.default[:server][:sumologic][:sources][:apache][:blacklist] = [
  '/var/log/httpd/access.log*',
  '/var/log/httpd/error.log*',
  '/var/log/httpd/ssl_request_log',
  '/var/log/httpd/access_log',
  '/var/log/httpd/error_log'
]

Your error "Symbol as array index" comes from that in your case
<% sources.each do |source| %>
  "sourceType" : "<%= source[:type] %>",
  [...]
<% end %>

source is actually an array [:apache, <hash-like-object>], so calling source[:type] fails.
sources is actually a hash-like collection of attributes and you should handle it accordingly. If you change the line to be like that
<% sources.each do |key, source| %>

everything will work. Here key will be ":apache" and source will be equal to node[:server][:sumologic][:sources][:apache].
Comment: OP has showed it, it's the variables attribute of the template resource. Thoose  variables passed to the erb templates are local to the template instance, the syntax is  `@source[]` to access them (I'm unsure of what it gives with a global scope insted of local one.)
Comment: Thanks for your explanation, I read up on that and understand a bit more of what I was doing.  Everything is working correctly but I'm running into a problem accessing the blacklist with source[:blacklist].  puts source[:blacklist] gives me an array `"[\"/var/log/httpd/access.log*\", \"/var/log/httpd/error.log*\", \"/var/log/httpd/ssl_request_log\", \"/var/log/httpd/access_log\", \"/var/log/httpd/error_log\"]"` so I'm working through that issue now.


db_query for a specific titles

Question: I'm building a custom module for webform and I want to get only a title for a specific content type.
In phpMyAdmin with sql query I've managed to sort what titles I need. This is the SQL query:
<code>SELECT title FROM `node` WHERE TYPE = 'outlets' AND uid
</code>
How can I wrap this into db_query() ?
Answer: You can read more about db_query() here.
<code>$result = db_query("
  SELECT title
  FROM {node} n
  WHERE n.type = :type
    AND n.uid =:uid
", array(':type' => 'outlets', ':uid' => $uid));

foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}
</code>

db_query for a specific titles


sequences and hyperplanes

Question: Consider a linearly independent sequence $(x_n)$ in a separable Banach space. Can we always find a closed hyperplane $H$ and and a finite non empty subset $F$ of $\mathbb{N}$ such that $\{x_j: j\in \mathbb{N}\setminus F\}\subset H$.  In others words, $H$ contains all but possibly finitely many members of the sequence.
If the closed span of the sequence is not the entire Banach space, then the answer is clearly yes.
My question seems to be connected to this one:
Sequence avoiding hyperplane
Comment: Am I missing something? Doesn't that link answer your question? A hyperplane that does not contain any point of the sequence does not contain finitely many points of the sequences right?
Comment: Your "In other words" isn't right: "$X$ does not contain finitely many members of $Y$" means "$X$ contains infinitely many members of $Y$". This is a weaker statement than "$X$ contains all but finitely many members of $Y$".
Comment: @RobArthan I edited the question to make it more clear.
Comment: @PrahladVaidyanathan You are right, the way I phrased it was confusing, hopefully now is more clear.
Comment: If the space is separable, consider a dense sequence. Every closed hyperplane misses infinitely many points of the sequence (if the hyperplane need not be closed, I don't know whether it might be possible). If the space is not separable, the closed space spanned by the sequence is not the entire space, so then it's possible.
Comment: @DanielFischer You are right. I added that the sequence is linearly independent. Sorry for moving the goal post. :)
Comment: @Markus, why don't you throw away $x_1$ and set $H:=\operatorname{cl span}\{x_2,\ldots,x_3\}$
Comment: @Norbert Even if you throw away a vector, that still might be the whole $X$.
Comment: @Markus Again, I do not understand why the link provided above doesn't answer your question?
Comment: @Norbert The hyperplane in the link misses all points. I want it to contain all points, except maybe finitely many.
Comment: Ok I've indicated this in your question
Comment: @Norbert I don't think your edit (non-empty) makes any difference. $F$ could be empty, so $H$ would contain ALL members of the sequence. That is not possible however, just take Banach space with a basis. No hyperplane can contain the basis. So, a posteriori, if such an $F$ exists it must be non-empty.
Comment: But anyway it is correct and more clear question equivalent to the original one.
Answer: Let $X$ be a Banach space with a normalized basis $(e_n)_{n=0}^{\infty}$ and consider, for each $n$, the vectors:
$$
x_n:=e_0+\frac{\lambda_n}{1!}e_1+\frac{\lambda_n^2}{2!}e_2+\dots...
$$
Where $\lambda_n\to 0$, and $\lambda_p\neq\lambda_n\neq 0$ for any $n,p$. It is easy to see that $(x_n)$ is linearly independent.
Let $(x_{n_k})$ be any subsequence of $(x_n)$. Then:
$$
   x_{n_k}\to e_0, \text{ so } e_0\in[x_{n_k}]
$$
$$
  \frac{1!}{\lambda_{n_k}}(x_{n_k}-e_0)\to e_1,  \text{ so } e_1\in[x_{n_k}]
$$
and so on, we obtain that for any $n$, $e_n\in[x_{n_k}]$. Therefore $[x_{n_k}]=X$. This means that any hyperplane can contain at most finitely many vectors form the sequence $(x_n)$.
Comment: How does this correlate with the OP's question? Your $x_n$ don't seem to have any connection with the $x_n$ that are data in the question. What justification do you have for the claims you make about limits of subsequences of the $x_n$?
Comment: I show that ANY subsequence spans the entire space, by showing the unit vector basis are in the span. Therefore, no closed hyperplane (or any closed proper subspace for that matter) can contain a subsequence. Thus, the sequence I provided answers the OP question in negative.

sequences and hyperplanes


How delta table support SQL queries?

Question: If we create a delta table(let's say in Azure ADLS), then the data is stored into ADLS in parquet file format. How are we able to use SQL queries on the stored data? Does Spark convert SQL queries into Java code internally?
Answer: SQL isn't supported by Delta directly, but it's a part of some engine, like, Apache Spark that translates SQL commands into the corresponding execution plan and executes it.  Spark supports many other file formats - CSV, JSON, Delta, Parquet, ..., and mostly works the same, but some file formats, like, Delta can implement additional optimizations, like, avoiding reading of not necessary data files, etc.

How delta table support SQL queries?


E/AndroidRuntime error with ImageButton

Question: I'm trying to handle 3 ImageButtons on my onClick function. but my application crashes and that's what I get on my logcat :
03-17 21:30:25.372: E/AndroidRuntime(17838):    at me.hicham.resume.HomeFragment.onCreate(HomeFragment.java:32)

it points to the line where i've set my ImageButton :
ImageButton fb_button = (ImageButton) getView().findViewById(R.id.button_facebook);

I don't see what might cause this problem (logcat error is not clear enough).
here is my class :
package me.hicham.resume;

import android.support.v4.app.Fragment;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import me.hicham.resume.R;

public class HomeFragment extends Fragment implements OnClickListener {

public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    ImageButton fb_button = (ImageButton) getView().findViewById(R.id.button_facebook);
    fb_button.setOnClickListener(this);

    ImageButton tw_button = (ImageButton) getView().findViewById(R.id.button_twitter);
    tw_button.setOnClickListener(this);

    ImageButton ln_button = (ImageButton) getView().findViewById(R.id.button_linkedin);
    ln_button.setOnClickListener(this);
    return rootView;
}

public void onViewCreated (View view, Bundle savedInstanceState){
    /*cool stuff in here*/

}
@Override
public void onClick(View v) {
    Intent socialintent;

    if (v.getId()== R.id.button_facebook){
        socialintent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
        this.startActivity(socialintent);

    }
    else if (v.getId()== R.id.button_twitter){
        socialintent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
        this.startActivity(socialintent);

    }
    else if (v.getId()== R.id.button_linkedin){
        socialintent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
        this.startActivity(socialintent);

    }
}

}

Thanks for the help guys :)
Answer: You should make all of your findViewById calls on rootView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    ImageButton fb_button = (ImageButton) rootView.findViewById(R.id.button_facebook);
    fb_button.setOnClickListener(this);

    ImageButton tw_button = (ImageButton) rootView.findViewById(R.id.button_twitter);
    tw_button.setOnClickListener(this);

    ImageButton ln_button = (ImageButton) rootView.findViewById(R.id.button_linkedin);
    ln_button.setOnClickListener(this);
    return rootView;
}

E/AndroidRuntime error with ImageButton


So I've installed FirebugForDrupal (updated)

Question: I installed the browser plug in and module in drupal. On this (development environment) I gave authenticated users access to the 'Access Firebug Debug' permission. Site Admin has access to that and 'Execute Firebug PHP'.
Browser/Client

Firefox 17.0.1
Ubuntu 11.10
Firebug 1.11.0
DrupalForFirebug 0.0.8 2.0
Logged in as User 1

Server (development box)

Drupal 6.25
Redhat 5.8
PHP 5.3.3

UPDATE:
Just this morning DfFB released it's 2.0 version. I spun up the DfFB module again, ran cron, and cleared cache. In the source code of my page, I can now see
's  with class names such as drupalforfirebug_general and drupalforfirebug_sql. So it appears that information is binging handed to the browser from Drupal.

UPDATE 2:
I switched to DfFB 2.0a and this what I see.

Is this what I'm supposed to see?
Comment: Are you actually logging anything?  FWIW, that module has caused me nothing but grief.  Not sure if recent versions are any better that the last time I used it.
Comment: Should I give up and go xDebug?
Comment: I can echo what @MPD said, that module is not good for one's sanity. If xDebug is an option, definitely go for that
Comment: I'm old school.  I just stare at code and debug with print as needed.
Comment: Well 2.0 was *just* released today https://addons.mozilla.org/en-US/firefox/addon/drupal-for-firebug/versions/?page=1#version-2.0 Trying this now
Answer: It seems the extension is not compatible with Firefox 14. The issue report has been opened on July 19, 2012, and it still is open.
The last comments from one of the co-maintainers of the module say:

unfourtunatly no, currently the new (from the ground up) plugin registers itself with firebug and firefox; it displays the drupal tabs and subtabs. But it doesn't gather the data from the drupalforfirebug drupal module yet.
Once it is ready I will package it as an xpi and allow it to be downloaded from bitbucket while mozilla reviews the update. I should be done sometime this week.

So now the code on bitbucket is functional. I wouldn't call it testable -- still hanging around pre-alpha.
Before I we call it testable I need to do two things.

Further abstract the connection between the Drupal Module and the Firefox Module. Right now the presentation layer calls the connector that returns the content directly. However, once I abstract that connection to an API call layer then changes to the API will be less problematic for Firefox plugin to deal with.
Remove the dependency on jQuery for the plugin. Currently the plugin loads jQuery to deal with a couple of UI niceties.<-- this is what is blocking the release.

By all means though, If you know how to install from code a firefox plugin then please do so. It works just like the old one for the time being.
Comment: Speaking of timing... DfFB 2.0 was released this morning. I'm putting any notes in the update above while testing today.
Answer: The Drupal variable/object you have in the pic could be had by just typing console.log(Drupal) on the console tab in FireBug. It's the Drupal JavaScript object that's recommended to be extended. eg if you run console.log(Drupal.behaviors) you'll see all the JavaScript functions that get called by Drupal on page load.
Anything specific you're trying to debug?
Just to make sure you've seen:
http://drupal.org/project/devel
http://drupal.org/project/devel_themer
http://drupal.org/project/search_krumo
Comment: FYI There's dsm is now `dpm($var, 'optional string')`, http://api.drupal.org/api/function/dpm/7 . Also to prevent the memory issue, you could get a list of keys, php `dpm(array_keys($var))` and then `dpm` that specific key  `dpm($var['key'])`.
Comment: I adore the devel_* modules and use them often. I am was trying to debug theme preprocess function using print_r() and dsm(). However, I'm running out of memory when I do so. I'm marking this correct (and upvoting this and kiamlaluno's response) because the work around is to set a variable and analyze it in devel_themer variable tree.


How to change rotation direction in three.js

Question: I'm new to three.js and having trouble finding documentation on how to change rotation direction. The current rotation is set so the sphere looks like it's spinning towards the viewer on a screen but I want it to rotate in a clockwise direction, so it looks like it's spinning from a side view if a viewer is looking at it.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 500 / 400, 1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 400);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry);
scene.add(cube);

camera.position.z = 10;
var render = function () {
    requestAnimationFrame(render);
        cube.rotation.x -= 0.10;
    cube.rotation.y += 0.00;

    renderer.render(scene, camera);
};

render();

http://jsfiddle.net/SF9tX/1968/
Answer: If I understand your question correctly, then rotation around different directions (or axis') can be achieved by incrementing different components of the objects rotation vector.
So for example, if you want to rotate the cube around the y-axis (ie to create a "spinning globe" effect) you can increment the .y component of the .rotation vector, as follows:
var render = function () {

    requestAnimationFrame(render);

    // This was casuing rotation around about the x-axis
    // cube.rotation.x -= 0.10;

    // Add this to cause rotation around the z-axis,
    cube.rotation.z += 0.10;

    renderer.render(scene, camera);
};

Comment: Hi!
Sorry I wasn't clear. The spinning globe effect is not what I want. I want it to look like as if there is a ball rolling across a floor but you are looking at it from the side. The original code is like as if a ball was rolling towards you instead.

So with the original code as my reference, I assume I would either need to add code in there to change the camera orientation so it pans around to the left and keep the rotation code intact or change the axis rotation so I'm "turning the ball" 45 degrees on the x axis plane to the right.
Answer: Ah I figured it out. It's as simple as replacing the cube.rotation.x to cube.rotation.z, so:
camera.position.z = 10;
var render = function () {
    requestAnimationFrame(render);
            cube.rotation.z -= 0.10;
   cube.rotation.y += 0.00;

    renderer.render(scene, camera);
};


Taking Twilio calls in a new Popup window

Question: I am facing a scenario where live Twilio call gets dropped, if the browser window in which call is received is reloaded. Is there a way to overcome this set-back without affecting the live calls?
Answer: Twilio Evangelist here.
Based on your question, I assume you are using the Twilio Client JavaScript SDK?  If that is indeed the case, then unfortunately, if the page thats hosting the SDK gets reloaded the connection between the browser and Twilio will drop since the browser is reloading everything, including the JavaScript SDK.
There are a couple of different techniques I can think of off the top of my head that you can use to help avoid page reloads, and another idea that could help you recover a call where the connection to the browser has dropped because of a page reload.  A lot of this is going to depend on your specific app and the experience you are trying to create for your users.
So to help avoid having to reload the page:
1) Use AJAX requests to your server in order to avoid page reloads.  If your page includes content like a form, or you want to update the page content with data form the server, you can look using AJAX requests to the server instead of a normal full page postback to submit the form, or to retrieve the data form the server.  This would help in avoiding having to reload the entire page in those two scenarios.
2) Use an iFrame to host your page content, and then put the Twilio SDK in the parent page (the one that defined the iFrame).  This would let you reload the content hosted in the iframe, without having to reload the entire host page, avoiding a reload the the Twilio library.  The downside to this is that communicating between content in an iframe and its host can get really messy fast.
Neither of these two techniques is fool-proof.  Obviously a user can always just hit the refresh button on their browser, and thats going to cause the connection to drop.
In a case where the page does get reloaded, and the connection from Twilio to the browser gets dropped, one idea is to leverage Twilios  capability to help reconnect the caller together.  When a user calls your twilio phone number, instead of connecting them directly to the Twilio Client running in the browser (by dialing a client with <Client>), instead dial that caller into a conference <Conference>, and then have the browser client connect into that same conference.  The benefit to that is if the browser disconnects, the original caller won't get hung up on, they will still be sitting in the conference room.  As long as you've saved the Conference SID or name, you can have the browser client reconnect to that conference.
Hope that helps point you in the right direction.
Comment: Any new developments in the last 7 years that would allow the call to persist between page loads? The conference call suggestion is the least hacky solution, but still not ideal. I'd prefer to store the connection to Twilio within the browser itself somehow, avoiding the disconnect on page-load.
Comment: Has anyone found a way to overcome this?


How to complete this proof involving factorials

Question: Recently I came across the following identity, but if I try proving it with induction, then I get stuck.

$$n! = \sum^n_{k=0}(-1)^{n-k}\binom{n}{k}(k+1)^n$$

While trying my induction step I get the following:

$$(n+1)! = (n+1)\sum^n_{k=0}(-1)^{n-k}\binom{n}{k}(k+1)^n$$
$$(n+1)! = \sum^n_{k=0}(-1)^{n-k}\binom{n+1}{k+1}(k+1)^{n+1}$$
$$\vdots$$
$$(n+1)! = \sum^{n+1}_{k=0}(-1)^{n+1-k}\binom{n+1}{k}(k+1)^{n+1}$$

(Question) How do I complete the proof?
Thanks in advance.
Answer: This is quite tough to show using induction. BUT ...
Using the $[x^k]:f(x)$ to represent the coeficient of $x^k$ in the power series for $f(x)$.
Note that
\begin{eqnarray*}
\frac{(k+1)^n}{n!} =[x^n]: e^{(k+1)x}.
\end{eqnarray*}
Now divide your equation by $n!$ and we have
\begin{eqnarray*}
\sum_{k-0}^{n} (-1)^{n-k} \binom{n}{k}\frac{(k+1)^n}{n!} &=&[x^n]: \sum_{k-0}^{n} (-1)^{n-k} \binom{n}{k} e^{(k+1)x} \\&=& [x^n]:e^x(e^x-1)^n =\color{red}{1}.
\end{eqnarray*}
Answer: Alternatively, and proceeding from a more general result, we have that
the Finite Difference of first order, and the next iterated ones, are defined as
$$
\eqalign{
  & \Delta _{\,x} f(x) = f(x + 1) - f(x)  \cr
  & \Delta _{\,x} ^n f(x) = \Delta _{\,x} \left( {\Delta _{\,x} ^{n - 1} f(x)} \right)
  = \sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{n - k} \binom{n}{k}f(x + k)}  \cr}
$$
Then, if $f(x)$ is a polynomial of degree $n$
$$
\eqalign{
  & f(x) = p_{\,n} (x) = a_{\,n} x^{\,n}  + a_{\,n - 1} x^{\,n - 1}  +  \cdots  + a_{\,0}  =   \cr
  &  = n!a_{\,n} \binom{x}{n}
 + \left( {n - 1} \right)!b_{\,n - 1} \binom{x}{n-1} +  \cdots  + b_{\,0}  \binom{x}{0} \cr}
$$
the $n$th order Difference will leave only the leading coefficient in the Newton expression, i.e.
$$
\Delta _{\,x} ^n p_{\,n} (x) = n!a_{\,n} \binom{x}{n-n} = n!a_{\,n}
$$
This for whichever $p_n(x)$ and in particular for $ x^n$ (then computed at $x=1$).


Remover acentos (javascript)

Question: Tenho este script abaixo com a função toLowerCase();
Gostaria de adicionar uma outra função à função toLowerCase();
Como ficaria a linha com as duas funções juntas?

Remover acentos (javascript)


How can I specify a row in awk in for loop?

Question: I'm using the following awk command:
my_command | awk -F "[[:space:]]{2,}+" 'NR>1 {print $2}' | egrep "^[[:alnum:]]"
which successfully returns my data like this:
fileName1
file Name 1
file Nameone
f i l e Name 1

So as you can see some file names have spaces.  This is fine as I'm just trying to echo the file name (nothing special).  The problem is calling that specific row within a loop.  I'm trying to do it this way:
i=1
for num in $rows
do
  fileName=$(my_command | awk -F "[[:space:]]{2,}+" 'NR==$i {print $2}' | egrep "^[[:alnum:]])"
  echo "$num $fileName"
  $((i++))
done

But my output is always null
I've also tried using awk -v record=$i and then printing $record but I get the below results.
f i l e Name 1

EDIT
Sorry for the confusion:  rows is a variable that list ids like this 11 12 13
and each one of those ids ties to a file name.  My command without doing any parsing looks like this:
     id      File Info      OS
     11      File Name1     OS1
     12      Fi leNa me2    OS2
     13      FileName 3     OS3

I can only use the id field to run a the command that I need, but I want to use the File Info field to notify the user of the actual File that the command is being executed against.
Comment: Why do you pass the output my_command back into the input of it -- or is that a posting typo?
Comment: that's a typo!  thx..
Comment: Running awk over the whole file every time through the loop just to extract one line is awfully inefficient.  What exactly are you trying to do?
Comment: @MarkReed I need to retrieve a list of fileNames using `my_command` and then tie a fileName to a num from a different command.
Comment: @MarkReed I see what you mean.  Thank you for that suggestion!
Comment: Start Again. Post your input and expected output and be clear. For example, when you say "My command..." are you talking about your tool named `my_command` or the whole script that calls the tool `my_command`. When you run the tool `my_command`, is it outputing excatly the same thing every time through the loop? Given your posted input and expected output there seems to be no point at all to the loop so why do you need it?
Comment: Actually, you'd be better of just posting a new question since you got an answer to your original question. You really should get help with the bigger picture though to get you on the right track.
Answer: I think your $i does not expand as expected. You should quote your arguments this way:
  fileName=$(my_command | awk -F "[[:space:]]{2,}+" "NR==$i {print \$2}" | egrep "^[[:alnum:]]")

And you forgot the other ).
EDIT
As an update to your requirement you could just pass the rows to a single awk command instead of a repeatitive one inside a loop:
#!/bin/bash

ROWS=(11 12)

function my_command {
    # This function just emulates my_command and should be removed later.
    echo "     id      File Info      OS
     11      File Name1     OS1
     12      Fi leNa me2    OS2
     13      FileName 3     OS3"
}

awk -- '
    BEGIN {
        input = ARGV[1]
        while (getline line < input) {
            sub(/^ +/, "", line)
            split(line, a, /   +/)
            for (i = 2; i < ARGC; ++i) {
                if (a[1] == ARGV[i]) {
                    printf "%s %s\n", a[1], a[2]
                    break
                }
            }
        }
        exit
    }
' <(my_command) "${ROWS[@]}"

That awk command could be condensed to one line as:
awk -- 'BEGIN { input = ARGV[1]; while (getline line < input) { sub(/^ +/, "", line); split(line, a, /   +/); for (i = 2; i < ARGC; ++i) { if (a[1] == ARGV[i]) {; printf "%s %s\n", a[1], a[2]; break; }; }; }; exit; }' <(my_command) "${ROWS[@]}"

Or better yet just use Bash instead as a whole:
#!/bin/bash

ROWS=(11 12)

while IFS=$' ' read -r LINE; do
    IFS='|' read -ra FIELDS <<< "${LINE//  +( )/|}"
    for R in "${ROWS[@]}"; do
        if [[ ${FIELDS[0]} == "$R" ]]; then
            echo "${R} ${FIELDS[1]}"
            break
        fi
    done
done < <(my_command)

It should give an output like:
11 File Name1
12 Fi leNa me2

Comment: Thanks, some weird things happened when I did the auto formatting...  I'm going to try your suggestions now.
Comment: You should also remove the `$` in `$((i++))` since you don't really intend to expand that to another command anyway but just increment the variable.
Comment: @inquisitor You could check my added solutions as well.
Answer: Shell variables aren't expanded inside single-quoted strings. Use the -v option to set an awk variable to the shell variable:
fileName=$(my_command | awk -v i=$i -F "[[:space:]]{2,}+" 'NR==i {print $2}' | egrep "^[[:alnum:]])"

This method avoids having to escape all the $ characters in the awk script, as required in konsolebox's answer.
Comment: I actually thought about that only that I found the quoting simpler than adding another variable with another argument. For more complex solution `-v` would be a preference. Other than that it could be anyone's.
Answer: It's pretty inefficient to rerun my_command (and awk) every time through the loop just to extract one line from its output.  Especially when all you're doing is printing out part of each line in order. (I'm assuming that my_command really is exactly the same command and produces the same output every time through your loop.)
If that's the case, this one-liner should do the trick:
paste -d' ' <(printf '%s\n' $rows) <(my_command |
  awk -F '[[:space:]]{2,}+' '($2 ~ /^[::alnum::]/) {print $2}')

Comment: `rows` is a variable that contains a list of ids I need to tie together with a specific `fileNames`.
Comment: then it would need to be `$rows` (or, if it's an array, `"${rows[@]}"`).
Answer: As you already heard, you need to populate an awk variable from your shell variable to be able to use the desired value within the awk script so thi:
awk -F "[[:space:]]{2,}+" 'NR==$i {print $2}' | egrep "^[[:alnum:]]"

should be this:
awk -v i="$i" -F "[[:space:]]{2,}+" 'NR==i {print $2}' | egrep "^[[:alnum:]]"

Also, though, you don't need awk AND grep since awk can do anything grep van do so you can change this part of your script:
awk -v i="$i" -F "[[:space:]]{2,}+" 'NR==i {print $2}' | egrep "^[[:alnum:]]"

to this:
awk -v i="$i" -F "[[:space:]]{2,}+" '(NR==i) && ($2~/^[[:alnum:]]/){print $2}'

and you don't need a + after a numeric range so you can change {2,}+ to just {2,}:
awk -v i="$i" -F "[[:space:]]{2,}" '(NR==i) && ($2~/^[[:alnum:]]/){print $2}'

Most importantly, though, instead of invoking awk once for every invocation of my_command, you can just invoke it once for all of them, i.e. instead of this (assuming this does what you want):
i=1
for num in rows
do
  fileName=$(my_command | awk -v i="$i" -F "[[:space:]]{2,}" '(NR==i) && ($2~/^[[:alnum:]]/){print $2}')
  echo "$num $fileName"
  $((i++))
done

you can do something more like this:
for num in rows
do
  my_command
done |
awk -F '[[:space:]]{2,}' '$2~/^[[:alnum:]]/{print NR, $2}'

I say "something like" because you don't tell us what "my_command", "rows" or "num" are so I can't be precise but hopefully you see the pattern. If you give us more info we can provide a better answer.


IOS How to shake to change View

Question: I've already know how to catch the shake gesture with the code below
<code>    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if ( event.subtype == UIEventSubtypeMotionShake )
    {
        // Put in code here to handle shake
        NSLog(@"Device Shaked");

    }

    if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
        [super motionEnded:motion withEvent:event];
}
</code>
The NSLog shows that it did received the shake
but how to push another view,or back to the last view, as we know the code below can only use in ViewController class instead of View class,   this Leavesview is handle by a LeavesviewController, and I use this viewController in another PDFViewController to display, so how could I make it jump to another view or dismiss back???
<code> UIViewController *myView = [[UIViewController alloc]init];
   [self.navigationController pushViewController:myView animated:YES];
</code>
Answer: <code>See this complet Code......

      - (BOOL) canBecomeFirstResponder {
            return YES;
        }

        - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {

            if (event.subtype == UIEventSubtypeMotionShake)
            {
                // Work which you want
            }
        }

    also dont forget these two methods...

    -(void)viewDidAppear:(BOOL)animated{
        [super viewDidAppear:animated];
        [self becomeFirstResponder];

       }

    -(void)viewDidDisappear:(BOOL)animated{
        [super viewDidDisappear:animated];
        [self resignFirstResponder];
    }
</code>
Comment: I don't think the resign in `viewDidDisappear:` should be called. It's harmless, but we don't usually add code to resign the first responder. But otherwise, great answer.
Answer: Ok, Obviously I am just a starter 2 months ago. Also, obviously the answer is the Delegation;

IOS How to shake to change View


Equality of localization by consideration of primes

Question: I am working through a number theory proof and there is one part whose justification I do not fully understand. I believe the reasoning is merely something related to localization.

Suppose $R$ is a Dedekind domain with fractions $K$. Let $L/K$ be normal with $G$ Galois group. Denote $R'$ the integral closure of $R$ in $L$. Let $\beta$ be a nonzero prime of $R'$, $p = R \cap \beta$ its contraction. Let $N$ denote the norm of an ideal, defined to be
  $$N(\mathfrak{a}) = \sum_{a \in \mathfrak{a}} RN(a)$$
  I wish to show $N(\beta)$ is a power of the prime $p$. Suppose not, that $N(\beta) = qm$ with $q \ne p$ prime and $m \subseteq R$. Let $C$ be the complement of $q$ in $R$ so that $R_q = R_C$. Since $q \ne p$, the prime ideal $\beta$ is not a factor of $qR'$. Thus $\beta_C = R'_C$ as the only prime ideals of $R_C '$ are the extensions of the primes appearing in the factorization of $qR'$.

I understand that if $S$ is a multiplicative set and we localize $S^{-1} A$ a ring with respect to $S$, then the primes in the localization correspond bijectively to the primes of $A$ such that $p \cap S = \emptyset$. In the case $S = R - q$, then this corresponds to the primes contained within $q$. The images then correspond to the primes appearing in the factorization of the image of $q$, namely $qR'$. I understand that since $q \ne p$, then $\beta$ is not a factor of $qR'$. I don't see how one puts this together to get the desired equality.
I am thinking that one shows the set of prime ideals on each side is the same and since $\beta \subset R'$, then this would show that their localizations are the same.
Comment: Your definition of norm is not clear: what is $N(a)$ for $a\in \mathfrak a$?
Answer: You just need to note that no prime $q\ne p$ divides $N(\beta)$ because $\Bbb Z$ has unique factorization. What the proof is doing is just saying another prime dividing $N(\beta)$ would imply that $qR'\supseteq N(\beta)$, but then take norms again and you get $N(N(\beta)) = q^{[R':R]}$ is a power of a different prime, $q$. But this is a contradiction to the fact that $(p)\supseteq\beta$.


Different types of grace notes

Question: This is a definition of a grace note from a Thompson piano course book:

But if they don't have any time value, why do I see grace note of different time values?
 In this picture there is an eighth grace note, but often I also see sixteenth grace notes.
Is there a difference in playing the two types?
Comment: To say that grace notes "have no time value" is useless and indeed meaningless. Grace notes and other ornaments use part of the time allocated to the principal note.
Comment: This is also known as a "Acciaccatura", not to be confused with "Appoggiatura".
Answer: Thanks for your good question. I didn't realize that there was so much to a grace note.
I culled the following from the article Embellishments – The Grace Note – Part 24f.
I think you should read the whole lesson as it really covers it all but here is what appears to answer your question.

The Grace Note – Movement, Placement and Duration
When describing the simple grace note, it is important to point out that the principal note is the note which ends the grace activity or movement, filling the total duration of a beat within a measure of music.
Some Reference Material
The number of beats and the note shape needed to fill one beat within
  a measure of music is determined by the time signature. In 4/4 time,
  there are four beats in a measure and a quarter note gets one beat,
  for example.

The duration of a beat is determined by the tempo set for the music. Tempo is time related and the tempo r̲a̲t̲e̲ is assigned to music by the composer. The tempo rate is measured in beats per minute.

Following our example of the 4/4 time signature, if a tempo of 120
  beats per minute is chosen, the four quarter notes are performed at
  the same r̲a̲t̲e̲ as if there were 120 quarter notes in a single measure
  of music. The 4/4 time signature specifically designates that there
  are only four beats in a measure. With a designated tempo of 120 bpm,
  the speed or rate at which the four quarter notes are performed is
  thus established.
Timing and the Grace Note
The auxiliary note embellishes or ornaments its principal note. Also,
  the grace note gets its time from the principal note's duration or
  time value, which is determined by its shape and the tempo of the
  music. In our examples, the principal note is shown as a quarter note
  which normally fills the timing of the beat. When a grace note is
  applied to the principal note they share the timing of the relative
  beat. In this way both the auxiliary note and the principal note are
  played on the same beat. The number of beats within the measure does
  not change and the timing or tempo of the beats is not altered either.
  The main point is the following.

The principal note's duration is divided between the auxiliary note and the principal note. The grace note gets only a fraction of a beat and the remaining fraction of the s̲a̲m̲e̲ beat is allocated to the principal note. Its actual duration is determined by both tempo and note shape.

Also, a grace note's duration is somewhat flexible. Depending upon the
  ornament type and which type of grace note is in use. The fraction of
  the beat assigned to it can be determined either at the discretion of
  the performer, if rhythmically correct, or as determined and written
  into the score by the composer. If designated by the composer, then
  the simple grace note's duration is to be performed as written and
  still, its duration is relative to the type of grace note in use and
  the choices made by the performer, if given an artistic license to do
  so.
Some of the grace ornaments are made up of more than one grace note.
  In these cases, the number of notes appearing in the ornament alters
  both the note shape used for the included notes but the duration of
  the embellishment is not changed.
Collectively all of the grace notes in these types of ornaments are
  played sharing the total beat duration with their relative principal
  note. An example would be the acciaccatura. This idea will be explored
  further in our presentation on the acciaccatura grace ornament.
If left unmarked, the grace note and its duration remains a
  non-specified fraction of the beat and of no predetermined duration
  other than the fact that it shares the same beat and timing with its
  principal note. To a degree the grace note is flexible and subject to
  personal and/or performance preferences. Some additional distinctions
  need to be made.
Answer: It should be noted that performance practice in some cases (Mozart in particular) calls for the grace note to be played as written. For example, as http://www.clarinet.org/clarinetfestarchive.asp?archive=46 points out, Mozart notated a run in the Clarinet Concerto that's invariably played as four sixteenth notes as sixteenth grace, eighth, and two sixteenths.
Comment: Since moved to http://clarinet.org/wp-content/uploads/2016/03/Koons-Mozart-Editions.pdf, btw.

Different types of grace notes


Uniformly quasi-isometric patches over classes of Riemannian manifolds

Question: Suppose $(M^d,g)$ is a closed, connected Riemannian manifold.
Is there a constant $R > 0$ such that for all $z \in (M,g)$, for all $x \in B_R(z)$, \begin{equation} \frac{1}{2} \lVert \xi \rVert_{\mathbb{R}^d}^2
\leq \sum_{ij} g^{ij}(x) \xi_i \xi_j
\leq 2 \lVert \xi \rVert_{\mathbb{R}^d}^2 \end{equation}
 for all $\xi \in \mathbb{R}^d$, where $g^{ij}(\cdot)$ is expressed in exponential coordinates centered at $z$?
My real question is this: can a constant $R>0$ be found satisfying the same inequalities
for all closed, connected $d$-dimensional Riemannian manifolds whose sectional curvatures are bounded both below and above?
Answer: I haven't done much with the metric tensor, but you can resolve this problem by compactness. Either the $g^{ij}$ approach $\delta_{ij}$ (actually, just have to approach values between 1/2 and 2 on the diagonal and be sufficiently small off the diagonal) as you approach $z$ or they don't.

If they do, then around each $z$ pick an $R$ sufficiently small that the inequalities hold at $z$ and in the ball of radius $R$, then cover the space by all balls at different $z$'s with radius $R/2$. Choose a finite subcover (centered at $z_1,...,z_n$ with radii $R_1/2,...,R_n/2$), and let $R'$ be the smallest $R_i/2$. Then $R'$ works, since every ball of radius $R'$ lies entirely in one of the balls around $z_i$ with radius $R_i$, so the inequalities hold.
If the tensor doesn't approach the identity near enough as you approach $z$, then $x=z$ is a counterexample.

Edit: I researched it more; Since you are using exponential coordinates case 1 holds. (The metric tensor approaches the identity, according to https://physics.stackexchange.com/questions/20781/are-there-any-clear-and-expressive-plainword-sense-of-metric-tensor-components).


SDK manager and AVD manager acting funny

Question: I'm getting some weird things happening when I try to create an AVD or launch the SDK manager. I've been searching for about half an hour and I think I have it narrowed down. Both the SDK manager and AVD manager exist twice on my machine.
They both exist here:
C:\Users\EGHDK\android-sdks
and here:
C:\Users\EGHDK\android-sdks\tools\lib
I don't know how or when it happened, but I do know that it worked perfectly before and now it's misbehaving.
Shouldn't they only exist once? And if so... how do I go about deleting them?
EDIT:
Now I typed sdk manager into Win 7 search and I see it three times. Two likes I mentioned above and another in C:\Program Files (x86)\Android\android-sdk
Does that change anything?
Answer: They will exist in both in android-sdk as well as inside lib.
So nothing in wrong as it exist twice. Your problem will be something different.


How to know if a date is in an interval using lubridate?

Question: If I have a lubridate interval: "2010-02-20" %--% "2012-03-15"
How may I know if a date, say "2011-01-12", is in that range?
I am using lubridate and the tidyverse packages.
Answer: ymd("2011-01-12") %within% ("2010-02-20" %--% "2012-03-15")

# [1] TRUE

Answer: library(data.table)
ymd("2011-01-12") %between% c("2010-02-20", "2012-03-15")

library(dplyr)
between(ymd("2011-01-12"), "2010-02-20", "2012-03-15")


Unlimited access to posts through API for Facebook/Google+/Instagram

Question: For Facebook, Instagram, or GOogle+, is there a program we can participate in that lets us access all public posts through an API on these social media platforms? The public search puts a limit on how many posts we can retrieve so is there one that does not have a limit?
Comment: Contact one of the media partners that have access to Public Feed API at Facebook: https://developers.facebook.com/docs/public_feed/
Answer: Facebook and Instagram do not have any program which allows you to access unlimited earned (public) data. Both platforms have very tight (and monitored) rate limits.
Google+ - unsure.


Customize folder name using same descriptor maven assembly plugin for different format

Question: I am new to maven world and I am having some problems with maven assembly plugin. I want to use the same descriptor file to generate different format with custom name for "dir" format.
Following is my maven assembly plugin configuration :-
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
            <execution>
                <id>assembly</id>
                <goals>
                    <goal>single</goal>
                </goals>
                <phase>install</phase>
                <configuration>
                    <descriptors>
                        <descriptor>src/main/assembly/descriptor.xml</descriptor>
                    </descriptors>
                    <finalName>service</finalName>
                    <appendAssemblyId>false</appendAssemblyId>
                    <outputDirectory>target</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>

This is the descriptor file :-
<assembly
        xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>assembly</id>
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <baseDirectory>.</baseDirectory>
    <files>
        <file>
            <source>target/service.jar</source>
            <outputDirectory>.</outputDirectory>
            <filtered>false</filtered>
        </file>
        <file>
            <source>src/main/deploy/version.txt</source>
            <outputDirectory>.</outputDirectory>
            <filtered>true</filtered>
        </file>
        <file>
            <source>src/main/deploy/start.sh</source>
            <outputDirectory>.</outputDirectory>
            <filtered>true</filtered>
        </file>
        <file>
            <source>src/main/deploy/stop.sh</source>
            <outputDirectory>.</outputDirectory>
            <filtered>true</filtered>
        </file>
    </files>
</assembly>

I want to use the same descriptor file(basically same files to combine) into a service.zip and also create another folder in target named deploy if I add
<format>dir</format>

then it will create a folder named service under target and will have all the listed files. I want a way to customize the name of directory to "deploy". I tried checking with the documentation but could not find anything helpful unless I create another descriptor which is not the right way since my new descriptor will have same configuration as the previous one with just format as "dir".
Any help will be appreciated thanks in advance.
Answer: You can achieve your requirement by using different maven profiles. In
In your assembly descriptor, you use a property instead of a fixed string:
<formats>
    <format>${distributionFormat}</format>
</formats>

distributionFormat is defined in pom.xml. The name of the property is your choice.
In your pom.xml, you define distributionFormat in two different profiles. There you also define a name for the assembly (assemblyName in my example).
<project>
    ...
    ...
    <profiles>
         <profile>
              <id>distAsZip</id>
              <activeByDefault>true</activeByDefault>
              <assemblyName>service</assemblyName>
              <distributionFormat>zip</distributionFormat>
         </profile>
         <profile>
              <id>distAsDir</id>
              <activeByDefault>false</activeByDefault>
              <assemblyName>deploy</assemblyName>
              <distributionFormat>dir</distributionFormat>
         </profile>
    </profiles>
    ...
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
            <execution>
                <id>assembly</id>
                <goals>
                    <goal>single</goal>
                </goals>
                <phase>install</phase>
                <configuration>
                    <descriptors>
                        <descriptor>src/main/assembly/descriptor.xml</descriptor>
                    </descriptors>
                    <finalName>${assemblyName}</finalName>
                    <appendAssemblyId>false</appendAssemblyId>
                    <outputDirectory>target</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
 ...
</project>

Now you can execute maven and define the profile that you want to use:
mvn clean package -PdistAsDir or mvn clean package -PdistAsZip
Comment: Thanks @JimHawkins I was able to generate the required files.


No method to invoke USQL programmatically works

Question: When I run Powershell command to submit a USQL job
Import-AzureRmContext -Path "c:\temp\Azure.json"
$adla = Get-AdlAnalyticsAccount -ResourceGroupName "test" -Name "dla"
Submit-AdlJob -Account $adla -Name "test" –ScriptPath "C:\temp\temp.usql"

Submit-AdlJob returns error:
Message        : An error occurred while sending the request.
Data           : {}
InnerException : System.Net.WebException: The remote name could not be resolved: 'microsoft.azure.commands.datalakeanalytics.models.psdatalakeanalyticsaccount.azuredatalakeanalytics.net'
                    at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
                    at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)

When I try AzureCLI, it doesn't work - azurecli isn't found. I find the installation is really not working fine on Windows but workarounds don't work too.
When I try .NET, I also face issues.
Anyway, it'd be nice if Powershell worked. Any idea what's the solution ? (When I submit it using portal it works.)
Thanks!
Answer: At least for Powershell, your problem is the parameter -Account in Submit-AdlJob just wants the name of the ADLA account. You're passing in the entire object representing the ADLA account that you got from Get-AdlAnalyticsAccount.  Try resubmitting the job with just:
Submit-AdlJob -Account "dla" -Name "test" -ScriptPath "C:\temp\temp.usql"


Cosine of a measurable set has smaller measure

Question: Let $A$ be a measurable subset of $[0,1]$ such that $|A| >0$, i.e., $A$ has positive measure. Prove that the set $\cos(A) = \{\cos x: x \in A\}$ has strictly smaller measure than $A$.
The cosine graph tells us that the function is one-one at $[0,1]$ and clearly the measure of $[\cos 1,1]$ is smaller than $1$. But other than that I have no idea how to even begin. Any help would be appreciated.
Answer: $\displaystyle\int_{\cos(1)}^{\cos(0)}f(t)\,\text{d}t=\int_0^1f(\cos(x))\sin(x)\,\text{d}x$
where you can regard $f(t)$ as the indicator function of $\cos(A)$.
In this way, since $\cos(x)$ is a bijection from $[0,1]$ to $[\cos(1),\cos(0)]$,
we have that $f(\cos(x))$ is the indicator function of $A$.
$\\$
Now, how large is $\sin(x)$ for $0\leq x\leq 1$?
Comment: Well, the second integral is simply $|A|$, whereas for the first one, the value of $\sin x$ from $0$ to $1$ is, again, contained strictly within $[0,1]$. It sort of explains why the integral is smaller in value, but how do I write it out explicitly? I'm not very sure how do I compute the integral of the product of the indicator function with a function, or at least write it out nicely.
Comment: @KelvinLian $\displaystyle\int_{\cos(1)}^{\cos(0)}f(t)\,\text{d}t=\int_0^1f(\cos(x))\sin(x)\,\text{d}x$ works for all Lebesgue-integrable functions $f:[\cos(1),\cos(0)]\to\mathbb{R}$, including any indicator function of a measurable subset of $[\cos(1),\cos(0)]$.
Comment: @KelvinLian The change of variables theorem yields that for measurable $A \subset [0, 1]$, $$m(\cos(A)) = \int_{A}|\cos'(x)|\,dx.$$ Then a bound on the integrand gives the result.
Comment: @ChrisSanders I let $B$ denote the set $\cos A$, and $1_B$ be the indicator function. So the measure of $B$ is written as $\int ^{\cos 0}_{\cos 1}1_B(t)dt$. When you make the substitution $t = \cos x$, we get $\int ^1 _0 1_B(\cos x)\sin x dx$. I'm thinking of using $$\int^1 _0 1_B(\cos x) \sin x dx = \sin \alpha \int^1 _0 1_B(\cos x) dx.$$
Comment: By the injectivity of cosine on $[0,1]$, $1_B(\cos x)$ is actually the indicator function of $A$ (as you already mentioned), and so the above integral becomes $(\sin \alpha) |A|$, for some $\alpha \in [0,1]$. But the above equality works if both functions are continuous on $[0,1]$, which I don't think the indicator function will satisfy...
Comment: @KelvinLian yeah you can put it that way. Or just more directly, $g$ is a non-negative function, and $0\leq\sin(x)\leq\sin(1)<1$ for all $x\in[0,1]$; therefore $0\leq g(x)\sin(x)\leq \sin(1)g(x)$ for all $x\in[0,1]$; then take the integrals.
Comment: @ChrisSanders of course your way should've been the obvious way to do it... don't know why I would go out to look for another result. Thanks a lot.


Prove the equality of left and right coset of a group rigorously

Question:
Let $H$ be a subgroup of a group $g$. Show that if $g_1H = Hg_2$ then $g_2H=Hg_1$.

My attempt is the following:

$\forall h_1 \in H, \exists h_2 \in H$ such that $g_1h_1=h_2g_2$.
Since each element of a group has unique inverse, I obtain $ h_2^{-1}g_1=g_2h_1^{-1}$.
If I call $h_1^{-1}$ as $h_2^*$, $h_2^{-1}$ as $h_1^*$, then $\forall h_2^* \in H, \exists h_1^* \in H$ such that $h_1^*g_1=g_2h_2^*$.
Repeat this argument for every $h_2 \in H$, I obtain that $g_2H=Hg_1 \ \square$

Is my proof complete and rigorous?
Is there a better and more elegant proof you can provide?
Comment: To show that $g_2H=Hg_1$, I would start with a $g_2h\in g_2H$, and show that it's writable as $h'g_1$ for some other $h'\in H$. This will show that $g_2H\subset Hg_1$, and the reverse inclusion will be similar. I think your proof can easily be modified to do this, but to me, the logic is less clear in your current version than it might be. For my argument, see below.
Answer: My argument: The set $g_1H=Hg_2$ is both a left coset and a right coset of $H$. It's a right coset containing $g_1$, so it's equal to $Hg_1$; and it's a left coset containing $g_2$ so it's equal to $g_2H$.


Algebra question involving square?

Question: Find the area of a square in square inches whose side is 1.3 ft?
I keep getting this one wrong I would think that 1.3 feet is 16 inches and then multiply that by that by sixteen but that is not the correct answer.
Comment: $1.3$ feet is not $16$ inches.
Comment: $1.3$ feet is $1.3\cdot 12=15.6$ inches.
Answer: One thing that can help when doing unit conversions is properly setting up your fractions. In this case, you need
$$
\frac{1.3\text{ ft}}{1}\times \frac{12\text{ in}}{1\text{ ft}} = 15.6\text{ in}
$$
Now it's clear from the fractions that you have to multiply 1.3 by 12 to convert feet to inches. The area of a square is $s^2$ where $s$ is the length of a side, so the area is $(15.6)^2=243.36$ square inches (don't forget the units).

Algebra question involving square?