Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables?

Question: Here is the problem: I am making a machine learning algorithm that takes the inputs and outputs of some software I've written, and I don't know how many datalines to produce to get results that are a 'good' fit. I realize the answer is 'the more the better' but I'm looking for any sort of minimum requirement. I also realize that the greater the number of variables the greater the number of datalines required.
So I'm looking for a rule of thumb for number of variables to number of datalines.
Answer: in addition to Dikran Marsupial's excellent advise:
While there is no hard minimum requirement for the training data you need,

There is a rule of thumb that says that with 5* cases per variate in each class you can usually have a stable linear classifier. Now, stable doesn't guarantee good, but unstable will always be bad. Note however, that in many disciplines with very wide data, good models are trained with far less samples.
* I've also seen 3 and 6, but that's the same order of magnitude.
you can calculate minimum sample sizes required for testing: usually, building a good model is not sufficient. You also need to show that the model performs well. For relatively easy problems for which, however, only small sample sizes are available, this can actually be the harder part of the problem.
Not sure whether it applies to your scenario, though: you may be able to generate enough independent rows that this is not the concern.
Note also that classification performance measures that are proportions of test cases (overall accuracy, sensitivity, specificity, predictive values, precision, recall, etc.) are subject to very high variance and thus need large test sample sizes. This can also cause considerable difficulties with the learning curve (see the paper below for illustrations). Frank Harrell will tell you that better measures, e.g. Brier's score, should be used (see e.g. the discussion linked below). However, depending on your field, you may have to report the proportions.

Here's a paper we wrote about this: Beleites, C. and Neugebauer, U. and Bocklitz, T. and Krafft, C. and Popp, J.: Sample size planning for classification models. Anal Chim Acta, 2013, 760, 25-33.
DOI: 10.1016/j.aca.2012.11.007
accepted manuscript on arXiv: 1211.1323
See also: How large a training set is needed?
Answer: When you choose the sample number for training, you may consider the trade-off between bias and variance.
One purpose (among many) of training is to estimate the out-of-sample error Eout given the obtained in-sample error Ein. There is such generalization in VC analysis: Eout <= Ein + Omega (also known as Hoeding inequality written in a probability format). So people tend to experimentally observe the changes of Eout and Ein. What they found is: as the sample number increases, the Eout would finally converged to Ein with a simple model; while Eout also converges from a huge value to a relatively constant value as well with a complex model, but still larger enough than Ein. Such VC analysis curve can be equivalently viewed as a bias-variance trade-off curve which indicates the variance decreases as the sample number increases. You can refer this slide for more details.  On the other hand, the target complexity also influences on the generalization error. This slide shows a overfit measure as the number of data points changes. You can observe that if the target is complicated, increasing the sample number may not necessarily reduce the overfitting any more (the red region in the figures), yet it is still effective in reducing the overfitting if the target is not complicated.
As analyzed above, the training sample size is usually related to model complexity (number of variates) and target complexity, whereas test sample size can be estimated based on a required accuracy performance. Like @Dikran suggested, you need to try the effects by observing your own learning curve.
Answer: There are no useful rules of thumb for this as the number of patterns required strongly depends on the nature of the problem, in particular the more complex the form of underlying relationship between the variables, the more data you will need to estimate it, the more noise corrupting the data, the more data you are likely to need to average out the effects of the noise.  There is also a fairly strong dependence on the nature of the machine learning algorithm as well, if the technique is well suited to the problem you will need less data, if it is not well suited, you will need more data.
At the end of the day, there is no minimum amount of data that you need to perform inference, the more data you have the more confident you can be of your inference, but it is generally a smooth relationship.
I would advise generating a learning curve - a plot of the test set error as a function of the number of training patterns.  This will give you a good indication of the amount of data you will need to train your model, and whether you have already reached the point of diminishing returns.


É correto usar bootstrap na finalização de um projeto?

Question: Olá, então ouvir muitos dizerem que usar bootstrap na finalização de um projeto e errado, eu particularmente não gosto muito de trabalhar com front-end então tento pular essa parte buscando algum tema responsivo pronto e adaptou ao meu gosto, porém como já ouvir muitos dizerem que é errado gostaria de saber se isso realmente é verídico ? e se sim, porque ?
Comment: Não entendi qual a relação do Bootstrap com finalização de projeto, ainda mais dizer se é _errado_ (ou _correto_). O Bootstrap é apenas um framework.
Comment: O que exatamente você está "finalizando" se ainda não possui o front-end?
Comment: Então eu pego um tema bootstrap adapto e completo com meu projeto e aí vem a finalização no caso com esse bootstrap entendeu ?
Comment: @Sam Então e porque muitos me disseram que e errado usar o bootstrap na versão final ou seja aquela que já está pronto o projeto e pode ser posto no ar, e que o correto é usar quando estiver criando o projeto para o ajudar no desenvolvimento mais pelo o que estou vendo e correto e não tem problema algum
Comment: Se vc colocar no ar sem carregar as bibliotecas do Bootstrap não vai funcionar.
Comment: @Sam No caso seria quando for finalizar o projeto tirar o tema bootstrap e criar seu próprio tema ou usar um sem ser bootstrap, me colocaram ele só como auxílio entendeu agora ?
Comment: Netflix, CNN e Salesforce, entre vários, vários outros sites, usam Bootstrap. Na universidade onde eu trabalho tanto o lado institucional quanto a intranet usam bootstrap. Estou curioso em relação aos argumentos de que seu uso é 'errado'.
Comment: Acho que vc se refere pq um tema provavelmente não vai usar todas as classes do Bootstrap, então seria "errado" importar o Bootstrap inteiro em produção já que vc só vai usar 30% dele. Mas não se preocupe, a situação é muito pior para quem usa WordPress pode acreditar.... Isso tudo que falam é baseado em opinião, eu preifiro deixar ele lá inteiro e se no futuro precisar de alguma classe já sei que está lá. Mas se vc quiser fazer um PostCSS ou um PurgCSS fica por sua conta. Se é que eu entendi a sua pergunta
Comment: @OnoSendai não disse que e errado eu queria saber se é , me disseram que era
Comment: @hugocsl Compreendido muito bem obrigado!
Comment: @ThiagoBomfim nesse caso o ônus de justificativa está com quem fez a afirmação.
Comment: Se vc puder trazer pra gente quais os motivos que levaram essa pessoa a falar isso, seria interessante
Answer: Bootstrap é um framework front-end. Usar ele desde o início ou em outra frase do projeto não tem problema algum. Desde que o framework esteja configurado correto com todas as classes importadas, tu podes usar no momento que quiser, como quiser. Isso não é errado pois não interfere no funcionamento do seu projeto. Ele é criado para se facilitar o desenvolvimento e ser colocado em produção.


Bug na biblioteca whirlpool Python

Question: Instalei a biblioteca whirlpool no Python 3.6.5 e no Python 2.7.9 para calcular hashes com ela. No entanto, ela apresentou um problema inusitado: em conjunto com outras bibliotecas, ela funciona, e quando está só, não. Inserida nesse código, em Python 2.7.9, ela funciona:
from Crypto.Hash import SHA512
from Crypto.Hash import SHA384
from Crypto.Hash import SHA256
from Crypto.Hash import SHA224
from Crypto.Hash import RIPEMD
from Crypto.Hash import MD5
from Crypto.Hash import MD4
from Crypto.Hash import MD2
import whirlpool
import hashlib

a = raw_input("Digite a string: ")
b = SHA512.new(a).hexdigest()
c = SHA384.new(a).hexdigest()
d = SHA256.new(a).hexdigest()
e = SHA224.new(a).hexdigest()
f = RIPEMD.new(a).hexdigest()
g = MD5.new(a).hexdigest()
h = MD4.new(a).hexdigest()
i = MD2.new(a).hexdigest()
j = whirlpool.new(a).hexdigest()
l = hashlib.sha1(a).hexdigest()
print "SHA512 = ", b
print "SHA384 = ", c
print "SHA256 = ", d
print "SHA224 = ", e
print "RIPEMD160 = ", f
print "MD5 = ", g
print "MD4 = ", h
print "MD2 = ", i
print "Whirlpool = ", j
print "SHA1 = ", l

Porém, quando crio o seguinte programa com ela:
import whirlpool
a = raw_input("Digite a string: ")
j = whirlpool.new(a).hexdigest()
print "Whirlpool = ", j

ela apresenta a seguinte mensagem de erro:
E:\>python whirlpool.py
Digite a string: sete
Traceback (most recent call last):
  File "whirlpool.py", line 1, in <module>
    import whirlpool
  File "E:\whirlpool.py", line 3, in <module>
    j = whirlpool.new(a).hexdigest()
AttributeError: 'module' object has no attribute 'new'

Se no programa anterior, ele não apresentou problemas com o atributo "new", por que nesse apresentou? Lembrando que nesse caso o atributo "new" é o dele próprio, não de outra biblioteca. Já desinstalei e instalei novamente a biblioteca e o problema persiste. Que acontece neste caso?
Comment: Marcelo, você você rodou esse outro código no Python2? Pois fiz o teste aqui, e funcionou perfeitamente.
Comment: Olá, Daniel! No Python 2 ele funcionou, porém no Python 3 parece que há alguma incompatibilidade. Troquei o nome do arquivo de "whirlpool" para "whirlpool-hash" e deu certo, mas só em Python 2.
Answer: Uma coisa que pode estar dando problema é que o nome do arquivo está igual ao nome da biblioteca importada.
Tente mudar o nome do arquivo e executar novamente.
Comment: Valeu, Geraldo! Deu certo, mas só no Python 2. O Python 3 parece que tem alguma incompatibilidade com a biblioteca.

Bug na biblioteca whirlpool Python


Expansion of $(\frac{x+2}{x})^{-\frac{1}{2}}$ and then find an approximate value...

Question:
First, obtain the four terms in the expansion of $
(\frac{x+2}{x})^{-\frac{1}{2}}$ then let x = 100 and use the result
  to find an approximate value of $(\frac{450}{51})^{\frac{1}{2}}$.

