Depois do clear:both, div com float não alinha corretamente

Question: Estou fazendo um site responsivo e estou usando "float" e "clear: both" pra colocar as divs nos seus lugares. Mas depois de usar "clear: both", a "div6" não alinha corretamente no lado direito.
Para esclarecer:
HTML:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Title</title>

1

2

3

4

5

6

CSS:
.clear
{
clear:both;
}

.container
{
width: 100%;
height:auto;
position:relative;
left: 0;
top: 0;
display:table;
background-color:#CCC;
}

.div1
{
background-color:#FF0;
position:relative;
width: 50%;
height:200px;
float:left;
margin-left:0;
}
@media screen and (max-width: 700px)
{
.div1
{
background-color:#FF0;
position:relative;
width: 100%;
height:200px;
float:left;
margin-left:0;
}
}

.div2
{
background-color:#FC0;
position:relative;
width: 50%;
height:40px;
float:right;
margin-right:0;
}
@media screen and (max-width: 700px)
{
.div2
{
background-color:#FC0;
position:relative;
width: 100%;
height:40px;
float:left;
margin-left:0;
}
}

.div3
{
background-color:#F90;
position:relative;
width: 50%;
height:40px;
float:right;
margin-right:0;
}
@media screen and (max-width: 700px)
{
.div3
{
background-color:#F90;
position:relative;
width: 100%;
height:40px;
float:left;
margin-left:0;
}
}

.div4
{
background-color:#F60;
position:relative;
width: 50%;
height:40px;
float:right;
margin-right:0;
}
@media screen and (max-width: 700px)
{
.div4
{
background-color:#F60;
position:relative;
width: 100%;
height:40px;
float:left;
margin-left:0;
}
}

.div5
{
background-color:#0C6;
position:relative;
width: 50%;
height:80px;
float:left;
margin-left:0;
}
@media screen and (max-width: 700px)
{
.div5
{
background-color:#0C6;
position:relative;
width: 100%;
height:80px;
float:left;
margin-left:0;
}
}

.div6
{
background-color:#396;
position:relative;
width: 50%;
height:40px;
float:right;
margin-right:0;
}
@media screen and (max-width: 700px)
{
.div6
{
background-color:#396;
position:relative;
width: 100%;
height:40px;
float:left;
margin-left:0;
}
}

Eu imagino que a solução para isso seja simples mas não estou conseguindo resolver esse problema. Agradeço a ajuda!
Comment: Posso te fazer uma pergunta? Já que vc esta na faze inicial do projeto, ainda na construção do grid, Pq vc não opta por fazer esse grid com Flex e não com float? Float eh uma técnica arcaica por assim dizer, e o Flex tem uma serie de vantagens, além das classes de alinhamento etc...
Answer: O que posso dizer é que o seu float está funcionando perfeitamente, só que não da forma que vc esperava...
Repare que vc colocou um div com clear:both, logo depois da div 4, com isso vc cria uma "linha de quebra" que limpa o fluxo do conteúdo e joga tudo que vier depois da div 4 para outra linha de baixo e tem outro fluxo de conteúdo.

Veja que na classe da div que faz o clear eu coloquei uma borda, assim fica fácil de vc visualizar onde ela "corta" o fluxo. Nada que vier abaixo dessa div clear vc vai conseguir passar para "linha de cima"... a não ser com gambiarra... Que foi o que eu fiz nesse modelo abaixo apenas para te mostrar que é possível, mas não é indicado!

Então não é por que vc pode que vc deve... Como falei no comentário, aproveite que vc está no inicio e considere usar Flexbox no sei projeto!
Segue o código da imagem acima:

.clear {
    clear: both;
    border: 1px solid #000;
}

.container {
    width: 100%;
    height: auto;
    position: relative;
    left: 0;
    top: 0;
    display: table;
    background-color: #CCC;
}

.div1 {
    background-color: #FF0;
    position: relative;
    width: 50%;
    height: 200px;
    float: left;
    margin-left: 0;
}

@media screen and (max-width: 700px) {
    .div1 {
        background-color: #FF0;
        position: relative;
        width: 100%;
        height: 200px;
        float: left;
        margin-left: 0;
    }
}

.div2 {
    background-color: #FC0;
    position: relative;
    width: 50%;
    height: 40px;
    float: right;
    margin-right: 0;
}

@media screen and (max-width: 700px) {
    .div2 {
        background-color: #FC0;
        position: relative;
        width: 100%;
        height: 40px;
        float: left;
        margin-left: 0;
    }
}

.div3 {
    background-color: #F90;
    position: relative;
    width: 50%;
    height: 40px;
    float: right;
    margin-right: 0;
}

@media screen and (max-width: 700px) {
    .div3 {
        background-color: #F90;
        position: relative;
        width: 100%;
        height: 40px;
        float: left;
        margin-left: 0;
    }
}

.div4 {
    background-color: #F60;
    position: relative;
    width: 50%;
    height: 40px;
    float: right;
    margin-right: 0;
}

@media screen and (max-width: 700px) {
    .div4 {
        background-color: #F60;
        position: relative;
        width: 100%;
        height: 40px;
        float: left;
        margin-left: 0;
    }
}

.div5 {
    background-color: #0C6;
    position: relative;
    width: 50%;
    height: 80px;
    float: left;
    margin-left: 0;
}

@media screen and (max-width: 700px) {
    .div5 {
        background-color: #0C6;
        position: relative;
        width: 100%;
        height: 80px;
        float: left;
        margin-left: 0;
    }
}

.div6 {
    background-color: #396;
    /* position: relative; */
    width: 50%;
    height: 40px;
    float: right;
    margin-right: 0;
    /* float: right; */
    /* margin-right: 0; */

    position: absolute;
    top: calc(40px * 3);
    right: 0;
}

@media screen and (max-width: 700px) {
    .div6 {
        background-color: #396;
        position: relative;
        width: 100%;
        height: 40px;
        float: left;
        margin-left: 0;
        top: initial;
    }
}

1

2

3

4

5

6

DICA
Comment: Obrigado pela resposta hugocsl foi bem esclarecedora. Realmente a solução é uma "gambi" pois ela calcula a altura das divs acima para posicionar a div6. No meu caso acredito que não seria a solução ideal pois as divs acima podem variar em quantidade e altura. Mas a dica do FLEXBOX parece uma boa. Não conhecia esse recurso e já estou navegando e estudando para aplicar. Agradeço seu tempo e sua ajuda que foi muito valiosa. Grande abraço!
Comment: @JohnSnowDad cara tem muito material sobre FlexBox por ai, vc vai ver que é bem fácil de usar e mais flexível que o float. O Bootstrap mesmo usa Flex no Grid deles. Se a minha resposta te ajudou de alguma forma e vc acha que o assunto está resolvido considere marca-la como Aceita, nesse ícone ✔ abaixo das setinhas no lado esquerdo da minha resposta :) assim o site não fica com a pergunta aberta pendente mesmo já tendo sido esclarecida. E se tiver alguma dúvida com Flex no futuro posta ai que a gente te ajuda!


Why derivative of $(3x^2 - 2)^{\frac{2}{x}}$ can be written as $(3x^2 - 2)^{\frac{2}{x}} \cdot (ln(3x^2 - 2)\cdot\frac{2}{x})'$?

Question: I am struggling with derivatives of exponents functions...
Why derivative of $(3x^2 - 2)^{\frac{2}{x}}$ can be written as $(3x^2 - 2)^{\frac{2}{x}} \cdot (ln(3x^2 - 2)\cdot\frac{2}{x})'$?
Where does that property come from?
Please provide a complete explanation with the rules you are using, otherwise for me its difficult, since I am quite newbie
Comment: $(3x^2 - 2)^{\frac{2}{x}}$ can be written $$\\exp{\left(\left(\frac{2}{x}\right) \ln(3x^2 - 2)\right)}$$
Comment: Exactly, perfectly and monumentally correct.
Answer: Hint:
Using:$ f=e^{\log f}$, We have:
$$
f(x)^{g(x)}=e^{g(x)\log f(x)}
$$
Than use chaining rule for derivative.
We have:
$$
\dfrac{d}{dx} e^{[ g(x)\log f(x) ]}=e^{[ g(x)\log f(x) ]}\dfrac{d}{dx}[ g(x)\log f(x) ]
$$
Comment: I've added to my answer.


Given points on graph, fit a line such that largest error is minimal

Question: Given points on graph, the popular method of fitting a line is by using the least-squares method. I need a different method - I need the worst error, i.e. the largest distance from a point to the line, to be as small as possible.
I need to implement it in Matlab, so if it provides relevant functions, that would be awesome.
Example:

The least-squares method would bring the line near the bottom dots, but the method that I need should bring it in the middle, because that would minimize the worst error.
Answer: What you're doing is called "minimax approximation", because you are trying to minimize the maximum error.
Alternatively, it's called "uniform approximation" because the error is measured using the uniform ($L_\infty$) norm, rather than the $L_2$ norm used in least-squares fitting.
You can find some useful material by googling these two terms.
For minimax approximation of a function by a polynomial, the standard technique is the Remez algorithm, which is fairly complicated. Your case is much simpler than this. You basically have only two variables (the slope and intercept of the line), so any decent optimization function should be able to find the best solution.
Comment: Thank you! I found an implementation here: http://stackoverflow.com/questions/20364675/minimizing-l-infinity-norm-in-matlab


The naive kernel density estimator definition

Question: On B W Silverman Explanation of KDE:
It is stated that from the definition of a probability density, if the random variable X has density f, then
$f(x) = \lim_{h\to 0} \dfrac{1}{2h}\Pr(x-h < X \le x+h) $
And that a natural naive density estimator is
$f(x) =  \dfrac{1}{2hn}[\text{no. of } X_1,..,X_n \text{ falling in }(x-h, x+h)] $
Where is the $\frac{1}{2}$ coming from?
If I have 2 values from a sample of 10 on the $(x-h,x+h)$ range $\Pr(x-h < X \le x+h) = \frac{2}{10}$ how does multiplying by $\frac{1}{2h}$ gives me the density?
Comment: The interval is $2h$ long...
Answer: The probability $2/10$ is the area under the density from $x-h$ to $x+h$, which has length $2h$ and has height $f(x)$ when approximating the area by a rectangle, thus
$$
\frac{2}{10} = f(x) \, 2h
$$
Comment: This is beautiful. Thank you.


problem involving inertia

