How can I animate a UIView's rotation only within a certain degree range?

Question: In my app, I've got a simulation of an analog readout dial, like you might find on a car dashboard or a control panel. Run the following snippet for an example of what I mean:

svg { height: 100vh; }
#dial {
  fill: white;
  stroke: #CCCCCC;
  stroke-dasharray: 405;
  transform: rotate(135deg);
  transform-origin: center;
}
#pointer {
  fill: #FF0000;
  animation: 2s infinite alternate dialrotate;
  transform-origin: bottom center;
  animation-timing-function: ease-in-out;
}
@keyframes dialrotate {
  from {
    transform: rotate(-135deg);
  }
  to {
    transform: rotate(135deg);
  }
}
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <circle id="dial" cx="99.5" cy="100.5" r="86"/>
 <polygon id="pointer" points="100.1,25.5 98.2,100 102,100"/>
</svg>

(I'm not using SVGs in my app--I just threw the example together using an SVG because I'm primarily a web developer)
Here's how I'm animating the dial movement right now:
UIView.animate(
    withDuration: 0.1,
    delay: 0.0,
    options: .curveEaseOut,
    animations: {
        self.dialPointer.transform = CGAffineTransform.init(rotationAngle: radians);
    },
    completion: nil
)

I want to animate the pointer's direction between the two extremes (270 degrees). But I DON'T want the pointer to rotate across the shorter 90 degree path outside the dial's bounds; i.e. this is WRONG:

svg { height: 100vh; }
#dial {
  fill: white;
  stroke: #CCCCCC;
  stroke-dasharray: 405;
  transform: rotate(135deg);
  transform-origin: center;
}
#pointer {
  fill: #FF0000;
  animation: 2s infinite alternate dialrotate;
  transform-origin: bottom center;
  animation-timing-function: ease-in-out;
}
@keyframes dialrotate {
  from {
    transform: rotate(225deg);
  }
  to {
    transform: rotate(135deg);
  }
}
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <circle id="dial" cx="99.5" cy="100.5" r="86"/>
  <polygon id="pointer" points="100.1,25.5 98.2,100 102,100"/>
</svg>

How can I force the UIView's rotation to rotate the long way around, instead of rotating over the shortest direction?
Answer: As you have discovered, by default UIView animation takes the shortest path when interpolating angle values.  You have a couple of options:

You can decompose the animation into several shorter steps, or keyframe it.
You can use a CABasicAnimation instead and animate your layer's transform using a cumulative animation

Playground example:
import PlaygroundSupport
import UIKit

let rect = CGRect(x: 0, y: 0, width: 300, height: 300)
let view = UIView(frame: rect)
let bar = UIView(frame: rect.insetBy(dx: 40, dy: 140))
bar.backgroundColor = .red
view.addSubview(bar)

let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.toValue = 1.25 * CGFloat.pi
animation.isCumulative = true
animation.duration = 5
bar.layer.add(animation, forKey: "spin")
bar.layer.transform = CATransform3DMakeRotation(1.25 * CGFloat.pi, 0, 0, 1)
PlaygroundPage.current.liveView = view

Comment: Note that `transform.rotation` means the same as `transform.rotation.z`.
Answer: You can do it like this
UIView.animate(
    withDuration: 0.1,
    delay: 0.0,
    options: .curveEaseOut,
    animations: {
        if radians > CGFloat.pi {
            self.dialPointer.transform = CGAffineTransform.init(rotationAngle: CGFloat.pi);
        }
        self.dialPointer.transform = CGAffineTransform.init(rotationAngle: radians);
    },
    completion: nil
)


Help me understand the z-value computed in wilcoxsign_test (R, coin package)?

Question: I'm using the coin-package in R to run comparisons on paired data using wilcoxsign_test. I use the exact version of the test, so I assume that the test goes through all permutations of the paired data and returns an accurate p-value.
What is unclear to me is how the z-value returned by default by the function is computed. I'm aware of the usual large sample approximation formulas used to convert Wilcoxon statistics to z scores, but I wonder how the z value is derived in the case of the exact permutation version of the test.
My questions are:

Are all of the w-statistics produced by the permutation enumerated so that the distribution of w is approximately normally distributed and the observed w value is then converted to a z value based on distribution yielded by the permutation?
As I understand it, the p-value of the exact test is accurate and the z value is some sort of approximation that normally requires a sample size of > 10 (at least when using the standard formulas) and thus not always a very useful statistic. Does the permutation version of the test somehow get around this?
The p-values returned do not always correspond to the p-values I obtain by converting the z values to p-values. Could someone clear this up for me?
Answer:

Are all of the w-statistics produced by the permutation enumerated so that the distribution of w is approximately normally distributed and the observed w value is then converted to a z value based on distribution yielded by the permutation?

I doubt it, since it's not necessary -- we can compute the mean and variance without knowing the exact distribution, even in the presence of ties. But you could only tell with absolute certainty what the code does by actually looking at it.

As I understand it, the p-value of the exact test is accurate and the z value is some sort of approximation that normally requires a sample size of > 10 (at least when using the standard formulas) and thus not always a very useful statistic.