I am stuck with this problem and would be very happy if someone could
help me how to move on with it...
Here is what I've attempted so far:
Factoring out $\sqrt{\frac{x}{2}}$ from the original equation. I ended
up with $\sqrt{\frac{x}{2}}(1+\frac{x}{2})^{-\frac{1}{2}}$.
I expanded it using this formula $
(1+x)^{n}=1+\frac{nx}{1!}+\frac{n(n-1)x^{2}}{2!}+\ldots $ and simplified
the resulting expansion.
My solution was $
\sqrt{\frac{x}{2}}-\frac{x^{\frac{3}{2}}}{4\sqrt{2}}+\frac{3x^{\frac{5}{2}}}{32\sqrt{2}}+\ldots
$ which is incorrect.
I feel there must be something simpler that I'm missing.
Answer: First, the binomial expansion: $$(\frac{x+2} x)^{-1/2}=(1+\frac 2 x)^{-1/2}$$ $$=1+\frac2 x(\frac{-1} 2)+(\frac 2 x)^2+(\frac{-1} 2)(\frac{-3} 2)+(\frac 2 x)^3(\frac{-1} 2)(\frac{-3} 2)(\frac{-5} 2)+(\frac 2 x)^4(\frac{-1} 2)(\frac{-3} 2)(\frac{-5} 2)(\frac{-7} 2)+...$$ $$=1-\frac 1 x+\frac 3 {x^2}-\frac 5 {2x^3}+\frac {35} {8x^4}-\frac {63} {8x^5}+...$$
Now, for x=100, we would simply have, $$=1-\frac 1 {100}+\frac 3 {100^2}-\frac 5 {2.100^3}+\frac {35} {8.100^4}-\frac {63} {8.100^5}+...$$
Consider $(\frac{450}{51})^{1/2}=(\frac{9\times 50}{51})^{1/2}=\sqrt 9(\frac 1 {1+1/50})^{1/2}=3(1+\frac 2 {100})^{-1/2}$, which can be calculated from the above expression using the first four terms after the initial "1" as 2.970442631
The actual value of $(\frac{450}{51})^{1/2}=2.9704426289...$
Answer: I wouldn't factor the way you did. The binomial expansion as a radius of convergence of 1, but with your factorisation, you have $\frac{x}{2}$, wich is clearly $>1$ when $x=100$.
Try to just rewrite $\frac{x+2}{x}$ as $1+\frac{2}{x}$, and then you can use the binomial expansion (because $|\frac{2}{x}|<1$ if x=100)


Why not perform weight decay on layernorm/embedding?

Question: I am learning the code of minGPT. In the function, the author excluded layernorm and embedding layer from experiencing weight decay and I want to know the reasons. Besides, what about batchnorm?
Answer: After some searching, I find some explanations:
karpathy's explanation and a disscusion in the pytorch forum.

@morganmcg1 the purpose of L2 regularization is to "spread out" the weights in dot products, ensuring that more "independent measurements" (dimensions of the input) get used more equally, instead of any one feature dominating the computation. This only makes sense for matrix multiply layers, which the embeddings and the layernorm parameters are not. L2 regularization is covered eg in CS231n.
Answer: The mechanism of weight decay seems to be not clearly understood in the research field. For example, a research paper [1] reported that "the regularization effect was concentrated in the BN layer.

As evidence, we found that almost all of the regularization effect of weight decay was due to applying it to layers with BN (for which weight decay is meaningless).

The reason why such an implementation is widely used in the first place might be that Google's public BERT implementation[2] and any other pioneer's works did so. However, since this trick is not described in the paper[3], I don't think there is clear evidence for it.
Therefore, I believe think there is no evidence beyond "that's what the pioneers did."

Note that, as discussed in the forum[4], the reason for excluding weight decay from updating Layer norm and bias might be based on the paper[5], where the author states "when Batch/Layer/Weight Normalization and weight decay are used together, weight decay regularization is not expected to be effective". However, this paper only points out that "setting |w|=1 avoids variation in the effective learning rate" and does not state whether weight decay should be disabled in the normalization layer.
Reference

[1] https://arxiv.org/abs/1810.12281
[2] https://github.com/google-research/bert/blob/master/optimization.py#L65
[3] https://arxiv.org/abs/1908.08962
[4] https://discuss.pytorch.org/t/weight-decay-in-the-optimizers-is-a-bad-idea-especially-with-batchnorm
[5] https://arxiv.org/abs/1706.05350


Can drush make fetch dependencies for a newly added module, without using it to build the whole site?

Question: If a module includes a drush make file to fetch its dependencies, is it possible to run that make file by itself somehow against a pre-existing site's codebase? In other words, I didn't use drush make to build the site, but I'd like to use it just to fetch the new module's dependencies. Is that possible?
Answer: Yes, it is possible. Just run the makefile on the current codebase, and specify --no-core option from the drupal root:
$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example

Here's the log of a test I did:
$ drush dl drupal
$ cd drupal-7.28/
$ drush dl mailchimp
  Project mailchimp (7.x-3.1) downloaded to /tmp/drupal-7.28/sites/all/modules/mailchimp.

$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example
  Make new site in the current directory? (y/n): y
  Beginning to build sites/all/modules/mailchimp/mailchimp.make.example.
  libraries-7.x-2.2 downloaded.
  mailchimp downloaded from https://bitbucket.org/mailchimp/mailchimp-api-php/get/2.0.4.zip.

$ ls sites/all/libraries/
  mailchimp
$ ls sites/all/modules/
  libraries  mailchimp  README.txt

If any of the projects/libraries declared in the makefile already exists, it will be overwritten.


Creating a PCL NET 4.0 gives me an error in Visual Studio 2015

Question: I am using VS 2015 Pro. If I create a new project Class Library (portable) Targeting:
NET Framework 4.0
Windows 8
all works fine.
BUT when I add to the targeting:
Windows Phone 8.1
the following two errors appear:

There was a mismatch between the processor architecture of the project
  being built "MSIL" and the processor architecture of the reference
  "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll", "x86".
  This mismatch may cause runtime failures.

And the Linq not found:

The type or namespace name 'Linq' does not exist in the namespace
  'System' (are you missing an assembly reference?)

(PS. I am sure that everything worked fine till I let Visual Studio 2015 update some Extensions)
NOTE If I target x86 the first error goes away, but the second remains.
1) What now is happening with the Windows Phone 8 and
where Visual Studio is loading the Windows Phone 8 assemblies?
2) How can I restore the Windows Phone 8 assemblies?

EDIT

EDIT2
IMPORTANT
If I change the targeting, and choose NET 4.0.3 the project compiles fine!