Question:
Update my lagrangian is
$$L=\frac{ml^2}2\left(\dot \theta_1^2+\frac 13\dot \theta_2^2+\dot \theta_1\dot \theta_2\cos\delta\right)+mgl(cos\theta_1+\frac 12\cos\theta_2)$$
and for my linearised equations of motion question (5) i got the following
$$(\ddot \theta_1) +\frac{2}{3}\ddot\theta_2=\frac{-2g}{l}\theta_2$$
and $$2\ddot \theta_1 +\ddot \theta_2=\frac{-2g}{l}\theta_1$$
These seem to give numerically unpleasant normal mode frequencies though, so I'm not entirely sure that they're right, maybe i went wrong on calculating the equations of motion. a futher solution would be ideal. Thanks
my differentials were
$$\frac{dL}{d\theta_1}=-\frac{ml^2}{2}\dot\theta_1\dot\theta_2\cos(\theta_1)sin(\theta_2)-\frac{ml^2}{2}\dot\theta_1\dot\theta_2\sin(\theta_1)\cos(\theta_2)-mgl\sin(\theta_1)$$
$$\frac{dL}{d\theta_2}=-\frac{ml^2}{2}\dot\theta_1\dot\theta_2\cos(\theta_1)\sin(\theta_2)+\frac{ml^2}{2}\dot\theta_1\dot\theta_2\sin(\theta_1)\cos(\theta_2)-\frac{mgl}{2}\sin(\theta_2)$$
$$\frac{dL}{d\dot\theta_1}=ml^2\dot\theta_1+\frac{ml^2}{2}\dot\theta_2\cos(\theta_2-\theta_1)$$
and finally $$\frac{dL}{d\dot\theta_2}=\frac{ml^2}{3}\dot\theta_2+\frac{ml^2}{2}\dot\theta_1\cos(\theta_2-\theta_1)$$
so the two equations of motion are
$$ml^2\ddot\theta_1+\frac{ml^2}{2}\dot\theta_1\dot\theta_2\cos(\theta_1)sin(\theta_2)+\frac{ml^2}{2}\dot\theta_1\dot\theta_2\sin(\theta_1)\cos(\theta_2)+mgl\sin(\theta_1)=0$$
and $$\frac{ml^2}{3}\ddot\theta_2+\frac{ml^2}{2}\dot\theta_1\dot\theta_2\cos(\theta_1)\sin(\theta_2)-\frac{ml^2}{2}\dot\theta_1\dot\theta_2\sin(\theta_1)\cos(\theta_2)+\frac{mgl}{2}\sin(\theta_2)=0$$
Answer:
For an arbitrary point on the rod, let $p$ be its distance from the point of connection to the wire. Since the mass is uniformly distributed, then
$$dm=\frac ml dp$$
and the distance of that point from the reference of rotation can be obtained from the law of cosines:
$$r^2=l^2+p^2+2lp\cos\delta$$
Here, $\delta=\theta_2 - \theta_1\,$. The moment of intertia is defined by:
$$dI=r^2 dm\implies I=\frac ml\int_0^l r^2 dp$$
Consequently
$$I=\frac ml\int_0^l(l^2+p^2+2lp\cos\delta)dp=m l^2\left(\frac 43+\cos(\theta_2-\theta_1)\right)$$
The kinetic energy is calculated from a similar procedure.
$$dK=\frac 12v^2dm\implies K=\frac m{2l}\int_l v^2 dp$$
where
$$\begin{align}v^2&=v_x^2+v_y^2=[\partial_t(l\sin\theta_1+p\sin\theta_2)]^2+[\partial_t(l\cos\theta_1+p\cos\theta_2)]^2\\&=
(l\dot{\theta_1}\cos\theta_1+p\dot{\theta_2}\cos\theta_2)^2+(l\dot{\theta_1}\sin\theta_1+p\dot{\theta_2}\sin\theta_2)^2\\&=
(l\dot{\theta_1})^2+(p\dot{\theta_2})^2+2lp\dot{\theta_1}\dot{\theta_2}\cos\delta\end{align}$$
Thus
$$K=\frac{ml^2}2\left(\dot{\theta_1}^2+\frac 13\dot{\theta_2}^2+\dot{\theta_1}\dot{\theta_2}\cos\delta\right)$$
And similarly, the potential energy is the result of an integral as well:
$$dU=-gh\,dm\implies U=-\frac {mg}l\int_0^l hdp$$
where
$$h=l\cos\theta_1+p\cos\theta_2$$
which results in $$U=-mgl(\cos\theta_1+\frac 12\cos\theta_2)$$
Lagrangian is given by $K-U$. Let $\omega_1=\dot\theta_1$ and $\omega_2=\dot\theta_2$ then
$$L=\frac{ml^2}2\left(\omega_1^2+\frac 13\omega_2^2+\omega_1\omega_2\cos(\theta_2-\theta_1)+\frac gl(2\cos\theta_1+\cos\theta_2)\right)$$
and from Euler-Lagrange equations
$$\frac d{dt}\left(\frac{\partial L}{\partial\omega_i}\right)=\frac{\partial L}{\partial\theta_i},\quad i=1,2$$
we have
$$2\dot\omega_1+\dot\omega_2\cos(\theta_2-\theta_1)-\omega_2^2\sin(\theta_2-\theta_1)+2\frac gl\sin\theta_1=0\\
\frac 23\dot\omega_2+\dot\omega_1\cos(\theta_2-\theta_1)+\omega_1^2\sin(\theta_2-\theta_1)+\frac gl\sin\theta_2=0$$
Thus the state-space equations, knowing that the state variables are $\theta_1,\theta_2,\omega_1,\omega_2$ can be written as:
$$\begin{align}\pmatrix{\dot\theta_1\\\dot\theta_2}&=\pmatrix{\omega_1\\ \omega_2}\\
\pmatrix{\dot\omega_1\\\dot\omega_2}&=\pmatrix{2&\cos(\theta_2-\theta_1)\\ \cos(\theta_2-\theta_1)&\frac 23}^{-1}
\pmatrix{\omega_2^2\sin(\theta_2-\theta_1)-2\frac gl\sin\theta_1\\
-\omega_1^2\sin(\theta_2-\theta_1)-\frac gl\sin\theta_2}
\end{align}$$
and you can linearize the system by calculating the Jacobian, $\frac{\partial f}{\partial x}|_{x=0}$ which is a straightforward but tedious process.
$$x=(\theta_1,\theta_2,\omega_1,\omega_2)^T\longrightarrow\left[\frac{\partial f}{\partial x}\right]_{x=0}=\pmatrix{0&I_{2\times 2}\\J_{2\times 2}&0}$$
where
$$J=\frac gl\pmatrix{-4&3\\6&-6}$$

problem involving inertia


how to force await to continue in same caller thread in Console application

Question: I am writing a .Net Console application in C#.
I need to convert the Event based Threaded call to async method.
For example :
public class WorkerClass
    {
        public EventHandler Progress;
        public EventHandler Finished;
        public void DoSomething()
        {
            Thread td = new Thread(Start);
            td.Name = "Worker Thread";
            td.Start();
        }

        private void Start()
        {
            int i = 0;
            while (i < 10)
            {
                Thread.Sleep(1000);
                i++;
                var progress = i * 10;
                Progress?.Invoke((object)progress, null);
            }
            Finished?.Invoke(null, null);
        }
    }

    Class MyMainClass
            {
                private static WorkerClass myWorkerClass;
                static void Main(string[] args)
                {
                    myWorkerClass = new WorkerClass();
                    RunAsynchronously(null);
                }
                private async void RunAsynchronously(EventHandler progress)
                {
                    //Main Thread Call

                    await DoSomethingAsync(progress);

                    //Resume after worker finished is not in main thread? :(
                    //Needed main thread to continue
                }
                private Task<int> DoSomethingAsync(EventHandler progress)
                {
                    var completionSource = new TaskCompletionSource<int>();

                    EventHandler Progress = null;
                    EventHandler Finished = null;

                    Finished = (o, e) =>
                    {
                        myWorkerClass.Finished -= Finished;
                        myWorkerClass.Progress -= Progress;
                        completionSource.SetResult(100);
                    };

                    Progress = (o, e) => { progress?.Invoke(o, e); };

                    myWorkerClass.Finished += Finished;
                    myWorkerClass.Progress += Progress;

                    myWorkerClass.DoSomething();

                    return completionSource.Task;
                }
            }

Due to some limitation i need the main thread to continue,
However after await resumes the in RunAsynchronously method , the current thread is something different than main thread (or the thread that called await).
I know this behaviour will automatically work if the caller is UI thread, but in my case it is console application and i dont have UI.
Please suggest solution.
Thanks in advance.
Comment: Why is `DoSomethingAsync(EventHandler progress)` async at all? It's just a classic synchronous method. Where's your `static void Main()` ? Which language version are you on?
Comment: Its just a sample code , consider static void Main() in MyMainClass class, which further calls DoSomethingAsync(null);

For Example:

static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            myWorkerClass = new WorkerClass();
            RunAsynchronously(null);
        }