No, the z value should be exact at any sample size (in the sense that it's a correct computation of the number of standard deviations the test statistic is from the mean under the null), but the resulting quantity doesn't have an exact normal distribution (under the null), so if you computed a p-value from that z, then the p-value would be approximate.

The p-values returned do not always correspond to the p-values I obtain by converting the z values to p-values.

Sure --

The test statistic isn't exactly normally distributed.
If they're using sampling of the permutation distribution rather than exact calculations, there's also some simulation error.
Comment: Im specifically using the exact version of the test though so there is no stochastics. Should this not give me an accurate p-value (in the sense that I get the probability of obtaining the observed value when the empirical distribution has been fully enumerated)? Normally the z-value is obtained before the p-value (the p-value is derived from the z-value), but in the case of permutation procedures the p-value is extracted from the empirical distribution without referencing any hypothetical distributions. So, I wonder what exactly is the origin of the z-value in this permutation procedure.
Comment: This is essentially covered in my answer already. How do you get a z-score? you take your value, subtract its population mean and divide by its population standard deviation. You can compute those for the signed rank test easily; textbooks -- or indeed the wikipedia page for the test typically give these, and the derivations are not that difficult. It's not that hard to adjust the variance formula for ties (often given in the same books). Since $W$ is approximately normal (in large samples), $Z=[W-\mu_W]/\sigma_W$ is approximately standard normal in the same situations...
Comment: ...  Since $W$ is known for this sample and we can compute $\mu_W$ and $\sigma_W$ (the population values for the mean and s.d. when the null is true), we know $Z$ for this sample exactly. It's not an approximation in any sense -- it's the correct z-score, but it just doesn't quite have a normal distribution. The approximation part only comes when you use that value of $Z$ as if it *did* have a normal distribution.


Working with closed intervals / sets.

Question: I have been having a lot of trouble understanding closed sets in the context of metric spaces. I understand that this means that the set (let's say X) contains all of its limit points. But I am having tons of problems in actually solving questions involving closed sets. Here is one in particular:

Let $\{[a_n, b_n]\}_{n = 1}^\infty$ be a sequence of closed intervals such that $|a_n|\leq 1$ and $|b_n|\leq 1$ for every positive integer $n$. Prove that $\{\{x_n\}_{n= 0}^\infty\mid x_n\in [a_n, b_n]\}$ is a closed subset of $H^\infty$.

Now obviously the sequence in question will be between -1 and 1 (inclusive) and is therefore closed. But how do I state this more elegantly and mathematically?
Comment: What do you mean by $H^\infty$?
Comment: @copper.hat It denotes the set of all real sequences $\{a_n\}$ such that $|a_n| <= 1$ for every positive integer n.
Comment: What is the metric? Can you show that $C_n = \{ x \in H^\infty | x_n \in [a_n,b_n] \}$ is closed and then conclude that $\cap_n C_n$ is closed?
Comment: @copper.hat I'm sorry, this whole concept has confused me. I understood metric spaces and the distance function, but upon getting to open and closed sets I'm lost. Do i show $C_n$ is closed by proving it contains all its limit points? How do I do that?
Comment: What is the distance function for $H^\infty$? Yes, showing that it contains all its limit points is certainly one way, There may be easier ways, but I don't know what distance you use on $H^\infty$ so cannot offer any direct assistance.
Comment: A set $U$ in a metric space is open **iff** for any $x \in U$ there is some $\epsilon>0$ such that $B(x,\epsilon) \subset U$. Since $B(x,r) = \{ y | d(x,y) < r \}$, we need the distance function to figure out if a set is open. A set is closed **iff** its complement is open. Your intuition from $\mathbb{R}^n$ will carry through to a limited extent.
Comment: The only thing I can see is that in a prior question in the book, when we first used $H^{\infty}$ , we had to prove that $$d(\{a_n\}, \{b_n\}) = \sum_{n=1}^{\infty} \frac{|a_n - b_n|}{2^n}$$
Comment: Presumably you mean $d$ is defined by this expression? This is indeed a distance. This is what is used to define the open and closed sets.
Comment: So would I be off base in saying that the numerator is less than or equal to 2, and thus the entire distance function is less than or equal to 1. So making epsilon equal to 1?
Comment: I'm not sure what you are getting at... I have added an answer below.
Answer: One way to show that the set $C$ is closed is to show that if $x_n \to x$ with $x_n \in C$, then $x \in C$.
Note that by $x_n \to x$, I mean $d(x_n,x) \to 0$ where $d$ is given by the
formula in the comments above.
Be careful with the indices here. Each $x_n$ is an element of $H^\infty$ and
is itself a sequence $x_n(1),x_n(2),...$.
Let $C = \{ x | x(k) \in [a_n,b_n] \}$, $x_n \to x$ and suppose $x_n \in C$ for all $n$.
We want to show that $x \in C$.
Since ${1 \over 2^k} |x_n(k)-x(k)| \le d(x_n,x)$, and $x_n \to x$, we see that
$x_n(k) \to x(k)$ for each $k$. Since $x_n(k) \in [a_k,b_k]$ for all $n$, we see that $x(k) \in [a_n,b_n]$. Since this is true for all $k$ we have
$x \in C$.
Comment: Excellent. I think I have finally gotten closer to understanding sets. Would you say that problems like these (at least when first being taught) are usually solved using the distance function?
Comment: Yes. The distance function is the essence of a metric space, so it is inextricably involved.
Comment: thank you very much, I had been banging my head against the wall on this one for awhile
Comment: Delighted to assist.

Working with closed intervals / sets.


Como criar um Type de função no Typescript

Question: Estou trabalhando em um projeto com React+TS, pesquisei bastante para tentar resolver antes de postar aqui, acho que preciso criar um Type para o parametro que eu passo na função onSubmit que é recebida como Props do Mainpage.tsx.
O erro recebido é:
( onde ele foi gerado esta marcado no código abaixo )
(property) onSubmit: (name: string, email: string) => void
Type '{ onSubmit: (name: string, email: string) => void; }' is not assignable to type 'IntrinsicAttributes & ((param?: any, param2?: any) => void)'.
  Property 'onSubmit' does not exist on type 'IntrinsicAttributes & ((param?: any, param2?: any) => void)'.ts(2322)

Form.tsx
import { FormEvent, useState } from "react"

export const Form = (onSubmit: (param?:any, param2?:any)=> void ) => {

    const [name, setName] = useState('')
    const [email, setEmail] = useState('')

    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();

        console.log( 'Submit Form: ' + name, email)
        onSubmit(name,email);
    }

    return(
        <form onSubmit={handleSubmit}>

                <input type="text" name="name" id="name" placeholder="name..." value={name} onChange={(e) => setName(e.target.value)}/>

                <input type="email" name="email" id="email" placeholder="email..." value={email} onChange={(e) => setEmail(e.target.value)}/>

            <button type="submit">Enviar</button>
        </form>
    )
}

Mainpage.tsx
import { useState } from "react";
import { Form } from "../../components/Form";
import { Greet } from "../../components/Greet";

const Mainpage: React.FC = () => {

    const [name, setName] = useState('')
    const [email, setEmail] = useState('')

    const onSubmit = (name:string, email:string ) => {

        console.log('Submit App: ' + name, email)
        setName(name)
        setEmail(email)
    }

    return(

            <Greet/>
            <Form onSubmit={onSubmit}/> **// O ERRO FOI GERADO AQUI**

    )
}
export default Mainpage;

Answer: Talvez o erro seja gerado pelo fato das props de todo componente React ser um objeto e não apenas uma função de callback.
Algumas tentativas pode ser feitas para solucionar o problema. Criar uma interface para as props e incluir a função onSubmit, possa resolver esse problema. Ficaria algo assim...
No arquivo do Form, crie a interface:
interface Props {
  onSubmit: (param?:any, param2?:any)=> void
}

Chame as props desta forma no componente:
export const Form = ({ onSubmit }: Props) => {...}

Veja o funcionamento neste playground.
Comment: Muito obrigado. Funcionou corretamente, e eu não sabia que as props de todo componente eram objetos.


Composer file that is only additive

Question: We have a Drupal 8.x instance maintained by one team and would like to be able to have another team add modules to this without overriding/removing what is already there. Is this possible?
Comment: Tell the other team not to remove any modules from composer.json and use git version control so you can yell at them if they do.
Comment: What's the problem with `composer require` ?
Answer: I think the best way would be using Composer and Git together:

Use GIT and create feature branches and merge them into your production / develop branch
Use $composer require drupal/module (keep the composer.json file in git repo)

Composer file that is only additive


Busca dinâmica em tempo real

Question: Na empresa que trabalho vamos implementar um sistemas no qual o Back-end será PHP e o banco de dados será CACHE (Intersystem).
A base de dados fica em um servidor diferente de onde será implementado o sistema em PHP, acontece que toda a comunicação entre eles será via Webservice para muitas consultas e registros ele funciona bem, porém será implementado um sistema de busca
A busca terá que ser dinâmica pois enquanto o usuário digita algo o sistema vai sugerindo resultados que coincidam com o que está sendo digitado, como nas imagens que estou pondo em este post.
Para ter esse tipo de resultado em tempo real precisarei usar o AJAX ou jQuery certo?
Dá para usar o PHP + Webservice + AJAX ou jQuery para dar respostam em tempo real enquanto o usuário digita algo?
Answer: A resposta é SIM... dá para obter resposta em tempo real quando um utilizador digita algo, no entanto alguns são os pontos a ter em consideração.
No caso da utilização do JQUERY e PHP como solicitado, requisição por AJAX é o caminho a tomar.
Numa análise simplista irá precisar de "ouvir" eventos de teclas no INPUT.
exemplo com keypress mas existe o keyup ou o keydown (coloco o enter, para outras teclas ver documentação):
$( "#target" ).keypress(function( event ) {
    if ( event.which == 13 ) {
        alert('enter pressionado');
    }
});

Como resultado a cada tecla pressionada poderás obter o conteúdo do INPUT:
var content = $( "#target" ).val();

Entregar content ao asynchronous HTTP (Ajax) request e assim que é retornado pelo webservice o resultado da pesquisa atualize o html.
Como disse esta é uma forma simplista e porquê?
Porque a velocidade de entrega do resultado da pesquisa nunca irá ser a mesma e porque quem digitar rápido... imagine os requests sucessivos. Bom na verdade com a implementação de uma QUEUE de requests pode ultrapassar esse problema, mas mais uma vez não seria nada prático neste caso particular.
Não é boa prática realizar AJAX requests à velocidade que se introduz o texto. E se o webservice estiver bem preparado irá concerteza bloquear a um determinado ponto ou negar-se a responder. Não se esqueça que um webservice é um serviço exposto, logo acedido por muitos. Imagine todos a teclar ao mesmo tempo. :)
Se o webservice for "seu" então você determinará as regras, no entanto, desgraçado do servidor que responder por um serviço exposto desta forma.
Existem algumas técnicas a implementar mas deixo uma simples que terá resultados imediatos, ou seja a utilização de um timer... exemplo: setTimeout. imagine algo do género:
$.fn.input_search = function () {
    var timer = 0;
    var input = $(this);
    input.keyup(function (e) {
        var code = e.keyCode ? e.keyCode : e.which;
        if (code > 45 || code === 32 || code === 8 || code === 13) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                alert('neste momento coloca a chamada AJAX '.input.val())
            }, 200);
        }
    });
};

Criei este plugin, não o testei mas a lógica não será certamente muito diferente. Cada tecla pressionada será validada quando a mesma for "largada" e o timer é reiniciado.
Por simplicidade o caracter terá de ser maior que 45 (consulte a tabela). Quando parar de teclar então o timer irá aguardar o tempo estipulado. No exemplo é de 200 milisegundos e executa o código dentro do setTimeout().
Realize testes e ajuste o valor do timer. Aumente o seu valor, no entanto, quanto maior, mais tempo demora a pesquisa a iniciar.
Coloquei validações que me lembrei em que o timer deve de ser reiniciado ao teclar, como tecla de espaço (32), backspace (8) e o enter (13)... veja outras hipóteses pois trata-se de um exemplo.
Answer: Você deverá fazer algo do tipo toda vez que o usuário digita algo realiza a busca, como nesse exemplo pegando em real time o que é digitado
Feito isso você deverá do lado do servidor trazer resultados, na volta deverá ter um autocomplete, pode ser com jQuery ui mesmo.
Answer: Sim, é só você colocar a URL do WebService no lugar onde ficaria o caminho do arquivo.
Exemplo em Ajax do Jquery:
$.ajax({
    url: 'http://ws.exemplo.com/'
});

Espero ter ajudado!
Lembrando que o WebService tem de estar preparado para receber as informações!

Busca dinâmica em tempo real


Proving that $\mathcal{C}([0,1])$ is a Banach space

Question:
Let $V=\mathcal{C}([0,1])$ be the space of all complex valued continuous functions with the norm $||f||_{\infty}=\sup_{x\in[0,1]}|f(x)|$. Then, $V$ with the norm $||\cdot||_{\infty}$ is a Banach space.