EDIT3 IMPORTANT
I have found that it has something to do with the Framework Profiles for NET portable, that are stored at:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETPortable
(link framework profiles
Using Package Manager Console for my project:
PM> $p.Properties.Item("TargetFrameworkMoniker").Value
.NETPortable,Version=v4.0,Profile=Profile328
In the folder for Profile328 I have noted that there aren't inside the .dlls
but only the .xml files... What happened?! How to restore?!
Comment: for Q1 . http://stackoverflow.com/questions/10113532/how-do-i-fix-the-visual-studio-compile-error-mismatch-between-processor-archit
Comment: Please see ["Should questions include "tags" in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"!
Answer: When you have the portable class library, you have this situation:
In the .NET assembly there is all library if you want.
Try to delete project and create new portable class library
Comment: In my project the References tab is empty... (it suggest to use Object browser ... but for what?) Please see my edit
Comment: I have tried to maually add the Linq reference from C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0
but nothing changes
Comment: No... I have been busy, sorry...
The problem is that I have created a new project (for investingating this issue). And the problem appear when I choose NET 4.0 and Phone 8.1
Comment: If I target NET 4.0.3 the project compiles fine!
(But for backward compatibility reason I can't change the targeting)
Where is VS2015 picking up the NET 4.0 and Phone 8.1 references...???
Comment: I use VS 2013 PRO, when I create the PortableClassLibrary I can choose the framework version. If i choose 4.0 my project run.


gulp-babel don't produce any output file or doesn't work properly

Question: I'm working on a JS library and I want to transpile all javascript code written in ES6 to ES5 standard to get more support in current browsers.
The thing is I want to use Babel with the Gulp tasks, so I've installed all this NPM packages [package.json]:
"devDependencies": {
  "@babel/core": "^7.1.2",
  "@babel/preset-env": "^7.1.0",
  "babel-cli": "^6.26.0",
  "gulp": "^3.9.1",
  "gulp-babel": "^8.0.0",
  "gulp-concat": "^2.6.1",
  "gulp-sourcemaps": "^2.6.4",
  "gulp-terser": "^1.1.5"
}

Next my .babelrc file has the following content:
{
  "presets": ["env"]
}

And the gulpfile.js is written as following:
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
const terser = require('gulp-terser');

gulp.task('minify', function () {
    return gulp.src('src/app/classes/*.js')
        .pipe(sourcemaps.init())
        .pipe(babel())     // I do not pass preset, because .babelrc do exist
        .pipe(concat('output.js'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('build/js'))
});

gulp.task('default', ['minify']);

The issue is when I execute the gulp command on the project root directory, it not produce output file. The console shows a successful execution but nothing appears inside build/js directory, or neither inside another directory of the project.
#user1:/project-route$> gulp
    [17:36:54] Using gulpfile /project-route/gulpfile.js
    [17:36:54] Starting 'minify'...

I also tried without sourcemaps functions and the result is the same, nothing!!!.
Answer: For an extrange reason, when I execute in terminal babel -V the result is:
#user1:/project-route$> gulp
    6.26.0 (babel-core 6.26.3)

This is not the same version I installed (that I remember):

"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",

So, I uninstalled all this dependencies:
"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"gulp-babel": "^8.0.0",

And I installed this ones in replacement:
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"gulp-babel": "^7.0.1",

And all functions works now!!!

Of course, the explanation is accordingly to this note on the README.md of the gulp-babel plugin, realizing about this matter cost me a lot of headaches:
Install guide (gulp-babel on GitHub)

Install
Install gulp-babel if you want to get the pre-release of the next
  version of gulp-babel.
# Babel 7
$ npm install --save-dev gulp-babel @babel/core @babel/preset-env

# Babel 6
$ npm install --save-dev gulp-babel@7 babel-core babel-preset-env

Comment: Hey man, I know this post is a few months old now, but I and as I've seen some other people (according to the open issue on gulp-babel github repo) still have this issue where it just wont transpile the code down properly. If I want to work with modules for example, and I have import/export, it just reads it the import (I think) as `require` and in the browser returns `require is not defined`. I did the same thing as you, installed the Babel 6 version, still the same problem. Mind sharing some more info how you got it working?
Comment: As you said, it was some months ago, but basically I did what I wrote, of course before to find out this solution, I tried many other solutions during my research.
Comment: So what do I actually type to install the working version? The readme is still unclear.
Comment: That's depend on what is the Babel version you are using. Execute in terminal `babel -V`  and the version of the `babel-core` that the terminal show, must be the same as the babel version installed in your project or that appears in the `package.json` file. Then execute the correct command to install `gulp-babel` accordingly to the right Babel version you have.


Let $R$ be a ring with identity such that it has no zero divisors. If every subring of $R$ is an ideal of $R,$ then prove that $R$ is commutative.

Question: Let $R$ be a ring with identity such that it has no zero divisors. If every subring of $R$ is an ideal of $R,$ then prove that $R$ is commutative.
This means, that $R$ is an integral domain.
By ideal, I think they mean a two-sided ideal. Now, a subring of a ring is a non-empty subset of a ring that forms a ring under the same operations of addition and multiplication as defined for the original ring.
My definition of a two-sided ideal is:
A non-empty subset $I$ of a ring is called an ideal of $R$ if :

$I$ forms a subgroup of $R$ under addition,
For every, $r\in R$ and $u\in I$ we have $ru,ur\in I.$

But unfortunately, I can't think of a way to solve this problem. Any help regarding thus will be greatly appreciated.
Comment: That's a very weird question. If by subring you mean that it must contain the identity (which is the usual definition) then it can only be an ideal if it is equal to the whole ring $R$. So you basically assume that there are no proper subrings. But then clearly $R=\mathbb{Z}\cdot 1_R$.
Comment: Consider the subring generated by $\{n\cdot1_R | n\in \Bbb{Z}\}$ and use the fact that this is also an ideal
Comment: @SoumikMukherjee Sorry, but I didn't get it. I just can't think of how to use that the set you mention is an ideal.
Comment: In the second bullet of your definition of ideal, you refer to membership in $U$ [which hasnot been defined], where I think you mean membership in $I.$
Comment: @Thomas Consider any arbitrary element $r$. Now $r\cdot1_R$ is in the subring. Can you do it from here?
Comment: @coffeemath Yes, thanks for pointing out the typo. I have fixed it. Any idea on how to solve the problem?
Comment: @SoumikMukherjee Oh! I think I got it. My solution is: If $r\in R$ then $r.1_R\in$ the subring you mention(say we call it $S$) as the subring is an ideal. This means, $R\subseteq S$ and thus all elements of $R$ can be written as a finite sum of sum of $1_R$'s or $-1_R$'s. Let $x,y\in R$ then, $\exists m,n\in\Bbb Z$ such that $x=m1_R$ and $y=n1_R$. We note that, $xy=(m1_R)(n1_R)=(mn)1_R=(nm)1_R=(n1_R)(m1_R)=yx.$ Since, $x,y\in R$ are arbitrary so, $xy=yx,\forall x,y\in R$ due to which, $R$ is commutative. Did I get it?
Comment: Whether or not subrings have to contain identity is not nearly as odd as the fact the "no zero divisors" hypothesis seems totally irrelevant.
Comment: @Mark I think the question has some typo. It does make sense if we don't require $R$ to have an identity. (See my answer).
Comment: @rschwieb If you try to prove the proposition for rings without identity, the fact that $R$ does not have zero divisors is needed. (See my answer)
Comment: @Nothingspecial Looks like this may be the case!
Answer: The proof is interesting if you don't require $R$ to have an identity.
Let $R$ be a ring such that it has no zero divisors and every subring of $R$ is an ideal of $R$.  We intend to prove that $R$ is commutative.
Pick a non-zero element $x\in R$ and consider its centralizer $C(x)$ which is a subring and also an ideal.
Pick another non-zero element $r\in R$, we have $rx\in C(x)$ (by definition of ideal).
\begin{align}(xr-rx)x &= xrx-rx^2\\ &= x(rx)-rx^2\\ &= (rx)x-rx^2\\&= 0 \end{align}
Now, $$(xr-rx)x=0\implies xr-rx=0$$ $\because \ R$ does not contain zero divisors and $x\neq 0$ by choice.
Thus, we have $rx=xr$ for all non-zero $r,x\in R$. $\blacksquare$
In case, $R$ has an identity (I believe it's a mistake or typo in your source), the proof is trivial. The centre of the ring $C(R)$ is an ideal and it contains the identity $1_R$. Thus, for every $r\in R$, the product $r\cdot 1_R=r\in C(R)$ and hence, $R\subseteq C(R)$.


Accessing specific parameter from parameter pack inside function scope, how?

Question: Given,
template<typename T, typename ...Args>
void foo(T t, Args ...args){/*foo scope*/}

When foo("bar",27,true); is called, how to access true, within the scope of foo?
Can a parameter simply be extracted like auto param3=args<2>;?
I'm trying to get both the parameter type and the value it contains.
Answer: std::tie creates a tuple of lvalue references. Paired with std::get will give you access to the arguments as if they were referred by name.
#include <tuple>

template <typename T, typename... Ts>
void foo(T t, Ts... ts)
{
    auto args = std::tie(t, ts...);
    auto param3 = std::get<2>(args);
}

DEMO
Note: Usually, one would also be interested in retaining and restoring the value categories of parameters passed by forwarding references. For that std::forward_as_tuple is a better choice.
Comment: @Xemdocia Tuples are index from `0`. For the call `foo("bar", 27, true)`, `t="bar"` and `ts...` becomes `27, true`. Together, `t, ts...`, becomes `"bar", 27, true`, with indices, `0, 1, 2`, respectively. Without `t` you will have indices `0, 1` for `27`, and `true`.
Comment: Why did we use `std::tie()` with `t` as its first parameter? When it's removed, index begins at second parameter. Can you explain also the logic please?
Comment: @Xemdocia It's your choice.
Comment: If it's called like `auto args=std::tie(ts...);` then `std::get<0>(args);` returns 2nd parameter, not the first. This I don't understand, can you explain? Why does `t` fix the indexing?
Comment: Thank you very much


Gaussian integers quotients vs polynomial ring quotient

Question: I've seen that in the Gaussian integers we have the isomorphism:
$$ \frac{\mathbb{Z[i]}}{(f(i))} \cong \frac{\mathbb{Z}[X]}{(f(X),X^2+1)} $$
Where $f \in \mathbb{Z}[X]$. In small cases I've seen this isomorphism with the ring isomorphism theorems. However, I'm not sure this happens for every $f$.
I think that the ring morphism $X \rightarrow i$ should be an isomorphism. As I'm new to this topic I wanted to know if my reasoning is correct.
Answer: Question: "In small cases I've seen this isomorphism with the ring isomorphism theorems. However, I'm not sure this happens for every f."
Answer: This is one of the "isomorphism theorems": When you write $\mathbb{Z}[i]/(f(i))$ you mean the ring $(\mathbb{Z}[x]/(x^2+1))/(f(\overline{x}))$ where $f(\overline{x})\in \mathbb{Z}[x]/(x^2+1)$. It follows there is an inclusion of ideals in $\mathbb{Z}[x]$
$$I:=(x^2+1) \subseteq (x^2+1,f(x)):=J$$ and isomorphisms
$$\mathbb{Z}[i]/(f(i)) \cong (\mathbb{Z}[x]/I)/(J/I) \cong \mathbb{Z}[x]/J :=\mathbb{Z}[x]/(x^2+1,f(x)).$$
Comment: Oh I think I was missing the part that the $(f(\bar{x}))$ is an ideal on $\mathbb{Z}[X]$ with the relation $x^2+1=0$. Then, we have that $(f(\bar{x})) = J/I$.
Answer: When $R$ is a commutative ring, and $x,y \in R$, the principal ideal of $R/(x)$ generated by $\overline y := y+(x)$, namely $(\overline y)$, coincides with $(x,y)/(x)$, as you can check. Thus, the  third isomorphism theorem (see 5 here) tells us that $$\frac{R/(x)}{(\overline y)} = \frac{R/(x)}{(x,y)/(x)} \cong \frac R{(x,y)}.$$
Hence, for $p \in \mathbb Z[X]$, $$\frac{\mathbb Z[X]}{(X^2+1,p)} \cong \frac{\mathbb Z[X]/(X^2+1)}{(\overline p)}.$$
Now, it is well-known that $\mathbb Z[X]/(X^2+1) \cong \mathbb Z[i] := \{a+bi : a,b \in \mathbb Z\}$ via the map that sends $\overline q \in \mathbb Z[X]/(X^2+1)$ to $q(i)$. Therefore, under this isomorphism, the ideal $(\overline p)$ corresponds to the ideal $(p(i))$, which means that
$$\frac{\mathbb Z[X]/(X^2+1)}{(\overline p)} \cong \frac{\mathbb Z[i]}{(p(i))}.$$


Multiple cases within an integral after a $u$-substitution

Question: The problem asks to solve this indefinite intregral:
$$I=\int{\frac{dx}{x\sqrt{x^2+1}}}$$
I did the following substitution (using $t$ as substitute value):
$$x^2+1=t\implies x=\pm\sqrt{t-1}$$
$$2xdx=dt\implies dx=\frac{dt}{2\sqrt{t-1}}$$
From here I separated two cases and did some basic integration to get the following:

$x<0$
$$I=-\int{\frac{dt}{2(t-1)\sqrt{t}}}=-\frac{1}{2}\ln\left|\frac{1+\sqrt{x^2+1}}{1-\sqrt{x^2+1}}\right|+C_1$$
$x>0$
$$I=\int{\dfrac{dt}{2(t-1)\sqrt{t}}}=\dfrac{1}{2}\ln\left|\dfrac{1-\sqrt{x^2+1}}{1+\sqrt{x^2+1}}\right|+C_2$$

Is this the correct solution the given indefinite integral?
Answer: Here is the correct procedure to evaluate with $x^2+1=t$, $2xdx=dt$
\begin{align}
\int{\frac{dx}{x\sqrt{x^2+1}}}=& \ \frac12\int{\frac{2x dx}{x^2\sqrt{x^2+1}}}=\frac12\int \frac{dt}{(t-1)\sqrt t}\\
 =&\ \frac{1}{2}\ln{\frac{\sqrt{t}-1}{\sqrt{t}+1}} =\frac{1}{2}\ln{\frac{\sqrt{x^2+1}-1}{\sqrt{x^2+1}+1}}
\end{align}
which is valid for both $x<0$ and $x>0$.
Comment: @bb_823 - then $\pm$ would cancel out $\pm$ from $x=\pm \sqrt{t-1}$, which leads to the same result for either case
Comment: @bb_823 Examining your two missteps carefully, and at the risk of belabouring the obvious: $(\pm^2=+),$ while $(\pm\times+=\pm).$
Comment: Why does doing it the way I did it give me the wrong solution?
Comment: @bb_823 - you should have the expression $dx=\pm\frac{dt}{2\sqrt{t-1}}$ instead
Comment: well that is what pretty much what I have, just seems like i forgot to write it. Wouldn't having that give me the solution that I got?
Answer: $$
\begin{aligned}
\int \frac{d x}{x \sqrt{x^2+1}} & =\int \frac{1}{x^2} d\left(\sqrt{x^2+1}\right) \\
& =\int \frac{1}{\left(\sqrt{x^2+1}\right)^2-1} d\left(\sqrt{x^2+1}\right) \\
& =\frac{1}{2} \ln \left|\frac{\sqrt{x^2+1}-1}{\sqrt{x^2+1}+1}\right|+C
\end{aligned}
$$
Comment: cool approach. just corrected the differential in the second step. +1
Answer: The negative-$x$ postion of your solution is incorrect. If you are comfortable with hyperbolic functions, then using the substitution $\displaystyle u=\frac1x$ and noting that
$\operatorname{arccosech}$ is an odd function:
\begin{align}\int\frac{\mathrm dx}{x\sqrt{x^2+1}}
&= \int\frac{-|u|}{u\sqrt{1+u^2}}\,\mathrm du\\
&= \begin{cases} \operatorname{arcsinh} u+C_1, &u<0;\\
    -\operatorname{arcsinh} u+C_2, &u>0\end{cases}\\
&= \begin{cases} \operatorname{arccosech}x+C_1, &x<0;\\
    -\operatorname{arccosech}x+C_2, &x>0\end{cases}\\
&= \begin{cases} -\operatorname{arccosech}(-x)+C_1, &x<0;\\
    -\operatorname{arccosech}x+C_2, &x>0\end{cases}\\
&= \begin{cases} \color{red}{-\operatorname{arccosech}|x|}+C_1, &x<0;\\
    -\operatorname{arccosech}|x|+C_2, &x>0.\end{cases}
\end{align}

Addendum (noting that $\operatorname{arccosech} x\equiv\ln\left(\frac1x+\frac1{|x|}\sqrt{x^2+1}\right)$)
$$= \begin{cases} -\ln\left(\frac1{|x|}+\frac1{|x|}\sqrt{x^2+1}\right)+C_1, &x<0;\\
    -\ln\left(\frac1{|x|}+\frac1{|x|}\sqrt{x^2+1}\right)+C_2, &x>0\end{cases}\\
= \begin{cases} \color{red}{-\ln\left(\frac{1+\sqrt{x^2+1}}{|x|}\right)}+C_1, &x<0;\\
    -\ln\left(\frac{1+\sqrt{x^2+1}}{|x|}\right)+C_2 &x>0,\end{cases}$$ exhibiting two independent parameters to caputure the complete set of antiderivatives.
P.S. Note that all the solutions currently on this page (Quanto's, zwim's, Bob's, mine; each using a different substitution) are equivalent to one another.
Comment: I am fine with hyperbolic function, but the solution in the form of $ln$ is preferable.
Answer: When you see some $\sqrt{\cdots}\ $ in an integral it is often interesting to substitute that (not always but there are many times this will lead to a simplification).
The inner of the integral being odd, anti-derivative will be even and the change $u=\sqrt{x^2+1}$ is bijective on $x>0,u>1$.
$u^2=x^2+1$ gives $2udu=2xdx\iff \dfrac{dx}x=\dfrac{udu}{x^2}=\dfrac{udu}{u^2-1}$
Therefore $\displaystyle\int\dfrac{dx}{x\sqrt{x^2+1}}=\int\dfrac{du}{u^2-1}=-\operatorname{arctanh}(u)+C=-\operatorname{arctanh}\left(\dfrac 1{\sqrt{x^2+1}}\right)+C$
You can have a different $C$ for $x<0$ and $x>0$ though.
Answer: What is wrong with $x=\tan\theta$ substitution? Then
$$I=\int\csc\theta\,d\theta=-\ln|\csc\theta+\cot\theta|+c=-\ln\frac{\sqrt{x^2+1}+1}{|x|}+c.$$


Explain difference between opencv's template matching methods in non-mathematical way

Question: I'm trying to use opencv to find some template in images. While opencv has several template matching methods, I have big trouble to understand the difference and when to use which by looking at their mathematic equization:

CV_TM_SQDIFF
CV_TM_SQDIFF_NORMED
CV_TM_CCORR
CV_TM_CCORR_NORMED
CV_TM_CCOEFF

Can someone explain the major difference between all these method in a non-mathematical way?
Answer: The general idea of template matching is to give each location in the target image I, a similarity measure, or score, for the given template T. The output of this process is the image R.
Each element in R is computed from the template, which spans over the ranges of x' and y', and a window in I of the same size.
Now, you have two windows and you want to know how similar they are:
CV_TM_SQDIFF - Sum of Square Differences (or SSD):
Simple euclidian distance (squared):

Take every pair of pixels and subtract
Square the difference
Sum all the squares

CV_TM_SQDIFF_NORMED - SSD Normed
This is rarely used in practice, but the normalization part is similar in the next methods.
The nominator term is same as above, but divided by a factor, computed from the
- square root of the product of:

sum of the template, squared
sum of the image window, squared

CV_TM_CCORR - Cross Correlation
Basically, this is a dot product:

Take every pair of pixels and multiply
Sum all products

CV_TM_CCOEFF - Cross Coefficient
Similar to Cross Correlation, but normalized with their Covariances (which I find hard to explain without math. But I would refer to
mathworld
or mathworks
for some examples
Comment: From what I see in the [OpenCV docs](https://docs.opencv.org/3.4.10/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d), **CV_TM_CCOEFF** only performs mean centering i.e., the window means of the target and template are subtracted from each pixel in the respective windows.

The full [normalised variant](https://en.wikipedia.org/wiki/Cross-correlation#Zero-normalized_cross-correlation_(ZNCC)) is **CV_TM_CCOEFF_NORMED**, which does the mean centering and also divides by the standard deviations.
Comment: awesome explanation. but there is a question: when  CV_TM_CCOEFF "normalized with their Covariance" then why we have (need) CV_TM_CCOEFF_NORMED ?
Comment: check out this link for good visuals of the different methods:
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html


Guitar tuning problems

Question: I have this guitar for a year already maybe little bit more and like 6 months ago it started doing weird things.
I always tuned guitar from high E to low E. But since something happened, when I tune it like that already tuned strings go out of tune when I'm already on low E string.
If I tune from low E to high E it all stays in tune.
This really is painful if you want to tune down to half or full step, the tuning process gets 20 mins long.
Why does this happen?
I have a fender electric guitar with normal tremolo bridge. Bridge has 3 springs.
Interestingly it does not go out of tune while using whammy.
Comment: When was the last time you changed your strings?
Comment: like month ago. they are new i change strings every 2 months
Answer: Changing the tuning on a Stratocaster is always a slow and painful process, unless you block the tremolo system. Small changes, like normal day-to-day tuning, simply return the bridge to balance and do not cause problems. However, changing to D tuning significantly changes string tension, which affects the balance of the bridge. Changing even one string down a tone (Drop D) will throw all of the other strings out of tune. This is normal. Floating bridges work best when you pick a tuning and stick to it.
If you really want to experiment with alternate turnings, I recommend freezing or at least decking the bridge. I did that to my Strat. Now I can only dive on the whammy bar, but it is much easier to retune.
You should not need to do that for ordinary tuning, however. If you are having problems even with day-to-day tuning, I suspect that the change of seasons or other environmental factors are throwing your guitar further out of tune than usual, so that you are experiencing retuning problems more often. If so, start tuning with the strings that change tension the most – in your case, that sounds like the low strings – or just deck the bridge like you would for drop tuning.
Comment: Szonye captures this, but to be explicit:  my understanding is that as you tighten/loosen the widest-gauged strings on any guitar, the neck will bend the the most, throwing out of tune the narrower-gauged strings.
Comment: @commonhare Thanks for the note! I was adding something similar to my answer as you wrote it.
Comment: Yeah thanks normal retuning does not really bother me but and even dropping e to d is easy but really down tunning every string is hard to do
Comment: I have done this on two guitars, a strat and a bitch. I literally cut the springs shorter and re-attached them. You can only whammy "down" but... I remove the whammy bar too, it's useless.
Comment: @brsgamer Here's how to freeze the whammy bar if you want to make this easier: http://music.stackexchange.com/questions/17290/decking-a-stratocaster-bridge
Answer: You mentioned that you used to tune it from the high E (1st) string to the low E.  Since you have a tremolo system, anytime that you change the tension on a string (by tuning it), the tremolo will move, as Bradd pointed out above (even if it moves just a tiny bit).  When you arrive at the 6th string to tune it, that string will have the most effect on the tremolo, since it's the heaviest string, and it is affecting the lighter strings the most.
Continue tuning your guitar starting with the 6th string.  Once that is close to tune, it will stay the most stable of all the strings.  Continue with a "rough" tuning of the rest of the strings (just get them close), go back to the 6th and fine tune it, and then follow with the 5th, 4th, etc.  Keep repeating this pattern until you're satisfied.  The main point is that the thickest string will affect the rest of the strings the most, so tune that one first.
Comment: I'm glad I could help :)
Answer: After a while you can learn how much your strings need to be tuned beyond where you expect and can rapidly tune a floating bridge to a different tuning.
You can also speed the process up by using the whammy bar to stretch the strings.

Guitar tuning problems


Máquina Virtual não compartilha pasta

Question: Problema:

Uso Virtual Box e MVWare em ambos os programas não consigo compartilhar pasta, utilizando a opção interna deles Pasta Compartilha.
Observe as imagens para uma esclarecimento melhor sobre o problema:

Foto 1: Pasta Compartilhada do Virtual Box

Foto 2: Local onde deveria aparecer o compartilhamento que fiz no
  processo anterior.

Dúvida:
Por que não encontro a pasta que está compartilhada?

Observação: O compartilhamento de rede não é trivial já que a Virtual Box e VMWare permitem um compartilhamento interno. Mostro
  o diretório /mnt/hfgs, nele encontrei a pasta quando comecei a usar
  a Máquina Virtual e hoje não encontro mais.
Comment: Acho que tem que instalar um utilitário no sistema operacional que está dentro da Máquina Virtual, para habilitar esta forma de integração do Sistema Operacional que está rodando dentro da Máquina Virtual, com outros recursos do Virtual Box.
Answer: Para funcionar,
Instale o Guest Additions
https://www.virtualbox.org/manual/ch04.html
Isto irá habilitar esta forma de integração do Sistema Operacional que está rodando dentro da Máquina Virtual, com o recurso do Virtual Box.
Outra forma é compartilhar a pasta normalmente no Sistema Operacional dentro da Máquina Virtual, e acessar ela através de um compartilhamento de rede, como se fossse um PC normal na rede, utilizando a sintaxe
\\NomeDoPC\PastaCompartilhada

Answer: Solução no VirtualBOX:

Sobre GuestAdditions: Guest Additions
Temos que fazer o seguinte:

As Adições de Convidado VirtualBox para todos os sistemas operacionais
  convidados suportados são fornecidos como um arquivo de imagem de CD
  -ROM único que é chamado VBoxGuestAdditions.iso . Este arquivo de imagem está localizado no diretório de instalação do VirtualBox . Para
  instalar os Adicionais para Convidado para uma determinada VM , você
  montar este arquivo ISO em sua VM como um CD -ROM virtual e instalar a
  partir de lá.
[Tradução Google Translate]

Montando unidade CD-ROM na máquina virtual
Montar o VBoxGuestAdditions.iso que está na pasta C:\Program Files\Oracle\VirtualBox (no meu computador) dentro da sua Máquina Virtual pasta ir nas configurações dela. Observe a imagem.

Imagem 1: Montando unidade de CD-ROM com o VBoxGuestAdditions.iso.

Iniciando instalação
Inicie a máquina virtual e vá até a unidade CD-ROM que parece com o nome VBoxGuestAdditions chegando lá execute autorun.sh escolha opção "Executar em Terminal" observe a imagem do terminal em instalação.
Observação:  Quando a instalação for concluída reinicia a Máquina Virtual.

Imagem 2: Depois que foi executado autorun.sh essa é a tela de instalação do mesmo.

Visualizando pasta compartilha
Agora fica de sua preferência acessar sua pasta compartilha via terminal ou console.
Observe a imagem onde está a pasta compartilhada:

Imagem 3: Nessa foto podemos ver a pasta que está compartilhada.

Legenda de cores da imagem 3:

Vermelho - Pasta onde está os compartilhamento
Verde - Pasta compartilhada em [sua VM > Configurações > Pasta
Compartilhadas]
Azul - CD-ROM que contém o VBoxGuestAdditions.iso. [sua VM >
Configurações > Armazenamento]

Observação: Sempre acessei a pasta compartilha em /mnt/hfgs, porém
  acabei encontrando ela agora em /media como segue a imagem. Esse processo resolveu meu problema, espero que ajude a todos.

Máquina Virtual não compartilha pasta


How to configure nginx-ingress with one load balancer for two ingress for two domains

Question: I have a k8s cluster like below

#kubectl get all

NAME                                                 READY   STATUS    RESTARTS   AGE
pod/nginx-ingress-controller-d78c45477-gxm59         1/1     Running   0          8d
pod/nginx-ingress-default-backend-5b967cf596-dc8ss   1/1     Running   0          8d

NAME                                    TYPE           CLUSTER-IP       EXTERNAL-IP     PORT(S)                      AGE
service/kubernetes                      ClusterIP      10.245.0.1                 443/TCP                      9d
service/nginx-ingress-controller        LoadBalancer   10.245.203.193   A.B.C.D   80:30033/TCP,443:31490/TCP   8d
service/nginx-ingress-default-backend   ClusterIP      10.245.58.229              80/TCP                       8d

NAME                                            READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx-ingress-controller        1/1     1            1           8d
deployment.apps/nginx-ingress-default-backend   1/1     1            1           8d

NAME                                                       DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-ingress-controller-d78c45477         1         1         1       8d
replicaset.apps/nginx-ingress-default-backend-5b967cf596   1         1         1       8d

As above, I have an external ip A.B.C.D.
I also have two domains domainA.com and domainB.com.
My DNS setting is like below:
for domainA.com:

-----domain A----
A www.domainA.com A.B.C.D
-----domain B----
A www.domainB.com A.B.C.D

After I install two apps with helm
I got

# kubectl describe ingress

Name:             app1
Namespace:        default
Address:          A.B.C.D
Default backend:  default-http-backend:80 ()
Rules:
  Host            Path  Backends
  ----            ----  --------
  www.domainA.com
                     app1:80 (10.244.1.15:80,10.244.1.33:80)

Annotations:
  kubernetes.io/ingress.class:  nginx
Events:
  Type    Reason  Age    From                      Message
  ----    ------  ----   ----                      -------
  Normal  CREATE  10m    nginx-ingress-controller  Ingress default/app1
  Normal  UPDATE  9m48s  nginx-ingress-controller  Ingress default/app1

Name:             app2
Namespace:        default
Address:          A.B.C.D
Default backend:  default-http-backend:80 ()
Rules:
  Host         Path  Backends
  ----         ----  --------
  www.domainB.com
                  app2:80 (10.244.1.15:80,10.244.1.33:80)

Annotations:
  kubernetes.io/ingress.class:  nginx
Events:
  Type    Reason  Age    From                      Message
  ----    ------  ----   ----                      -------
  Normal  CREATE  8m24s  nginx-ingress-controller  Ingress default/app2
  Normal  UPDATE  7m49s  nginx-ingress-controller  Ingress default/app2

I don't know why the backends have two IPs.
www.domainA.com and www.domainB.com may route to same ip(10.244.1.15:80) which is I don't want.
I want a single external ip route to different pods by hosts like virtual server

www.domainA.com
                     app1:80 (10.244.1.15:800)

-----------------
www.domainB.com
                     app2:80 (10.244.1.33:80)

How could I fix my configuration?
Thank you
Comment: share ingress, service,deployment yaml
Answer: If I understood the situation correctly you would like to have single external IP domains A and B resolved to, single Ingress and two different apps (one per domain). And at the moment the issue is that traffic is delivered to Both Apps instated of proper routing.
Unfortunately, you haven't provided your Ingress and Services configs. That is why I'll have to explain all needed setup :)
What is needed here is to have  2 distinct apps (with different labels), 2 distinct services that route to endpoints for each service and single Ingress that lists both domains.
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: name-virtual-host-ingress
spec:
  rules:
  - host: domain-A
    http:
      paths:
      - backend:
          serviceName: service-A
          servicePort: 8080
  - host: domain-B
    http:
      paths:
      - backend:
          serviceName: Service-B
          servicePort: 8080

here we've created Ingress that routes traffic for 2 different services
apiVersion: v1
kind: Service
metadata:
  name: Service-A
spec:
  selector:
    app: nginx
  ...

I've omitted half of the services specs for clarity. The most important point is  "selector"
It is needed to create 2 services with 2 different selectors.
You can check services and corresponding EndPoints with the  kubectl get svc -o wide and  kubectl get ep
Needless to say, that both apps shall be deployed separately to have different labels.
Please check your config and compare with the above.
Hope that helps. Will be happy to elaborate further if needed.
Comment: yes, you are so right. I followed your instruction and all works fine now. I post the final settings below for reference.
Answer: My working settings:
deployment_app1.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app1
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app1
  template:
    metadata:
      labels:
        app: app1
    spec:
      containers:
      - name: name
        image: image
        ports:
        - containerPort: 80

deployment_app2.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app2
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app2
  template:
    metadata:
      labels:
        app: app2
    spec:
      containers:
      - name: name
        image: image
        ports:
        - containerPort: 80

ingress_app1.yaml:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: app1
spec:
  rules:
    - host: www.domainA.com
      http:
        paths:
          - backend:
              serviceName: app1
              servicePort: 80

ingress_app2.yaml:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: app2
spec:
  rules:
    - host: www.domainB.com
      http:
        paths:
          - backend:
              serviceName: app2
              servicePort: 80

service_app1.yaml:

apiVersion: v1
kind: Service
metadata:
  name: app1
spec:
  type: ClusterIP
  selector:
    app: app1
  ports:
    - name: port1
      protocol: TCP
      port: 80
      targetPort: 80

service_app2.yaml:

apiVersion: v1
kind: Service
metadata:
  name: app2
spec:
  type: ClusterIP
  selector:
    app: app2
  ports:
    - name: port1
      protocol: TCP
      port: 80
      targetPort: 80


Using a lambda inside Linq.Expressions

Question: I need to call a lambda from a Linq.Expression. I know I can get some method info from the lambda like this:
Func<double, double> square = x => x * x;
MethodInfo mInfo = square.Method;

But that MethodInfo requires a System.RuntimeServices.Closure first argument. Since I'm using .NET Core, that class is internal to System.Linq.Expressions. Even when an instance of that class is created using reflection, I cannot call square from a System.Linq.Expression.
Is there any workaround for this? I'm writing a simple formula evaluator, but I need lambdas for implementing thinks like predicate logic, Newton-Raphson, etc.
Updated:
This code does not work:
        static void Main(string[] args) =>
            Console.WriteLine(DoubleIt()(4));

        static double CallAndDouble(Func<double, double> f, double x)
        {
            return f(x) + f(x);
        }

        static Func<double, double> DoubleIt()
        {
            var input = Expression.Parameter(typeof(double), "x");
            var call = Expression.Call(typeof(Program).GetMethod(nameof(CallAndDouble)),
                CreateLambda(), input);
            return Expression.Lambda<Func<double, double>>(call, input).Compile();
        }

        static Expression CreateLambda()
        {
            var input = Expression.Parameter(typeof(double), "x");
            var mult = Expression.Multiply(input, input);
            return Expression.Lambda<Func<double, double>>(mult, input);
        }

In actual code, I'll have some library functions taking lambdas as arguments (like the CallAndDouble from the above code).
Comment: The only thing you can do is to construct an expression which invokes that `square` lambda (i.e. `Expression> expr = x => square(x)`). There's no way to construct an expression which represents the operation `x * x`
Comment: Changed `var` to `Func`.
Comment: Even with the change, it's hard to know exactly what you're trying to achieve. Please provide more context - including how you expect to use the expression tree later.
Comment: More code added.
Comment: Your code works for me: https://dotnetfiddle.net/oEGtpG . It's doing `(4 * 4) + (4 * 4)` because that's what you constructed, but hey. What exactly is wrong with it?
Comment: Ha, ha, canton7! It doesn't work for me! Yes, that's what it is supossed to do. Might it be that I'm running it in .NET Core 5? It throws an `ArgumentNullException` at the second line in `DoubleIt`. I'll try it in FW 4.8 to check that.
Comment: @IanMarteens I had to fix the BindingFlags passed to `GetMethod`, because it's not set up to find a private method by default.... But I assumed that was an error with your sample which wasn't there in your actual code, because it's nothing at all to do with expressions or lambdas, just `GetMethod` returning null
Comment: Geez, I'm an idiot. Thanks, @canton7
Comment: No problem! Voting to close this as "Caused by a typo" -- while it wasn't exactly a typo, it's still something unrelated to the original question which is unlikely to help others
Answer: Solved by @canton7. Just a typo: I was missing the BindingFlags.

Using a lambda inside Linq.Expressions


How do I find the points at which the following functions intersect? And how many times do they intersect?

Question: I have a function $f(x) = 4x^3 − 2x^2 − 4x − 2 $
And a line $y = 4x -1$
And I need to know where they intersect, I know that I have to do $4x^3 − 2x^2 − 4x − 2 = 4x -1$
But I can't find the x-values and I'm not allowed to use graphs.
As for how many times they intersect, I think it's three because the polynomial is third degree
Comment: Are you sure about those functions? The equation that you reached has no simple solution.
Comment: I'm sure of it, which happens to be why i'm stumped.
Comment: Probably is there a typo?
Comment: Could the Intermediate Value Theorem help here?
Comment: @MathLove `I think it's three because the polynomial is third degree`. Yes but it's not necessary that all the three are real. You may even get (not for this question) pairs of complex conjugate roots. In that case they **wouldn't intersect the real axis thrice**, at least not in the conventional way.
Answer: The
discriminant
of the cubic $ax^3+bx^2+cx+d$ is
\begin{align}
\Delta(a,b,c,d) &=18abcd-4b^3d+b^2c^2-4ac^3-27a^2d^2
,
\end{align}
in particular for the cubic
\begin{align}
4x^3-2x^2-8x-1
\tag{1}\label{1}
\end{align}
the discriminant is
\begin{align}
\Delta(4,-2,-8,-1)&=6832>0
,
\end{align}
hence, \eqref{1} has three distinct real roots.
Dividing \eqref{1} by $4$
and substituting $t+\tfrac16$ for $x$, we get
a reduced cubic equation
\begin{align}
t^3+pt+q=&0
\tag{2}\label{2}
,
\end{align}
\begin{align}
\text{where}\quad
p&=-\tfrac{25}{12}
,\quad
q=-\tfrac{16}{27}
.
\end{align}
Applying
Trigonometric solution for three real roots
to \eqref{2},
we can find the roots as
\begin{align}
t_k&=
2\sqrt{-\frac{p}3}
\cos\left(\frac1{3}\arccos
\left({\frac{3q}{2p}}\sqrt{-\frac3p}\right)
-\frac{2\pi k}3\right)
\quad \text{for}\quad k=0,1,2
,\\
\end{align}
\begin{align}
t_0&=\phantom{-}\tfrac53\cos(\tfrac13\arccos(\tfrac{64}{125}))
\approx  1.56878
,\\
t_1&=-\tfrac53\cos(\tfrac13\arccos(\tfrac{64}{125})+\tfrac\pi3)
\approx -0.29702
,\\
t_2&=-\tfrac53\sin(\tfrac13\arccos(\tfrac{64}{125})+\tfrac\pi6)
\approx -1.27176
.
\end{align}
Then the corresponding roots of \eqref{1} are
\begin{align}
x_0&=t_0+\tfrac16\approx 1.73545
,\\
x_1&=t_1+\tfrac16\approx -0.13036
,\\
x_2&=t_2+\tfrac16\approx -1.10509
.
\end{align}
Comment: +1. Nice solution. I didn't know that it could be this simple for distinct real roots.
Answer: Hint:
Method 1: You essentially need the root of:
$$4x^3-2x^2-8x-1=0$$
If you use Descartes' Rule, you can see that the above equation has a positive real root and two negative real roots.
So this tells you that you have three real roots and hence three intersections.
Now finding them is difficult without a graph so you may use Newton Raphson's method for each root or you may get an accurate root and you could factor it out to get the other roots but that would be pretty lengthy.
You should notice that the product of the roots: $$x_1*x_2*x_3=\frac{-(-1)}{4}=\frac{1}{4}$$
Also sum of the roots: $$x_1+x_2+x_3=\frac{-(-2)}{4}=\frac{1}{2}$$
In case you are using Newton Raphson's method you could use the above equations for the initial three good guesses required for the three roots.
Answer: Hint:
Method 2: you could take: $$y=x-\frac{1}{6}$$
This will eliminate the quadratic term and reduce the equation to:
$$y^3 - \frac{25 y}{12} - \frac {16}{27} = 0$$
For this equation we have a wicked formula known as the Cubic Formula. You can find the formula and similar methods here at Wiki.


How do I allow other files in the root directory of my site to be accessible?

Question: Alright so I've noticed that the .txt files in the root directory of my Drupal install are accessible just using http://drupalsite.com/SOMETHING.txt, but when I try to add other .txt files, I get a 404 when I try to access them from the browser. I've even set these files to have exactly the same user:group and permissions as the .txt files that I can access, and I've tried restarting Apache, but nothing seems to work.
The reason I need this is because I want to use Majestic SEO, which requires you to place a .txt file at the root of your website.
Comment: Do you get a Drupal 404 or a Apache 404 (very simplistic)?
Answer: I use Site verification for tasks like this, although it may not work for this particular case. IIRC it tried the module for a Majestic .txt file, and it added some dummy content for the text file, which the Majestic service did not accept (the file has to be empty). So I uploaded the file directly to the Drupal root via SFTP. I just checked that website, and the Majestic .txt loads normally. I don't see any reason why you would get a 404, other than that the file is indeed not present. I don't think Drupal is to blame, because if the file is present, Apache will serve it. Only if it's not present Drupal starts doing stuff.
So, unless you have done something in .htaccess it should work, and I only have a silly suggestion: double-check that the file is in the correct folder, copy the file name from that directory and paste it in the browser to check.
Comment: Yes, the default .htaccess explictly checks if a actual file exists for the request and only passes the request to Drupal if that's not the case. So that doesn't sound like a Drupal issue...
Answer: I am not sure I've got exactly what is happening straight, so my explanation may have the details a little off...  Browsers are very fussy about opening files due to security risks for users. In Drupal, any file that you want to open must be uploaded to the site using file_save (permanent location), or file_save_upload (temporary location).  This process is similar to uploading image files.  I have not researched exactly what is happening, but suspect that the file identity is then added to the database and allows Drupal to handle it properly.  I am adding files using a custom module function.  There may be modules that can do this for you if the Majestic SEO does not load them.


how to do exact match in elasticsearch?

Question: Here I have given my updated mapping
curl -X PUT localhost:9200/testing/listings/_mapping -d '{
  "listings" : {
    "properties" : {
        "address" : {
           "properties": {
              "location": { "type" : "string",
                            "index" : "not_analyzed"
               }
            }
        },
        "suggest" : { "type" : "completion",
                      "index_analyzer" : "simple",
                      "search_analyzer" : "simple",
                      "payloads" : true
        }
      }
   }
}'

my mapping is created index as follows
{
  "testing": {
    "mappings": {
      "listings": {
        "properties": {
          "address": {
            "properties": {
              "city": {
                "type": "string"
              },
              "line1": {
                "type": "string"
              },
              "line2": {
                "type": "string"
              },
              "line3": {
                "type": "string"
              },
              "location": {
                "type": "string",
                "index": "not_analyzed"
              },
              "pincode": {
                "type": "string"
              }
            }
          },
          "title": {
            "type": "string"
          }
        }
      }
    }
  }
}

but still my data is not matching.
my sample data is
{
  "listings": {
    "title": "testing 3",
    "address": {
      "line1": "3rd cross",
      "line2": "6th main",
      "line3": "",
      "landmark": "",
      "location": "k r puram",
      "pincode": "",
      "city": "Bangalore"
    }
  }
}

when I give the query as k r puram I am getting the matched results.
But when I am giving the query as r r puram or r k puram that time also I am getting the results which is belongs to k r puram.
In above query I am having listings only for k r puram others I don't have listings so other than k r puram it should give the empty results.
this is my query:
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "published": true
          }
        },
        {
          "match": {
            "inActive": false
          }
        },
        {
          "range": {
            "propertyDetailsCategory.build_up_area": {
              "lte": 200
            }
          }
        },
        {
          "match": {
            "type": "commercial"
          }
        },
        {
          "match": {
            "purpose": "rent"
          }
        },
        {
          "range": {
            "commercialsCategory.exp_rent": {
              "lte": 50000
            }
          }
        },
        {
          "match": {
            "address.location": "k r puram"
          }
        }
      ]
    }
  }
}

Comment: 1. why use multi_match against only a single field?  2. what does "address.location" actually contain?  3. How is it analysed?
Comment: I used match also that time also same results came. address.location contains the locations, 'address.location' is the field in listings object'. @OllyCruickshank
Comment: Let me rephrase my question - does "address.location" contain the exact value of "k r puram" ?
Comment: yes it contains k r puram
Comment: if the data is exactly "k r puram" and you're searching for exactly "k r puram" - then it sounds like you don't need an analyser.  Have you set the field to "index": "not_analyzed" in the mapping?
Answer: If the data is exactly "k r puram" and you're searching for exactly "k r puram" - then you shouldn't use an analyser.
When inserting data the default behaviour in Elasticsearch is to use the standard analyser.
To disable this use
 "index": "not_analyzed"

in the mapping for the appropriate field.

if your mapping is as follows:
curl -XPOST http://localhost:9200/index/address/_mapping -d '
{"address": {
  "properties": {
    "city": {"type": "string"},
    "line1": {"type": "string"},
    "line2": {"type": "string"},
    "line3": {"type": "string"},
    "location": { "type": "string", "index": "not_analyzed"},
    "pincode": {"type": "string"}
 }}}'

then your data must match it, for example this doesn't match it:
curl -XPOST http://localhost:9200/index/address/ -d '
{"title":"testing",
 "address":
      {"line1":"#51",
       "line2":"3rd cross",
       "line3":"6th main",
       "location":"k r puram",
       "pincode":"560041"}}

This however does match (my modifications):
curl -XPOST http://localhost:9200/index/address/ -d '
{"line1":"#51",
 "line2":"3rd cross",
 "line3":"6th main",
 "location":"k r puram",
 "pincode":"560041"}'

And this query finds the document as expected:
curl -XGET http://localhost:9200/index/address/_search -d '
{
   "query" :{"match" : {"location": "k r puram"}}
}'

if you can't change your data, then add the extra level to the mapping,e.g.:
curl -XPOST http://localhost:9200/index/address3/_mapping -d '{
  "address3" : {
    "properties" : {
      "address" : {
        "properties" : {
          "city" : {
            "type" : "string"
          },
          "line1" : {
            "type" : "string"
          },
          "line2" : {
            "type" : "string"
          },
          "location" : {
            "type" : "string", "index": "not_analyzed"
          }
        }
      },
      "title" : {
        "type" : "string"
     }
   }
 }
}'