Comment: Can you confirm that this actually works (be it on the wrong thread)? I'd expect the application  to terminate at `await DoSomethingAsync...`.
Comment: I am using C# 7.0 version. DoSomethingAsyc(EventHandler progress) is async because of two reasons 1) It will be performing long running operation so i don't want to block the thread . 2) I want to convert Event based asynchronous pattern to one single API call.
Comment: @ Haukinger Yes it is actually running fine , the only problem is after await the continuation is in wrong thread in case of Console application , If we use WinForm or WPF then even the continuation is in Correct thread i.e UI thread.
Comment: @Haukinger  Please dont be confused by ** before DoSomethingAsync, I tried making them bold and Editor added ** to it :P
Comment: When I try this, I get one thread id and "done", but the program's not waiting for the delay: internal class Program
{
 static void Main( string[] args )
 {
  DoSomethingAsync();
  Console.WriteLine( "done" );
 }

 private static async void DoSomethingAsync()
 {
  Console.WriteLine( Thread.CurrentThread.ManagedThreadId );
  await Task.Delay( 3000 );
  Console.WriteLine( Thread.CurrentThread.ManagedThreadId );
 }
}
Comment: Here's the explanation and solution for this case: https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/
Comment: Or use an async main in the first place (that's why I asked for c# version) - but he doesn't want to await in main, obviously
Answer: I feel like you have a fundamental misunderstanding of what to expect from a console application and the threading model of a .NET application.
A console application runs until its entry thread completes execution of the Main method. This means you either keep the thread busy doing work, or you block the thread until another signal unblocks it and allows the method to exit. It's a very simple construct designed to allow you to start your application, do some work, then exit when you're done. It means the thread is never "free" to do other work; you can't schedule a task to continue on this thread without completely changing the work-scheduling model to a much more sophisticated one.
In a UI-based application, your application follows a much more complex model. Instead of the application doing some work, then exiting, instead the main thread is asked to pump a message queue, doing work based on messages received and only exiting when it receives a "quit" message. This model takes a single thread and gives it a queue of work to do, each piece of work signalled by a message. This is what allows you to have a Task resume on the UI thread.

This kind of confusion is why the async void pattern is generally considered an anti-pattern, and certainly why it is only acceptable to use in applications with a UI. The application only works correctly because of a very specific task-scheduling model. Any other model causes this construct to break, swallowing exceptions and making it impossible to know when work has completed.


Memory for scala types: heap or stack

Question: Scala's String maps to Java's String. So reference will be in heap.
Scala's int, float maps to Java's Integer or primitive int. When does it refer to wrapper class and primitive types?
If it is wrapper class, will ref be at heap? If it is primitive, will ref be at stack?
How does that switch happen for a single variable? I read that scala uses both for optimization.
Answer:
When does it refer to wrapper class and primitive types?

Wrappers are used when primitive types can't be: e.g. it's used as a type parameter (other than for Array) or passed to a method taking Any/AnyRef.
You can tell what is used in a specific case by looking at bytecode, see e.g. https://www.toptal.com/scala/scala-bytecode-and-the-jvm.

If it is wrapper class, will ref be at heap? If it is primitive, will ref be at stack?

If it's primitive, there's no reference. And stack is only used for local variables. For local variables of type Int or Float, yes, primitive types are used.

Memory for scala types: heap or stack


Overload implementation

Question: In the video I've found that interfaces can use strange overload technique. The code below is compiled but does not work.
I have some questions, all of them are placed inside of the code:
interface X{

// how can the class implements such overload ?
    f:{
        (s:string):string;
        (s:number):string;
        data:any;
    };
}

class xxx
{

// how to initialize this structure ?
    f:{
        (s:string):string;
        (s:number):string;
        data:any;
    };
}

var x = new xxx();

// how should the class xxxx look to be used with this function ?
function a(x:X):string{
    return x.f("1");
}

a(x);

Answer: I think you're trying to call the function f with either a string or a number.
In your interface, you define the overloads like this:
interface X{
    b(s:string) : string;

    f (s:string):string;
    f (s:number):string;
}

And you implement the interface like this.
class xxx implements X
{
    b(s:string) : string
    {
        return "";
    }

    f (s: string): string;
    f (s: number) : string;
    f (s: any) : string {
        return s.toString();
    }
}

Here is complete example you can paste into the Playground to try:
interface X {
    b(s:string) : string;
    f (s:string):string;
    f (s:number):string;
}

class xxx implements X {
    b(s:string) : string {
        return "";
    }

    f (s: string): string;
    f (s: number) : string;
    f (s: any) : string {
        return s.toString();
    }
}

var x = new xxx();

alert(x.f("1"));
alert(x.f(5));

Comment: FTR: Reverted to original answer, which is the readable way to define overloads in TypeScript. Additionally, I would define data separately to the function overload in a class field.
Comment: You did skip the most important thing - field data as method's property. I know full well how to make override.
Comment: Well, I covered that in my previous comment. This answer is for people who encounter the question and want to use overloads. Your answer is for your localised scenario. Everyone is a winner.
Comment: No, I'd like to know how to use the interface from my post, not yours.
Comment: Updated based on your comment.
Comment: You still have different declaration of the interface.
Comment: Yes - because you can't access the functions unless they have a key.
Answer: The only solution I've found is to use type cast. It works, but looks quite ugly. To me this is an error in the compiler or there should be different way to do this.
UPD: Indeed, this is the only solution, http://typescript.codeplex.com/discussions/401235
interface X{
    f:{
        (s:string):string;
        (s:number):string;
        data:any;
    };
}

class xxx
{
    constructor()
    {
        this.f = <{ (s:string):string; (s:number):string; data:any; }> function (s:any):string {return s.toString();};
        this.f.data = "data"
    };

    f:{
        (s:string):string;
        (s:number):string;
        data:any;
    };
}

var x = new xxx();

function a(x:X):string{
    return  x.f("1") + x.f(1) + x.f.data;
}

alert(a(x));

Comment: Downvoters: can you explain why this is a bad solution?

Overload implementation


Complex integral $\int_{-\infty}^{\infty} e^{-zt^2+2wt}dt$

Question: The goal is to show this integral
$\int_{-\infty}^{\infty} e^{-zt^2+2wt}dt = \sqrt{\frac{\pi}{z}} e^\frac{w^2}{z}$ for $z,w \in \mathbb{C}$ with $\Re(z)>0$ using the identity:
$
\int_{-\infty}^{\infty}e^{-\pi x^2}e^{-2\pi ix \psi}dx = e^{-\pi \psi^2}
$ for $\psi \in \mathbb{R}$
I have proven in a previous far that the function is holomorphic as a function of $z$ on all of $\mathbb{C}$ but I'm not sure how to do this next part. I looked for a substitution that would help but I only know the substitution formula for real number so I cannot just replace the $x$ in the identity with some complex number.
Any help welcome :)
Comment: You probably meant holomorphic as a function of $w$ on all of $\mathbb{C}$. Also, take a look at https://math.stackexchange.com/q/2185537
Comment: @metamorphy sorry it was a typo now it is correct
Comment: complete the square in the $-z t^2 + 2 wt$ exponent. let's see, they want $z t^2 - 2 wt = \pi x^2 + 2 \pi i \psi x + C$ to start, so we need to deal
Comment: @Gary its definitely z
Comment: @leoli1 it is the same integral, but I am expected to use the method in the problem statement i.e. using the identity!
Comment: @citizenfour How do you define your function holomorphically for $z=0$ or $z<0$ (there is $1/z$ and a $\sqrt{z}$ in the formula for the function)?
Answer: I'm not certain this is correct but it is my best shot:
We complete the square in the exponent:
$zt^2 -2xt = \pi x^2 + 2\pi \psi ix +C\\
(\sqrt{z}t-\frac{w}{\sqrt{z}})^2-\frac{w^2}{z} = \pi x^2 + 2\pi ix \psi + C$
This gives us a value for $C = \frac{-w^2}{z}$, a value for $\psi = 0$ and a substitution $t =\sqrt{\frac{\pi}{z}}x + \frac{w}{z}$ (this is the bit I am unsure of - can I substitute a real number for this complex one????) But this reduces the function down to:
$
f(z) = e^{\frac{w^2}{z}} \sqrt{\frac{\pi}{z}} \int_{\infty}^{\infty}e^{-\pi x^2}dx
$
Using the identity given with $\psi =0$ we know the integral is one and therefore we get the result:
$f(z) = e^{\frac{w^2}{z}}\sqrt{\frac{\pi}{z}}$
Answer: $$\int_{-∞}^∞ e^{-zt^2+2wt}dt= \int_{-∞}^∞ e^{-z(t-\frac{w}{z})^2+\frac{w^2}{z}}dt$$
$$= e^{\frac{w^2}{z}} \int_{-∞}^∞ e^{-z(t-\frac{w}{z})^2}dt$$
Take $(t-\frac{w}{z})=u$ the integral becomes
$$e^{\frac{w^2}{z}}\int_{-∞}^∞ e^{-zu^2}du=\sqrt{ \frac{π}{z}}e^{\frac{w^2}{z}}$$


Same drupal webform is showing error messages in two different way, on different palces in the same website

Question: I am using drupal webform for my website, I am using single Contact Us form on multiple places in my website.
But the problem is on different places the way of showing error message is different, its not uniform through out the website.

Here is the image that shows the first way that how error messages comes-

and here is the image that shows the second way to show error messages-

I want first type of error messages which is in red box.
Please help me that how can I achieve this.
Thanks
Comment: The first version is _server-side_ validation; the second version is _client-side_ validation. Trust me, you want both
Comment: So if I am not specifying anywhere that whether to use client side validation or server side validation then on behalf of what it is deciding?
Comment: Client-side validation is driven by attributes on form elements, so it's likely you have a module or theme installed which is adding the HTML5 `required` attribute, for example. You'll probably also have `` for email fields, which will require a valid email before form submission, and so on
Answer: Try to use Webform Validation module. I hope through this you can solve your issue.

This module adds an extra tab to each webform node, allowing you to
  specify validation rules for your webform components. You can create
  one or more of the predefined validation rules, and select which
  webform component(s) should be validated against those. By using the
  hooks provided by this module, you can also define your own validation
  rules in your own modules.


site-onload-gif within php

Question: problem is, that the website is loading like for about 20 second or longer (user-problems preprogrammed)
my solution was to load a pre-site where the user sees a loading screen.
i did this with this html-site but i want to do the same in php.
the test-page is http://kater.selfhost.me/test/
Source Code:

<title></title>

Please wait while the page loads...

i tried some workarounds, but after searching & testing for about three hours i give up...
thanks in advance for any help provided! :-D
Comment: You can't make a pre-load with backend (such as PHP, Java, etc..) as it's running at server side, not at the client's browser. So the PHP's content is sent to brownser at once... you can't print partially a PHP response just with pure PHP. Also, this way is fine to accomplish what you want.
Comment: Try combining all the country flags into a single file. How do you determine the country anyway? If you query a remote service on every request that will also slow down your site
Comment: @onetrickpony how do you mean this with all in one file? please describe how to gain the single image out of this big image please. i use a script i found for reading a small database vs the transmitted ip.
Comment: @Wagner my main goal is to get rid of the iframe, due to sizing issues
Comment: So you can load by ajax, is much better, see my answer
Comment: @Kater: see for example: http://flag-sprites.com
Answer: Adding what I alredy said at your question commentary, I made a code loading this content via AJAX:

            Please wait while the page loads...

This is the most used way to load asynchronous content in the web. But pay attention at this: The http://kater.selfhost.me/stats/skins.php page is made to open as single page in the web, so it has  , ,  , etc.. tags, so..after loading this page into another you'll have two ,  .. tags in a same page, this is bad, but modern browsers have an awesome common sense and don't bother by this, but you should know that, and be aware.
The actual problem why it isn't loading yet, is this javascript in your content:

I removed that and now works fine. Remember that's a quick fix, I don't know what this JS does.
Why it works in  and doesn't via AJAX? When you open in  is like opening in a new browser window..and via AJAX, as I have said, it'll load the page content straight inside your "parent" page.
So, removing this Javascript will work, but awesome further solutions:

If you need to open this page both as content to load (via AJAX), both as single page, you can make two pages.. one for each need.
If you just want to use as content to load, remove , , etc.. tags, and fix Javascript to work inside another page.
Comment: Sorry! I forgot to remove "container" div  that hide entire content. Try again removing "containter" div, I have updated my answer, you can use my new code again.
Comment: i edited it: http://kater.selfhost.me/test/ have a look for yourself... somehow i think i am not seeing the clue why this just doesn't get the data from /stats/skins.php
Comment: I have updated my answer at the end, read that, you have a bit of Javascript that isn't working when loads, and I explained why it worked before with . Remove this slice of code and try again.
Comment: ok i found this part of code... its within my php, it's a external tracking tool i used to monitor in the past and had it left in the code... dumb me but a big thanks for your answer! works fine!

site-onload-gif within php


How many permutations are there of M, M, A, A, A, T, T, E, I, K, so that no two consecutive letters are the same?