I'm having problems to understand some part of the proof. I will proceed proving the previous statement until the question comes.
Given a Cauchy sequence $(f_n)_{n\in \mathbb{N}}\in V$, that's to say, for all $\varepsilon >0$ there exists $N\in \mathbb{N}$ such that for all $n,m \geq N$ we have that $||f_n-f_m|||_\infty \leq \varepsilon$; we need to find a candidate $f$ for the limit of $(f_n)_{n\in \mathbb{N}}$. Fixing $x\in[0,1]$ and noting that for all $n,m\geq N$ we have that
$$|f_n(x)-f_m(x)|\leq \sup_{z\in[0,1]}|f_n(z)-f_m(z)|=||f_n-f_m|||_\infty \leq \varepsilon.$$
Thus, $(f_n(x))_{n\in \mathbb{N}}$ is a Cauchy sequence in $\mathbb{C}$ and since $\mathbb{C}$ is complete we know that $\lim_{n\to \infty}f_n(x)$ exists. Then, our candidate will be $f(x):=\lim_{n\to \infty}f_n(x)$.
Now, we want to prove that $f$ is continuous. Fixing $x\in[0,1]$ and letting $\varepsilon >0$ we can choose $N\in \mathbb{N}$ such that for all $n,m\geq N$ we have that $||f_n-f_m|||_\infty \leq \varepsilon/3$. Also, as $f_N\in (f_n)_{n\in \mathbb{N}}\subset V$, for this $\varepsilon >0$ there exists $\delta >0$ such that if $|x-y|\leq \delta$ then $|f_N(x)-f_N(y)|\leq \varepsilon/3$. Furthermore, for any $n,m\geq N$ and $y\in \mathbb{C}$ such that $|x-y|\leq \delta$ we have that
\begin{align*}
|f(x)-f(y)|  =&|f(x)-f_n(x)+f_n(x)-f_N(x)+f_N(x)\\
& -f_N(y)+f_N(y)-f_m(y)+f_m(y)-f(y)| \\
\leq&|f(x)-f_n(x)|+|f_n(x)-f_N(x)|+|f_N(x)-f_N(y)|\\
& +|f_N(y)-f_m(y)|+|f_m(y)-f(y)|
\end{align*}
I think it's important to do it that way since then $\delta$ could depend on $N$ but not on $n$. The second and the third terms are less or equal that $\varepsilon/3$. However, I don't think I can use the same argument with the fourth, since $y$ may not be in $[0,1]$. The only thing I know is that $|x-y|\leq \delta$. If I prove that the fourth them is less or equal than $\varepsilon/3$, then I know how to finish the prove.
Comment: How come $y$ may not be in $[0,1]$?
Comment: If we can first show $f_n$ uniformly converges to $f$, then the continuity of $f$ follows.
Comment: @Song this is exactly what is to shown here... so you cannot "prove" a theorem using it.
Comment: I believe we *can* assume $y \in [0,1]$, because we only want to check continuity in the interval $[0,1]$. Also note that $f_n(y)$ is only defined for $y \in [0,1]$! I think this is what @Berci hinted at?
Comment: @red_trumpet Yes, exactly.
Comment: Yes, I think both of you are correct
Answer: We'll prove that the $f_n$ converges uniformly to $f$ on $[0,1]$, because this in general a useful result, that uniform convergence of a sequence is in fact equivalent to the sequence being Cauchy in the sup norm. Your desired result will follow because we know that the uniform limit of continuous function is continuous.
Fix $\varepsilon>0$. As you have already shown we know that there exists a $N\in \mathbb N$, such that for all $n,m>N$ and $x\in[0,1]$ we have
$$|f_n(x)-f_m(x)|<\varepsilon/2.$$
Now for any $m>N$ and $x\in[0,1]$ we have, that for any $n\in \mathbb N$,
$$|f(x)-f_m(x)|\leq|f_m(x)-f_n(x)|+|f(x)-f_n(x)|<\varepsilon/2+|f(x)-f_n(x)|.$$
What is crucial here, is that we can pick any $n$ we like and this inequality holds, which implies that, because of pointwise convergence of $f_n$ to $f$,
$$\lim_{n\to\infty}|f(x)-f_m(x)|\leq\lim_{n\to\infty}\varepsilon/2+|f(x)-f_n(x)|=\varepsilon/2<\varepsilon.$$
The LHS is independent of $n$ though, so the limit has no affect. We have thus shown for any $\varepsilon>0$ there exists a $N\in \mathbb N$ such that for all $m>N$ and $x\in[0,1]$ we have
$$|f(x)-f_m(x)|<\varepsilon.$$
This is the definition of uniform convergence, which we wanted to show.
Note that you could have directly applied this method to finish your direct proof of continuity. Just take the limit as $n$ and $m$ tend to infinity on both sides of your final inequality.
Comment: I might be getting something wrong, but shouldn't you use the fact that $[0,1]$ is compact at some point in your proof? OP only showed that for **fixed** $x \in [0,1]$ there exists $N \in \mathbb{N}$ such that for all $n,m > N$ your inequality holds.
Comment: @Nicolas You only need compactness to guarantee that the sup norm is actually a norm on the space. The OP's wording is a bit imprecise. He should only have fixed his $x$ after his claim about the existence of $N$, but if you analyse his argument you'll note that his $N$ does not depend on $x$ at all, same as mine doesn't.


Does it ever make sense to average the median, mean, and mode?

Question: Consider four subjects (A,B,C,D) competing 12 times in a game with 5 possible scores (5,6,7,8,9):
A) Median: 7  Mean: 6.92  Mode: 5
    5:#####              avgL||avgR
    6:                    6.9||8.5 (+3.2)
    7:##                555557789999
    8:#                      ^^
    9:####

B) Median: 7  Mean: 7.08  Mode: 7
    5:#                  avgL||avgR
    6:###                 6.2||8.0 (+1.8)
    7:####              566677778899
    8:##
    9:##

C) Median: 7  Mean: 7.00  Mode: 7
    5:                   avgL||avgR
    6:                    7.0||7.0 (±0.0)
    7:############      777777777777
    8:
    9:

D) Median: 7  Mean: 6.83  Mode: 7
    5:##                 avgL||avgR
    6:##                  6.0||7.7 (+1.7)
    7:######            556677777799
    8:
    9:##

In this case: Who won?

Going by the median, they're all equal
A has the lowest mean and the lowest mode, but the highest average right half of the scores
B has the second-highest mean and the most normal distribution
C has the most consistent score
D has the highest mean, but the second-lowest skew toward the higher scores

Would it make sense to average out or otherwise combine a few metrics?
Comment: The winner is whoever has the highest score of the metric of your choosing. In case of the median then everyone (or no one) is a winner. In case of the mean it's D. avgL and avgR are very arbitrary.
Comment: Why do you think that the median or mean do not answer your question, about who is the winner? Why do you think they are inappropriate? Does the shape of the distribution bother you?
Comment: This is a subjective question.  The average score (D wins) makes the most sense to me because of the simplicity.  Btw, I like the way you present the data.
Comment: For right skewed data one often has mode < median < mean. So maybe it makes sense just to use the median. These three measures of centrality have very different definitions and thus different appropriate uses in practice, so it would be difficult to explain what criterion for 'best' is expressed by an average of mean, median, and mode. [For left-skewed data its often mode > median > mean; for roughly symmetrical unimodal data (think normal) the three may be about equal.]
Comment: After some additional thought, it seems I should have mentioned (as did @NickCox) that with data from only 12 games played by each participant, you may have ties values for the 'mode'. This strengthens @FrankHarrel's advice against averaging mean, median, and mode. // Perhaps more important, it seems that your ultimate objective is to find a way to say which participant is would be 'best' in a match up between any two. I have posted an Addendum showing one way that might be answered.
Answer: Three examples:
Right-skewed data. Salaries within an organization may be right-skewed. Mode is the most common salary, mean is total payroll divided by number of employees considered. Any one of mode, median, mean might be the one best way to describe or summarize the data.
The summary of the data below shows the median and mean of hypothetical data.
set.seed(2020);  x = rgamma(500, 3, .01)
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  20.69  175.49  268.61  294.28  384.20  964.41

Roughly, the midpoint (250) of the tallest histogram bar might be used as the 'mode' of the sample. A better way to
estimate the mode of the population distribution might be to find where (234) the kernel density estimator (KDE) of the sample is a maximum.
It is not clear what attribute of the data the average (about 266) of the mean, median, and mode might describe. As mentioned in my comment, this is not far from the median, which does have a clear meaning.
hist(x, prob=T, col="skyblue2", main="500 Salaries")
 lines(density(x), col="red", lwd=2)

mx = max(density(x)$y); mx
[1] 0.002711106
mode = mean(density(x)$x[density(x)$y==mx]);  mode
[1] 233.6744