Again the query works well:
curl -XGET http://localhost:9200/index/address3/_search -d '
{
   "query" :{"match" : {"address.location": "k r puram"}}
}'

Comment: if the "index" is set to "not_analysed", then elasticsearch would have not split the text based on space, i.e. the entire text will be considered as a single token. Hence, during search the complete text will be searched.. Another simple solution is replace spaces with some other character before indexing. eg: "k r puram" => k_r_puram.
Comment: @Olly my modified mapping is  curl -X PUT localhost:9200/testing/listings/_mapping -d '{
  "listings" : {
    "properties" : { "address" : {
               "properties": {
                  "location": { "type" : "string",
                                "index" : "not_analyzed"
                   }
                }
            },
        "suggest" : { "type" : "completion",
                      "index_analyzer" : "simple",
                      "search_analyzer" : "simple",
                      "payloads" : true
        }
      }
   }
}'
Comment: nope it does not give the single result for any location @OllyCruickshank
Comment: Can you add some sample data to your question?
Comment: "address": {"properties": { "city": {"type": "string"},
"line1": {"type": "string"},
"line2": {"type": "string"},
"line3": {"type": "string"},
"location": { "type": "string", "index": "not_analyzed"},
"pincode": {"type": "string"}
}}} This how it gets mapped @OllyCruickshank
Comment: @OllyCruickshank sample data is "listings":{"title":"testing","address":{"line1":"#51","line2":"3rd cross","line3":"6th main","location":"k r puram","pincode":"560041"}}
Comment: your data doesn't match your mapping, see my updated answer. Also - please update your question!!
Comment: @OllyCruickshank How to perform OR operation on purpose field? Actually purpose field would contains 'rent' or 'sale' or 'lease' so some times i need both listings which are containing wither 'rent' or 'sale' like that please help to solve this.. Thanks in advence
Answer: Have you tried this? (use .raw sub field to match value on "not tokenized" value)
{"query":{
   "bool":{
      "must":[
       {"match":{"published":true}},
       {"match":{"inActive":false}},
       {"range":{"propertyDetailsCategory.build_up_area":{"lte":200}}},
       {"match":{"type":"commercial"}},
       {"match":{"purpose":"rent"}},
       {"range":{"commercialsCategory.exp_rent":{"lte":50000}}},
       {"match":{"address.location.raw": "k r puram"}}
     ]
   }
 }
}