Question: How many permutations are there of
$$ M, M, A, A, A, T, T, E, I, K $$
so that there are no two consecutive letters are the same?
I would use the Inclusion-exclusion principle where
$$ A_{i} = \{ \text{on} \ i-\text{th} \text{ and }(i+1)-\text{th} \text{ position, there are two same consecutive letters} \}. $$
So my answer would be
$$ \frac{10!}{2!3!2!} - 9 \cdot \left(\frac{9!}{3!2!} + \frac{9!}{3!2!} +\frac{9!}{2!2!}\right)+ 8 \cdot \left(\frac{8!}{2!2!}\right) +8 \cdot 7 \cdot \left(\frac{8!}{3!} + \frac{8!}{2!} +\frac{8!}{2!}\right) - 7 \cdot 6 \cdot 5 \cdot 7!$$
Answer: As you observed, there are $10$ letters, of which $3$ are $A$s, $2$ are $M$s, $2$ are $T$s, $1$ is an $E$, $1$ is an $I$, and $1$ is a $K$.
If there were no restrictions, we would choose three of the ten positions for the $A$s, two of the remaining seven positions for the $M$s, two of the remaining five positions for the $T$s, and arrange the $E$, $I$, $K$ in the remaining three positions in
$$\binom{10}{3}\binom{7}{2}\binom{5}{2}3! = \frac{10!}{3!7!} \cdot \frac{7!}{2!5!} \cdot \frac{5!}{2!3!} \cdot 3! = \frac{10!}{3!2!2!}$$
in agreement with your answer.
From these, we must subtract those arrangements in which or more pairs of identical letters are adjacent.
Arrangements with a pair of adjacent identical letters:  We have to consider cases, depending on whether the identical letters are $A$s, $M$s, or $T$s.
A pair of $A$s are adjacent:  We have nine objects to arrange: $AA, A, M, M, T, T, E, I, K$.  Choose two of the nine positions for the $M$s, two of the remaining seven positions for the $T$s, and then arrange the five distinct objects $AA$, $A$, $E$, $I$, $K$ in the remaining five positions, which can be done in
$$\binom{9}{2}\binom{7}{2}5!$$
ways.
A pair of $M$s are adjacent:  We have nine objects to arrange:  $A, A, A, MM, T, T, E, I, K$.  Choose three of the nine positions for the $A$s, two of the remaining six positions for the $T$s, and arrange the four distinct objects $MM, E, I, K$ in the remaining four positions, which can be done in
$$\binom{9}{3}\binom{6}{2}4!$$
ways.
A pair of $T$s are adjacent:  By symmetry, there are
$$\binom{9}{3}\binom{6}{2}4!$$
such arrangements.
Arrangements with two pairs of adjacent identical letters:  This can occur in two ways.  Either the pairs are disjoint or they overlap.
Two pairs of $A$s are adjacent:  This can only occur if the three $A$s are consecutive.  Thus, we have eight objects to arrange: $AAA, M, M, T, T, E, I, K$.  Choose two of the eight positions for the $M$s, two of the remaining six positions for the $T$s, and arrange the four distinct objects $AAA, E, I, K$ in the remaining four positions, which can be done in
$$\binom{8}{2}\binom{6}{2}4!$$
ways.
A pair of $A$s are adjacent and a pair of $M$s are adjacent:  We have eight objects to arrange: $AA, A, MM, T, T, E, I, K$.  Choose two of the eight positions for the $T$s and arrange the six distinct objects $AA, A, MM, E, I, K$ in the remaining six positions in
$$\binom{8}{2}6!$$
ways.
A pair of $A$s are adjacent and a pair of $T$s are adjacent:  By symmetry, there are
$$\binom{8}{2}6!$$
such arrangements.
A pair of $M$s are adjacent and a pair of $T$s are adjacent:  We have eight objects to arrange: $A, A, A, MM, TT, E, I, K$.  Choose three of the eight positions for the $A$s and then arrange the remaining five distinct objects $MM, TT, E, I, K$ in the remaining five positions in
$$\binom{8}{3}5!$$
ways.
Arrangements with three pairs of adjacent identical letters:  We again consider cases.
Two pairs of $A$s are adjacent and a pair of $M$s are adjacent:  We have seven objects to arrange, $AAA, MM, T, T, E, I, K$.  Choose two of the seven positions for the $T$s and arrange the five distinct objects $AAA, MM, E, I, K$ in the remaining five positions in
$$\binom{7}{2}5!$$
ways.
Two pairs of $A$s are adjacent and a pair of $T$s are adjacent:  By symmetry, there are
$$\binom{7}{2}5!$$
such arrangements.
A pair of $A$s are adjacent, a pair of $M$s are adjacent, and a pair of $T$s are adjacent:  We have seven objects to arrange: $AA, A, MM, TT, E, I, K$.  Since all the objects are distinct, there are
$$7!$$
such arrangements.
Arrangements containing four pairs of adjacent identical letters:  We have six objects to arrange: $AAA, MM, TT, E, I, K$.  Since all the objects are distinct, there are
$$6!$$
such arrangements.
By the Inclusion-Exclusion Principle, there are
$$\binom{10}{3}\binom{7}{2}\binom{5}{2}3! - \binom{9}{2}\binom{7}{2}5! - \binom{9}{3}\binom{6}{2}4! - \binom{9}{3}\binom{6}{2}4! + \binom{8}{2}\binom{6}{2}4! + \binom{8}{2}6! + \binom{8}{2}6! + \binom{8}{3}5! - \binom{7}{2}5! - \binom{7}{2}5! - 7! + 6!=47760$$
arrangements in which no two adjacent letters are identical.
Comment: I have added the final result, it matches perfectly with my computations. So +1
Answer: If I calculated everything correctly, your answer is 446880.
I used the following program to check it:
<code>public class PermutationCounter {
    public static int[] duplicate(int[] source) {
        int[] dest = new int[source.length];
        System.arraycopy(source,  0, dest, 0, source.length);
        return dest;
    }

    public static boolean allLettersExhausted(int[] source) {
        for(int i = 0; i < source.length; i++) {
            if(source[i] != 0) {
                return false;
            }
        }
        return true;
    }

    private char[] letters;
    private int[] count;

    public PermutationCounter(char[] letters, int[] count) {
        this.letters = letters;
        this.count = count;
    }

    public int countPermutations() {
        return countPermutations(-1, count, "");
    }

    private int countPermutations(int last, int[] alphabet, String permutation) {
        if(allLettersExhausted(alphabet)) {
            System.out.println(permutation);
            return 1;
        }
        int sum = 0;
        for(int i = 0; i < alphabet.length; i++) {
            if(i != last && alphabet[i] > 0) {
                int[] alphabetCopy = duplicate(alphabet);
                alphabetCopy[i]--;
                sum += countPermutations(i, alphabetCopy, permutation + letters[i]);
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        char[] letters = new char[] {'M', 'A', 'T', 'E', 'I', 'K'};
        int[] count = new int[] {2, 3, 2, 1, 1, 1};
        PermutationCounter counter = new PermutationCounter(letters, count);
        System.out.println("TOTAL PERMUTATIONS: " + counter.countPermutations());
    }
}
</code>
My answer is 47760 (much lower number) and the full list of all permutations can be found here (yes, the word "MATEMATIKA" is also there).
The code starts with two lists. The first contains the list of letters, the second list contains the number of appearances of each letter in the final word. The code is recursive: it tracks the last letter and counts all shorter words starting with a different letter.
I know this is not the answer you were hoping for but it might help you to conclude if your answer is right or wrong.


Can I use permutation tests for to avoid the multiple comparison problem in the context of proportions?

Question: I am evaluating the effectiveness of 5 different methods to predict a particular binary outcome (call them 'Success' and 'Failure'). The data look like so:
<code>Method    Sample_Size    Success    Percent_Success
1         28             4          0.14
2         19             4          0.21
3         24             7          0.29
4         21             13         0.61
5         22             9          0.40
</code>
I would like to perform a test among these 5 methods to assess the relative superiority of the methods. In other words, I want to order the methods in order of performance as method 1 > method 2 > ... method 5. To avoid the issue of multiple comparisons, I plan to do a permutation test along the following lines:
Step 1: Pool all the data so that the overall sample size is 114 with overall 37 successes.
Step 2: Randomly split the data into 5 groups with the corresponding sample sizes of 28, 19, 24, 21 and 22.
Step 3: Increment a counter if the observed order of Percent_Success from step 2 is consistent with the ordering of my data.
Step 4: Repeat steps 2 and 3 many times (say 10000).
Desired p-value = Final Counter Value / 10000.
Questions:

Is the above procedure ok?
Is there anything in R that would enable me to perform the above test?
Any suggestions for improvement or alternative methods would be helpful.
Comment: @whuber Do you have R code perhaps to share on how you did this?
Answer: The proposed procedure does not answer your question.  It only estimates the frequency, under the null hypothesis, with which your observed order would occur.  But under that null, to a good approximation, all orders are equally likely, whence your calculation will produce a value close to 1/5! = about 0.83%.  That tells us nothing.
One more obvious observation: the order, based on your data, is 4 > 5 > 3 > 2 > 1.  Your estimates of their relative superiorities are 0.61 - 0.40 = 21%, 0.40 - 0.21 = 11%, etc.
Now, suppose your question concerns the extent to which any of the ${5 \choose 2} = 10$ differences in proportions could be due to chance under the null hypothesis of no difference.  You can indeed evaluate these ten questions with a permutation test.  However, in each iteration you need to track ten indicators of relative difference in proportion, not one global indicator of the total order.
For your data, a simulation with 100,000 iterations gives the results
\begin{array}{ccccc}
  & 5 & 4 & 3 & 2 \cr
 1 & 0.02439 & 0.0003 & 0.13233 & 0.29961 \cr
 2 & 0.09763 & 0.00374 & 0.29222 &  \cr
 3 & 0.20253 & 0.00884 &  & \cr
 4 & 0.08702 &  &  &
\end{array}
The differences in proportions between method 4 and methods 1, 2, and 3 are unlikely to be due to chance (with estimated probabilities 0.03%, 0.37%, 0.88%, respectively) but the other differences might be.  There is some evidence (p = 2.44%) of a difference between methods 1 and 5.  Thus it appears you can have confidence that the differences in proportions involved in the relationships 4 > 3, 4 > 2, and 4 > 1 are all positive, and most likely so is the difference in 5 > 1.
Comment: That's a much better answer than mine! I failed to read the question properly I'm afraid (Step 3 in particular). I thought of deleting my answer, but I stand by the greater interpretability of a Bayesian approach is it's really the ranking that's of interest.
Comment: Just to make sure I understand correctly- The indicator that tracks the relative difference between method 4 and 5 will be updated whenever we see a difference that is greater than 0.21.
Comment: @sxv Yes, that's right.  (Well, I actually used greater than or equal.  Ties do happen.  I think including equality among the significant results is the correct thing to do, because we're evaluating the probability that differences *this large or larger* can occur by chance.)
Answer: Your suggested Monte-Carlo permutation test procedure will produce a p-value for a test of the null hypothesis that the probability of success is the same for all methods. But there's little reason for doing a Monte Carlo permutation test here when the corresponding exact permutation test is perfectly feasible. That's Fisher's exact test (well, some people reserve that name for 2x2 tables, in which case it's a conditional exact test). I've just typed your data into Stata and -tabi ..., exact- gave p=.0067 (for comparison, Pearson's chi-squared test gives p=.0059). I'm sure there's an equivalent function in R which the R gurus will soon add.
If you really want to look at ranking you may be best using a Bayesian approach, as it can give a simple interpretation as the probability that each method is truly the best, second best, third best, ... . That comes at the price of requiring you to put priors on your probabilities, of course. The maximum likelihood estimate of the ranks is simply the observed ordering, but it's difficult to quantify the uncertainty in the ranking in a frequentist framework in a way that can be easily interpreted, as far as i'm aware.
I realise I haven't mentioned multiple comparisons, but I just don't see how that comes into this.
Comment: Fisher's exact test and Pearson's chi-squares test the null hypothesis that all 5 methods are equally effective against the alternative that at least 1 is better than the others. The p-values tell me that the null is rejected. So, if I want to find out which methods is actually better than the others won't I have to do 10 pairwise comparisons?


Can a pre-Hilbert space be separable?

Question: I am confused about separability and completeness and I would like to know if there exists a non complete inner product space that is separable?
Thanks
Answer: Consider the space $C_c(\mathbb N)$, the space consisting of (say complex valued) functions with finite support. It is a pre-Hilbert space with inner product given by
$$
\langle f,g\rangle = \sum_{\mathbb N} f(n)\overline{g(n)}
$$
This space is separable but not complete.
Answer: As every subset of a separable space is separable, you can take any dense proper subspace of a separable hilbert space. For example $C^1([0,1])$ is a dense subspace of $L^2([0,1])$. As $L^2([0,1])$ is separable it follows that $C^1([0,1])$ is separable too, but it is not complete with respect to the $L^2$-norm.
Comment: You want to take a dense subspace of a separable Hilbert space. Not all Hilbert spaces are separable.
Comment: Yes, that's true, thanks for mentioning. I've edited my post.

Can a pre-Hilbert space be separable?


Compute Integral