[Note: For this gamma population distribution the mean, median, and mode are 300, 267.4, and 200, respectively.]
Symmetrical, unimodal data. For data from a normal population, the mean, median, and mode may be nearly the same (all about 100 for the sample below). Perhaps averages are most often used to describe the center of such a distribution; but for various purposes the mode or median might be used as well, and if they are all nearly the same, it doesn't much matter.
set.seed(1215);  y = rnorm(500, 100, 15)
summary(y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  49.59   91.30   99.69  100.44  109.07  146.51

hist(y, prob=T, col="skyblue2", main="500 Test Scores")
 lines(density(y), col="red", lwd=2)

Left-skewed data. Here the mean (17.1) tends to be
smallest and the mode (18.5) largest. Depending on the type of device under study, any one of these three
measures of centrality might be most useful.
set.seed(1159);  v = 24*rbeta(200, 10, 4)
summary(v)
  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  10.23   15.30   17.50   17.13   19.13   22.13

hist(v, prob=T, col="skyblue2", main="200 Voltages")
 lines(density(v), col="red", lwd=2)

mx = max(density(v)$y); mx
[1] 0.1479789
mode = mean(density(v)$x[density(v)$y==mx]);  mode
[1] 18.51482

[Note: For this population distribution, a multiple of a beta distribution, the mean, median, and mode are 17.14, 17.39, and 18.0, respectively.]
Addendum. Of two participants, which is best? One answer is to try
to predict which of the two would win if the participants faced each other in a match:
Consider A vs. D.  On the 12 games for which you have data A averaged 6.92 and D averaged 6.83.
# A vs D
A = c(5,5,5,5,5,7,7,8,9,9,9,9)
summary(A)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  5.000   5.000   7.000   6.917   9.000   9.000
summary(D)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  5.000   6.000   7.000   6.833   7.000   9.000

It seems reasonable to ask whether A is likely to win in a match with D.
By choosing performances on the 12 earlier games at random, we can simulate
a thousand matches between A and D. It seems that A beats or ties D about 63% of the time.
set.seed(1216)
a = sample(A, 1000, rep=T)
d = sample(D, 1000, rep=T)
mean(a >= d)
[1] 0.628

Playing around with a few other such hypothetical tournaments
of 1000 games, I found that the player with the higher average
does best. But it is possible to make up player histories of 12 games
where this is is not the case when averages over the 12 games are
nearly equal. I will let you play around with similar simulated
tournaments. If this criterion for 'best' appeals to you, you might
search this site and google for information on stochastic domination.
Here is one more hypothetical tournament---for B vs. C, both of whom
have averages near 7 for the 12 games you report. However, B has more
games with high scores, which seems to give B an advantage: B wins or ties about 67% of the time.
B = c(5,6,6,6,7,7,7,7,8,8,9,9)
summary(B)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  5.000   6.000   7.000   7.083   8.000   9.000
C = rep(7, 12)
summary(C)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
      7       7       7       7       7       7

# B vs C
set.seed(1217)
b = sample(B, 1000, rep=T)
c = sample(C, 1000, rep=T)
mean(b >= c)
[1] 0.673

Comment: Executive summary, perhaps: If measures agree, it doesn't much matter in practice what you use, except that on principle you might prefer one. If measures disagree, they're capturing different aspects of the distribution, and quoting two or three might be informative.
Comment: And (not explicitly noted above) if knowing _population parameters_ is an issue: for a given sample size the mean is often most accurately estimated and the mode least accurately estimated.
Comment: @Vaelus I doubt that Bruce ET is in a better position than the OP to know what is best for the problem. You're always at liberty to post an answer yourself if dissatisfied.
Comment: In this particular case, I would worry first that there are ties for mode given the discreteness of the variable.
Comment: @Frank Harrell The general rule seems sound, but still to me leaves some scope for exceptions. The midrange is the average of the minimum and maximum. It is, or was, quite often used as a summary, e.g. in reporting from min-max thermometers observed daily. It is a practical choice whenever those extremes are the only available measurements. Daily range of temperatures is, however, unusual because _all_ the temperatures between extremes are known to have been experienced in the previous 24 hours.
Comment: The answer to the original question is no, it does not make sense to average point estimates that are estimating different quantities.
Comment: (ctd) Tukey used the trimean https://en.wikipedia.org/wiki/Trimean as a weighted average of median and quartiles and there are many such compromise  estimators in _Robust Estimates of Location_ from Andrews, Bickel, Hampel, Huber, Rogers and Tukey in 1972. Most such ideas haven't survived but I suspect because they were too arbitrary or complicated for any but their proposers to want to use or explain to others, not because they were unsound in principle.
Comment: This answer should outline when each measure might be an appropriate criterion for winning in the actually example scenario from the question. Additionally, it should explicitly answer the title question.
Comment: Just don't average mean, median, or mode.


Chamar evento de dentro do código

Question: Tenho esse evento em meu código:
protected void rdbGarantiaConfissao_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Declarações
            RadioButtonList vrblAprovado = sender as RadioButtonList;
            try
            {
                //Instâncias e Inicializações

                //Desenvolvimento
                if (vrblAprovado.SelectedValue == "1")
                    MostraConfissaoGarantia(1);
                else
                    MostraConfissaoGarantia(2);
            }
            catch (Exception Ex)
            {
                Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
                Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
            }
        }

Como eu faço para em outra parte do código eu executar esse evento?
Só quero evitar isso:
if (rdbGarantiaConfissao.SelectedValue == "1")
   wucCadastroConfissaoDividaPV.Visible = true;
else
   wucGarantiaAdicionalPV.Visible = true;

Pois o evento SelectedIndexChanged já faz isso, como pode ser visto.
Comment: Que outra parte do código? Seja específico.
Comment: Chame o método da forma como faz com qualquer outro. Passe um `RadioButtonList`. O parâmetro `EventArgs` pode ser null.
Comment: Eu quero chamar o SelectedIndex do meu Radiobuttolist, de outro método.
Comment: Dentro desta mesma classe? É preciso saber exatamente quem vai chamá-lo para chamar do jeito correto (e ver se pode chamar).
Comment: O sender é o seu `Radiobuttolist`
Comment: Mas quem é o `Radiobuttolist`? Se o método está protegido você só pode chamar dentro desta classe ou de uma que herde desta.
Comment: seja mais específico, aonde voce quer chamar esse metodo, esse RadioButtoList tem metodo onchange ?
Comment: @pnet, a chamada será feita da mesma Classe (Page ou UserControl) ou de outra Pagina ou UserControl?
Comment: @bigown nesse caso o `Radiobuttolist` é `this`
Comment: @ramaral É o que eu acho mas não tenho certeza.
Comment: Tudo está na mesma classe.
Answer: Assim resolveu:
protected void rdbGarantiaConfissao_SelectedIndexChanged(object sender, EventArgs e)
        {
           NomeMetodo(sender);
        }

private void NomeMetodo(object sender){
 //Declarações
            RadioButtonList vrblAprovado = sender as RadioButtonList;
            try
            {
                //Instâncias e Inicializações

                //Desenvolvimento
                if (vrblAprovado.SelectedValue == "1")
                    MostraConfissaoGarantia(1);
                else
                    MostraConfissaoGarantia(2);
            }
            catch (Exception Ex)
            {
                Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
                Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
            }
}

protected void NomeEvento2(){
   NomeMetodo(rdbGarantiaConfissao);
}

Comment: Não percebo por que não usa simplesmente: `rdbGarantiaConfissao_SelectedIndexChanged(this, null);`
Comment: Sim. Claro que isto só é válido porque a chamada é feita na própria classe, também não seria possível de outro modo já que o método é `protected`
Comment: Não pensei nisso. O this seria meu sender, certo?
Answer: Tente usando Eventhandler
https://msdn.microsoft.com/pt-br/library/system.eventhandler%28v=vs.110%29.aspx
Ou crie um método que use RadioButton como parâmetro.
  protected void rdbGarantiaConfissao_SelectedIndexChanged(object sender, EventArgs e)
    {
//Chame o metodo
             Metodo(meuradiobtn);
     }

Comment: Você tem certeza que isto responde a pergunta?
Comment: não, em realidade o evento funciona. Tanto funciona, que eu quero agora executá-lo fora, só para não que ficar fazendo if com ele. Já fiz isso uma vez em outra empresa e não me lembro como foi feito.
Answer: Se você pretende utilizar somente a propriedade SelectedValue do RadioButtonList, você pode criar um método que recebe um parâmetro do tipo String, algo assim:
protected void MeuMetodo(String selectedValue)
{
    try
    {
        //Instâncias e Inicializações

        //Desenvolvimento
        if (selectedValue == "1")
            MostraConfissaoGarantia(1);
        else
            MostraConfissaoGarantia(2);
    }
    catch (Exception Ex)
    {
        Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
        Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
    }
}

Para utilizar esse método no evento SelectedIndexChanged ou em qualquer outra parte do código, você pode fazer algo assim:
protected void rdbGarantiaConfissao_SelectedIndexChanged(object sender, EventArgs e)
{
    RadioButtonList vrblAprovado = sender as RadioButtonList;
    if (vrblAprovado != null)
        MeuMetodo(vrblAprovado.SelectedValue);
    else
        // o que você irá fazer se sender não for do tipo RadioButtonList
}

protected void QualquerOutroMetodoQueVoceTem()
{
    MeuMetodo(SeuRadioButtonList.SelectedValue);
}

Caso você precise realmente trabalhar com mais informações que estão no RadioButtonList, pode fazer assim:
protected void MeuMetodo(RadioButtonList radioButtonList)
{
    try
    {
        //Instâncias e Inicializações

        //Desenvolvimento
        if (radioButtonList.SelectedValue == "1")
            MostraConfissaoGarantia(1);
        else
            MostraConfissaoGarantia(2);
    }
    catch (Exception Ex)
    {
        Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
        Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
    }
}

E para chamá-lo:
protected void rdbGarantiaConfissao_SelectedIndexChanged(object sender, EventArgs e)
{
    RadioButtonList vrblAprovado = sender as RadioButtonList;
    if (vrblAprovado != null)
        MeuMetodo(vrblAprovado);
    else
        // o que você irá fazer se sender não for do tipo RadioButtonList
}

protected void QualquerOutroMetodoQueVoceTem()
{
    MeuMetodo(SeuRadioButtonList);
}

Note que o "tratamento" das exceções é feito dentro do MeuMetodo, aqui no SOpt tem algumas perguntas que tratam desse assunto.

Chamar evento de dentro do código


A generalisation of Cauchy–Schwarz