Try to use this query on your old mapping, it should work :)

how to do exact match in elasticsearch?


python: SyntaxError: invalid syntax Expected member name after "."

Question: I'm using argparse to parse the parameters, but when I get args.global, a strange error appears, I don't know where I did it wrong

...

parser.add_argument('-u','--update', action='store_true', default=None)
parser.add_argument('-g','--global', action='store_true', default=None)
args = parser.parse_args()

...

if args.update:
    print(args)
    print( args.global )
    print( args.update )

$ python ./anpm.py -g -u
  File "./anpm.py", line 67
    print( args.global )
                     ^
SyntaxError: invalid syntax

This is the error given by vscode

$ python --version
Python 3.6.8

Comment: `global` is a Python keyword, you can't use it as an attribute name
Answer: global is a keyword in Python (as are if, while, etc.) and you cannot use these as attribute names, which means they also don't work in a NameSpace object.
More on that here:
https://docs.python.org/3/reference/lexical_analysis.html#keywords
However, you can still access these values if you need to use these names:
my_args = vars(args)
print(my_args['global'])

This works because it doesn't use the reserved word, instead it just uses a string (containing the reserved word) to access its value.
If you only need access once, or infrequently and you don't want to keep the vars() result around, you can also just:
print(vars(args)['global'])