Question: Let $s, \alpha$ and $k$ be a real numbers. I would like tu compute the following integral
$$
I=\int_{0}^{x}(\alpha^kz)^{-s}dz.
$$
In my opinion I do as follow
$$
I=\int_{0}^{x}(\alpha^kz)^{-s}dz.
$$
$$
I=\alpha^{-sk}\int_{0}^{x}z^{-s}dz.
$$
$$
I=\alpha^{-sk}\frac{x^{1-s}}{1-s}.
$$
But is not the correct result.
Comment: Please if it possible some one can provide me the result to verify.
Answer: The integral does not converge for all values for $s$.
Namely, $s \geq 1$.
For all other values, your expression is correct.
Answer: my approach would be:
$$I=\int_0^x\alpha^{-sk}z^{-s}dz=\alpha^{-sk}\left[\frac{z^{1-s}}{1-s}\right]_0^x$$
but you have to be careful where $s=1$ as it does not follow this general formula, and the bottom of the fraction will not work

Compute Integral


Are parallel 5ths 8tvs allowed between beat 4 and beat 1 of new bar?

Question: I am working in a grade 4 melody writing exercise textbook and it says that you should not have parallel 5ths and octaves on the upbeat before the new bar and the 1st beat of the new bar. It was my understanding that parallels dont sound good only when they are on consecutive downbeats and that they can be used on upbeats because of their weaker metric positioning. Can someone please clarify?
Answer: I wasn't going to answer as @Phoog's simple reply was enough, but then I read the comment about the Piston Counterpoint example.
Don't cherry pick examples, especially taken out of context, to rationalize mistakes in exercises.
The fig. 126 from Counterpoint you gave as an example in comments is presented in the text as: "Following are examples of such consecutive octaves and fifths." The operative word being "such", referring back to fig. 124, which is a table of 9 examples of consecutive perfect intervals in various rhythmic and melodic contexts.

Fig. 126 is given as either an example of good or bad. It's just a real example of many ways consecutive intervals can be encountered. It is an example of (g) from the table in fig. 124. Piston's comments on that are:

...On the other hand, the formula at g seems to be open to question. It is used by Bach and others, and its acceptability appears to depend upon the rhythmic importance of the off beats.

Compare (g) which places the octaves on the weak beats of 2 and 4 with (f) which places the octaves on the strong beats of 1 and 3. Piston is saying weak metrical accent is a mitigating factor in the acceptability of parallel octaves. You can probably extend that to any perfect, parallel intervals.
Now that we have digested the Piston text we can return to your question.

Are parallel 5ths 8tvs allowed between beat 4 and beat 1 of new bar?

Piston's table in fig. 124 has only one example crossing a bar line with (i). We can broaden the picture a bit and say categorically crossing the barline is a movement from a weak to a strong beat. Fig. (e) sort of gives us that, as the first octave is on weak beat 2. But, both (i) and (e) put the second octave not on the strong beat and instead after the strong beat. Unfortunately we don't have a perfect example. But, Piston says (e) does not excuse the parallel movement while (i) does, because (i) present more rhythmic difference between the two parts.
IMO, from Piston's examples, parallel, perfect intervals crossing the barline is generally not acceptable. Certainly if the question is asked without any qualification it is not acceptable. If the idea is "crossing the bar line mitigates parallel, perfect intervals", that is certainly false. You can probably generalize that an say "any parallel movement to a strong beat will accentuate the parallel movement." And that will undermine the contrapuntal sense of melodic independence. If you do it, make sure something other than melodic contour accentuates melodic independence, the obvious choice being to make the line rhythmically independent.
Another point should be made about rhythm, meter, and these examples. In fig. 124, g the weak beats are full beat durations, while fig. 126 put the parallel octaves after both strong and weak beats with only a sixteenth note duration. Longer rhythm values are a basic way of creating metrical accent. So, teaching example (g) accentuates the parallelism more than the real example in fig. 126. The OP question is a bit unclear on this nuance of duration.
Back to my point about cherry picking examples. If you are teaching yourself, you need more intellectual rigor when reading texts, not less. Read carefully and be a harsh critic. That doesn't mean you can't write parallel harmony any way you want. Do it, but own it. Don't pull out Piston and Bach to justify it out of context. If you want to write like Bach or Haydn, etc. be very careful about the voice leading conventions they used.
Answer: In the traditional rules of voice leading and counterpoint, parallel fifths and octaves are forbidden regardless of where they occur.
Comment: @armani there are no parallel fifths in that example.  The right hand alternately ascends by thirds and descends by steps. The left hand ascends by steps.  To have a parallel fifth, you would need both parts moving in the same direction at the same time by the same interval.  As the question you link to notes,  this contrapuntal technique _avoids_ the parallel fifths that would be present if the right hand had two voices in parallel thirds.
Comment: @armani Just wanted to chime in. I think that the rule of parallel 5ths is more of a spectrum vs a black and white "yes this is okay" or "no, now you will be punished." In this case, Bach does have several 5ths in a row which is generally bad practice, BUT he also broke them up so that the pitches aren't convective and moved them away from the strong beats, so it's not so bad. In school, it's helpful to learn all the rules, but when you're writing on your own time you can break them and do whatever you want. :)
Comment: That is not true. In traditional strict rules, parallel 5ths are allowed on upbeats. https://music.stackexchange.com/questions/114978/is-staggering-fifths-a-good-way-to-avoid-parallels
Comment: here is an example where Bach uses 5ths on upbeats https://ibb.co/XxZhFy1
Comment: Do you see all the intervals marked with a 5? are you saying those are not 5ths? The 5th is on the upbeat but against the bass it is still a 5th. This is what the teacher says in the video. He says that Bach chose to use them there because of their weak metric positions and had they been on the down beat they would be unacceptable
Comment: *consecutive (sorry for the typo)
Comment: @armani As phoog pointed out there are no parallel fifths in that example.
Comment: @armani of course I see all those fifths.  But the fifths are all separated by thirds.  You have C/E, a third, then C/G, a fifth, then D/F, a third, then D/A, a fifth, and so on.  It's only a parallel fifth if you have two consecutive intervals of a fifth.
Comment: in counterpoint it is not allowed parallel fifths on consecutive downbeats even though you have intervals in between on the upbeats... those are considered parallel 5ths arent they?
Comment: @armani I thought this might be helpful; here's an excerpt from The Craft of Tonal Counterpoint (p. 45) by Thomas Benjamin: "Parallel perfect fifths are not found in [Bach's] music, nor are fifths by contrary motion. Further, fifths on successive strong beats (or strong parts of beats) are not used, **though fifths falling on successive weak beats (or parts) are possible.**" According to Benjamin, parallel 5ths falling on weak beats are allowed; however, it is a rare occurrence in counterpoint. In general, he says that successive perfect consonances should be avoided.
Comment: I added a picture from the book to my answer.
Answer: One of the main reasons for avoiding parallel 5ths and octaves in 4-part writing is that it causes the two voices in question to temporarily lose independence and sound like one voice. The 5th and octave are strong fundamentals, so when you add parallel 5ths/octaves, the upper voice sounds like it just disappeared. But that's not to say they were never used.
Parallel 5th/octaves are generally avoided no matter where they are, but if you can break up the parallelism even momentarily, in a suspension for example, you regain voice independence, and is generally accepted.
Edit:
An excerpt from The Craft of Tonal Counterpoint (p. 45) by Thomas Benjamin: "Parallel perfect fifths are not found in [Bach's] music, nor are fifths by contrary motion. Further, fifths on successive strong beats (or strong parts of beats) are not used, though fifths falling on successive weak beats (or parts) are possible." According to Benjamin, parallel 5ths falling on weak beats are allowed; however, it is a rare occurrence in counterpoint. In general, he says that successive perfect consonances should be avoided.
Comment: @DarrelHoffman: Parallel octaves as a **doubling** were *never* a "rule" violation. You can see it occasionally in Bach and earlier too when it's deliberate. Textures and ensembles were generally smaller back then, which is the main reason they were rare.  As for the assertion that parallel fifths are "regularly seen" in Beethoven, Mozart, Haydn, etc., I'd like some source to back that up.  Aside from certain stereotypical figures (e.g., resolution of Ger+6 chord), they are quite rare (setting aside some of Beethoven's crazier late music and deliberate evocation of "rustic" music on occasion).
Comment: Note that these rules are very old and rarely followed 100% anymore.  Parallel 5ths and especially octaves are used all over the place even in most classical music (generally *because* it sounds like one voice, that's kind of the point).  It's really only Baroque counterpoint and earlier that made such a point of avoiding them.
Comment: @DarrelHoffman the prohibition persisted well into the 19th century.
Comment: @phoog And yet you still see it all over the place, Beethoven, Mozart, Haydn, etc. used parallel octaves all the time.  5ths were less common, but still regularly seen.
Comment: The rules are just meant for pedagogical purposes, but their principles can still apply to modern music.
Answer: I'd like to point out that that's not quite what the textbook says. It's offering some general guidelines, not hard rules (you will certainly find "tunes" that end in other ways than ^7 -> ^1). It says that first and last beats should not both be 5ths or octaves, regardless of parallelism. In the printed example, the downbeat of the third bar is an octave between the Fs in the upper and lower voice, but the preceding beat is a 9th. They're saying that it would not have been ideal if that preceding beat had been a fifth, or another octave even if the motion were not parallel.
Answer: It's important to start with an understanding of timbre.  If you have access to an old organ with multiple stops, you know that by reinforcing overtones, you can change the quality of a sound.  Octaves make a kind of flutier sound, and 5ths make a slightly buzzier sound, and so on.
When you play multiple perfect 5ths in a row, the 5th acts as a temporary timbre of the note below it, rather than as fully functional part of its own.  It doesn't matter whether they are on an upbeat or a downbeat.


$\int_{\gamma}\frac{1}{z^2-2z}dz$

Question: Let $\gamma(t)=2+e^{it}, t \in[0,2\pi]$ find $\int_{\gamma}\frac{1}{z^2-2z}dz$
I did the following
$\int_{\gamma}\frac{1}{z^2-2z}dz=-\frac{1}{2}\int_{\gamma}\frac{1}{z}dz+\frac{1}{2}\int_{\gamma}\frac{1}{z-2}dz$
The integral $\int_{\gamma}\frac{1}{z-2}dz$ is equal to $2\pi i$ because $D(2,1)\setminus 2$ is not simple connected
I don't know how to justify properly the fact that $\int_{\gamma}\frac{1}{z}dz$ is equal to $0$ I can't say the image of the curve is  simple connected because we don't include $2$ and if I consider another curve- disc it has to have 0 as center which we can't include, and again it won't be a simple connected, so we can't use Cauchy theorem.
How can I justify properly that   $\int_{\gamma}\frac{1}{z}dz=0$ without calculating the integral?
Answer: $z=0$ is outside of the contour, so $\frac{1}{z}$ is holomorphic throughout. What does that tell you?
Comment: You have two separate integrals: one with integrand $\frac{1}{z}$, one with integrand $\frac{1}{z-2}$. The only place where $\frac{1}{z}$ is not holomorphic is $z=0$ which lies outside of the contour. The only place where $\frac{1}{z-2}$ is not holomorphic is $z=2$ which lies inside the contour.
Comment: So we  just don't care about the problematic point 2 when we use Cauchy theorem ? Or it is something else I am missing ?
Answer: Rewrite $\int_{\gamma} \frac{1}{z^2 - 2z} dz$ as $\int_{\gamma} \frac{1/z}{z -2} = \int_{\gamma} \frac{f(z)}{z - 2}.$
$f(z) = \frac{1}{z}$ is holomorphic everywhere on the complex plane except $z = 0,$ which is exterior to $\gamma,$ so $f(z)$ is holomorphic everywhere interior to $\gamma$ and we can directly apply the Cauchy Integration Formula: $\int_{\gamma} \frac{f(z)}{z - 2} = 2\pi i \cdot \frac12 = \pi i.$

$\int_{\gamma}\frac{1}{z^2-2z}dz$


How to configure babel-node --preset env without .babelrc

Question: How do you pass options to the env preset when using babel-node through the command line? I've looked through the docs but was unable to find how to configure the babel-node env preset.
What I'm trying to target the current version of node installed on my machine. The equivalent with a <code>.babelrc</code> file would be
<code>{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}
</code>
Thanks!
Answer: You can use inline --presets flag.
For Example:
<code>  babel-node index.js --presets=env
</code>
Comment: and how do you configure the env preset?


Unable to load an Image into Canvas and get base64 encoding for that image

Question: I am trying to generate a PDF from HTML using jspdf plugin. I am stuck with loading Images into PDF. There is a function addImage() in plugin which takes base64 encoding of an image, but converting an image to base64 is not working.
I have used below two ways
//Create canvas, draw image in context and get the data url
imgToDataURL =  function (img, outputFormat){
        var canvas = document.createElement('canvas');
        canvas.width = 20;
        canvas.height = 20;
        var c = canvas.getContext('2d');
        c.height = img.height;
        c.width=img.width;
        c.drawImage(img, 0, 0);
        c.save();
        var dataurl = canvas.toDataURL(outputFormat);
        return dataurl;

    }

var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "image path"
img.height= 60;
img.width=60;
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);

This is printing wrong dataURL I am getting a white image. If I hard code the base64 code i.e return a hardcoded dataURL then addImage works fine. So the issue is with canvas.toDataURL which is giving me wrong output
this is the 2nd way
convertImgToBase64URL =  function (url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
}

this.convertImgToBase64URL("Image Path",function(base64){

    renderer.pdf.addImage(base64, 'PNG', 20, 20,48,48);
})

I have run this inside a javascript and the onload function is not even running I am not sure what is my mistake is.
Please suggest me what mistake I am doing in either way
Comment: You have to wait for your images are loaded before drawing them to the canvas context. Also, are you sure you serve the image with correct cross-origin headers? If your server is not set correctly, the `"anonymous"` request will be blocked and your image won't ever load. Beside it, there are few issues in your first snippet (i.e context2d has no width nor height properties, and `save()` is useless here) but none should block your code.
Comment: True, but I am not sure how can I check that whether image is loaded or not.
And for few images I do get below exception
" Image from origin 'Image server path' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
So what does this exactly mean.
I am a novice in javascript/HTML and all these stuff I am sorry if I am asking any obvious question.
Comment: well you're lucky I just wrote these question and answer for these exact same cases (you're not the only one in that case) : http://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue/32880642#32880642
Comment: @Kaiido I wrote a similar one but unfortunately the img.onload never get executed. And I am not sure how to set the Access-Control_Allow-Origin" header .
One point to note is I am writing everything in a single JS file and adding this file in HTML. Will this be any problem for loading the image ?
Comment: @Kaiido I am able to get the images now but I am using CORS extension of chrome and enabled cross-origin-resource sharing there.  If I disable there then Images are not loading. Can you help me resolving this issue.
And the images that I am accessing is in public folder of a server I am able to access the image from web browser
Comment: Did you read the link in the dupe answer? CORS headers must be supplied by the server. I don't know what your extension pretends to do, but it won't be able to hack it. You are able to display it in an `` element, and even to draw it, but you won't be able to use the `toDataURL()` or `getImageData()` of the canvas anymore. If some of your images are from your server, and some others are from a CORS compliant server, then you could try setting the `img.crossOrigin="anonymous"` by default and add an `onerror=function(){this.crossOrigin=''; this.src=this.src};` for the ones from your server.
Comment: @Kaiido I tried to replace all the server images to local file system images even then I am getting this error
Image from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access.