Question: Let $u_1,\dots,u_n$ be vectors in an inner-product space and define $a_{ij} = \langle u_i , u_j \rangle$. So
$$ A=(a_{ij}) = \begin{pmatrix} u_1^{\dagger} \\ \vdots\\ u_n^{\dagger} \end{pmatrix} \begin{pmatrix} u_1 & \cdots & u_n \end{pmatrix} = U^{\dagger} U, $$
where $U$ is the matrix of column vectors $u$ stacked side-by-side. But then
$$ x^{\dagger} A x = \langle Ux,Ux \rangle \geqslant 0, $$
with equality only if $Ux=0$, i.e. $x=0$ or the matrix $U$ is singular, which occurs precisely when the $u_i$ are not independent.
Therefore $A$ is a positive operator, and hence (by Sylvester's criterion) all the principal minors are positive:
$$ a_{11}>0, \\
a_{11} a_{22}-\lvert a_{12} \rvert^2 > 0, \\
a_{11}a_{22}a_{33} - (a_{11}\lvert a_{23}\rvert^2 +a_{22}\lvert a_{31}\rvert^2+a_{33}\lvert a_{12}\rvert^2 ) + 2\Re(a_{12}a_{23}a_{31}) > 0, \\
\vdots $$
with equality only if there is linear dependence in the system. The first is trivial, the second is Cauchy–Schwarz, the third and on are unfamiliar.
My question is, are the subsequent inequalities just consequences of Cauchy–Schwarz itself? Do they have any particular use? And are they a known result?
Answer: Have a look here, https://en.wikipedia.org/wiki/Gramian_matrix. You'll find the relationship to be
$$ || u_1 \wedge \ldots \wedge u_n ||^2 $$
Comment: Ah, I might have known someone would have dealt with it. And I see that such inequalities are even mentioned in Hardy–Littlewood–Polya...

A generalisation of Cauchy–Schwarz


Drag & Drop JQuery UI como ocultar Div após drop?

Question: Estou tentando fazer a seguinte operação, tenho 3 divs uma Droppable e 2 Draggable, quero que quando eu arrastar uma das draggables e soltar em cima da droppable a Draggable seja ocultada parando de ser exibida na tela.

Droppable

Draggable 1

Draggable 2

No caso na hora que eu dropar a Div de classe draggable em cima da droppable ele teria que distinguir entre a Draggable 1 ou a Draggable 2 e ocultar a correta.
se alguém souber ou tiver ideia de como fazer isso e puder postar os código seria ótimo.
Answer: O drop tem um evento dropque dispara uma função do jQuery, essa função tem dois parametros, um deles o objeto ui que contem o elemento que foi "largado". Assim dentro dessa função só precisa esconder o elemento (.hide() no meu exemplo) ou removê-lo.
drop: function (event, ui) {
    ui.draggable.hide()
}

Exemplo.
Documentação.
Comment: Perfeito, obg :)


Circular Geometry

Question: A circle of radius $1$ is internally tangent to two circles of radius $2$ at points $A$ and $B$, where $AB$ is a diameter of the smaller circle. What is the area of the region, shaded in the picture, that is outside the smaller circle and inside each of the two larger circles?