Comment: @januwa - same solution: don't try to access `args.del`, `del` is a reserved word. Use `vars(args)['del']` or alternatively, `getattr(args, 'del')`. Naming attributes using keywords is just a really bad idea and `argparse` making use of `NameSpace` objects sadly causes this conflict for command-line parameters as well, where you may be unable to avoid these keywords.
Comment: ... or rename the corresponding option.
Comment: ```    if args['del']:
TypeError: 'Namespace' object is not subscriptable```
Comment: After `args.global`, I encountered `args.del` again. I think this is a problem caused by a design flaw in the python interpreter.
Comment: @tripleee - obviously, but the answer already states "if you need to use these names"
Answer: Use getattr:
print(getattr(args, 'global'))

This would get the attribute global.
Answer: Global Explanation
Global is a reserved keyword in python that is used to declare a variable globally inside the functional scope.
Example:
def p():
    global x
    x=23
p()
print(x)
//returns 23

Keywords and example
A keyword can't be used as an argument or a variable in python. you can have other examples like
yield=23
return=34
pass=34
continue=23
.....

All these make an error.
Solution
Try changing the name from global to __global or _global or something like this.


Advance Plucking Lessons

Question: Check this out.
http://www.youtube.com/watch?v=LA-GadOp9sA (In this video it is not me)
I like plucking a lot. Most of the time I play Blackmoor's night. I can play several famous Blackmoor's Night track, including Under a Violate Moon, Catherin Howards Fate, Possum Goes to Prague etc.
But When I saw this plucking I was mesmerized! How do I even get started to get my control to this level?
Here I want to mention that, my first guitar lesson was One Last Breath - Creed, it took a long time to complete it. But, I just love plucking so much.
So, is there any suggesting about how can I focus more about plucking. Basically I am an amateur who is looking for some advanced lessons for improving my plucking skill.
Answer: You need a teacher or if not get hold of a copy of The acoustic guitar bible by Eric Roche. This is a brilliant advanced level book and will keep you busy for some time.
Comment: Can you suggest any particular guitarist's lesson who would be good for plucking?
Comment: If you want Internet lessons I reckon Justinguitar & Jamplay are the best, there are also some Tommy Emmanuell lesson but not many on you tube.  But for home study Like I said  The Acoustic Guitar Bible is the one.  Check out the author Eric Roche on Youtube a brilliant guitar player and teacher.