What does this mean.. my HTML,JS,Images are all on local file system then why am i getting this error.

And when you say server is supposed to supply can you provide me an example what and how the  changes are to be done at server side( PS we are using PTC integrity server )
Comment: images from file system won't ever be served with proper CORS. What you need instead, is that it comes from the same server (if on a local machine, it would be `http://localhost/`), and then don't set the ``'s crossOrigin attribute, or via an external server, sent with  `Access-Control-Allow-Origin: *` in the header of the response, and by setting ``'s crossOrigin attribute to `'anonymous'`. I don't know about PTC integrity, but it does looks like an ALM, not a server system. You can have a look at http://enable-cors.org/server.html it may help you set your server correctly
Answer: In the first you missed assigning an onload function to your image. For that reason, the moment you try to create the dataURL, the image might not be loaded yet, ergo, the blank image. You could try changing the last few lines to this:
...
img.width=60;
img.onload = function () {
  var dataURL = this.imgToDataURL(img,"image/jpeg");
  renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
}
img.src = "image path";

As for the second one, there seems to be a problem with the convertImgToBase64URL() which accepts 3 parameters, but you are passing 2. In you example, outputFormat parameter is undefined.
Comment: you can call `canvas.toDataURL(undefined)` or any other non-valid value, it will fall back to the default `'image/png'`
Comment: I tried to include img.onload in the first one but the onload function never gets executed. I kept an alert statement to knwo the dataURL but I never got that alert. One thing to be noted is all the processing is going in single JS file. I am passing the image source link and height width from other function and calling imgToDataURL function and get the dataURL link.


Open Form By Variable Value

Question: Form Name comes from a variable.  I would like to open Form from variable value.
In VBA load("UserFormName") will show the form.  But I don't know how to do it in VB.Net.
Comment: https://www.tek-tips.com/viewthread.cfm?qid=1756182
Comment: When you say `Form Name comes from a variable`, do you mean something like: Dim formToDisplay = New , so that when it comes to compile time, you are not 100% certain which exact form will be needed?
Comment: Check Activator.CreateInstance()
Comment: Possible duplicate of https://stackoverflow.com/questions/7598088/purpose-of-activator-createinstance-with-example, though it may not look like it at first glance, and that question is on C#.
Comment: See the code that activates a Form by name [here](https://stackoverflow.com/a/55804333/7444103) (first code snippet). It's the `Dim form = CType(Activator.CreateInstance(Type.GetType($"{appNameSpace}.{formName}")), Form)` part.
Answer: Ok, of course one would want to be able to open a form by string name.
When you create a vb.net winforms project, then all forms are available as a "base" static class.
You often see a LOT of code thus simply use the base form class.
If I need to display say form2, then I really don't  need to create a instance of that form (unless you want to have multiple instances of that form. So a truckload of code will simply launch + use the "base static" class of that form.
eg:
Form2.Show()

I don't consider this all that bad of a practice, since what do you think the project settings to "set" the startup form in the project settings does?
It simply sets the built in instance of "mainForm" = to your startup form and it does NOT create  new instance.
So, now that we all can agree for 15+ years anyone who has set the startup form in their project is NOT creating a NEW instance of that form, but in fact using the base class instance. This is really a programming choice.
So, code to display (show) the base static instance of a form by string name will look like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim strForm As String = "Form1"
    ShowFormByName(strForm)

End Sub

Public Sub ShowFormByName(strFormName As String)

    System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(ProductName & "." & strFormName).show()

End Sub

Private Function FormByName(strFormName As String) As Form
    Return System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(ProductName & "." & strFormName)
End Function

However, above includes a helper sub that will simply "show" that built in instance of the forms.
And above also includes a function to return class type of the form, since for sure a good many developers prefer to first create a instance of the form, and then "show()" it.
So, often we do want multiple instances, or we just perfer the codeing approach of creating a new instance of the form object.
So, we use the 2nd helper function to return a form object of the type we passed by string.
So, to display 3 instances of form1, but the FIRST instance being the base class, then two more but brand new instances of  that  form, we have this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim strForm As String = "Form1"
    ShowFormByName(strForm)

    Dim f1 As Form = FormByName(strForm)
    Dim f2 As Form = FormByName(strForm)

    f1.Show()
    f2.Show()

End Sub

So the above code snip shows how to display the  built in base class form without having to create a instance of that form.
However, the next two forms we load are "new" instances of that form as "string".
So the helper sub, and helper function will give you both choices as to which preference floats your boat.
Comment: Right, my example (first one) shows an example of launching the form based on a string - an no new instance is created nor is it required. So, of my two examples - first example does as you ask.  So, just call that ShowByName(" your string form name") and it will show/display the form without having to create a instance. I of course included both ways, as it often common to create a instance of the form first - but as the first example code shows you don't need to create a instance - it just shows the given form based on the passed string.
Comment: I would like to invoke built in base class form from variable value.  Because the form name comes from my DB which is stored in variable.  I decide which form is accessible to which person by taking control of the DB.  So I want to invoke the built in base class form by variable value.  I don't want the instances of the form.
Comment: I use that code with small changes: System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(My.Application.Info.Title & "." & strFormName).show()
Answer: Dim form = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(Application.ProductName & "." & MySubForm)
Dim frm As New Form
frm = form
frm.MdiParent = AFrmMainScreen
frm.WindowState = FormWindowState.Maximized
frm.Show()

Comment: Hellow, "LarsTech" , I am somehow new on "stackoverflow.com", but is it normal to edit someone answers? I mean can you even edit the code answer itself as well?
Comment: Yes.  We prefer not any noise, like "thank you" etc.  Just the answer.  An explanation of your code might improve it.
Comment: Yes, got it. Thanks for sharing ^_^
Answer: I prefer to use Reflection.Assembly.GetEntryAssembly because I use several different projects in one solution.  This allows me to put this code in a different project(dll) that has a usercontrol that I can then reuse across multiple solutions.  You also don't need to know the "Namespace" for the form as long as it is in the startup project.
The code below gets the form type from the exported types from the entry assembly and then uses Activator.CreateInstance to create a new instance of the form.  Then I return that form in the function.
Public Function GetForm(ByVal objectName As String) As Form
    Try
        Dim frmType = Reflection.Assembly.GetEntryAssembly.GetExportedTypes.FirstOrDefault(Function(x) x.Name = objectName)
        Dim returnForm = TryCast(Activator.CreateInstance(frmType), Form)
        Return TryCast(returnForm, Form)
    Catch ex As Exception
        Return Nothing
    End Try
End Function

To use the above function:
Dim MyForm = GetForm(FormLocation)
If MyForm IsNot Nothing Then
    MyForm.ShowDialog()
    'You can do any form manipulation from here.
Else
    MessageBox.Show($"{FormLocation} was not found.")
End If

Open Form By Variable Value


How to bulk update text filter format on fields in drupal 7

Question: I have multiple fields across my site, and multiple text filters. I need to delete one of the filters, but I know that it will result in users getting that whacky permission denied error when they try to edit the field.
Is there a way to bulk update all fields input filters? I started looking at field_update_field in the field CRUD api, but I'm at a loss.
Comment: Hi Erin, you can have a look at http://drupal.stackexchange.com/questions/2403/change-the-input-format-for-3000-nodes as that method might solve your problem.  If you find a better way, please let me know ;)
Comment: Yep, that question is totally the same thing. Sweet.
Answer: Turns out this was solved in a different question, the answer is below:

Try this way, by making a loop for all nodes of certain type:
<code>$node = node_load(nid);
$node->body[$node->language][0]['format'] = 'full_html'; // plain_text
node_save($node);
</code>

Kudos to Ek Kosmos for sorting this out.


Help with proof of $ \mathbb{C}[X] \simeq R $ where $R$ is a $ \mathbb{C}$-algebra without nilpotents

Question: I am trying to understand the proof of the following proposition:

Let $X \subset \mathbb{A}^n$ be closed. Let $ R $ be a finitely generated $ \mathbb{C}$-algebra without nilpotents. There exists an affine variety $ X $ such that $\mathbb{C}[X] \simeq R $ (as $ \mathbb{C}-$ algebras).

where $\mathbb{C}[X]$ is the ring of regular functions on $X$.
Proof: Let $ \alpha _1, \cdots, \alpha _n $ be generators (over $ \mathbb{C} $) of $ R $, and let $ \phi: \mathbb{C}[z_1,\cdots,z_n] \longrightarrow R$ be the surjection of algebras mapping $ z_i$ to $\alpha_ i$ . The kernel of $ φ $ is an ideal $ I \subset \mathbb{C}[z_1,\cdots,z_n]$, which is radical because $ R $ has no nilpotents. Let $ X:= V(I) \subset \mathbb{A}^n$. Then $ \mathbb{C}[X] \simeq R $.
I can't understand the sentence in bold, i.e. why if $ R $ is a finitely generated $ \mathbb{C}$-algebra without nilpotents then $ I $ is radical.
Have you any ideas?
Thank you in advance.
Comment: Terminology nitpick: You pick an $X\subseteq \Bbb A^n$ as a closed set (which is not necessarily a variety) before mentioning $R$, and then later you pick $X$ as a variety (without an explicit ambient space). This looks strange.
Answer: Well, let $f$ be a polynomial with $f^n\in I$, i.e., $\phi(f^n)=0$. Then $\phi(f)^n=\phi(f^n)=0$ and so $\phi(f)$ is nilpotent in $R$. By hypothesis $\phi(f)=0$ and so $f\in I$. Hence, $I$ is radical.


$.parseJSON returns correct items plus infinite undefined response

Question: I'm currently developing a flask application that retrieves the teams from a football league. The teams_list method returns the following response from an ajax request. I'm getting the right output but it's leading me into an infinite loop that really slows down the entire web application.
How I got the response:
teams = []
@app.route('/get_team_list', methods=['POST'])
    def team_list():
        league = request.form['team_name']
        id = get_league_id(league)
        get_teams(id)

        json_str = json.dumps({'status':'OK','id': id, 'league': league, 'teams': teams})
        json_obj = json.loads(json_str)

        temp = json_obj['teams'] #a subarray
        team_str = json.dumps(temp)
        print("STR:  ",team_str)
        print("JSON: ", str(temp))

        clear_team_array(teams)
        return team_str

Response:
["Juventus Turin", "Cagliari Calcio", "Hellas Verona FC", "SSC Napoli", "Atalanta BC", "AS Roma", "Udinese Calcio", "AC Chievo Verona", "US Sassuolo Calcio", "Genoa CFC", "UC Sampdoria", "Benevento Calcio", "SS Lazio", "SPAL Ferrara", "FC Internazionale Milano", "ACF Fiorentina", "Bologna FC", "Torino FC", "FC Crotone", "AC Milan"]

Ajax call:
$('#test').click(function() {
   $.ajax({
       url: '/get_team_list',
       data: $('form').serialize(),
       type: 'POST',
       success: function(response) {
           var json = $.parseJSON(response);
                for (var i = 0; json.length - 1; i++) {
                    console.log("RESPONSE: " + json[i]);
                }
       },
       error: function(error) {
           console.log("ERROR: "+ error)
       }
   });
});

It is working fine but the problem I'm heaving is that when I retrieve the teams through the for loop it gives me the following output:
RESPONSE: Juventus Turin
RESPONSE: SSC Napoli
RESPONSE: Atalanta BC
RESPONSE: AC Milan
RESPONSE: ...
(140231)REPONSE: undefined

Answer: The loop conditional is json.length - 1 which never changes so the loop keeps going forever.
It should be
for (var i = 0; i < json.length; i++) {

Comment: It still giving me the same output. Plus, I wonder if the response from my function returns a valid JSON string? Right?
Comment: I got it! I changed `for (var i = 0; i < json.lenght - 1; i++) {..}` to `for (data in json) { consolse.log(json[data]); }` thanks anyway! I figured it out because of this.


The server encountered an internalException org.hibernate.validator.InvalidStateException: validation failed for: com.contact.ContactRegistration

Question: I am really new to Struts and Hibernate. I am working on a web app where user fills a form. I have to put some validations on some fields, I am trying to use validations in POJO class on some fields.
Like @Past on Date, @Max on int.
But its not working properly and throwing these exceptions.
HTTP Status 500 validation
failed for: com.contact.ContactRegistration
type Exception report
message validation failed for: com.contact.ContactRegistration
description The server encountered an internal error that prevented it from       fulfilling this request.
exception
org.hibernate.validator.InvalidStateException: validation failed for:    com.contact.ContactRegistration
org.hibernate.validator.event.ValidateEventListener.validate(ValidateEventListener.java:148)
org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172)
org.hibernate.action.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:119)
org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:42)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)