(source: https://artofproblemsolving.com/wiki/index.php?title=2004_AMC_10B_Problems/Problem_25 )
This is my work can someone please tell me what I did wrong
Call the center of the circle with radius 1 o. Call the intersection point between the 2 circles c and d. Now let oc equal h. Since ac equals 2 we use pythag and get
h^2+1=4
so h=sqrt(3)
Now we know that the desired area is the difference of AOC(the ellipse sector) and the quarter circle. Now we do arithmetic and get sqrt(3)pi-pi
Comment: You used the formula for the area of an ellipse, but that is NOT an ellipse.
Comment: You need to provide a specific drawing for your work (or on top of existing diagram) In general - calculate the intersection between the two large circles and than subtract the small circle. Is this what you tried to do?
Answer: Label the intersections $C$ and $D$.
Obviously, $\triangle CAB$ and $\triangle DAB$ are equilateral. Meaning sector $BCD$ and $ACD$ has an angle of $120^\circ$. The area of the shaded region plus the area of the circle in the middle is twice the area of the sector less the area of the triangle:
$$\begin{align}
A&=2(A_{\text{sector } ACD}-A_{\triangle ACD})\\
&=2\left(\frac{4\pi}3-\sqrt3\right)
\end{align}$$
Finally, subtract the area of the circle in the middle:
$$A_{\text{shaded}}=\frac{8\pi}3-2\sqrt3-\pi=\frac{5\pi}3-2\sqrt3$$

Circular Geometry


Virtual Directory Path in HTML Files

Question: I tried to create a development server by copying a website from one host to a second different host, but the servers seem to handle virtual paths differently.
On the main server this works:
<link href="/styles/styles.css" rel="stylesheet" type="text/css">

On the dev server the same path would need to be written as (without the first slash):
<link href="styles/styles.css" rel="stylesheet" type="text/css">

How can I make the dev server work with the main servers files without rewritting the paths? Is this something I can do from .htaccess with mod rewrite?
Answer: First, some background on how paths work.  Absolute paths are based on the server root.  Relative paths are based on the URL (not the file path) of the current page.  However, this behavior is NOT handled by the server--its handled by the client, and this behavior is universal (Yes, even IE6... I know, surprise!).  The only thing that would cause these two paths to NOT be the same would be if they're not relative to the root of the web site.
For example, if we're trying to access the URL you mentioned above (/styles/styles.css), here's how they would behave on the following two examples:
"Main Server" web site hosted at http://mainwebsite/index.html
styles/styles.css  => http://mainwebsite/styles/styles.css
/styles/styles.css => http://mainwebsite/styles/styles.css

"Dev Server" web site hosted at http://devsite/some_sub_dir/index.html
styles/styles.css  => http://devsite/some_sub_dir/styles/styles.css
/styles/styles.css => http://devsite/styles/styles.css

If you clarify your answer (these servers are clearly not hosting the same data in the same way), I could provide a more accurate description.  However, if I had to guess, I'd say you're probably running into the issue I described.
Good luck!
Andrew
Comment: What you've described makes sense. I'll try it out on Monday and post back if I need more help. Thanks

Virtual Directory Path in HTML Files


cadences with triads with two different notes

Question: Can a cadence consist of a triad with only 2 different notes?
Let's say I'm in Fmaj and want to include an imperfect cadence (ii - V):
G - D - G followed by C - E - G. The first triad has only two different notes (G and D), is this possible?
EDIT:
My question arose because I'm doing an exercise that requires writing a short melody ending in an imperfect cadence in Fmaj. I decided to use the ii-V cadence with the chords shown above.
However, when I played the excerpt and finished with the "imperfect" cadence, it sounded a lot like a "perfect" cadence - the roots of the chords are G and C which are also in the perfect cadence in Cmaj and all notes are also present in the Cmaj scale. It certainly doesn't sound imperfect, which is why I was wondering if this would be allowed in music.
Comment: Yes, it's possible. Like anything in music. There is no rule saying it can/cannot be done. The acid test is doing it, and listening. It will 'work' in some situations, but not in others.
Answer: For a start, if a chord has only two notes it isn't a triad.  It might IMPLY a particular triad, or be viewed as an incomplete triad.  But a triad has three notes.
The example you give is certainly possible.  In an F major context he bass notes - G, C - clearly outline a ii, V cadence all by themselves.  Omitting the 3rd of the first chord means it isn't fully defined as G major or G minor, but that doesn't negate the overall shape.
If we're talking about 'harmony exercise' SATB writing, we must consider whether dropping into 3 part texture for one chord is effective.  If we're writing in a more contrapuntal style, this sort of thing happens all the time.
Comment: Thank you, and you are right, it isn't really a triad. I've edited my question with additional information.
Answer: For the cadence from Gmin to Cmaj:
Ommiting the third (Bb) of Gmin would make it Gind as it is "indeterminate". It is arguable whether a cadence can have the third ommitted because it makes it extremely weak. I could also find no cases of such a cadence. Furthermore, this  would mean that it is also not an imperfect cadence.
So while this is possible, its not very strong.
To avoid large jumps in the treble voicings, here is an example of how to do it in terms of voice leading:

S: D - C
A: G - G
T: D - E
B: G - C
Comment: Thank you for your answer, it makes sense. I've edited my question with additional information.
Answer: Yes, it's possible, like Tim says.
In early counterpoint it was even the rule that the final chord has no 3rd - in purpose to end in a perfect tonic. Even by Bach we can find still this practice.
There are 2 voice-canons missing the full harmony if sang without accompaniment like this one: youtube.com/watch?v=AGrsasgsFuQ
My question is: do we still speak of a cadence if there is only a single tune? but we could hear the chord progression I-IV6-V7-I ???
Comment: Thank you for your answer. I've edited my question with additional information.


Form error messages appearing in the middle of the form

Question: I've got a hopefully EASY question. I'm using a Drupal Commerce-based form in my Drupal 7 site. The form has some required fields. When a user clicks the button to 'continue registration' at the bottom, and they hadn't filled out all the required fields, the form, of course, throws error messages in an error block that tells the user certain fields are required.
But the error messages are not showing up in the correct location. Please see the image below. The main error that there are problems with the form is displaying correctly at the top of the form, but then the problems with individual fields are displaying in THE MIDDLE OF THE FORM. Obviously, not ideal.
So, how do I make all the errors display at the top of the page?
I've already checked my tpl file for the page and the $messages variable is at the top.
Comment: Is it overlapping on the fields of the form?
Comment: yes, it is...i dont know why.
Comment: Strip all the css (using Web Developer plugin for Firefox or Chrome) OR change to the drupal default theme to check that it's not some css that is causing this. Also, use a javascript blocker, to check that there is no .js file that is causing this.
Comment: If it no longer overlaps after doing the above, then you found your problem.
Answer: This is actually due to the way the checkout module has been written (and is in line with recommended best practices for checkout form submission). The idea is to place the actual error message as close to the form element that generated it to reduce confusion in correcting errors on the form. There is no simple way to undo this behavior in the checkout module.
However, the fact that these are appearing halfway down the page is a good thing - what you really need to do is figure out what it is about your CSS that's causing the messages to float weirdly relative to your form elements.
Comment: Yeah, for the CSS probably need a clear:both and maybe even add the clearfix hack to the messages div element as well if the clear:both is a #failblog.
Comment: Adding clear: both to the .error class made the error block on its own line as suggested. It's below the title field...but not sure if there's any way to fix that given what was said above it being the default behavior to be inline.


Deploy de projeto em Laravel 5.4 no Umbler

Question: Olá,
eu vi a comunidade brasileira de Laravel comentando sobre o Umbler um bom servidor BR para deploys de projetos em Laravel. Eu fui testar o deploy de um projeto, mas não consegui fazê-lo funcionar no serviço site PRO.
Primeiramente aqui estão os arquivos upados no umbler:

Se fosse um shared host, teria funcionado normalmente, e meu servidor já está apontando pro meu domínio. Eu sei que existe um template  pra usar o laravel aqui no umbler, mas eu preciso usar o serviço Cloud Sites só pra poder usar o laravel?
Desde já agradeço!
Answer: É só descer um nível de diretório para que o seu index.php possa ser localizado.
Vc deixou public/public/index.php
Answer: Resolvido, foi um problema com o usuário FTP, no Umbler, não conseguia fazer o upload da pasta vendor corretamente, depois que eu troquei a senha do usuário FTP(não logava no filezilla), eu entrei pelo filezilla e implantei o site diretamente de lá!


clique em campo texto jquery

Question: Como faço para logo que minha pagina iniciar, for dado um clique em um campo texto?
Quero fazer com jQuery
Comment: Poste o seu código para podermos compreender e simular seu problema. Pesquise por `$("#campo").trigger("click");` talvez te ajude http://api.jquery.com/trigger/
Comment: Quando você diz "clicar" não seria "focus"? Ou seja, o utilizador pode digitar qualquer coisa sem a necessidade de clicar sobre o input, uma vez que o foco já está atribuído ao input.
Comment: nao o .click mesmo, eu estou com um problema no campo de login e senha, ao iniciar o site, o place-holder dos campos sobem para dar lugar ao texto digitado, porem o do campo senha nao está subindo, somente quando da um clique no campo o efeito acontece, acontece que quem deixa usuario e senha salvos e os campos ja vem preenchidos entao nao foi dado esse "clique", entao vem em cima do texto, nao sei se conseguiu entender kkkk
Comment: Estás a utilizar o materializecss?
Comment: Pelo visto vc está utilizando Materialize certo? É mais fácil vc tentar resolver pq o framework não está subindo o label (placeholder), do que fazer uma função para subir o mesmo. Só o campo senha não está subindo ou login tbm? No site do Materialize eu fiz um teste e deu certo. Dei um clique no input subiu o label para cima e então preenchi, aí fui para outra página, dei um voltar e os campos estavam preenchidos e com o label já em cima, não seria alguma erro no seu código?
Comment: Entao Leandro, nao entendo o Login funciona normalmente, logo que executo o site, o label usuario sobe pois o campo ja vem preechido, porem a senha nao sobe, só após o clique dentro do campo texto... Nao tem erro no codigo pois nao alterei nada, somente copiei e colei o html pronto. Não estou usando o materialize nao, estou usando esse exemplo https://colorlib.com/etc/lf/Login_v2/index.html
Comment: Dei uma olhada no link, como vc está utilizando isto, é um plugin?
Comment: Se vc analisar, clica no link, preenche o usuario e da um enviar e depois clica em voltar, o label vai ficar em cima do conteudo digitado tb igual ta ficando pra mim, nao sei se seria bug do navegador mas creio que nao
Comment: Sim verdade, então pq está utilizando isto? Já que vc quer utilizar este efeito no formulário utilize o Materiallize.
Answer: Arthur se vc puder utilizar frameworks css para a aplicação da para utilizar assim com Materiallize:

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

    <form class="col s12">

          <input id="icon_prefix" type="text" class="validate">
          First Name

          <input id="icon_telephone" type="tel" class="validate">
          Telephone

   </form>

clique em campo texto jquery


React Redux - Pass data from state to another component to display list of results

Question: How to pass data from Redux obtained in one component to another component.
let map_usersList = users.data && users.data.map((userlist => (

...
...

              {map_usersList}

In the same search.js component, this displays the result fine.
The problem is when I have a separate component to display the list and the results:
import SearchResult from './Result/searchResult'

Here is searchResult.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import AppLink from '../../../others/link/link'

class SearchResult extends Component {

SearchResult.propTypes = {
  id: PropTypes.number.isRequired,
  username: PropTypes.string.isRequired,
}

export default SearchResult

I am getting the count but nothing in the data. For example, user_id is undefined.
Answer: Are you sure you are trying to use the right object property names? I see that you use userlist.id for your key. So, your users value must be something like: { id: 1, username: "foo" } But, in your SearchResult component you use those variables like user_id, user_username. Here is a simple, working example mostly with your code.

const users = [
  { id: 1, username: "foo" },
  { id: 2, username: "bar" },
  { id: 3, username: "baz" },
];

class App extends React.Component {
  render() {
    let map_usersList = users && users.map(userlist => (
      <SearchResult key={userlist.id} {...userlist} />
    ));

    return
{map_usersList}
;
  }
}

class SearchResult extends React.Component {
  render() {
    let {
      id,
      username,
    } = this.props

    console.log("USER IS IS     " + id)

    return (

User Id: {id}, Username: {username}

    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Comment: That was my mistake, It works fine using the right property. Thanks much.


Globally rewrite broken image links in node bodies

Question: I'm migrating my site from Drupal 6 to Drupal 7, and while most of it just worked after migration, the change from the Image module to the core image handling left a large number of broken images on the site.
Images that were inserted in the node body were not handled at all by the migration, and the links are now in an invalid format. Fortunately, fixing those links is pretty straightforward, I just need to change
http://mysite.com/sites/default/files/images/[image-name].[style].jpg

to
http://mysite.com/sites/default/files/styles/[style]/public/images/[image-name].jpg

This looks like it should be relatively straightforward to do, but I didn't find an easy way to do this replacement. I found the Search and Replace Scanner module, but that doesn't seem to allow using parts of the original match in the substitution.
How can I fix these image links all at once without having to do it manually?
Answer: Assuming MySQL, you can fix that up with a search and replace SQL query.
Perhaps easiest from the MySQL command line, though could also use db_query.
The pattern is:
UPDATE tablename SET fieldname = REPLACE(fieldname, 'search', 'replace');

Something like:
UPDATE field_data_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

UPDATE field_revision_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

Backup the database first.
You may need to do it one image style at a time, or else make all the images uses a new standard style.
More info: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
Comment: This seems to have the same limitation the Search and Replace Scanner module has. I need to get the image style out of the original filename, put that one into the new path and remove the image style part out of the filename.
Comment: Yeah, you may need to do it one image style at a time, or else make all the images uses a new standard style.


Change behavior of TXMLDocument.SaveToFile

Question: In production we sometimes have Exception of type "Access denied".
The call stack is from this line
vXML.SaveToFile(Filename);
where vXML is IXMLDocument.
Problem here is that Filename is not logged.
I tried this small testprogram.
implementation

uses
  xmldoc, Unit12;

{$R *.dfm}

procedure TForm11.FormShow(Sender: TObject);
const
  cnFile = 'C:\Program Files (x86)\test.xml';
var
  vXML: TAttracsXMLDoc;
begin
  vXML := TAttracsXMLDoc.Create(nil);
  try
    vXML.Active := True;
    // Process vXML
    vXML.SaveToFile(cnFile);
  finally
    vXML.Free;
  end;
end;

And other unit
unit Unit12;

interface

uses
  xmldoc,
  xml.xmldom,
  Xml.XMLIntf;

type
  TAttracsXMLDoc = class(TXMLDocument)
    procedure SaveToFile(const AFileName: DOMString); override;
  end;

implementation

uses
  Sysutils;

procedure TAttracsXMLDoc.SaveToFile(const AFileName: DOMString);
begin
  try
    inherited SaveToFile(AFileName);
  except
    on E: Exception do
    begin
      E.Message := E.Message + ' ' + AFileName + ' cannot be saved';
      raise;
    end;
  end;
end;

end.

It works as intended. But problem is that interface IXMLDocument is not used anymore. I want to use code like this:
procedure TForm11.FormShow(Sender: TObject);
const
  cnFile = 'C:\Program Files (x86)\test.xml';
var
  vXML: IXMLDocument;
begin
  vXML := NewXMLDocument;
  // Process vXML
  vXML.SaveToFile(cnFile);
end;

And with minimum changes on existing code catch exception above with a clear error of reason. What is the best path ?
Comment: @dummzeuch it is not "spotty", the behavior is fully documented. When constructed will a nil owner, it acts as an interfaced object and must be assigned to an interface variable to maintain lifetime. When constructed with a non-nil owner, it acts as a normal owned object where the owner manages the lifetime. Either way, this has no effect on the functionality of the document, only its lifetime
Comment: If I remember correctly, the XMLDocument has spotty problems if owner is passed as NIL in the constructor.
Comment: @RemyLebeau I am aware of the documented behaviour, unfortunately that's not the end of it. I had very odd errors whenever I tried to pass NIL, even though I used the resulting instance only as an interface. If you didn't, be grateful, it was a pain in the lower back to debug.
Comment: @dummzeuch I have never heard of the XMLDocument behaving differently in terms of node/file processing depending on whether it has a nil owner or not.
Comment: Now you have...
Answer: Simply replace NewXMLDocument() with TAttracsXMLDoc, then you will get the behavior you want:
function NewAttracsXMLDocument: IXMLDocument;
begin
  Result := TAttracsXMLDoc.Create(nil);
end;

procedure TForm11.FormShow(Sender: TObject);
const
  cnFile = 'C:\Program Files (x86)\test.xml';
var
  vXML: IXMLDocument;
begin
  vXML := NewAttracsXMLDocument; //NewXMLDocument;
  // Process vXML
  vXML.SaveToFile(cnFile);
end;

Comment: Thanks, didn't know that .Create could return an interface
Comment: @RolandBengtsson it doesn't. But the object that it returns does implement an interface, so it can be assigned to an interface variable


With what probability one coin is better than the other?

Question: Let's say we have two biased coins C1 and C2 both having different probability of turning head.
We toss C1 n1 times and get H1 heads, C2 n2 times and get H2 heads. And we find that the ratio of heads for one coin is higher than the other.
What is the probability with which we can say that one coin is better than the other? (better here means higher actual probability of turning head).
Comment: If you want a *probability* that one coin is better than another, you can do that with a Bayesian approach; all you need is a prior distribution on the probability. It's a fairly straightforward calculation.
Comment: Isn't this a hypothesis testing problem where you have to test whether the estimates of probability of turning up heads for the coins are different.
Comment: There is no way by which this data is gonna give you a *probability that one coin is better than the other*. You need additional info/assumptions about a prior distribution for how coins are distributed. Say in a Bayesian approach then the result will differ *a lot* based on your prior assumptions. For instance if those coins are regular coins than they are (a priori) very likely to be equal and you would need a large amount of trials to find decent probability that one is 'better' than the other (because the probability is high that you got two similar coins that accidentally test different)
Comment: @katosh, it is as exact as the prior. Say you have coins between p=0.49 and p=0.51. If in such case you use the assumption that the coins are uniform distributed between 0 and 1, then the probabilities that you assign are more like updated bad assumptions rather than updated probabilities. You will too often assign a high probability of being 'better' to the wrong coin. It would be wrong to consider the outcome as 'the' probability for the coin being 'better' than the other. Bad data in = bad results out. In this problem we shouldn't work on solving the math but on solving the knowledge.
Comment: In that way it is stated correctly. It is a 'believe' and this is not so easily equated to a 'probability'.
Comment: When using uniform distribution as prior then it would be a better practice to report a posterior distribution for the *difference* between the coins. Then it becomes directly clear how good the information (or guess) is based on how wide this distributions is.
Comment: Providing a prior would change the question but it would not make it more or less answerable. The result of my answer calculates the believe that $p_1>p_2$ when no prior is given. We could formulate a stronger believe if we had a prior but that is not what the OP asked for.
Comment: @MartijnWeterings Why can I not use the uniform prior for the coins distribution as in my answer below?
Comment: @katosh, you can use the uniform prior when your prior information is truly such that the distribution is uniform. But would you use a similar uniform prior when we have, say, two *regular* coins (of which we know they are unfair, due to small dents etc. but not by much)? We can not *just* plug-in *some* prior information (that has not been based on some good thought). The prior might greatly influence the end result.
Comment: @MartijnWeterings I tried to lay out my thought on the prior in my answer.
Comment: @katosh, your answer describes nicely the recipe for finding the posterior distribution when we have a prior distribution (in the form of a beta distribution), however, it remains important to stress that the existence of this mathematical trickery does not make it clear cut how we get to a (posterior) probability. Unless we are able to have a large amount of data (and can allow ourselves to be less accurate) it becomes very difficult to make a fine argument in favor of one particular method. We can not base the result on the data alone, and the stated question should be seen as insufficient.
Comment: @MartijnWeterings I agree, that a small sample size $n_1$, $n_2$ will lead to insignificant probabilities close to $0.5$ for any coin to be better. But this value is as exact as you can solve the integral. It is not wrong due to the lack of a more informative prior.
Answer: It is easy to calculate the probability for making that observation, given the fact the two coins are equal. This can be done by Fishers exact test. Given these observations
$$
\begin{array} {r|c|c}
 &\text{coin }1 &\text{coin }2 \\
\hline
\text{heads} &H_1 &H_2\\
\hline
\text{tails} &n_1-H_1 &n_2-H_2\\\end{array}
$$
the probability to observe these numbers while the coins are equal given the number of tries $n_1$, $n_2$ and the total amount of heads $H_1+H_2$ is
$$
p(H_1, H_2|n_1, n_2, H_1+H_2) = \frac{(H_1+H_2)!(n_1+n_2-H_1-H_2)!n_1!n_2!}{H_1!H_2!(n_1-H_1)!(n_2-H_2)!(n_1+n_2)!}.
$$
But what you are asking for is the probability that one coin is better.
Since we argue about a believe on how biased the coins are we have to use a Bayesian approach to calculate the result. Please note, that in Bayesian inference the term belief is modeled as probability and the two terms are used interchangeably (s. Bayesian probability). We call the probability that coin $i$ tosses heads $p_i$. The posterior distribution after observation, for this $p_i$ is given by Bayes' theorem:
$$
f(p_i|H_i,n_i)= \frac{f(H_i|p_i,n_i)f(p_i)}{f(n_i,H_i)}
$$
The probability density function (pdf) $f(H_i|p_i,n_i)$ is given by the Binomial probability, since the individual tries are Bernoulli experiments:
$$
f(H_i|p_i,n_i) = \binom{n_i}{H_i}p_i^{H_i}(1-p_i)^{n_i-H_i}
$$
I assume the prior knowledge on $f(p_i)$ is that $p_i$ could lie anywhere between $0$ and $1$ with equal probability, hence $f(p_i) = 1$. So the nominator is $f(H_i|p_i,n_i)f(p_i)= f(H_i|p_i,n_i)$.
In Order to calculate $f(n_i,H_i)$ we use the fact that the integral over a pdf has to be one $\int_0^1f(p|H_i,n_i)\mathrm dp = 1$. So the denominator will be a constant factor to achieve just that. There is a known pdf that differs from the nominator by only a constant factor, which is the beta distribution. Hence
$$
f(p_i|H_i,n_i) = \frac{1}{B(H_i+1, n_i-H_i+1)}p_i^{H_i}(1-p_i)^{n_i-H_i}.
$$
The pdf for the pair of probabilities of independent coins is
$$
f(p_1,p_2|H_1,n_1,H_2,n_2) = f(p_1|H_1,n_1)f(p_2|H_2,n_2).
$$
Now we need to integrate this over the cases in which $p_1>p_2$ in order to find out how probable coin $1$ is better then coin $2$:
$$\begin{align}
\mathbb P(p_1>p_2)
&= \int_0^1 \int_0^{p'_1} f(p'_1,p'_2|H_1,n_1,H_2,n_2)\mathrm dp'_2 \mathrm dp'_1\\
&=\int_0^1 \frac{B(p'_1;H_2+1,n_2-H_2+1)}{B(H_2+1,n_2-H_2+1)}
f(p'_1|H_1,n_1)\mathrm dp'_1
\end{align}$$
I cannot solve this last integral analytically but one can solve it numerically with a computer after plugging in the numbers. $B(\cdot,\cdot)$ is the beta function and $B(\cdot;\cdot,\cdot)$ is the incomplete beta function. Note that $\mathbb P(p_1=p_2) = 0$ because $p_1$ is a continues variable and never exactly the same as $p_2$.

Concerning the prior assumption on $f(p_i)$ and remarks on it: A good alternative to model many believes is to use a beta distribution $Beta(a_i+1,b_i+1)$. This would lead to a final probability
$$
\mathbb P(p_1>p_2)
=\int_0^1 \frac{B(p'_1;H_2+1+a_2,n_2-H_2+1+b_2)}{B(H_2+1+a_2,n_2-H_2+1+b_2)}
f(p'_1|H_1+a_1,n_1+a_1+b_1)\mathrm dp'_1.
$$
That way one could model a strong bias towards regular coins by large but equal $a_i$, $b_i$. It would be equivalent to tossing the coin $a_i+b_i$ additional times and receiving $a_i$ heads hence equivalent to just having more data. $a_i + b_i$ is the amount of tosses we would not have to make if we include this prior.
The OP stated that the two coins are both biased to an unknown degree. So I understood all knowledge has to be inferred from the observations. This is why I opted for an uninformative prior that dose not bias the result e.g. towards regular coins.
All information can be conveyed in the form of $(H_i, n_i)$ per coin. The lack of an informative prior only means more observations are needed to decide which coin is better with high probability.

Here is the code in R that provides a function P(n1, H1, n2, H2) $=\mathbb P(p_1>p_2)$ using the uniform prior $f(p_i)=1$:

mp <- function(p1, n1, H1, n2, H2) {
    f1 <- pbeta(p1, H2 + 1, n2 - H2 + 1)
    f2 <- dbeta(p1, H1 + 1, n1 - H1 + 1)
    return(f1 * f2)
}

P <- function(n1, H1, n2, H2) {
    return(integrate(mp, 0, 1, n1, H1, n2, H2))
}

You can draw $P(p_1>p_2)$ for different experimental results and fixed $n_1$, $n_2$ e.g. $n_1=n_2=4$ with this code sniped:
library(lattice)
n1 <- 4
n2 <- 4
heads <- expand.grid(H1 = 0:n1, H2 = 0:n2)
heads$P <- apply(heads, 1, function(H) P(n1, H[1], n2, H[2])$value)
levelplot(P ~ H1 + H2, heads, main = "P(p1 > p2)")

You may need to install.packages("lattice") first.
One can see, that even with the uniform prior and a small sample size, the probability or believe that one coin is better can become quite solid, when $H_1$ and $H_2$ differ enough. An even smaller relative difference is needed if $n_1$ and $n_2$ are even larger. Here is a plot for $n_1=100$ and $n_2=200$:

Martijn Weterings suggested to calculate the posterior probability distribution for the difference between $p_1$ and $p_2$. This can be done by integrating the pdf of the pair over the set $S(d)=\{(p_1,p_2)\in[0,1]^2|d=|p_1-p_2|\}$:
$$\begin{align}
f(d|H_1,n_1,H_2,n_2)
&= \int_{S(d)}f(p_1,p_2|H_1,n_1,H_2,n_2) \mathrm d\gamma\\
&= \int_0^{1-d} f(p,p+d|H_1,n_1,H_2,n_2) \mathrm dp + \int_d^1 f(p,p-d|H_1,n_1,H_2,n_2) \mathrm dp\\
\end{align}$$
Again, not an integral I can solve analytically but the R code would be:
d1 <- function(p, d, n1, H1, n2, H2) {
    f1 <- dbeta(p, H1 + 1, n1 - H1 + 1)
    f2 <- dbeta(p + d, H2 + 1, n2 - H2 + 1)
    return(f1 * f2)
}

d2 <- function(p, d, n1, H1, n2, H2) {
    f1 <- dbeta(p, H1 + 1, n1 - H1 + 1)
    f2 <- dbeta(p - d, H2 + 1, n2 - H2 + 1)
    return(f1 * f2)
}

fd <- function(d, n1, H1, n2, H2) {
    if (d==1) return(0)
    s1 <- integrate(d1, 0, 1-d, d, n1, H1, n2, H2)
    s2 <- integrate(d2, d, 1, d, n1, H1, n2, H2)
    return(s1$value + s2$value)
}

I plotted $f(d|n_1,H_1,n_2,H_2)$ for $n_1=4$, $H_1=3$, $n_2=4$ and all values of $H_2$:
n1 <- 4
n2 <- 4
H1 <- 3
d <- seq(0, 1, length = 500)

get_f <- function(H2) sapply(d, fd, n1, H1, n2, H2)
dat <- sapply(0:n2, get_f)

matplot(d, dat, type = "l", ylab = "Density",
        main = "f(d | 4, 3, 4, H2)")
legend("topright", legend = paste("H2 =", 0:n2),
       col = 1:(n2 + 1), pch = "-")

You can calculate the probability of $|p_1-p_2|$ to be above a value $d$ by integrate(fd, d, 1, n1, H1, n2, H2). Mind that the double application of the numerical integral comes with some numerical error. E.g. integrate(fd, 0, 1, n1, H1, n2, H2) should always equal $1$ since $d$ always takes a value between $0$ and $1$. But the result often deviates slightly.
Comment: I am sorry for my bad notation  but you do not need to plug in a fixed value for $p_1$. The (now changed) $p'_1$ in the integral is the variable you integrate over. Just like you can integrate $\int_0^1 x^2 \mathrm dx$ without having a fixed value for $x$.
Comment: Fisher's exact test is more specifically about the hypothesis that the coins have the same probability *and* the marginal totals are *fixed*. This is not the case in this coin problem. If you do the test again then you could observe some other total amount of heads.
Comment: @ThirupathiThangavel the problem with Fisher's test is about the not fixed marginal totals. The exact test model assumes that the probability of heads are the same and fixed, but *also* marginals are fixed before the experiment. That second part is not the case. This gives a different conditional probability for extreme values. Overall the Fisher test will be conservative. The probability of the result given the TRUE hypothesis (ie. fixed and similar probability for heads, but *not* necessarily fixed marginal totals) is smaller than calculated (you get higher p-values).
Comment: @MartijnWeterings How do you like the edit?
Comment: It is still a bit odd to make an introduction with this Fisher's exact test example since the provided probability does not relate to an experiment where this test applies (since the $H_1 + H_2$ is not fixed). But I'd say it is much less disturbing now since at least the statements are correct now. Sorry for having been pedantic. (I do get however what point you are trying to make, that probabilities relate to a distribution over observations and you can easily compute probabilities for observations given a model/hypothesis but not the other way around, unless doing Bayesian analysis)
Comment: I don't know the actual value of p1
Comment: @MartijnWeterings in my case, the probability of turning head for a coin is fixed always. Isn't that enough?
Comment: I do not suggest to use Fishers test to answer the question about probability. I presented it however as an easy alternative that is typically used to compare two coins. In hypothesis testing you reject the 0-hypothesis (that the coins are equal) if the p-value is small (e.g. below 0.05). I do not understand what you mean about the marginals. The p-value are exact even if column sums differ. (from Wikipdia: *"This remains true even if men enter our sample with different probabilities than women."*) Only if you calculate multiple p-values you will have to adjust for multiple testing.
Comment: It relates to https://en.wikipedia.org/wiki/Lady_tasting_tea
In that experiment you can use Fisher's exact test or the hyper-geometric distribution
You can *not* do this for an experiment with flipping coins.
If you flip the coins each four times then the Fisher's exact test will give $p=2/70$ for the most extreme situation. But this situation (or more extreme) occurs much less often than $2/70$, more precisely $2p^4(1-p)^4$ which is at best $2/256$, thus much more rare.
Comment: "The prior knowlage f(pi) is that pi could lie anywhere between 0 and 1 with equal probability" This should be more clearly labeled an assumption. In the real world, this does not hold.
Answer: I've made a numerical simulation with R, probably you're looking for an analytical answer, but I thought this could be interesting to share.
set.seed(123)
# coin 1
N1 = 20
theta1 = 0.7

toss1 <- rbinom(n = N1, size = 1, prob = theta1)

# coin 2
N2 = 25
theta2 = 0.5

toss2 <- rbinom(n = N2, size = 1, prob = theta2)

# frequency
sum(toss1)/N1 # [1] 0.65
sum(toss2)/N2 # [1] 0.52

In this first code, I simply simulate two coin toss. Here you can see of course that it theta1 > theta2, then of course the frequency of H1 will be higher than H2. Note the different N1,N2 sizes.
Let's see what we can do with different thetas. Note the code is not optimal. At all.
simulation <- function(N1, N2, theta1, theta2, nsim = 100) {
  count1 <- count2 <- 0

  for (i in 1:nsim) {
    toss1 <- rbinom(n = N1, size = 1, prob = theta1)
    toss2 <- rbinom(n = N2, size = 1, prob = theta2)

    if (sum(toss1)/N1 > sum(toss2)/N2) {count1 = count1 + 1}
    #if (sum(toss1)/N1 < sum(toss2)/N2) {count2 = count2 + 1}
  }

  count1/nsim

}
set.seed(123)
simulation(20, 25, 0.7, 0.5, 100)
#[1] 0.93

So 0.93 is the frequency of times (out of a 100) that the first coin had more heads. This seems ok, looking at theta1 and theta2 used.
Let's see with two vector of thetas.
theta1_v <- seq(from = 0.1, to = 0.9, by = 0.1)
theta2_v <- seq(from = 0.9, to = 0.1, by = -0.1)

res_v <- c()
for (i in 1:length(theta1_v)) {

  res <- simulation(1000, 1500, theta1_v[i], theta2_v[i], 100)
  res_v[i] <- res

}

plot(theta1_v, res_v, type = "l")

Remember that res_v are the frequencies where H1 > H2, out of 100 simulations.

So as theta1 increases, then the probability of H1 being higher increases, of course.
I've done some other simulations and it seems that the sizes N1,N2 are less important.
If you're familiar with R you can use this code to shed some light on the problem. I'm aware this is not a complete analysis, and it can be improved.
Comment: Interesting how `res_v` changes continuously when the thetas meet. I understood the question as it was asking about the coins intrinsic bias after making just a single observation. You seem to answer what observations one would make after knowing the bias.


UserControl Property Changing

Question: I have created a User Control(Popupcontrol) and in that control i have created a property(PageType) and when i am using the Popupcontrol on the page then i set the property(pagetype) according to the page.
but now there is some problem i have to two button on the page and on the second button click i want to change the pagetype property .So is there any solution for the same.
Comment: please rewrite your question with punctuation. The question is hard to understand
Comment: so why don't you just set that property to the necessary value in the "second" button click handler?
Comment: if i am setting the property on the button click then it's not getting change bcause on the page load it set to previous defined property.
Answer: Based on your comment, it seems you bind the data (PageType property in your question) in the Page_Load event, instead of this it should be done in overrided DataBind method which should be called if the page is not in post back request (otherwise your data will be overwritting in the next Page_Load event as you mentioned in your comments):
protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        DataBind();
    }
}

public override void DataBind()
{
    PageType = someValue;
}

after this your click handler may looks like:
protected void button2_Clicked(object sender, EventArgs e)
{
    PageType = someOtherValue;
}

Answer: Are you setting the variable in a page load event? You may need to add:
if (!Page.IsPostback) {
    // Code here.
}

UserControl Property Changing