Advance Plucking Lessons


Sampling frame of a voluntary survey

Question: If one is conducting a survey in which all the respondents are volunteers, would there be a true sampling frame?
I see three possibilities:

We could view this as a situation where there is no set list of subjects from which those that end up being included in the sample are chosen -- so therefore there is no sampling frame
The sampling frame could be every possible individual in the world that has access to a computer (it it's online) or exits in physical space and who might encounter the person administering the survey- say anyone in the world who might live in or might be visiting the city and might happen to walk by the corner where the person who is administering the survey might be standing.  This would just mean that the vast majority of the sampling frame would have an extremely low inclusion probability
The sampling frame is all people who have a reasonable opportunity to take the survey- so if it were an internet survey, all of those who were asked to take the survey by email or had seen a page that had a link to the survey.  Similarly if someone were administering a survey in say a mall, then the sampling frame would be all people who were shopping in that mall in a given time.
Answer: Your first possibility is correct-there is no frame.  Your second and third define potential populations of volunteers.  A frame is not a population-rather it is a method that  allows you to link random numbers to (ideally)  every member of the population.
Then a draw of random numbers (perhaps in several stages) will identify the sample. Many people think that a frame must be a master list of the population members, but that's often not the case.  A multi-stage area sample, for example, starts with a list of areas (primary sampling units or PSUs), and random numbers draw a sample of these.  In each selected PSU  a list of smaller areas is prepared, and a random sample of these is taken.  The process can continue down to the selection of households and of individuals in households. The process is complicated when populations shift over time-consider post-voting surveys. In such cases, the method is to take a systematic sample of voters in time order.

Sampling frame of a voluntary survey


How to get node url of selected language?

Question: I have a node with an array of multiple languages.
 [19] => Drupal\node\Entity\Node Object
        (
            [in_preview] =>
            [values:protected] => Array
                (
                    [vid] => Array
                        (
                            [x-default] => 19
                        )

                    [langcode] => Array
                        (
                            [x-default] => en
                            [ca] => ca
                        )

I'm getting its url as:
$options = array('absolute' => TRUE);
$link = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $key], $options);

print($link) is giving me http://test-d8.local/en/node/19 where as I want url of "ca" language not "en" language. i.e. http://test-d8.local/ca/node/19
Is there any way that gives node translations of particular langcode?
This line $language = $entity->get('langcode')->value; is giving me the value of chosen language from select list.
Answer: You want to use toUrl() with the language option.
$node->toUrl('canonical', ['language' => $node->language()]);

Unfortunately, toUrl() currently doesn't automatically respect the active language.
Comment: `$node->toUrl('canonical', ['language' => $node->language()];` is not working. I added `$node->toUrl('canonical', ['language' => $node->language()]->toString();` Now its giving `/en/node/19` not even absolute url.
Comment: To make it absolute you can use the setAbsolute method `$url->setAbsolute(TRUE)`
Answer: $language = 'ca';
$link = $value->getTranslation($language)->url();
$title =  $value->getTranslation($language)->title->value;

this worked for me.
Answer: You can get the translation of the node like this:
$node = $node->getTranslation('ca');

And, depending what you need, you can get the link or url like this:
$link = $node->toLink();
$url = $node->toUrl();

Comment: Doesn't actually work like that AFAIK, see my answer.
Comment: I have tried this, but `$node = $value->getTranslation('ca');
       $link = $node->toUrl();
       print_r($link);die;` is giving a 404 infinite loop.


CKEditor and IMCE: how to access to public files directory

Question: I have a problem that I can't access public files directory from IMCE as file browser (and CKEDITOR as editor). When an user write a blog post, he can't upload images to public directory because this path doesn't appear in the IMCE directory tree.
Prior to post this question I have searched in Drupal Answers, in Drupal forum and in Google if there is an answer to my question but without success. I've read some other answer to similar questions but without success. I put here my configuration.
Config media file system:

Public path: sites/default/files
Private path: sites/default/files/private
Temp path: tmp
Checked: Private files served by Drupal

CKEditor file explorer: IMCE (for all)
Users, that can write blog post, has permission to "Bypass file access control", "Administer files", "add and upload new files", etc.
When they write a blog post and open IMCE to upload an image in the body, the paths shown in the directory tree are all relative to private directory and they can't select public path.
It's for Drupal 7.
How should I do to allow user to upload files to public path with IMCE?
UPDATE
After some days searching about this question, I have found where is the problem. There are two, very old, open issues in IMCE that are just my problem.
https://www.drupal.org/project/imce/issues/2018863
https://www.drupal.org/project/imce/issues/1700438
CKEditor launch IMCE according to the method you have selected to download files in Admin > Configuration > Media > File system, under the "Default download method". If you select private download then CKEditor always open IMCE in private folder and then you can't switch to public folder, despite of the new node will be public (blog post).
I think it's a very big problem. I should have the option to select if I want public or private directory in IMCE when It was launched by CKEditor.
Answer: Chances are you haven't set filebrowser permissions within the IMCE config page.

Go to Configuration > Media > IMCE
Setup/confirm the IMCE Profile for filebrowsing.  NOTE:  IMCE has its own "profiles" which can be used as roles specific to the filebrowser functionality. The default User-1 role has the ability to see all files/folders.  If you need more granular access to subfolders/specific folders within the files directory, setup a new profile.
Check that your blogger/blog contributor role has a profile assigned in Public Files column (and if necessary, private files column).

In addition to checking the IMCE filebrowser permissions, you'll want to check the individual field settings.  It can only be set to save/upload to either Drupal's public files directory or private files directory.  It doesn't allow content managers to choose which directory to upload/save to at time of upload/per piece of content.
Comment: Thanks for your help but I knew this configuration options and I have put it before I posted the question. I have the configuration as you said.
Comment: In order to show files in the public path, the field itself may need to be set to store uploaded files in the public files directory.  I've added a screenshot of that to my answer.  Note: if this solves the issue moving forward, you'll need to determine if your legacy files previously uploaded in private upload directory should be visible in public upload directory for future selection.
Comment: Thanks again for your support. I'm sorry but this is not the problem. As I wrote in the question, the problem is when CKEditor launch IMCE it always goes to private directory in spite of the content type is public. It isn't a problem with file fields.
Answer: It would be helpful to provide information on which Drupal Version you are working with and what editor related modules are activated.  In Drupal 8 the ckeditor module is activated as part of core.  IMCE can be added (and used to browse files) as a contributed module.  The comments provided by Drupal for the settings php file indicate that you need to set the private path outside
Drupal site path (i.e., not in sites/default/files).
From settings ...

A local file system path where private files will be stored. This
  directory must be absolute, outside of the Drupal installation directory   > and not accessible over the web.

In Drupal 8 there is a separate configuration step for IMCE (admin/config/media/imce that lets you set folder paths for an admin profile and a member profile.  Maybe you have something set in your member profile that's directing them the so-called private path?
I'd would recommend checking out the folder path settings in IMCE and maybe eliminating the private path settings in settings.php entirely.  Also, see if an admin can create a blog post and put the image in the public directory.  And clarify what Drupal version you are using.
Comment: I'm sorry. It was my fault. It's for Drupal 7.


To hide a "dl" in function of a label content in a "dt" in jQuery

Question: i have the following html code :

DL TO HIDE

            <select name="options[40]" id="select_40" class=" required-entry product-custom-option" title="" onchange="opConfig.reloadPrice()">
                <option value="">-- Faites un choix --</option>
                <option value="231" price="0">2005</option>
                <option value="232" price="0">2006</option>
                <option value="233" price="0">2007</option>
                <option value="234" price="0">2008</option>
                <option value="235" price="0">2009</option>
                <option value="236" price="0">2010</option>
                <option value="237" price="0">2011</option>
                <option value="238" price="0">2012</option>
                <option value="239" price="0">2013</option>
                <option value="240" price="0">2014</option>
            </select>

And if in the "dt" of the current "dl", the label is equal to "DL TO HIDE", i would like to hide all the dl concerned(the dt and the dd quoted above) .
Do you have an idea how to do?
Comment: @M.chaudhry Have a look at MDN: [](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd) and [](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl).
Comment: @M.chaudhry - It's `` description/definition list.
Comment: Do you have the ability to flag this in some other way?  Selecting element based on their text content is slow.
Comment: what is d1 ? and dd ? never saw before
Answer: Here is one way to do it -
var findText = "DL TO HIDE";
if(1 == $('dl dt label:contains(' + findText + ')').length ) {
    $('dl dt label:contains(' + findText + ')').closest('dl').hide();
}

http://jsfiddle.net/jayblanchard/rAww5/
Answer: Doesn't this work?
$('dl dt label:contains(DL TO HIDE)').closest('dl').hide();

However, what other people are saying is correct.  It's not a good idea to filter elements based on text content.  Hopefully, you would have tagged the elements with some kind of meta data before-hand to indicate that they should be hidden.  Alternatively, you could be tracking the element(s) to be hidden in a javascript variable.  Then you could do something like:
dlsToHide.hide();

or, if you only track the labels:
labels.closest('dl').hide();


show that $\exp(-t^4)$ is not a characteristic function

Question: I found, by assuming that exists a random variable $X$ that accepts $\exp(-t^4)$ as characteristic function , $E[X^2] = 0$, which means that $P[X=0] = 1$ implying the function is $0$. It's acceptable to use this fact to prove what I want, but I really don't know a formal way to say that, would someone help me with formality?
Thaks in advance.
Comment: How did you "find" this? Could you please elaborate? It is hard to suggest a formal way to prove it (your way) without knowing what you did.
Comment: http://en.wikipedia.org/wiki/Bochner%27s_theorem might prove helpful
Answer: The characteristic function is defined as:
$$ \varphi(t) = \mathbb{E}[e^{itX}] \tag{1}$$
and assuming either $X\in L^2$ or $\varphi\in C^2$ we have:
$$ \frac{d^2}{dt^2}\,\varphi(t) = \mathbb{E}[-X^2 e^{itX}]\tag{2} $$
by the linearity of the expected value, hence $\varphi''(0)=0$ implies $\mathbb{E}[X^2]=0$.
As you already noticed, that leads to a contradiction since it implies that the distribution of $X$ is concentrated in a single point, $\mathbb{E}[X]$. A more striking contradiction is also given by:
$$ -24 = \varphi^{IV}(0) = \mathbb{E}[X^4] \geq 0.\tag{3}$$


Show that $\lim_{p\to\infty}\int_{A}f^{p}d\mu=\infty$.

Question: Let $\left(X,M,\mu\right)$ be a measure space. Suppose $f:X\to[0,\infty)$ is measurable and the set $A:=\left\{ x\in X\mid f\left(x\right)>1\right\}$  has positive measure. Show that $\lim_{p\to\infty}\int_{A}f^{p}d\mu=\infty$.
Hint: Let $A_{n}=:\left\{ x\in X\mid f\left(x\right)>1+\frac{1}{n}\right\}$.
Even with the hint, I still don't know where to start. Any help will be much appreciated.
Answer: The sequence {$A_n$} increases to $A$. So, $\mu(A_n) \leq \mu(A)$ for each $n$(By montonicity) . Since $\mu(A)< \infty$, $\mu(A_n)<\infty$. So,
$\int_{A} f^p d\mu \geq \int_{A_n} f^p d\mu > \int_{A_n} (1+ \dfrac{1}{n})^p d\mu=(1+ \dfrac{1}{n})^p \int_{A_n}1 d\mu = (1+ \dfrac{1}{n})^p  \mu(A_n)$
Letting $p \to \infty$, the rightmost term apporaches $\infty$. Hence, $\int_{A} f^p d\mu \rightarrow \infty$ as $p \to \infty$


Javascript assumed conflict with Drupal

Question: I have a website, where I have been trying to build a form with server side and client side validitations of the input fields. More or less I have been achieving progress. Then I put my code from my testing enviroment to the drupal based website, to see how many tweaks do I need to make. Needless to stay lot of things fell apart. Most important at the moment is that my javascript checks if the input field has the correct information, if it does, it colors the input field and changes the helper thex accordingly. This got fully broken on the site. I read a lot and I assumed this may be cause drupal uses an older JQuery that which I was testing with. So with a little help in another question here I invoked the noConcflict and I used the newer jquery with my code. Sadly this did not fix my problem.
The html of the site is located here:
http://www.htconsulting.hu/test/form
The javascript:
http://www.htconsulting.hu/form/validation.js
Ps.: After the noconflict, my popup Jquery UI broke as well, so I hope to find a possible solution outside using noConflict, or solving the popup window now...
Answer: You should use the jQuery provided by Drupal and try to work with what Drupal provides (JavaScript, Form API, Theme system, etc.) instead of trying to work without it or, worse, against it. The jQuery update module allow you to use updated jQuery releases in Drupal. That would be 1.6.2 for Drupal 7 and 1.3.2 for Drupal 6. Drupal 7 also provides jQuery UI while for Drupal 6, the jQuery UI module should be used to provide it. This way you can avoid compatibility issues between different version of the same library, unnecessary workarounds and fixes over fixes.
Also, you shouldn't use $(document).ready() in Drupal, but add your function to Drupal.behaviors as explained in the Drupal JavaScript API guide (also available for Drupal 6). And off course, for the form generation, validation and submission server-side code, you should use the Form API.
Keep in mind that your are trying to add a form to a Drupal site, not to a stand alone simple PHP script that doesn't already provides all the (server-side) API your need.
Answer: The problem appears to be that when you load jquery the first time, you call no-conflict and assign it to $jq.  You then load jquery again, re-assigning $ to this 2nd jquery (same version by the way) and after that you load jquery ui.  This means that jquery ui is going to attach to the most recently loaded jquery (the one still using $ and not $jq).  So $("#dialog").dialog() should work, but $jq("#dialog").dialog() will not, because $jq does not have ui, $ does.
From looking at this page, there is no need for noConflict at all, since both versions of jquery you are loading are 1.6.2.
Comment: I "fixed" that part, the noConflict was not used because of that. noConflict was invoked, since a few lines above the implemented code, the Drupal system loads a different jquery script:

Now my popup button does work. But the validation all of it, is now non-functional as of last check..
Answer: Shameless pug, we created a module todo this, see http://atix.be/docv, the only thing we don't support for the moment is to display the errors in a popup, but feel free to open an issue

Javascript assumed conflict with Drupal


Nested condition of if-statement in bash

Question: I want to check that of two variables both or neither are set. I've tried multiple options, and this is the most clean solution I've come up with:
if [ ! -z $A -a -z $B ] || [ -z $A -a ! -z $B ]; then
  #error
fi
  #success

When I run the script with both A and B set - it runs fine. But when I run it with A missing I get:
./test.sh: line 3: [: too many arguments
./test.sh: line 3: [: too many arguments

line 3 being the condition statement.
When I run it with B missing, I get:
./test.sh: line 3: [: argument expected
./test.sh: line 3: [: argument expected

Is it my condition that has wrong syntax or am I missing smth else?
Comment: Double quote the variables, otherwise if empty, they expand to nothing.
Answer: You should try to avoid -a; it's non-standard and considered obsolete by the POSIX standard. Since || and && have equal precedence, you need to use { ... } to properly group the individual tests.
(This is in addition to the immediate need to quote your parameter expansions.)
if { [ ! -z "$A" ] && [ -z "$B" ]; } || { [ -z "$A" ] && [ ! -z "$B" ]; }; then

However, a simpler expression might be
if [ -z "$A$B" ] || { [ "$A" ] && [ "$B" ]; }; then

The concatenation of two strings is empty if and only if both strings are also empty.
[ "$A" ] is short for [ -n "$A" ], which is equivalent to [ ! -z "$A" ].

Using bash's [[ ... ]] command, you can write the more natural
if [[ -z $A && -n $B || -n $A && -z $B ]];

Quotes are optional in this case, and || and && are usable inside [[ ... ]] with the precedence you expect.
Answer: Quote your variables:
if [ ! -z "$A" -a -z "$B" ] || [ -z "$A" -a ! -z "$B" ]; then

If the variables are unquoted and unset, they are replaced with nothing, meaning that the command essentially becomes:
if [ ! -z -a -z ] || [ -z -a ! -z ]; then

resulting in the error you see.
Comment: kill me now... that simple?!
Thanks, it works.
Comment: You might also mention `[[`, `&&` ... :)
Comment: @PesaThe: True, there are many options, depends on what shells/platforms are targeted..
Answer: You forgot to use quotation marks around your vars:
if [ ! -z "$A" -a -z "$B" ] || [ -z "$A" -a ! -z "$B" ]; then
    echo "error"
fi

Bash will replace your vars in your script with the values, so when A=5 and B is unset, your version will read:
if [ ! -z 5 -a -z  ] || [ -z 5 -a ! -z ]; then

You see that the syntax is wrong, as -z expects an argument. When using quotes, is reads:
if [ ! -z "5" -a -z "" ] || [ -z "5" -a ! -z "" ]; then

AS you can see, now the argument for B is an empty string, which is valid.
Also your version would have failed when setting A="string with spaces" when unquoted.


PS0224 No message text found! error after installing .net 4.5.2

Question: I have recently installed the .net 4.5.2 dev pack and cannot compile a few .net 4.0 projects that implement postsharp 4.1.13 aspects. The relevant items in the output windows after clean and build are

: message PS0220: PostSharp needs to generate binding maps for the
selected platform. This could take a while. The result will be cached
and the next build will be faster.
: postsharp error PS0224: [PS0224].> No message text found!.

4.5.2 Projects that do and do not use post sharp 4.1.17 can compile correctly.
We have removed the .13 nuget package from the projects and added the .17 version, and that seems to have corrected the problem, but that revision increment comes with its own postsharp versioning issues we would like to avoid.
Does anyone have an idea of how to determine what may be causing this or how to go about correcting it and remaining on version .13?
Comment: What kind of versioning issues would you like to avoid by keeping 4.1.13?
Comment: @JakubLinhart part of our work is to build extensible frameworks that other developers in our company (and ourselves) use.  If our framework is built to use .13, then all dll extensions or implementers are essentially locked into .13. If we update to .17, then we force all callers to update.
Answer: PS0224 means that PostSharp could not access a file while generating binding maps for the current compilation. All of these files are stored in C:\ProgramData\PostSharp\BindingMaps and the most likely problem is that the user under which PostSharp is running does not have write access to this directory.
Since you have installed .NET 4.5.2, which is an in-place upgrade, PostSharp needed to generate new binding maps as it running on a different version of .NET.
Indeed there was a merge issue in our codebase sometime ago and the message text was not included in this version.
Hope this helps.
Comment: Some of us run VS "as adminstrator" and were getting the same error. I do have that folder in my local, and it has a 4.5.2 subfolder with a bunch of assemblymap files, but my bindingmap folder has different content from others's folders. Do you know what the ideal folder structure looks like so we can continue this inspection?
Comment: Everything should be in `BindingMaps\v1`. Next level is target framework (of the compiled assembly). In this level you will have `.AssemblyMaps` file and `.AssemblyMap` file for each referenced target. Next level is for native framework (version of .NET used when running PostSharp). Since this is a cache and is created lazily, different machines may have different content. We use a global Mutex for synchronization if possible. You can always delete the folder and PostSharp should recreate it - if it is able. Since 4.1.13 is missing the error message we cannot be sure which file it is.