I have included these jars.

classmate-1.0.0
hibernate-validator.jar
jboss-logging-3.1.0-CR2
validation-api-1.1.0.Final
Answer: Hibernate validations are performed when you are trying to persist an object. The exception stacktrace shows that you are saving transient instance in Hibernate session.
It throws an exception because the object being validated has invalid values. The exception allows you to rollback the current transaction.
The org.hibernate.validator.InvalidStateException could be caught by your code to get some info for the error happened. It has a method getInvalidValues() which returns validation errors.


Dynamically added items do not trigger observers

Question: I'm adding some items to an Array, using the Array mutation methods. The items are displayed within a <dom-repeat> and can can be edited on the fly. While the edits do change the data in the object, any attached observers do not fire to indicate that a change occurred.
tl;dr
I'm properly using the Array mutation methods to push items
this.push("data.contents", {
  id: 1,
  name: "Modifying this text doesn't trigger an observer"
});

I'm displaying the items in a dom-repeat
These items are displayed using a <dom-repeat>, and the sub-property name is displayed in a <paper-input> where they can be amended on the fly.
  <template>
    <template is="dom-repeat" items="[[data.contents]]">
      <paper-input value="{{item.name::input}}"></paper-input>
    </template>
  </template>

It seems that while the data is modified in the object itself, any attached observers do not fire for these sub-properties.
I'm attaching wildcard observers
I'm observing using the usual wildcard observers like so:
observers: [
  "logChange(data.*)"
],

Notes
Note that:

Changing the item via a direct this.set() like so:

this.set("data.contents.0.name", "Foo")
will trigger the observers just fine
An MCVE for the above.
How to use:

Press the button to push some items to the Array
Edit any one of the added items
Console should log that a change occurred in any of the items (it doesn't)

<base href="https://polygit.org/components/">

<link href="polymer/polymer.html" rel="import">
<link href="paper-input/paper-input.html" rel="import">
<link href="paper-button/paper-button.html" rel="import">

<dom-module id="x-example">
  <template>
    <paper-button on-tap="pushItem">Push to Array</paper-button>
    <template is="dom-repeat" items="[[data.contents]]">
      <paper-input value="{{item.name::input}}"></paper-input>
    </template>
  </template>

</dom-module>

<x-example></x-example>
Comment: Maybe you can change data type to array instead of object
Answer: Solved here: https://github.com/Polymer/polymer/issues/4140#issuecomment-259465035

The observer isn't firing because you have one-way binding annotations on the items property, which prevents change notifications from flowing up to the element. Change it to: items="{{data.contents}}" and you'll see the changes.

In essence, turn this:
<template is="dom-repeat" items="[[data.contents]]">
  <paper-input value="{{item.name::input}}"></paper-input>
</template>

to this
<template is="dom-repeat" items="{{data.contents}}">
  <paper-input value="{{item.name::input}}"></paper-input>
</template>


Cannot use the XOR operator with two char's for some reason, does anyone get why?

Question: Is there some formal standards that do not allow one to use the ^ or XOR function in C# with two chars?
    public char[] XORinput(char[] input, char SN)
    {
        int InputSize = input.Length;
        //initialize an output array
        char[] output = new char[InputSize];

        for (int i = 0; i < InputSize; i++)
        {

            output[i] = input[i] ^ SN;

        }

        return output;

    }

For whatever reason this code is giving me this error, Error    1400    Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?)
This does not make any sense.
Caller:
                string num = "12345";
                char SN = Convert.ToChar(num);//serial number

                string sCommand = ("Hellow");

                char[] out = new char[sCommand.ToCharArray().Length];

                out = calculator.XORinput(sCommand.ToCharArray(), SN);

Comment: What does the caller look like?
Comment: I see the problem, num is not a char, its a char array
Comment: Perhaps you should modify your function to work with bytes / shorts instead.  `char` is 16bit, which is fine on its own, but it is meant to hold UTF-16 non-surrogate characters, you could potentially fill it with a value that cannot be represented by UTF-16.  This could cause problems if you ever try and render that character, if you're never rendering it, then why have a char in the first place?
Comment: In your conversion from string to char array, this is the way to do it: `char[] out = sCommand.ToCharArray(0,sCommand.Length);`
Answer: The error is not with the function, but with the result of it.
When you do input[i] ^ SN; your result is an int, which you "Cannot implicitly convert type 'int' to 'char'.
You can cast it like this:
(char)(input[i] ^ SN);

Comment: Because certain operations, such as arithmetic and XOR, are only defined on `int`s in .NET.  The `char`s are implicitly converted to `int`s (so now it's `int ^ int`) so that they can be XORed, which results in an `int` result.
Comment: Why does `char ^ char` return `int`, though?
Comment: @TimS.: Thanks for the response. Further reading: http://stackoverflow.com/a/942349/120955
Answer: The xor operator (along with other operators) return an integer result. So a single cast to char is sufficient.
output[i] = (char)(input[i] ^ SN);

In this case you wouldn't have to cast, but it's less efficient in your case:
output[i] = input[i];
output[i] ^= SN;

Comment: how come its more efficient to use the latter case?
Comment: @Recurrsion: Because you have to set the value of the array index twice instead of just once.
Comment: First case is more efficient as only one lookup in the output array is needed. Just mentioned the second case as an example of when you can use bitwise operation without needing to cast.
Answer: If you have a character, a char, you can convert it to an integer, an int.
And then you can use the ^ operator to perform XOR on it. You don't appear to be using that operator at the moment, which might be the source of your problem.
    output[i] = (char)((uint)input[i] ^ (uint)SN);

Comment: That appeared to work, although I am using the ^ if that's what your referring to ?
Comment: The issue I now need to fix is                       string num = "12345";
                char SN = Convert.ToChar(num);//serial number


"URI is not registered" when use http://xmlns.jcp.org/jsf/html" in XHTML page

Question: pom.xml file
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.2.0-m08</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.2.0-m08</version>
    <scope>provided</scope>
</dependency>

xhtml file

web.xml file
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>

Always "http://xmlns.jcp.org/jsf/html" shown in red colour and it says "URI is not registered".
I need to know, why is it say so and how it fix it. Anyone have any idea?
I am using Intellij IDEA and maven for build project.
Comment: I didn't find the best solution. I used the web.xml code from this tutorial and use in the project. Then, that was working www.tutorialspoint.com/jsf/jsf_first_application.html
Answer: I faced same problems when wrote jsf-based application in Intellij IDEA Community Edition. Only ultimate version has jsf support.
Comment: I have ultimate support. Even I am having problem


Protractor error - Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves

Question: I am learning protractor but I am facing a problem with a "Promise" error. I read Mocha testing with promises: Error: Timeout of 2000ms exceeded and https://github.com/angular/protractor/blob/master/docs/control-flow.md#disabling-the-control-flow but I am still stuck in this simple code.
Basically if I add the line
element(by.css(gotograb_css)).click();
There will be an error
 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
Do I add a .then () after this ? I tried it and the error is still there even with done() at the end of the script.
My test framework in config.js for protractor is mochai
Background
1.The element css is correct as I can run it in Selenium / Java.

I try this

it("testing site", (done)=> {

 .......
   done();
})

It does not work out too. Same error
var title_css = "h1[ng-bind='::$ctrl.primaryText']";
var gotograb_css = "a[ng-bind='::$ctrl.linkoutText']";

  it("testing site", ()=> {

    browser.get('https://www.eat24.com/');

    let EC = protractor.ExpectedConditions; //
    let title_element = element(by.css(title_css));
    let condition = EC.presenceOf(title_element);
    browser.wait(condition, 30000)
    element(by.css(gotograb_css)).click(); //ERROR

  })

Answer: I think the problem is that the browser.wait function is not getting resolved.
Try this:
    let condition = EC.presenceOf(title_element);
    return browser.wait(condition, 30000)
        .then(function () {
            return element(by.css(gotograb_css)).click();
        });

Answer: Looks like you have global timeout set to 2000 ms in your config.
And what happens is you try to wait up to 30 sec, which obviously more than your global timeout.
So just open the config and see if this is the case
Comment: I have added the timeout in here. The issue is not this. Thanks
Answer: If you are working with mocha probably you will need disable timeout adding to config file something like this:
  mochaOpts: {
    enableTimeouts: false
  },


find upper and lower bounds on average causal effect $\theta$

Question: I am working on some problems in All of statistics by Wasserman, and I am not quite sure how to tackle this problem.
Suppose you are given data $(X_1, Y_1), \dots, (X_n, Y_n)$ from an observational study where $X_i \in \{0, 1\}$ and $Y_i \in \{0, 1\}$. Although it is not possible to estimate the causal effect $\theta$, it is possible to put bounds on $\theta$. Find the upper and lower bounds on $\theta$ that can be consistently estimated from the data.
The hint says to use $\mathbb{E}(C_1) = \mathbb{E}(C_1 | X=1) \mathbb{P}(X=1) + \mathbb{E}(C_1 | X=0) \mathbb{P}(X=0)$. Then,
\begin{align*}
\theta &= \mathbb{E}(C_1) - \mathbb{E}(C_0) \\
&= \mathbb{E}(C_1|X=1)\mathbb{P}(X=1) + \mathbb{E}(C_1 | X=0)\mathbb{P}(X=0) - \mathbb{E}(C_0 | X=1) \mathbb{P}(X=1) - \mathbb{E}(C_0 | X=0)\mathbb{P}(X=0)
\end{align*}
Not sure where I go from here...
EDIT:
here's a nice table that summarizes the setup
\begin{array}{|c|c|c|c|}
\hline
   X& Y & C_0 & C_1 \\
\hline
   0 & 0 & 0 & 0^* \\
\hline
   0 & 0 & 0 & 0^* \\
\hline
   0 & 0 & 0 & 0^* \\
\hline
   1 & 1 & 1^* & 1 \\
\hline
   1 & 1 & 1^* & 1 \\
\hline
   1 & 1 & 1^* & 1 \\
\hline
\end{array}
Comment: What are $C_0$ and $C_1?$
Comment: @AdrianKeister $C_0$ and $C_1$ are random variables (also known as **potential outcomes**). $C_0$ is the outcome if the $X=0$ and $C_1$ is the outcome when $X=1$
Comment: What's the relationship between the $C_i$ and the $Y_i?$
Comment: @AdrianKeister $Y = C_1$ if $X=1$ and $Y = C_0$ if $X=0$.
Comment: They're counterfactuals, then?
Comment: @AdrianKeister well $C_0$ would be counterfactual for $X=1$ and $C_1$ would be counterfactual for $X=0$
Answer: I'm impressed that a stats book has causality in it. This is Problem 16.6.3. The author defines $\theta$ as the average causal effect, or average treatment effect. In your toy data example, you could actually compute $\theta$ as
$$\theta=\frac{0+0+0+1+1+1}{6}-\frac{0+0+0+1+1+1}{6}=0,$$
as the author does in Example 16.2. But in your actual problem, you don't have this data.
So I think here's an idea for moving forward. Your initial writing out of $E(C_1)$ and $E(C_1)-E(C_0)$ is exactly right. Let's continue. First of all, note that every expectation you wrote down is non-negative; indeed, they are all in the interval $[0,1].$ So that for an upper bound, we can say that
\begin{align*}
E(C_1)-E(C_0)
&=E(C_1|X=1)P(X=1)+E(C_1|X=0)P(X=0)\\
&\quad-E(C_0|X=1)P(X=1)-E(C_0|X=0)P(X=0)\\
&\le E(C_1|X=1)P(X=1)+E(C_1|X=0)P(X=0)-E(C_0|X=0)P(X=0).
\end{align*}
We're not done, yet, because in this last expression, we still have the counterfactual $E(C_1|X=0)P(X=0),$ which we can't get from the data. We can get the first term and the last term from the data. Well, what's the biggest that the counterfactual can be? It can't be bigger than if all the missing rows were $1$'s, so we can say that
$$E(C_1)-E(C_0)\le E(C_1|X=1)P(X=1)+P(X=0)-E(C_0|X=0)P(X=0),$$
which is all available in the data.
Similarly, we can write
\begin{align*}
E(C_1)-E(C_0)
&\ge E(C_1|X=1)P(X=1)-E(C_0|X=1)P(X=1)-E(C_0|X=0)P(X=0)\\
&\ge E(C_1|X=1)P(X=1)-P(X=1)-E(C_0|X=0)P(X=0).
\end{align*}
Comment: BTW, these bounds are often called "Manski bounds", see Manski, Charles F. "Nonparametric bounds on treatment effects." The American Economic Review 80.2 (1990): 319-323.
Comment: ahhh I see, and because the bounds use $\mathbb{P}(X)$, you get bounds that have a width of 1! This makes so much sense! Thank you!
Comment: You're very welcome!


How to set the value of a field when hidden from certain users/roles?

Question: I have a field which I don't want to be displayed for certain users, however I still want a value to be entered for that field, which is extrapolated from other fields they enter data in.
In order to do this, I'm setting the field as hidden in hook_form_alter:
$form['field_target']['#type'] = 'hidden';

and then setting the value of the field from within a form_validate function based on another field, such as:
$form_state['values']['field_target']['und']['0'] =
    $form_state['values']['field_source']['und']['0'];

And this works fine, unless I force a form validation error on field_source. When I correct the validation error and submit again, I get a white screen with PHP Error:
PHP Fatal error:  Cannot create references to/from string offsets
    nor overloaded objects in includes/common.inc on line 6288

This error happens even if I comment out the setting of field_target. However I can fix this error by removing the [#type'] = 'hidden' line and everything works fine, except that the field shows for all users.
Is there any way to fix my above approach, or is there a better way to achieve what I'm trying to do?
Answer: Ok it seems I can get around this error by setting:
$form['field_target']['#access'] = FALSE;

instead of ['#type'] = 'hidden'; and Drupal no longer freaks out.
If anybody has a better idea though I'll glady accept a different answer :)


When you have multiple replications of a study do you combine the data or analyze separately?

Question: Assuming that I have multiple replications of survey data, each one with exactly 1000 unique participants, do I run statistical analyses by combining the data into one large set of 3000 participants? or do I run the analyses separately? If one of these option is incorrect procedure, what is a consequence of doing it?
Answer: Were all three samples randomly selected from the same population?
If so then there is no reason you shouldn't combine the data together. I suspect that assumption probably won't hold though if you are dealing with survey data - are they from different time points?
Combining the data gives you a large sample size with which to detect statistically significant differences. However, in doing so you want to ensure that there is not systematic bias in the data that you haven't accounted for - i.e. regional differences in your population or temporal effects, such as people attitudes shifting through time.
Likewise, you don't really want to carry out three separate analyses if you can avoid it. Each one will have less statistical power (following the same logic as above), meaning you may not pick up on true differences (i.e. true positives). In addition, carrying out multiple tests can lead to type II error inflation, which essentially means you are more likely to generate false positives - these are ideally controlled for with familywise error rate adjustments.
So what do you do if you do have three datasets that are approximately the same but might contain systematic biases? Fit a mixed effects model, with a random effect for any potential biases. This effectively sweeps out any variation in your data due to the temporal/spatial effects that you aren't interested in and leaves you with greater statistical power to get at the questions you are interested in.
There are some good packages in R to fit these models, as well as some comprehensive guides online for doing so if you are unfamiliar with them.


Prediction intervals for kNN regression

Question: I would like compute prediction intervals for predictions made by kNN regression. I can't find any explicit reference to confirm, so my question is - is this approach to computing prediction intervals correct?
I have a reference dataset where each row is one location (e.g. city).
I have two features (say, x1 and x2), describing a sample from the population of that location (e.g. x1 could be the average income of the residents). Sample size is different for each location. I predict a target variable (say, y, e.g. the total number of cars in that city) based on x1 and x2.
A prediction for a new location Z is made by finding k nearest neighbors of Z in terms of x1 and x2 (the Euclidean distance), and averaging over the target variable of those k neighbors.
I compute prediction intervals as y* +- t*s, where s is the standard deviation of the target among k nearest neighbors, and t comes from the standard normal distribution (e.g. for 95% prediction interval t=1.96). I ignore x1 and x2, and I ignore the fact that x1 and x2 are estimated over different samples.
Does the approach make sense?
Answer: You've got two options, I think.

Bootstrap

Generate 100 synthetic data-sets by sampling with replacement from the original data-set. Run the knn regression over each new data-set and sort the point predictions. The confidence interval is just the distance between the 5th and 95th point prediction.

Pseudo-Residuals

Basically you either use a pooled variance estimator (if you have multiple observations at the same $x$) or pseudo-residuals to get an estimate of the variance. Assuming homoskedastic and normal error you can use the t-distribution such that:
$ \bar y_i \pm t(h,\alpha) \frac{\sigma}{\sqrt{n_i}}$
Where $\bar y$ is the average predicted, $h = \frac{n-2}{n}$ is the degrees of freedome of the t-distribution and $n_i$ is the number of points in the neighborhood.
You can read more about it here
Comment: At least the first option (bootstrap) is not providing a *prediction* interval but a *confidence* interval for the true average prediction.
Comment: I'd be very interested in learning more about that. To not hijack this question, I've opened a new thread (http://stats.stackexchange.com/questions/226565/bootstrap-prediction-interval)
Comment: This is a common misconception. Prediction interval is just as possible through bootstrap, see for example section 6.3.3 of "Bootstrap methods and their applications" by Davison
Comment: @CarrKnight Is it possible / correct to use these methods when your data are time-series?

Prediction intervals for kNN regression