Examples of $C^2(0,1)\cap C[0,1]$

Question: I need examples of $C^2(0,1)\cap C[0,1]$. Are $x^2$ and $e^x$ examples. What is the importance of the closed interval $[0,1]$?
Comment: $C^2(0,1)\cap C[0,1]=\emptyset$ because the functions don't have the same domain. But there are functions in $C[0,1]$ whose restriction to $(0,1)$ are in $C^2(0,1)$.
Answer: If by $u\in C^2(0,1)\cap C[0,1]$ you mean that $u:[0,1]\to\mathbb{R}$ is continuous and $u$ restricted to the interval $(0,1)$ is $C^2$, then you can consider the function $u$ defined by $$u(x)=\sqrt{\frac{1}{4}-\left(x-\frac{1}{2}\right)^2}$$
Note that $u$ is not in $C^2[0,1]$.
In partial differential equations it is common to see the space  $ C^2(0,1)\cap C[0,1]$. For example, in trying to solve the equation (for suitables $f$ and $g$)
$$\tag{1}
 \left\{ \begin{array}{rl}
 \Delta u=f &\mbox{ in $(0,1)$} \\
  u=g &\mbox{ in $\partial(0,1)$}
       \end{array} \right.
$$
a natural space to look for solutions is: $C^2(0,1)\cap C[0,1]$. This happens because we need two derivatives for the laplacian and if $g$ has some regularity on the boundary, we would expect that also $u$ has some regularity near the boundary (for example it is continuous).
Comment: You were inspired by the circle with center on $(\frac{1}{2},0)$ whose formula is $(x-\frac{1}{2})^2+y^2=(\frac{1}{2})^2$. The derivatives do not exist at the endpoints where the tangents become vertical. A similar function is $u(x)=\sqrt{x}+\sqrt{1-x}$. Both functions become non-real outside $[0,1]$.
Comment: Yes you are right @JeppeStigNielsen. I like your example, it is so simple.
Comment: @Tomas: Could you show me why this is the case
Comment: Sorry @Vaolter, but I can't understand your qeustion> Could you be more specific?
Comment: @Tomás, I mean show why $u\in C^2(0,1)\cap C[0,1]$ but not in $C^2[0,1]$.
Comment: This is because the graph of $u$ is the upper part of the circle with center in $(1/2,0)$ and radius $1/2$, indeed, the tangent lines to the circle in the points $(1,0)$ and $(0,0)$ are parallel to the $y$-axis.
Answer: You can consider the function $x \, \mapsto \, x \sin(\frac{1}{x})$ which is continuous on $[0,1]$ and $\mathcal{C}^{2}$ on $]0,1[$.
Edit : (explanations)

The function $x \, \mapsto \, x \sin(\frac{1}{x})$ is $\mathcal{C}^{2}$ on $]0,1[$ since it is the composition and product of functions which are $\mathcal{C}^{2}$ on $]0,1[$.
From the inequality $\vert x \sin(\frac{1}{x}) \vert \leq \vert x \vert$, we deduce that $\lim \limits_{x \rightarrow 0} x \sin(\frac{1}{x}) = 0$. The function $x \, \mapsto \, x\sin(\frac{1}{x})$ which is defined on $]0,1]$ can be defined on $[0,1]$ by letting :
$$
f(x)=
\begin{cases}
x \sin(\frac{1}{x}) & \text{if } x \neq 0 \\
0 & \text{if } x =0 \\
\end{cases}
$$
The function $f$ is continuous on $[0,1]$. But the derivative of $f$ at $x=0$ doesn't exist. Consider $\frac{f(x)}{x}$ : we have
$$ \frac{f(x)}{x} = \sin(\frac{1}{x}) $$
$\sin(\frac{1}{x})$ does not converge as $x \rightarrow 0$. So $f$ is not differentiable at $x=0$.
Comment: Could you show me why this is the case.
Comment: I edited my post.
Answer: All polynomials, $\exp$, $\cos$, $\sin$ are in $C^\infty\left(\Bbb R\right)$. Also, for $f,g \in C^\infty\left(\Bbb R\right)$, $f+g\in C^\infty\left(\Bbb R\right)$, $fg\in C^\infty\left(\Bbb R\right)$ and $f\circ g \in C^\infty\left(\Bbb R\right)$. Then, you can restrict those functions to $[0,1]$ to get functions that are in $C^\infty[0,1]$ and whose restriction to $(0,1)$ are in $C^\infty(0,1)$ and therefore are examples of such functions.

To understand why having less smoothness on the slightly bigger interval is interesting, let's look at properties of functions $f:[0,1]\to \Bbb R$ so that $f$ is $C^0$ on $[0,1]$ and $C^1$ on $(0,1)$ but $f$ is not $C^1$ on $[0,1]$. Since $f'$ is $C^0$ on $(0,1)$, we would be able to make $f$ $C^1$ on $(0,1)$ if we could extend $f'$ by continuity. Since we can't, at least one of the limits between $\lim\limits_{x\to 0}f'(x)$ and $\lim\limits_{x\to 1}f'(x)$ does not exist. A classic example of such a function is $x\mapsto x\sin\frac{1}{x}$. The idea here is that when you differentiate it, you'll get a $\sin\frac{1}{x}$ term because of the product rule and it won't converge near $0$ since it won't have the $x$ factor to drag it towards $0$.

The one thing here you should remember is the example $x\mapsto x\sin\frac{1}{x}$ which helps to understand the necessity of most of the seemingly useless hypothesis of current real analysis theorems.

Examples of $C^2(0,1)\cap C[0,1]$


Text Selection Pop Menu

Question: if user Select a text there should be quicknote menu
will popup so I Need to show a popup menu when user select text in my flutter project .
I Need to show a popup menu when user select text in my flutter project ,can any body give me any example for this
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: <code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Text Selection Menu Example'),
        ),
        body: TextSelectionMenuDemo(),
      ),
    );
  }
}

class TextSelectionMenuDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: SelectableText(
        'Select this text to show the popup menu.',
        style: TextStyle(fontSize: 18.0),
        onTap: () {
          // Handle text selection here (if needed).
        },
        onSelectionChanged: (TextSelection selection, SelectionChangedCause cause) {
          if (selection.baseOffset != selection.extentOffset) {
            // Text is selected, show the popup menu.
            showTextPopupMenu(context);
          }
        },
      ),
    );
  }

  void showTextPopupMenu(BuildContext context) {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;

    final RenderBox text = context.findRenderObject() as RenderBox;
    final Offset offset = text.localToGlobal(Offset.zero, ancestor: overlay);

    final TextSelection selection = TextSelection(baseOffset: 0, extentOffset: 0);
    final List<PopupMenuEntry<String>> popupItems = [
      PopupMenuItem<String>(
        value: 'Copy',
        child: Text('Copy'),
      ),
      PopupMenuItem<String>(
        value: 'Cut',
        child: Text('Cut'),
      ),
      PopupMenuItem<String>(
        value: 'Paste',
        child: Text('Paste'),
      ),
    ];

    showMenu<String>(
      context: context,
      position: RelativeRect.fromRect(offset & text.size, Offset.zero & overlay.size),
      items: popupItems,
    ).then((String? selectedValue) {
      if (selectedValue != null) {
        // Handle selected menu item here.
        print('Selected: $selectedValue');
      }
    });
  }
}
</code>

Text Selection Pop Menu


How can I copy a Virtual Machine on VMWare ESXi 4 while maintaining Thin Provisioning?

Question: We have an ESXi host we use for testing, which results in a ton of VMs being created and copied on a regular basis. We don't have the storage capacity to use thick provisioned VMs on this server, and have been maintaining the copies using VMWare Converter. But using the converter is an incredibly slow operation which copies the entire contents of the VM over the network several times before actually finishing the copy.
Is there a way to simply clone the VM but maintain the thin-provisioning?
Answer: I get around this by making copies with the OVFtool from a command line. It isn't perfect, but it does the trick for me (note: ovftool is an app that runs on a linux system somewhere, which then connects to the ESXi host):
<code>#Copy a VM to an OVF (must be turned off, but you can hotclone it to a new VM first if you have vCenter):
ovftool vi://USER:PASSWORD@ESXIHOSTIP/VMNAME TARGETDIR/TARGET.ovf

#Deploy an OVF to an ESX[i] server with thin disks:
ovftool --name="Name of new VM" -dm=thin -ds=TARGET-DATASTORE SOURCEFILE.ovf vi://USER:PASSWORD@ESXIHOSTIP/
</code>
You could also try ghettoCloneVM.pl, which is a tool to clone a VM on an ESX or ESXi server without vCenter (but the page says you have to have the "licensed" version of ESXi, not sure if that means the free version won't work). It looks like it has the ability to clone to a thin disk, so it might work for you. I haven't used this tool myself, but it is something to try.
Comment: That requires a Virtual Center or ESX license -- it doesn't work with the free version of ESXi. But +1 because it'd work if I had a license for it.
Comment: @Billy ONeal, No, it works fine with the free version of ESXi. I just tested it to an ESXi box that is using the free license.
Comment: Also, the `ovftool` can be used to deploy to VMware Server 2, which is really handy. Almost everything is the same, except the disk mode needs to be `monolithicSparse` to be the equivalent of thin.
Comment: @Jed Daniels: Oh .. I thought you were saying run those commands *on the server*, which of course you can't do via ESXi. Unfortunately that method is no faster than using VMWare Converter on the VM :(.
Comment: @Billy ONeal Really it isn't any faster? How big are your VMs? I can backup and re-deploy a copy of a 30GB vm in about 5 minutes (the particular OVF I'm working with now compresses down to about a gig). Additionally, this is script-able, so you don't have to sit around and wait for the converter.
Comment: @Jed Daniels: The virtual disk is about 40 GB, of which about 20GB is used. It takes about 2 hours each way while the converter takes about 3 but runs in a single step. I think being transferred over the network is the bottleneck at this point.
Answer: Use vmkfstools:
<code>vmkfstools –i <sourcedisk> -d thin <targetdisk>
</code>
To use vmkfstools, you can utilize unsupported mode on the physical console, or using Remote CLI (RCLI).  This document outlines how to use RCLI, with a complete section on vmkfstools alone:
vmware.com/pdf/vsphere4/r40/vsp_40_vcli.pdf
You can also use PowerCLI if you're licensed for ESXi:
<code>$vm = get-vm "vmname"
Get-HardDisk -VM $vm | Copy-HardDisk "[Storage1]/destinationfolder" -DestinationStorageFormat thin
</code>
Comment: @Billy ONeal: You can use it without using what you're deeming as "unsupported hacks" if you'd like, too.  Either way results in the same outcome.  Please reference the following document, which outlines how to use RCLI for ESXi.  There's an entire section on how to utilize vmkfstools via RCLI.
http://www.vmware.com/pdf/vsphere4/r40/vsp_40_vcli.pdf
You may want to try the PowerCLI method as well, since that's by far the easiest command string.  Not sure if it would work with ESXi free or not, although I would think it would not work since ESXi free supports only read only access to the API.
Comment: Without a licensed version of ESXi then, guess you're out of luck if you don't want to use the command line mode in ESXi.  Should you go down that path, and need the ability to do it remotely, you can enable SSH on ESXi, which would definitely fall under the realm of unsupported.  Utilizing the console in ESXi entering unsupported mode I wouldn't call a hack though.  You're issuing the same commands as vCLI, utilizing the same tools.  Either way, good luck with it.
Comment: @amargeson: Err.. no it is not. You're thinking of ESX, not ESXi. ESXi does not have a command line, much less vmkfstools.
Comment: That causes the drive to become thick provisioned.
Comment: @Billy ONeal: There is a command line in ESXi.  On the main menu screen, hold ALT and hit F1.  At the prompt, type unsupported and enter the password.  At this point, you can use vmkfstools.
Comment: @amargeson: I don't have physical access to the box. And even if I did, I wouldn't count unsupported hacks as acceptable solutions for a production environment.
Comment: Also, wanted to add from your original post...
"We have an ESXi host we use for testing..."
Didn't sound like a production environment to me, but neither here nor there...
Comment: RCIL and PowerCLI both require a paid license of ESX. When I say "testing", I mean the environment our developers are using, not what I personally am testing with.
Comment: How do I do that? Where do I get "vmkfstools"? It certainly didn't come with the VMWare Virtual Infrastructure client.
Comment: It's on the ESXi server.
Answer: Are they Windows machines? I've set up a base install and sysprepped the machine. I then copy that sysprepped vmx and vmdk file into a new folder on the datastore; right-click the vmx and choose add to inventory. When I boot that machine I have a new machine... Would that work for you?
Comment: The copy operation causes the virtual disk to become thick provisioned. That's the entire original issue.
Comment: Doh! My bad... :)
Answer: Use PowerCLI and this:
"A powershell module to perform Storage VMotions from Thick-to-Thin. Meant to be used in place of Move-VM. Currently only accepts one VM and strings for performance reasons, will accept objects in next revision as well as more documentation."
http://poshcode.org/1579
Comment: PowerCLI only works for paid - for copies of ESXi.
Comment: Can you guys get away with an essentials license?
Comment: No.


Não somar campo se coluna igual Mysql

Question: Opa,
Estou somando o total de uma coluna double, o que preciso é que, a consulta não some esta coluna caso a coluna Cod seja igual.
Explicando melhor, a coluna cod pode se repetir, caso ela se repita o valor da coluna desconto também se repetirá, ou seja, não somar o desconto caso tenha uma outra cod igual
Select sum(desconto) From ordem where cod != cod and data='2015-10-29'

Comment: Qual linguagem você está usando na aplicação? PHP?
Comment: Aqui na empresa ainda usando VB6
Comment: Não conheço VB, mas sei resolver seu problema usando logica com PHP. Ajudaria? Você conseguiria adaptar?
Comment: Por favor, pode mandar, caso seja alteração direta na sql será melhor
Answer: Quando você coloca cod != cod você está comparando o código com ele mesmo.
Uma alternativa seria agrupar pelo código e pegar somente os grupos que tem uma ocorrencia:
select sum(t.total)
from (select sum(desconto) total
      from venda
      group by cod
      having count(*) = 1) as t

Comment: Opa, funcionou parcialmemnte, ele não somou os descontos com o Cod igual, ele deve caso não seja igual adicionar o campo a soma, caso seja igual, adicionar apenas um campo desconto a soma. desculpe-me se não expliquei bem
Comment: select cod , sum(desconto) total .........having count(cod) = 1)

Não somar campo se coluna igual Mysql


Sequence of real numbers (sequences)

Question: Let ${x_n,n\geq 1}$ be a sequence of real numbers in $(0,\infty)$ such that $\sup\{\frac{1}{x_{n}}\sum_{j=1}^{n}\frac{x_{j}}{j}:n\in\mathbb{N}\}<\infty$, Can it be concluded that $\lim_{n\rightarrow\infty}x_{n}=\infty$. Give a proof or else give a suitable counterexample.
Comment: Suggestion: Show what you have tried so far.
Answer: We are given that there is an $L$ so that
$$
\frac1{x_n}\sum_{k=1}^n\frac{x_k}k\le L\tag{1}
$$
Inequality $(1)$ implies
$$
x_n\ge\frac1L\sum_{k=1}^{n-1}\frac{x_k}k\tag{2}
$$
For $n\ge2$, $(2)$ says
$$
x_n\ge\frac{x_1}L\tag{3}
$$
Plugging $(3)$ into $(2)$ yields
$$
\bbox[5px,border:2px solid #C0A000]{x_n\ge\frac{x_1}{L^2}H_{n-1}}\tag{4}
$$
Answer: Let $a_n=\frac {1}{x_n} \sum_{j=1}^{n} \frac {x_j}{j}.$
Then $\lim_{n \to \infty} a_n \le m \lt \infty$. ($\because \sup\{\frac{1}{x_{n}}\sum_{j=1}^{n}\frac{x_{j}}{j}:n\in\mathbb{N}\}=m<\infty$).
Suppose $\lim_{n \to \infty} x_n = l \lt \infty$ and $l \neq 0$.
Then $\frac {1}{l} \sum_{j=1}^{\infty} \frac {x_j}{j} \le m$.
$\Rightarrow \sum_{j=1}^{\infty} \frac {x_j}{j} \le ml$.
If $x=\inf \{x_n : n \in \Bbb N \}$ (note that $x \neq 0$), then $x \sum_{j=1}^{\infty} \frac 1{j} \le ml \; \Rightarrow \; \sum_{j=1}^{\infty} \frac 1{j} \le \frac {ml}{x}.$ Which is not possible...........($1$)
If $l = 0$, then we have $\lim_{n \to \infty} a_n = \dfrac {\lim_{n \to \infty} \sum_{j=1}^{n} \frac {x_j}{j}}{\lim_{n \to \infty} x_n} $. Now as $n \to \infty$, either $\sum_{j=1}^n \frac {x_j}{j}$ converges to a non-zero positive number or diverges. Thus in both cases, $a_n \to \infty$. Which is contradiction..........($2$)
Also if we suppose that $x_n$ is divergent, $\sup \{x_n : n \in \Bbb N\}=k \lt \infty$ and $x_n$ doesn't have a subsequence converging to zero, then $\frac 1k \sum_{j=1}^{\infty} \frac {x_j}{j} \le \lim_{n \to \infty} \frac {1}{x_n} \sum_{j=1}^n \frac {x_j}{j} \le m \Rightarrow \sum_{j=1}^{\infty} \frac {x_j}{j} \le mk$. Again let $x=\inf \{x_n : n \in \Bbb N\}$, then as in ($1$), we get contradiction...........($3$)
If $x_n$ is divergent, $\sup \{x_n : n \in \Bbb N\} \lt \infty$, and $x_n$ has a subsequence $s_n$ converging to zero :
Let $b_n$ be subsequence of $a_n$ with having terms of $s_n$ only.
Then $\lim_{n \to \infty} b_n \le \lim_{n \to \infty} a_n \le m$.
Going by same way as in ($2$), $\lim_{n \to \infty} b_n = \dfrac {\lim_{n \to \infty} \sum_{j(n)} \frac {s_{j(n)}}{{j(n)}}}{\lim_{n \to \infty} s_n}$. Now as $n \to \infty$, either numerator diverges or converges to a non-zero positive number. Thus, in both of these cases $b_n \to \infty$. Which is a contradiction..........($4$).
Comment: why does the limit of $a_n$ exist?
Comment: @robjohn oops. Perhaps I should stay with 'm'.

Sequence of real numbers (sequences)


Access entity reference in Block Plugin

Question: I have a content type that has an entity reference field. It's a content type for news articles with a field for tagging the article with taxonomy terms.
I'm attempting to access these terms in a block plugin, however I'm having difficulty. Getting other fields like text fields, and dates work just fine. For example
<code>    $node = \Drupal::routeMatch()->getParameter('node');
    $node->get('body')->value
</code>
Successfully returns the contents of the node's body
 but when I use:
<code>    $node = \Drupal::routeMatch()->getParameter('node');
    $tags = $node->get('field_tags')->value;
</code>
$tags comes up empty.
<code> die(print_r($tags));
</code>
Does not display anything.
I know it's in there somewhere though because when I use
<code>die(print_r($node));
</code>
I do see the tag id's in there.
Is there a way to display the value of an entity reference field for taxonomy terms, in a block plugin?
Answer: I found that in order to get the values I had to use getValue() instead of ->value like so:
<code>$tags = $node->get('field_tags')->getValue();
</code>
Answer: ->value is what most field types use but it is in no way restricted to that, they can use whatever they want.
What you want is $node->get('field_tags')->target_id for the ID or $node->get('field_tags')->entity for the referenced term object. You can also loop over it with foreach ($node->get('field_tags') as $item) and then $item->target_id/entity.
As always, have a look at the amazing Entity cheat-sheet here: https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more examples and info.

Access entity reference in Block Plugin


Caccioppoli-Leray Inequality for De Giorgi's regularity theorem

Question: I am studying De Giorgi's proof of Holder continuity of solutions of elliptic equations with bounded measurable coefficients.
This is the translation of the original paper
De Giorgi paper
At page 163, De Giorgi refers to a "Lemma by Caccioppoli and Leray" but I can't find it anywhere, the referenced book is very hard to come across.
If anyone has it ("Equazioni alle derivate parziali di tipo ellittico" by C.Miranda) and can look at what this lemma at page 153 is it would be great.
The inequality I am struggling with, is, in any case:
$$\int_{A(k)\cap B(y,\varrho_2)} (u(x)-k)^2 dx\geq (\varrho_2-\varrho_1)^2 \frac{\tau_1}{\tau_2}\sqrt{\int_{A(k)\cap \partial B(y,\varrho _1)}(u(x)-k)^2d\mu_{n-1}\cdot \int_{A(k)\cap \partial B(y,\varrho _1)}|\nabla u(x)|^2d\mu_{n-1}}$$
where $A(k)$ is the subset of the domain where the solution of the elliptic equation (with constants $\tau_1, \tau_2$) $u(x)$ is greater than $k$, $B(x,r)$ is the n-dimensional ball centred at $x$ of radius $r$ and $\partial$ indicates the boundary.
Thank you very much for any hint, reference or idea!
Comment: For future reference, please do not post a question both on MathOverflow and Math.SE. http://meta.math.stackexchange.com/questions/10067/i-found-mo-has-been-included-in-se-network-today
Answer: I was not able to find Miranda's book, however, there is some books in the literature that might be useful too you.
Take a look in Fanghua Lin and Qing Han book page 20. Also Giusti's book is a good reference for regularity theory: take a look in page 214. I think that Giusti's theorem fits more in what you want (in fact I think it is a generalization of De Giorgi theorem).
Comment: http://mathoverflow.net/questions/134980/caccioppoli-leray-inequality-for-de-giorgis-theorem-proof

someone could find the book fortunately, thank you very much for the suggestions though!
Comment: You are welcome!


ERROR 1215 (HY000): Cannot add foreign key constraint

Question: Estou aprendendo um pouco de mysql e decidi faer um sisteminha de mercado, eu tenho as seguintes tabelas:
CREATE TABLE IF NOT EXISTS cliente(cliente_cpf BIGINT NOT NULL PRIMARY
KEY,cliente_nome VARCHAR(100) NOT NULL,cliente_sexo BIT NOT
NULL,cliente_nascimento DATE NOT NULL,cliente_email
VARCHAR(50),cliente_telefone BIGINT,cliente_celular BIGINT);

CREATE TABLE IF NOT EXISTS produto(produto_id INT AUTO_INCREMENT PRIMARY
KEY,produto_nome VARCHAR(100) NOT NULL,produto_preco FLOAT(5,2) NOT NULL);

CREATE TABLE IF NOT EXISTS item_pedido(item_pedido_id INT NOT
NULL,item_pedido_produto_id INT NOT NULL,item_pedido_produto_quantidade
TINYINT NOT NULL,FOREIGN KEY(item_pedido_produto_id) references
produto(produto_id));

CREATE TABLE IF NOT EXISTS pedido(pedido_id INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,pedido_cliente_cpf BIGINT NOT NULL,pedido_item_pedido_id INT NOT
NULL DEFAULT 0,pedido_data_compra TIMESTAMP DEFAULT
CURRENT_TIMESTAMP(),pedido_valor_total FLOAT(6,2),FOREIGN KEY
(pedido_item_pedido_id) REFERENCES item_pedido(item_pedido_id),FOREIGN KEY
(pedido_cliente_cpf) REFERENCES cliente(cliente_cpf));

Estou com um problema na tabla pedido com relação a adicionar a definir pedido_item_pedido_id na tabela pedido, todo o resto funciona certinho e se eu nao adicionar essa foreign key a tabela pedido tambem funciona, o erro é ERROR 1215 (HY000): Cannot add foreign key constraint, eu pesquisei e eu não vi o porque dar esse erro, alguem consegue me ajudar?
Answer: Motivo do erro:
Você precisa "indexar" o item_pedido_id da tabela item_pedido.

Por quê?

A chave estrangeira requer referência a uma chave primária e/ou única.

Resolução:
Coloque item_pedido_id da tabela item_pedido como UNIQUE e/ou PRIMARY KEY.

Exemplo em seu script:
CREATE TABLE IF NOT EXISTS item_pedido(
      item_pedido_id INT NOT NULL UNIQUE PRIMARY KEY,
      item_pedido_produto_id INT NOT NULL,
      item_pedido_produto_quantidade TINYINT NOT NULL,
      FOREIGN KEY(item_pedido_produto_id) references produto(produto_id)
);

Comment: Eu cheguei a pensar nisso mas como eu preciso que um valor se repita varias vezes em item_pedido_id na tabela item_pedido eu nao fiz isso, nesse caso essa seria a unica forma de resolução?
Comment: Sim. Não tem lógica você fazer uma referência em outra tabela se ela te retornar mais de 1 registro. A solução seria alterar a estrutura das tabelas pelo visto. Se quiser uma ajuda, abra outra pergunta, mostrando como está a estrutura do seu banco, o seu "problema" com isso, e possíveis soluções. Com certeza o pessoal irá te ajudar.


Losing internet connection after adding second IP address (Windows)

Question: I'm creating simple program to add address via windows form.
It's actually only call this command:
netsh interface ip add address

The address was successfully added, but after executing that command, I lost my internet connection.
I had to restart to regain the connection.
Is there a command to add second ip address without losing internet connection?
Thanks
Comment: What Windows version are you using?
Comment: @Daniel, it's windows 7
Comment: Could you be more specific about your nic cards:- i.e. weather you have two nics and you are trying to give ip address to one while using other for internet, or only one nic and you are trying to give it an ip address. In second case, if your ISP is providing you IP address i.e. dynamic IP address, and you are trying to use your own then obviously it would cause issue. This  might be due to one of two reasons 1)
Comment: @Damon, it's the second case. On linux i use this command: "ip address add 10.10.1.1 dev wlan0" & works fine (address added & internet still connected). So I'm looking for similar solution in windows.
Comment: Mostly ISPs don't allow you to edit your IP address unless you have requested static IP from your ISP. If you still edit your IP statically, it might cause IP conflict, and would cause the Internet to disconnect.
Answer: The netsh command you are using is correct. However, you can only add IP addresses to an interface with a static ip.
If your interface is connected with a dynamic IP address assigned by a DHCP server, the netsh interface ip add address command switches the interface from dynamic to static and then adds the IP address.
You are either losing your internet connection because you assign an IP address from a different net, or because you are assigning an IP address in the same net without setting the gateway.


Caracteres Duplos em Expressões Regulares

Question: Estou treinando meu javascript e estou querendo saber como eu procuro caracteres repetidos em uma expressão regular
Exemplo: Eu digito aa em uma textbox e, dentro de um método de validação, o método verifica se o caracter a, digitado duas vezes seguidas, está dentro da RegExp
Comment: Aceite a resposta se ela resolve seu problema :)
Answer: O que você quer fazer precisaria de algo chamado backreference (http://www.regular-expressions.info/backref.html), onde se referência um grupo anteriormente capturado dentro da expressão regular. Teria essa cara:
(.)\1

Ou seja:

(.) Dê match em qualquer caractere e crie um grupo
\1 Encontre o caractere que você acabou de encontrar de novo

Você pode misturar isso com + ou os ranges de repetição {min,max} para fazer qualquer match:
(.)\1{2,4}

(.) Mesmo de acima
\1{2,4} Dê match em 3 a 5 caracteres repetidos

Ou:
(.)\1{2}

(.) Mesmo de acima
\1{2} Dê match em exatamente 2 caracteres repetidos

Ou:
(.)\1+

(.) Mesmo de acima
\1+ Dê match em 2 ou mais caracteres repetidos

Se quiser ser mais específico (está procurando só por repetições de caracteres tipo espaço, por exemplo), é só alterar o grupo (.) para o que gostaria de encontrar repetido.

Em código:
function hasRepetition(str) {
  return /(.)\1/.test(str);
}

hasRepetition('best') // false
hasRepetition('beest') // true


Skewness of $Y=\alpha X+\beta$

Question:
Let Y be a random variable defined by $Y=\alpha X+\beta$, where X is also a random variable. Find the skewness of Y.

I know that $$Sk_1(Y)= \frac{\mu_3(Y)}{[\mu_2(Y)]^\frac{3}{2}}=\frac{\mu_3(\alpha X+\beta)}{[\mu_2(\alpha X+\beta)]^\frac{3}{2}}$$
$\mu_3(Y)=\mathbb{E}[(Y-\mu_Y)^3],\quad \mu_Y=\mu_3'(Y)$
$\mu_3(Y)= \mathbb{E}(Y^3-3Y^2\mu_Y+3Y\mu_y^2-\mu_y^3)$

So at the end I have to prove that it can be expressed in terms of X or $Sk_1(X)=Sk_1(Y)$
Then how do I resolve this?
Comment: You can write all the (central and non-central) moments of $Y$ in terms of the (central and non-central) corresponding moments of $X$: $E[(Y-\mu_Y)^k] = E[(\alpha X + \beta - (\alpha \mu_X + \beta))^k = E[(\alpha X - \alpha \mu_X)^k ] = \alpha^k E[(X -\mu_X)^k]$.
Comment: Okay, i forgot about that but then i did the steps and all that is equal to $$\frac{\alpha ^2E(X^3)-3\alpha ^2 \mu_X E(X^2)+3 \alpha ^2 \mu_X ^2 E(X)- \alpha ^2 \mu^3 X}{[\alpha ^2 E(X^2)-2 \alpha ^2 \mu_X E(X)-2 \alpha ^2 \mu_X ^2]^\frac{3}{2}}$$ am i right?
Comment: Nevermind, i make a little mistake. But i already solve it, thank you!
Comment: You are making it unnecessarily complicated. Use @Batman's Comment with $k=3$ in the numerator, then again with $k = 2$ in denominator. The $\beta$s disappear at once and $\alpha^3$ in numerator and $(\alpha^2)^{3/2} = \alpha^3$ in denominator cancel. As the Answer (+1) is trying to tell you, the def'n of skewness is devised so that it is invariant under linear transformations such as $Y = \alpha X + \beta.$ (Refers to your prev comment, now changed.)
Answer: For any random variable $Z$, define $$\mathrm{standard}(Z) = \frac{Z - \mathbb{E}[Z]}{ \sqrt{\mathbb{E}[(Z - \mathbb{E}[Z])^2]}}.$$
Notice that $\mathrm{standard}(Z)$ is unchanged under any linear transformation $Z \mapsto \alpha Z+\beta,\; \alpha, \beta \in \mathbb{R}$; and that $\mathrm{skew}(Z) = \mathbb{E}[(\mathrm{standard}(Z))^3] $. Thus $\mathrm{skew}(X) = \mathrm{skew}(Y)$.

Skewness of $Y=\alpha X+\beta$


How to compare if System.Windows.Media.SolidColorBrush and Microsoft.Office.Interop.PowerPoint.ColorFormat has same color?

Question: I have a VSTO application written in C#.Net.
In Powerpoint color of a Shape is defined by Microsoft.Office.Interop.PowerPoint.ColorFormat
Ex: Shape.Fill.ForeColor
But I need to compare it with System.Windows.Media.SolidColorBrush
Is there a proper way to compare the RGB values of them without any conversion issues in Alpha/Opacity etc?
Answer: Microsoft.Office.Interop.PowerPoint.ColorFormat looks like it has a RGB property of int-type. The name suggest this does not contain the alpha-component, but the documentation is lacking.
a SolidColorBrush have a Color property that can be used. Unfortunately the color does not seem to have a way to convert it to an int directly. You could either use the R, G, B, properties and shift them into the right place for an int. Or use System.Drawing.Color FromArgb and ToArgb to make it into an int. When doing the conversion you can chose to include the Alpha value or not.
In the end you should have two int values you can compare directly.


OpenLDAP replication fails, "syncrepl_entry: rid=666 be_modify failed (20)"

Question: I've configured a second host to replicate the main LDAP server via syncrepl in the slapd.conf:
syncrepl rid=666
        provider=ldaps://my-main-server.com
        type=refreshAndPersist
        searchBase="dc=Staff,dc=my-main-server,dc=com"
        filter="(objectClass=*)"
        scope=sub
        schemachecking=off
        bindmethod=simple
        binddn="cn=repadmin,dc=my-main-server,dc=com"
        credentials=mypassword

When I restart slapd, it writes to /var/log/debug
Jun 11 15:48:33 cluster-mn-04 slapd[29441]: @(#) $OpenLDAP: slapd 2.4.9 (Mar 31 2009 07:18:37) $ ^Ibuildd@yellow:/build/buildd/openldap2.3-2.4.9/debian/build/servers/slapd
Jun 11 15:48:34 cluster-mn-04 slapd[29442]: slapd starting
Jun 11 15:48:34 cluster-mn-04 slapd[29442]: null_callback : error code 0x14
Jun 11 15:48:34 cluster-mn-04 slapd[29442]: syncrepl_entry: rid=666 be_modify failed (20)
Jun 11 15:48:34 cluster-mn-04 slapd[29442]: do_syncrepl: rid=666 quitting

I've looked into the sources for the return code and found only
#define LDAP_TYPE_OR_VALUE_EXISTS       0x14

in include/ldap.h. Anyway, I don't quite get what the error message means.
Can you help me debugging this problem and figure out why the LDAP replication doesn't work? I've managed to put a "manual" copy via slapcat and slapadd into the database, but I'd like to sync automatically.
UPDATE:
"Solved" by removing /var/lib/ldap/* and re-importing the database with slapadd.
Answer: Are you sure that slapd have the right to write in dirs ? Usually, after a from scratch insert, you must change the owner of directories.
Comment: what directories exactly do you mean?
Comment: On my debian, the datas are stored in /var/lib/ldap, which should be owned by openldap:openldap. All files in the dir should have the same owner.
Comment: yeah, it's the same on my ubuntu box.


LINQ query returns way more results than in the entire database

Question: I have the following LINQ query. The problem is it's returning 13k results when tblSurveys only has 20 total. What am I doing wrong?
from s in surveyContext.tblSurveys
from st in surveyContext.tblTypes_for_Surveys
from t in surveyContext.tblSurvey_Types
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
      (s.Unsubstantiated ||
         (st.SurveyID == s.SurveyID && st.SurveyTypeID == t.SurveyTypeID &&
         t.UnsubstantiatedAvailable && (from d in surveyContext.tblDeficiencies
                                         where d.SurveyID == s.SurveyID
                                        select d.DeficiencyID).Count() == 0))
orderby s.Survey_Date
select s;

Answer: I can see a cross join in there, look at the <-------
           from s in surveyContext.tblSurveys
           from st in surveyContext.tblTypes_for_Surveys
           from t in surveyContext.tblSurvey_Types
           where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
                 (s.Unsubstantiated || <-------
                    (st.SurveyID == s.SurveyID && st.SurveyTypeID == t.SurveyTypeID &&
                    t.UnsubstantiatedAvailable && (from d in surveyContext.tblDeficiencies
                                                   where d.SurveyID == s.SurveyID
                                                   select d.DeficiencyID).Count() == 0))
           orderby s.Survey_Date
           select s;

it seem you need to do a left join in here
Comment: A cross join will produce the Cartesian product of your three sets (hence your 13k rows instead of 20). You should either use explicit join statements or set the join conditions in your where clause.
Comment: cross join is, if you have 20 record in tblSurveys  and 30 in tblTypes_for_Surveys then 50 in tblSurvey_Types, this will return 30,000 rows
Comment: I don't see what's bad about a cross join. (Just had to look it up) (I didn't down vote it) Either return a tblSurvey record if (the date stuff and s.Unsubstianted) or (date stuff and everything else)
Answer: Do you have foreign keys and relationships setup in your database? If so, you can greatly simplify your query. I'd also recommend renaming your tables in the .dbml file so they aren't all prefixed with 'tbl'.
If you do have relationships setup, your query could look (something) like this:
from s in surveyContext.tblSurveys
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
     (s.Unsubstantiated ||
        (s.tblTypes_for_Surveys.Any(st => st.tblSurvey_Type.UnsubstantiatedAvailable) && s.tblDeficiencies.Count() == 0))
orderby s.Survey_Date
select s;

Comment: Wow and I thought LINQ-SQL was powerful before. This is great. That just made a lot of my stuff way easier knowing that the foreign keys/relationships handles this for you.


Printing array of characters using printf

Question: Is there a way I can print an array of characters using 'printf' in the following way (I know this isn't correct C code, I want to know if there is an alternative that will yield the same result).
printf("%s", {'h', 'e', 'l', 'l', 'o' });

Comment: Unfortunately they must be in the character array format ('h', 'e', 'l', 'l', 'o').
Comment: @Michi he says he wants to print using the syntax `{'h','e','l','l','o'}`. There's no `'\0'` in that. My interpretation of the question is that he does not want to change the array.  If you read the question differently that's your prerogative, you can post your own answer or request clarification from OP.
Comment: `printf("%s", "hello");`
Comment: That's the format it needs to be printed? You need to use a loop in that case
Comment: `printf("%.5s", (char[]){'h', 'e', 'l', 'l', 'o' });`
Comment: @M.M that isn't a c string. If that even compiles it might crash.
Comment: @M.M That worked perfectly, thank you!
Comment: @MM why `"%.5s"` and not `"%s"`. What is the difference ? Any way, you forgot `'\0'`
Comment: @Michi There isn't a difference really, only you need a null termination (\0) if you use %s.
Comment: @Michi `%.5s` means to read and output at most 5 characters. I didn't "forget \0", OP has specified that there is no `\0` .
Comment: @user2907877 [Are you sure about that](http://pastebin.com/raw.php?i=DcEPPPKT)? in that example the `%s` is used so the `'\0'` is needed too.
Comment: @M.M there is no need of `.5` in your example. [The following](http://ideone.com/QU4KxE) should be enough.
Comment: @Michi yes there is, otherwise `%s` will read off the end of the array because there is no `\0` .
Comment: @M.M I do understand your point, but why should he use `.5` instead of adding the `'\0'` ?
Comment: @Michi because he is asking how to print an array that doesn't have a `\0` on it
Comment: @M.M please show me where did he said something about `'\0`. Or you speak about his comment ?
Comment: @M.M Now I see your point, don't yell please :D. But to be honest we cannot rely on that. Any way thank you for clarification.
Answer: This will work, but the length of the array must either be hard-coded in the format string or as a parameter or else the array must be defined twice (perhaps by one macro) so that its size can be calculated by the compiler:
printf("%.5s", (char []) {'h', 'e', 'l', 'l', 'o' });

Comment: I believe you can also specify the length in the format string as a variable: `printf("%*s", length, array);`
Comment: It should be `%.5s`, not `%5s`
Comment: Assumptions -- dangerous things they are.
Comment: that doesn't change the fact that it must either be hard-coded or taken from a second instance of the array (by sizeof()) (which is of course still all done at compile time, but unless both instances are provided by macro expansion then errors can creep in)
Comment: Why does it have to be done at compile time? This could be in a function that takes a `char*` and `int`. And why do you need another copy for sizeof? `char arr[] = { 'a', 'b', 'c' }; int len = sizeof(arr);`
Comment: because that's the way the question asks for it to be done
Comment: @GregA.Woods How about `'\0'`?
Comment: If a trailing NUL byte were allowed in the array then this wouldn't be much of a question, would it?
Comment: Well, how would you deal with internal `NUL`-bytes?
Comment: The question doesn't have any NUL bytes in it, so, it's not a problem.
Comment: @Deduplicator the answer would still be correct even with internal nul bytes, if we assume that such a byte indicated to stop output
Comment: @GregA.Woods actually it would... what problems do you foresee?
Answer: How about a simple while loop?  Assuming the array is null-terminated, of course.  If not - you'll need to adjust to counting the number of characters in the array.
char a[] = {'h','e','l','l','o','\0'};
int i = 0;
while (a[i] != "\0")
{
   printf ("%c,", a[i]);
   i++;
}

Output:
h,e,l,l,o,

Note: do NOT try this on a char**! This is for char[] only!
Comment: It makes no sense to compare a character to `NULL`.
Comment: @PaulGriffiths: fixed.
Comment: this line: `while (a[i] != "\0")`  will not work as expected.  Suggest: `while (a[i] != '\0')`  as checking characters, not strings


Variance and CI for the difference in medians

Question: One way to obtain a (1-alpha)% confidence interval for the difference in medians for two samples is to use bootstrapping. Generate 10,000 bootstrap samples of both group's samples and find the difference in medians of each, forming a bootstrap distribution for the difference in medians. However, I am looking for a formula that would not require bootstrapping.
For example, the confidence interval for the difference in means (under appropriate assumptions) is (xbar1-xbar2) +/- t_0.025 * se , is there a similar formula for the difference in medians? Maybe a non-parametric test, but there has to be something, no?
Answer: There is a median test, based on a chi-square test. It breaks each group up into cases above and below the individual medians, and determines whether the frequencies of those groups differ from what would be predicted if all the data came from the same distribution. "[I]t only considers the position of each observation relative to the overall median," so it doesn't have much power to distinguish true differences in medians.
You will sometimes find the Wilcoxon-Mann-Whitney (WMW) test cited as a test for medians, but that is not a test for medians if the distributions being compared differ in symmetry or scale parameters. So although it's not a parametric test per se, you have to make some assumptions about the underlying distributions to use it as a test on medians.
And neither of those tests can provide confidence intervals (CI) for the difference in medians. With the WMW test, for example, what you can get with a 2-sample test, according to the manual page for wilcox.test, is:

a nonparametric confidence interval and an estimator... for the difference of the location parameters x - y ... the estimator for the difference in location parameters does not estimate the difference in medians (a common misconception) but rather the median of the difference between a sample from x and a sample from y.

That's why bootstrapping is so useful in situations like this: it doesn't require any assumptions about the underlying distributions, although in some cases it does require some care in finding the most reliable estimate of the CI. I understand some reluctance to approach bootstrapping if you haven't had any experience with it, but it's well worth your while to become familiar with it as it's useful in so many applications.
Comment: It's not that I do not trust bootstrapping, it's that I have a situation where I need to emulate the results of bootstrapping without using it (obviously some small tolerance is warranted due to the random nature of a bootstrap sampling.)
Comment: @StevenSarasin getting CI requires having a distribution function from which to get the desired limits. That distribution function is of an assumed form in parametric tests or empirical in bootstrapping. It's hard to think of a situation where you have the data and can't use bootstrapping. You might find some suitable hints on the page I linked for the Wilcoxon-Mann-Whitney test, for example a [t-test based on data transformed to ranks](https://en.wikipedia.org/wiki/Mann–Whitney_U_test#Alternatives).
Comment: Both those tests can provide confidence intervals, e.g. for a shift alternative (though it won't necessarily be a ci for the desired difference in medians). Indeed the shift-parameter CI corresponding to the Wilcoxon-Mann-Whitney is available in many packages (R does it, simply by setting the relevant argument in the call).
Comment: @Glen_b thanks, I've clarified in the answer what you can get with respect to CI for the WMW test.


JPA 2.0, Criteria API, Subqueries, In in Subquery

Question: I have tried to write a query statement with a subquery and an IN expression for many times. But I have never succeeded.
I always get not right result after building query in JPA. My SQL request below:
SELECT distinct
  ss.*
FROM
  table1 ss
where
  ss.active=1
and
  ss.id not in (select ia.organization_id from table2 ia where ia.is_allow = 'Y')

My code using Criteria API below :
CriteriaQuery<Table1> cq = qb.createQuery(Table1.class);
Root<Table1> table = cq.from(Table1.class);
cq.select(table);
List<Predicate> predicateList = new ArrayList<Predicate>();

Subquery<Table1> subquery = cq.subquery(Table1.class);
Root<Table2> subroot = subquery.from(Table2.class);
subquery.select(subroot.get(Table2_.table1));
subquery.where(qb.equal(subroot.get(Table2_.isAllow.getName()), Boolean.TRUE));

predicateList.add(qb.not(qb.in(table.get(Table1_.id.getName())).value(subquery)));
if (!predicateList.isEmpty()) {
            Predicate[] array = new Predicate[predicateList.size()];
            cq.where(qb.and(predicateList.toArray(array)));
}
cq.distinct(true);
TypedQuery<Table1> qry = entityManager.createQuery(cq);
return qry.getResultList();

After this i get follow sql request:
SELECT DISTINCT t0.*

FROM TABLE1 t0
WHERE (t0.ACTIVE = 1 AND NOT (t0.ID IN (SELECT 1 FROM TABLE2 t2, TABLE1 t1 WHERE ((t2.IS_ALLOW = 'Y')
AND (t1.ID = t2.ORGANIZATION_ID)))))

Why in this code "SELECT 1 FROM TABLE2 t2, TABLE1 t1" and etc.... I wait in this t1.id.
Could you help me?
Answer: If Subquery returns just and integer
select ia.organization_id from table2 ia where ia.is_allow = 'Y'

try this.
Subquery<Integer> subquery = cq.subquery(Integer.class);
Root<Table2> subroot = subquery.from(Table2.class);
subquery.select(subroot.get("organization_id"));
subquery.where(qb.equal(subroot.get("is_allow"), Boolean.TRUE));

Subquery above should return the integers that will be placed in the IN statement.
Then your logic could apply.
CriteriaQuery<Table1> cq = qb.createQuery(Table1.class);
Root<Table1> table = cq.from(Table1.class);
cq.select(table);
cq.distinct(true)
   .where(qb.not(qb.in(root.get("get")).value(subquery))
   .and(cb<Integer>equals(root.get("active"),1))

Not sure if this will work.
TypedQuery qry = entityManager.createQuery(cq);
If cq "Criteria Query" is type of Table1.class, then the TypedQuery will be
Change to
TypedQuery<Table1> qry = entityManager.createQuery(cq);


Choosing the correct hypotheses

Question: I was trying out some questions on hypothesis testing when some questions started challenging me. Here is an example:
A lot of product X is to be rejected if the temperature of the lot is greater than $75$ degree Celsius and is to be expected if the case is otherwise? (Then the question gives some data regarding a sample and asks) Should the lot be rejected?
What should be by alternate hypothesis in the question. How would I know what the researcher wants to prove through his research?
One more question on the same lines:
A company will open a new store in the area if more than $5 \%$ of the people of the area had good opinion about its products. (Then some data is given regarding a sample that we collected and asks) Should the company open store in the area?
Kindly tell me the thought procedure involved in the process of choosing null and alternate hypotheses.
Comment: If the lot is to be rejected on the basis of a measured temperature then there is not much to hypothesise about. Measure the temperature and reject or not.
Comment: There's a lot of wisdom in that comment by Michael Lew. If you have the whole population and get that they are warmer than $75 ^\circ $C, then they're warmer than $75 ^\circ $C. There's no statistics to do here. If you have a sample and are interested in the population from which the sampled observations were drawn, then you can do statistics and conduct hypothesis testing.
Comment: @MichaelLew 's comment also applies to your second question. There is no hypothesis here.
Answer: It sounds like the difference is only interesting to you if the difference is in a particular direction, so one-sided testing would be appropriate. If you did two-sided testing, I'm imagining this conversation with your boss.
YOU: "...and then after hypothesis testing, I conclude that it was not 75 degrees celcius, and 5% of people did not have a positive opinion of the products. I rock!"
BOSS: "Was it hotter or colder than 75 degrees?"
YOU: "I didn't test that, just if it's 75 degrees."
BOSS: "Did fewer or more than 5% of people have a positive opinion?"
YOU: "I didn't test that, just if it's 5%."
BOSS: "How enlightening..."
If you do one-sided testing, you can answer her questions.
For the first situation:
$$H_0: \theta \le 75 ^\circ C$$
$$H_a: \theta > 75 ^\circ C$$
For the second situation:
$$H_0: \theta \le 5\%$$
$$H_a: \theta > 5\% $$
In both cases, $\theta$ is whatever it is that you're measuring. It's a common variable to use in statistics, and it doesn't necessarily have anything to do with angles like you may be thinking from trig or physics class.
NOTE: Many teahers, particularly in intro classes, will write the following:
$$H_0: \theta = 5\% $$
$$H_a: \theta > 5\% $$
This is equivalent to what I wrote above.

Choosing the correct hypotheses


Fiddler-like host and port remapping using nginx on Linux

Question: I am trying to set up host and port remapping on Linux using nginx as a reverse proxy.
So far, I've got a working ghetto hack solution using the if directive, which is evil.
Is there a better solution without using if?
What I have tried - nginx configuration
/etc/nginx/nginx.conf (or some /etc/nginx/conf.d/*.conf file):
server {
    listen 3000;
    server_name dev.example.com test.example.com prod.example.com
    location / {
        if ($http_host ~ dev.example.com) {
            proxy_pass 127.0.0.1:13000;
        }
        if ($http_host ~ test.example.com) {
            proxy_pass 127.0.0.1:23000;
        }
        if ($http_host ~ prod.example.com) {
            proxy_pass 127.0.0.1:33000;
        }
    }
}

/etc/hosts:
127.0.0.1 dev.example.com
127.0.0.1 test.example.com
127.0.0.1 prod.example.com

What I would like to do - Fiddler HOSTS configuration
For those familiar with Fiddler, I am trying to emulate this HOSTS configuration:
localhost:13000 dev.example.com:3000
localhost:23000 test.example.com:3000
localhost:33000 prod.example.com:3000

Answer: Leverage the map module:
http context:
map $http_host $proxy_target {
    "dev.example.com" "127.0.0.1:13000";
    "test.example.com" "127.0.0.1:23000";
    "prod.example.com" "127.0.0.1:33000";
}

server context:
proxy_pass $proxy_target;

Also, you could try to only differentiate the port, and use something like
proxy_pass 127.0.0.1:$proxy_port;

but I'm not sure if joining like this will work.
Answer: Use separate server blocks:
server {
    server_name dev.example.com;
    listen 3000;

    proxy_pass http://127.0.0.1:13000;
}

server {
    server_name test.example.com;
    listen 3000;

    proxy_pass http://127.0.0.1:23000;
}

And another one for prod.example.com.
If these site configurations contain common elements, include them in another file and use the include directive to apply those elements to each virtual server.
Comment: I had to increase `server_names_hash_bucket_size` to 128 (possibly because my actual server names are a bit longer).


Von Neumann Correspondence

Question: In Popa's preprint https://www.math.ucla.edu/~popa/popa-correspondences.pdf his initial definition of an $N-M$ correspondence between two von Neumann algebras is a Hilbert space $\mathcal{H}$ and a seperately weakly continuous commuting action of two Von Neumann algebras $N$ and $M$ on $\mathcal{H}$. Could somebody clarify what is meant here by weakly continuous as if $N$ is not already seen as a Von Neumann algebra on $\mathcal{H}$ there is no way to define a weak topology on it as it depends on the Hilbert space it is acting on. Does Popa instead mean $\sigma$-weakly continuous?
Answer: Most likely. If you look at the other equivalent definitions he gives, he talks about normal. So yes, it has to be $\sigma$-weak. Most of the time the distinction doesn't matter, because when an element in $N$ is a sot limit of a net in $N$, by Kaplanski's Density Theorem the net can be replaced by a bounded net, and then the convergence is also $\sigma$-sot.

Von Neumann Correspondence


Ordering of a deck of cards

Question: If you shuffle n cards as follows: Go through the deck one card at a time and at each card, flip a fair coin.  If the coin comes up head, then leave the card where it is, and if it comes up tails move that card to the end of the deck. For example, if n =4,  and the initial ordering is 1,2,3,4, and outcome of the successive flips is h,t,t,h, then the ordering at the end of the round is 1,4,2,3. Assuming all possible outcomes of the coin flips are equally likely, what is the probability that the ordering after one round is the same as the initial ordering?
Attempt:
If the ordering after n flips is the same as the initial ordering, then you would have to roll all heads since rolling heads doesn't change the ordering. So the answer would be (1/2)^n?
Comment: Your attempt show one possibility.
But, if you would get all TAILS, the ordering would also be the same.
Comment: I assume that, given $n$ card, by "one round" you mean going through the deck from the first to the $n$th card, without continuing on the card putted at the end through the described process.
Answer: To see what head-tail-sequences give the identity permutation, see that if you obtain one head, you leave the corresponding card to its place, and the described process continues only for the following cards.
What you're doing is applying to the array $[1,\dots,n]$ the permutation $(n\ n\!-\!1 \ \cdots\ 2\ 1)$ as long as you're obtaining tails;
after one head you continue applying to you're vector the permutation $(n\ n\!-\!1 \ \cdots\ 3\ 2)$, and after $m$ heads the permutation $(n\ n\!-\!1 \ \cdots\ m\!+\!2\ m\!+\!1)$.
Than all sequences beginning with all heads and, at some poing, starting and continuing with all tails give the identity, for example

hhh...hhhtttt...tttt

To see that no other head-tail-sequence gives the identity, assume you're on the card $7$ (lucky number!), if you obtain a tail you put that number to the end, and now you move on number $8$, and if you obtain head you leave it there and pass over... than your final string will have the $8$ occurring before the $7$!!
In general, having a head after a tail, do not preserve the ordering.
So the probability to end the process with the same string is $(n+1)/2^n$ where $n+1$ is the number of the strings (described above) of the form all-heads followed by all-tails.
PS I have to point out that by $(n\ n\!-\!1 \ \cdots\ 2\ 1)$ I'm referring to the positions, I mean $n$ in that notation mean the $n$th card in the cards-array, and not  the actual card of value $n$.

Ordering of a deck of cards


Prove that $\Bbb{R}^2/\Bbb{Z}^2\approx S^1\times S^1$

Question: Here $\Bbb{R}^2/\Bbb{Z}^2$ is the quotient space obatined from $\Bbb{R}^2$ by identifying points of $\Bbb{Z}^2$ i.e. $(x,y)\sim (x',y')\iff (x,y),(x',y')\in\Bbb{Z}^2$.
$S^1\times S^1:=\{(z,w)|\ z,w\in S^1\}$
I define $f:\Bbb{R}^2\to {S^1}\times S^1$ by $f(x,y)=(e^{2\pi i x},e^{2\pi i y})$. $f$ is continuous and onto.
As $f(n,m)=(1,1)\ \forall (n,m)\in \Bbb{Z}^2$ i.e. $f$ agrees on $\Bbb{Z}^2$. By the property of quotient space, $f$ induces a continuous map $\tilde{f}:\mathbb{R}^2/\Bbb{Z}^2\to S^1\times S^1$ such that $\tilde{f}([x,y])=f(x,y)$. This map is onto as well. But this map is not injective. I couldn't move forward from here.
Although I have observed one thing- instead of only identifying the points of $\Bbb{Z}^2$ if we identify the points as follows-
$$(x,y)\sim (x',y')\iff (x-x',y-y')\in\Bbb{Z}^2$$
Then we would have $\Bbb{R}^2/\sim\approx S^1\times S^1$, the same $f$ will give rise to this homomorphism.
Can anyone help me to solve the problem? Thanks for help in advance.
Comment: The map is injective. But I find it easier to show first that $\mathbb R^2/\mathbb Z^2\cong(\mathbb R/\mathbb Z)^2$, and then $\mathbb R/\mathbb Z\cong S^1$.
Comment: @DeltaEpsilon: $[1/2,1/2]=[3/2,3/2]$, since $3/2-1/2\in\mathbb Z$.
Comment: How does the map injective? Like $\tilde{f}([1/2,1/2])=\tilde{f}([3/2,3/2])$ but $(1/2,1/2)$ is not related to $(3/2,3/2)$
Comment: Basically, I read the definition: If $A\subset X$ then $X/A$ is defined to be the quotient space of $X$ where only the points of $A$ has been identified i.e. $x\sim x'\iff x,x'\in A$. Then by this definition $(1/2,1/2)$ not related to $ (3/2,3/2) $
Comment: I have mentioned it in the last part (in bold). Here I am confused.
Answer: What you are observing is an ambiguity in the "slash" notation $/$ for quotient spaces.
In the context of $\mathbb R^2 / \mathbb Z^2$, you should think of the group $\mathbb Z^2$ acting on the space $\mathbb R^2$, where $(m,n) \in \mathbb Z^2$ takes the point $(x,y) \in \mathbb R^2$ to the point $(x',y') = (x+m,y+n) \in \mathbb R^2$. This action defines a decomposition of $\mathbb R^2$ into orbits: the orbit of $(x,y) \in \mathbb R^2$ is just the set of all $(x',y') \in \mathbb R^2$ such that $x-x',y-y' \in \mathbb Z^2$. And the meaning of $\mathbb R^2 / \mathbb Z^2$ in this context is that it is the orbit space of the action, namely the quotient space with respect to the decomposition of $\mathbb R^2$ into orbits.
As your question indicates, the slash notation is also used for a different kind of quotient: namely when one is given a topological space $X$ and a subset $A \subset X$, one forms the quotient $X/A$ whose decomposition elements are $A$ itself and all singleton subsets $\{x\} \subset X$ for which $x \in X-A$.
Comment: Okay I understand
Answer: You are right, there is probably a typo in your original question. It should be $(x,y)\sim (x',y')\iff (x,y)-(x',y')\in\Bbb{Z}^2$
Answer: Your map $f$ is a surjective group homomorphism between the abelian groups $\mathbb R^2 = \mathbb R \times \mathbb R$ (with componentwise addition) and $S^1 \times S^1$ (with componentwise complex multiplication). We have $\ker f =  \mathbb Z^2$, thus $f$ induces a group isomorphism
$$\bar f :  \mathbb R^2/\mathbb Z^2 \to S^1 \times S^1 .$$
Since we give $\mathbb R^2/\mathbb Z^2$ the quotient topology with respect to the map $p :  \mathbb R^2 \to  \mathbb R^2/\mathbb Z^2$, $\bar f$ is continuous. It remains to show that $\bar f$ is a homeomorphism. To do so, it suffices to show that $f$ itself is a quotient map (which means that $V  \subset  S^1 \times S^1$ is open iff $f^{-1}(V) \subset \mathbb R^2$ is open). We shall prove that $f$ is an open map; this implies that it is quotient map. So let $U \subset \mathbb R^2$ be open. It is well-known that $g : \mathbb R \to S^1, g(t) = e^{2\pi i t}$, is an open map (see e.g. Open sets on the unit circle $S^1$). Thus $f = g \times g$ is an open map.
If you identify $\mathbb Z^2$ to a point, then you do not consider the quotient group $\mathbb R^2/_{group}\mathbb Z^2$, but the topological quotient space $\mathbb R^2/_{top}\mathbb Z^2$.


How do we determine if the data has to be transformed to reduce skewness? Visually or metrics?

Question: I am wondering what would be the normal way for a data scientist to validate if the data is skewed or not. Is it by plotting the histogram or by finding skewness/kurtosis value (ex:- using pandas methods etc)?
What is the correct way? and what is the normal way it's done in real data analysis/machine learning work?
Comment: Kurtosis is different from skewness.
Comment: Skewness can be analyzed in detail by studying the N-letter summary and plotting the mid-letter statistics against the spreads, as described by John Tukey in *EDA.*  See https://stats.stackexchange.com/a/96684/919 for an explanation and examples. I believe few data scientists know or even care about this technique, but it is simple, powerful, and useful.  Perhaps asking about "correct" or "normal" methods is not going to yield very good answers... .
Comment: @whuber i am still going through the link. Thanks for the link.
Comment: Welcome to Cross Validated! For what purpose would you be examining the skewness?
Comment: Wording such as "correct way" and "normal way" isn't especially helpful. Who knows across all the practitioners and all the projects anywhere which methods are especially common? @BrudeET guesses boxplots; I guess histograms are still more common than boxplots; but where are the data?
Comment: @Dave I just want to make sure that the independent variables are not highly skewed, though i have not read it any where.
Comment: @NickCox yes, Kurtosis and Skewness are different. I think i was asking about distribution being normal. Though i am not sure why it should be normally distributed, as i have not read any reference  document/book which says it should be. But i have seen plenty of models created after making distribution of input variable normal.
Answer: Evaluation:

Maybe looking at boxplots is the most common way. Strongly skewed data often show far outliers. But even normal and some other symmetrical distributions can show outliers.

Example: Out of 100,000 normal samples of size 100, over half had outliers; there was almost one outlier per sample on average.
out = replicate(10^5,
    length(boxplot.stats(rnorm(100))$out))
mean(out>0)
[1] 0.5204
mean(out)
[1] 0.92163

If the issue is that you'd like normal data, then
using formal tests of normality is not usually
the best approach. For small samples, normality tests can fail to reject for data from skewed distributions; for large samples, these tests can reject for data that is close enough to normal for many purposes. Look at normal probability plots instead.

Examples: The Shapiro-Wilk test is one of the best tests of normality. Even so, out of 100,000 exponential samples of size ten, this test found less than half to be non-normal.
pv = replicate(10^5, shapiro.test(rexp(10))$p.val)
mean(pv <= .05)
[1] 0.44557

Moreover, out of 100,000 samples of size 1000 from Student's t distribution with 30 degrees of freedom (hardly distinguishable from normal
for many practical purposes) about 20% failed the S-W test of normality.
pv = replicate(10^5, shapiro.test(rt(1000,30))$p.val)
mean(pv <= .05)
[1] 0.20981

Execution:

If possible, try to find a method that works well for untransformed data. Transformation, even when necessary, can make it hard to understand and explain the results of tests.

Example: Suppose we have an exponential sample
of size 40 from a population with $\mu = 50.$
Some might depend on the robustness of t methods to get the (approximate) 95% CI $(33.1,64.1)$ for $\mu.$ However, the relationship
$\frac{\bar X}{\mu}\sim\mathsf{Gamma}(40,40)$
can be pivoted to give the exact 95% CI
$(36.5, 68.0).$
x = rexp(40, 1/50)
mean(x)
[1] 48.60372

t.test(x)$conf.int
[1] 33.07733 64.13012
attr(,"conf.level")
[1] 0.95

mean(x)/qgamma(c(.975,.025), 40, 40)
[1] 36.46582 68.03293

If transformation is necessary, try to use one that minimizes difficulties of interpretation. In some instances, using a rank transformation works and results are easy to understand. Differences in logs amount to ratios of original data.
Comment: I, too, suspect they might be applied to *response variables* too often in small statistical applications, but perhaps not often enough in large, complex cases where some black box algorithm will be applied and "feature engineering" can be important or where transformations of the explanatory variables could allow for simpler or more accurate modeling.
Comment: Until the very end, this answer seems focused exclusively on what *not* to do, rather than on what *to* do!  Valid advice, to be sure--but not terribly responsive to the original question... .
Comment: @whuber. That's a fair comment on my Answer, and probably also on my views of transformations to avoid skewness. I probably have much to learn about transformations, but my current view is that they are used too often.
Answer: Read up on and consider lognormal distributions. They are very common in many fields of science. A log transform converts a lognormal distribution to a gaussian. But this is not just a mathematical trick, to be done when a normality test flags the distribution as nonnormal. There are reasons why data are lognormal, and it is appropriate to account for this with a log transform of the data before some analyses, and a reverse log transform of some results (to convert differences between logs to the ratio of actual values).
For ratio data (only positive values are possible; changes are multiplicative rather than additive), some argue that assuming a lognormal distribution should be the default.


How to turn off Captcha for search?

Question: I've installed the Captcha module and I need to remove it from the search button and form (just an unnecessary nuisance there). Captcha configuration allows me to turn it off for specific values of a "Form_ID". I tried that with "search", but I guess the form ID is more complicated than that. What Form_ID(s) do I need to use to get Captcha to stop showing up in search?
Thank you.
Answer: For a block, the form_id should be:

search_block_form

and for a page:

search_form

To easily find this information, install the Devel module:

A suite of modules containing fun for module developers and themers

and use something like this in your theme's template.php file:
<code>function myTheme_form_alter(&$form, &$form_state, $form_id)
{
    dpm($form);

}
</code>
This will show a hierarchical display of all forms on the page - you can then scroll quickly through the info to find what you need. Very handy for searching arrays.
Answer: Simple uncheck this "Default challenge on non-listed forms." on admin/config/search/settings

How to turn off Captcha for search?


Pre filled fields in form without ajax

Question: This is my first project. I want, when I update my record at that time in form all fields are pre filled with previous data.Which are stored in table.
This is my Function code:-
    public function getData($query)
      {
    $result = $this->connection->query($query);
    if ($result == false) {
        return false;
    }

    $rows = array();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }

    return $rows;
}

This is my html file code:
      <?php
      $result = $crud->getData("SELECT * FROM creative_workshop ");
      foreach ($result as $res) {
      $id = $res['id'];
      $title = $res['title'];
      $message = $res['message'];
      $title1 = $res['title1'];
      $message1= $res['message1'];
      $image1= $path .$res['image1'];
      $title2 = $res['title2'];
      $message2= $res['message2'];
      $image2= $path .$res['image2'];
       }
       ?>
<form name="form" method="post" action="" enctype="multipart/form-data">
<textarea rows="4" cols="50" name="title" value="<?php echo $title;?>">
<textarea rows="4" cols="50" name="message" value="<?php echo $message;?>">
 </form>

Comment: Use Ajax for this
Comment: no Without ajax
Comment: can you print `$result ` to check what's there?
Comment: ok wait i will try
Comment: Hey Buddy when i print the Result Am getting same thing like $ result .
Answer: Problem is in this line of statement
$result = $crud->getData("SELECT * FROM creative_workshop ");

Make sure the member function $crud->getData is working properly, getData is not returning the fetched results
Answer: There is no value attribute for Textarea.
you can use. Like
<form name="form" method="post" action="" enctype="multipart/form-data">
 <textarea rows="4" cols="50" name="title" ><?php echo $title;?></textarea>
 <textarea rows="4" cols="50" name="message" ><?php echo $message;?></textarea>
</form>

Comment: just check $result have any data. using print_r
Answer: First:
What you are currently doing on your form is getting all rows from your table and looping over them to eventually take the last row returned and show it in your form.
Unfortunately, you get no guarantees from your DB that your data will come back in a certain order.
This means that looping over the results from your SELECT may return the last row entered but it is not guaranteed.
Instead you want to go and either select your rows with an ORDER BY or, and this would be more efficient, add a where to get a specific row.
If you have an auto incrementing ID field you could have a look at this.
Second:
To show data in a textarea field you need to echo it into the tag content, not the attribute, ie:
<textarea><?php echo $text ?></textarea>
Third:
Echoing text directly from your datasource (in your case your DB table) to the page is insecure.
You should consider escaping it to avoid undesired behaviour - specifically, having HTML in the data rendered.
Imagine $text was this:
</textarea>
Parsing that into the form would make the resulting HTML on the page look like this, thus causing a but of JS being executed on your page.
<textarea></textarea></textarea>
Avoid this behaviour by using htmlentities:
<textarea><?php echo htmlentities($text) ?></textarea>
With that the output becomes:
<textarea></textarea><script>alert('uh-oh');</script></textarea>
Looks daft but stops the browser from rendering the content as HTML, thus securing your form :-)

Pre filled fields in form without ajax


Wilcoxon Test - non normality, non equal variances, sample size not the same

Question: I know there are already a lot of posts out there, but I couldn't find this exact combination in any of them.
Comparing two samples (Prices associated with men and with women), but I have neither the same sample size ($n = 790$ vs $n=795$) nor equal variance or normality.
My hypothesis is whether the prices for Women are greater than prices for Men. The Wilcoxon test is significant on a 4 % level.
Can I actually say anything helpful since so many assumptions are violated? Would another test be better?
EDIT Some additional infos:
<code>Prices Women: Median 28.00, Mean 28.47,  Std. Dev. 17.17,  Skewness 0.91, Kurtosis 5.41
Prices Men:   Median 26.00, Mean, 29.08, Std. Dev. 22.43,  Skewness 2.39, Kurtosis 12.74
</code>
Comment: I found some other resources which state the opposite: https://data.library.virginia.edu/the-wilcoxon-rank-sum-test/ "This is where the Wilcoxon Rank Sum Test comes in. It only makes the first two assumptions of independence and equal variance."
Or: http://kasuya.ecology1.org/stats/utest01e.html
Comment: The assumptions of the Wilcoxon rank-sum test are well described at https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test#Assumptions_and_formal_statement_of_hypotheses.  They do not include any of the characteristics you mention.
Comment: @whuber: the wiki page you linked seems to disagree with you!  Specifically *3. Under the null hypothesis H0, the distributions of both populations are equal* implies equal variance (if exists).
Comment: This test is in many ways better thought of as estimating -- in your example -- the probability that the price for males is greater than that for females, or its complement -- with a popular significance procedure on the side. For that probability to be estimated only which way the inequality runs is needed (modulo small print about ties).
Comment: The Wilcoxon test doesn't assume normality or equal variances, so what's the worry? Another way to think about the data would be to work on logarithmic scale. Log price may behave better than price.
Comment: Independence, sure.
Comment: @Heike Lehner: Could you post at least some summary stats (means or medians, standard devs)? or some plots, or a link to the data?
Comment: @Kjetil I apologize for being vague.  I agree with you that the Wikipedia article stipulates "equal distributions" as the null hypothesis.  I was focusing on the alternative hypothesis, which does not require equal variances.  In some formulations of the Wilcoxon test, the alternative is more restricted and does imply equal variances.  There are implications for how one interprets the test.
Comment: Showing the two distributions graphically would help us and help you. Again, log prices might have more meaning. When people talk about a 5% price increase or 25% off in a sale, they're understanding that prices vary multiplicatively, i.e. an underlying logarithmic scale is implied.
Answer: tl;dr if you want to interpret the rejection of the null hypothesis as evidence that prices for women are greater than those for men, then you do need the assumption of equal variance (in fact, equal distributions) between the two populations. If you are satisfied with showing that the distribution of prices for women differs in some way from that of men, then you don't need the extra assumption.
You don't need to worry about unequal sample size (this will affect the power of the test, but not its validity) or Normality.
For what it's worth, testing whether one group's values are larger on average than another group's when their variances also differ is a surprisingly deep question, even for Normally distributed data (where it's known as the Behrens-Fisher problem).
Referring to the Wikipedia page: the "very general formulation" says:

Under the null hypothesis H0, the distributions of both populations are equal.[3]
The alternative hypothesis H1 is that the distributions are not equal.

The next paragraph says:

Under more strict assumptions than the general formulation above, e.g., if the responses are assumed to be continuous and the alternative is restricted to a shift in location, i.e., $F_1(x) = F_2(x + δ)$, we can interpret a significant Mann–Whitney U test as showing a difference in medians ...

(emphasis added)

Note to technical readers: I think this is a reasonable summary, but if anyone wants to be more rigorous, feel free to comment or edit or post an alternative answer ...
Answer: Ben Bolker's answer is great. I just wanted to add an answer to the "Would another test be better?" part.
If you want to be able to conclude that prices for women are greater than those for men without the assumptions of equal distributions under the null, Brunner-Munzel's test can be recommended. For a full technical description of this test, see Chapter 3 in https://link.springer.com/content/pdf/10.1007/978-3-030-02914-2.pdf. For a non-technical introduction and comparison to the Wilcoxon test, see https://journals.sagepub.com/doi/full/10.1177/2515245921999602 (Disclaimer: I am the author of this one).
A disclaimer: this test is not optimal in any strict sense. However, it seems to be the most reasonable test for the nonparametric Behrens-Fisher problem available at the moment, just as Welch's t test is not optimal in any sense but most reasonable if you want to test equal means. Indeed, Brunner-Munzel's test is almost Welch's t test on ranked data, while the Wilcoxon test is close to Student's t test on ranked data.


Can you jump on a free throw?

Question: In basketball can you jump on a free  throw? I have got multiple answers for a bunch of different people that I trust that know a lot about basketball.
Please help me out with this guys, I'm not sure what to think.
Answer:
Can you jump on a free throw?

Yes, given the free throw shooter does not leave the defined area at any point during the procedure of a free throw(1).
There is nothing restricting this...
...according to the NBA given the free throw shooter is in compliance with Rule 9, Section I-A:

When a free throw is awarded, an official shall put the ball in play
  by placing it at the disposal of the free throw shooter. The shooter
  shall be above the free throw line and within the upper half of the
  free throw circle.

... according to the NCAA given the free throw shooter is in compliance with Rule 8, Section 1, Article 1:

A free throw is the privilege given a player to score one point by an
  unhindered try for goal from within the free-throw semicircle and
  behind the free-throw line.

... according to the FIBA given the free throw shooter is in compliance with Article 43.1.1:

A free throw is an opportunity given to a player to score 1 point,
  uncontested, from a position behind the free-throw line and inside the
  semi-circle

Can you jump on a free throw?


Missing locales on CentOS 7

Question: We are running a Werewolf cluster and the node images are missing the locales. Only C and POSIX are available. The system uses CentOS 7 as base.
It isn't really an issue but it's a very annoying to receive warnings at each command, like those:
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_COLLATE to default locale: No such file or directory

I've double checked if glibc is installed and everything appears to be ok:
[root@n01 ~]# rpm -qa | grep -i glibc
glibc-common-2.17-106.el7_2.6.x86_64
glibc-headers-2.17-106.el7_2.6.x86_64
glibc-2.17-106.el7_2.6.x86_64
glibc-devel-2.17-106.el7_2.6.x86_64

And locale -a outputs this:
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_COLLATE to default locale: No such file or directory
C
POSIX

Any idea to generate all the missing locales?
Comment: try an strace to see what file is missing: strace -f locale -a 2>&1|grep open
Answer: A tad late, but yum has glibc-langpack-* modules:
yum list glibc-langpack-\*

Comment: Centos8 has it. Centos7 doesn't :(
Answer: You could try
yum reinstall glibc-common

which should just erm, reinstall the package.
Comment: Update: I fixed this, probably not in the best way, but it works, and could not find any solution to reinstalling/replacing the missing files another way. My `/usr/share/i18n/locales` and `/usr/share/i18n/charmaps` folders were completely empty. No amount of reinstalling packages seemed to fix this. I finally took the contents of the folder from another instance that was working fine, then ran `sudo localedef -i en_US -f UTF-8 en_US.UTF-8` to generate the locale information for me. `locale -a` now shows en_US as available and all my errors are gone.
Comment: Already tried this. Unfortunately it does not work. :(
Comment: It would have been a good thing to mention that then.
Comment: @ViníciusFerrão did you solve this? Same problem for me on a brand new AWS EC2 instance. I'm missing the language packs and cannot figure out how to generate them.
Answer: since I don't find any better answer, you fix this by setting LANG , LANGUAGE and LC_ALL on logon, for example on /etc/profile add :
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8

Missing locales on CentOS 7


AS3 - Ball overspeed

Question: I'm making a little app with Flash Pro CS6 and I made this ball that moves using the arrow keys (made using the Code Sippets) at a speed of 4 pixels per frame. The problem is that, whenever I die I get to another frame there I can hit replay and try again the game, but this time, the speed of the ball is 8 pixels/frame, and this number keeps incresing everytime I replay the game. Is there any way to fix that? Here is the snippet I'm using:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;

ball.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey); //I think the problem might be this "Enter Frame"
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
    ball.y -=  4;
}
if (downPressed)
{
    ball.y +=  4;
}
if (leftPressed)
{
    ball.x -=  4;
}
if (rightPressed)
{
    ball.x +=  4;
}
}

function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
    case Keyboard.UP :
        {
            upPressed = true;
            break;

        };
    case Keyboard.DOWN :
        {
            downPressed = true;
            break;

        };
    case Keyboard.LEFT :
        {
            leftPressed = true;
            break;

        };
    case Keyboard.RIGHT :
        {
            rightPressed = true;
            break;

    }
}
};

function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
    case Keyboard.UP :
        {
            upPressed = false;
            break;

        };
    case Keyboard.DOWN :
        {
            downPressed = false;
            break;

        };
    case Keyboard.LEFT :
        {
            leftPressed = false;
            break;

        };
    case Keyboard.RIGHT :
        {
            rightPressed = false;
            break;

    }
}
};

Comment: Is `ball` an instance name of a MovieClip on the stage?
Comment: Yes, it's the instance of the movieClip on the stage
Answer: The way it looks to me, you create a new ball instance each time you gotoAndPlay the first frame - but there still is an event listener attached to the original one, even after it is removed from the stage.
So on each new ENTER_FRAME, the method is called not only once, but once for each instance of the ball.  The solution is to remove the event listener when "you die", or to use weak references, so that the ball instance can be removed cleanly.
BTW this is the short version of your script - there is no need for all those if- and switch-statements, and instance variables:
var keyPressed:int = -1;
ball.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_SetKeyPressed(event:KeyboardEvent):void {
    keyPressed = event.keyCode;
}

function fl_UnsetKeyPressed(event:KeyboardEvent):void {
    keyPressed = -1;
}

function fl_MoveInDirectionOfKey(event:Event) {
    ball.y += keyPressed == Keyboard.UP ? -4 : keyPressed == Keyboard.DOWN ? 4 : 0;
    ball.x += keyPressed == Keyboard.LEFT ? -4 : keyPressed == Keyboard.RIGHT ? 4 : 0;
}

Comment: "The solution is to remove the event listener when "you die", or to use weak references, so that the ball instance can be removed cleanly."  I'm a bit new on as3 so I don't know yet what a  weak reference is.
Comment: `addEventListener` has an optional third parameter, `weakReferences`.  If you set that to `true`, the instance of `ball` will be properly garbage collected, even if the listener is still attached to the object.  If you don't, you *have* to remove the listener in order for the ball to be erased from memory. http://dispatchevent.org/mims/creating-weak-references-in-as3/
Comment: Thank you for teh code, now the moviment is more realistic. Ok, while waiting for your reply I added a ball.removeEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey) so now there are no more errors!

AS3 - Ball overspeed


Proving that $x/(x+1)$ is continuous at $x=2$ by the definition

Question: I came upon this question,
the function $f(x)=\frac{x}{x+1}$ is continuous at $x=2$ by the definition.
Do I have to show that limit at $x=2$ exits first? I am confused with the steps, can someone please help?
Comment: You need to show that for any $\varepsilon>0$ there is $\delta>0$ such that $|f(x)-f(2)|<\varepsilon$ if $|x-2|<\delta$. In other words, imagine that someone gives you an $\varepsilon$ (say, 0.001). You need to find a formula for $\delta$ that depends on this $\varepsilon$ and prove that your $\delta$ works.
Comment: Can you use some of the theorems about continuous functions or do you have to do this from the definition of continuity?
Comment: it should be from the definition sir , @stevengregory
Answer: Write $f(x)=1-\frac{1}{x+1}$ so that
$$
f(x)-f(2)=\frac{1}{3}-\frac{1}{x+1}=\frac{x-2}{3(x+1)}.
$$
Note that for $x$ sufficiently close to $2$, we have $x+1>1$. So for all such $x$, $|f(x)-f(2)|<\frac{|x-2|}{3}$.
The observations above should be enough for you to show $f(x)\to f(2)$ as $x\to 2$. But if you get stuck:

$$\forall e>0,\exists\delta=\min\{2,3e\}>0:|x-2|<\delta\implies|f(x)-f(2)|<e.$$
Comment: Thankyou so much
Comment: but sir while I was working on , I found that from  |x-2| < 1 that |x+1|>2  : by |x+1 -3|<1 , |3 -(x+1)|< 1 then by triangular inequality |x+1|>2  .   is this wrong sir ? I'm getting a totally different answer. @yurnero
Comment: @lasanmanujitha If something is bigger than 2 than it is also bigger than 1.


How to automatically skip intermediate redirects?

Question: I've run into the issue where I end up with something like this:
about-us01 --> about-us02 --> about-us

The correct path is "about-us". But due to admins changing things I have ended up in a situation where there are sometimes old redirects lingering in the system. The problem is that these google says it's not good to redirect multiple times. So the above redirect is not very effective.
Is there a way that I can get Drupal 7 to automatically skip the 'middle' redirect if it knows that is only going to result in another redirect? So instead of:
about-us01 --> about-us02 --> about-us

I want:
about-us01 --> about-us
about-us02 --> about-us

In both cases of accessing the links, it must take you directly to the about-us page and not any inbetween links if it knows the true destination?
Comment: I don't think there is an automatic away.
Comment: @NoSssweat : are you sure?
Answer: Use the Rules module with a custom  rule which looks like so (in Rules export format):
{ "rules_redirect_multiple_paths" : {
    "LABEL" : "Disallow multiple paths",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "about-us\\d+",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirect to path about-us ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "about-us" } }
    ]
  }
}

Some details about how to use read this rule:

Rules Event: use the "Drupal is initializing" event, to ensure that the rule gets triggered BEFORE the actual content (of a path to be redirected) is shown. If you'd use an event like "content is viewed", you'd be too late, the content "would" already be shown.
Rules Condition: verify if the path to be redirected matches any of the paths you want to be redirected, such as about-us01 or about-us02 ( * ).
Rules Actions:

Show a message about the redirect, which is just for QA testing (feel free to remove that Rules Action after you saw it working).
Perform the actual redirect to the desired page.

( * ) Note that the actual Regular Expression I used goes a bit further: it would also perform a similar redirect for paths such as  about-us03 or  about-us456, though it would not trigger such redirect for (eg)  about-us/789. Here is an attempt to translate the various parts used in the regular expression about-us\\d+:

about-us: it must start with about-us.
\: escape character.
\d: it must be followed by a digit (anything from 0 to 9).
+: it may be followed by 1 or more of the preceding token (so one or more extra digits).

PS: If you're struggling with regular expressions, then have a look at RegExr.
Comment: @NoSssweat : does this help?
Comment: @NoSssweat : "now" you make me doubt, a very little bit. As "Drupal is initializing" indicates, it happens pretty early, so chances are that it will indeed overrule the original redirect. But the result may also vary, based on which technique is used for those "old redirects lingering in the system". So instead of us guessing which technique it could be (actually does the OPer know?), I suggest OPer adds more details about the technique used, and also performs an appropriate experiment using the rule I suggested.
Comment: Can you put in words the logic of your rule?
Comment: hmmm the only question is, will this over-rule the original redirect from module "x" ?


Remove spaces between characters of output Batch file

Question: I have a batch file that outputs the Wi-Fi adapter MAC address to a text file using the command wmic nic where "name like '%%802%%'" get name,macaddress and there are spaces between characters. I get the same thing for sfc /scannow in a batch file.
The output of the wmic command is:
Hostname: SOME-COMPUTER
  A C A d d r e s s                   N a m e
 3 4 : F 6 : B 3 : J 3 : 6 3 : 1 3     B r o a d c o m   8 0 2 . 1 1 n   N e t w o r k   A d a p t e r

The snippet of output of the sfc scan is:
n   3 0 %   c o m p l e t e . V e r i f i c a t i o n   3 1 %   c o m p l e t e . V e r i f i c a t i o n   3 1 %   c o m p l e t e . V e r i f i c a t i o n   3 2 %   c o m p l e t e . V e r i f i c a t i o n   3 2 %   c o m p l e t e . V e r i f i c a t i o n   3 3 %   c o m p l e t e . V e r i f i c a t i o n   3 3 %   c o m p l e t e . V e r i f i c a t i o n   3 4 %   c o m p l e t e . V e r i f i c a t i o n   3 4 %   c o m p l e t e . V e r i f i c a t i o n   3 5 %   c o m p l e t e . V e r i f i c a t i o n   3 5 %   c o m p l e t e . V e r i f i c a t i o n   3 5 %   c o m p l e t e . V e r i f i c a t i o n   3 6 %   c o m p l e t e . V e r i f i c a t i o n   3 6 %   c o m p l e t e . V e r i f i c a t i o n   3 7 %   c o m p l e t e . V e r i f i c a t i o n   3 7 %   c o m p l e t e . V e r i f i c a t i o n   3 8 %   c o m p l e t e . V e r i f i c a t i o n   3 8 %   c o m p l e t e . V e r i f i c a t i o n   3 9 %   c o m p l e t e . V e r i f i c a t i o n   3 9 %   c o m p l e t e . V e r i f i c a t i o n   4 0 %   c o m p l e t e . V e r i f i c a t i o n   4 0 %   c o m p l e t e . V e r i f i c a t i o n   4 1 %   c o m p l e t e . V e r i f i c a t i o n   4 1 %   c o m p l e t e . V e r i f i c a t i o n   4 2 %   c o m p l e t e . V e r i f i c a t i o n   4 2 %   c o m p l e t e . V e r i f i c a t i o n   4 2 %   c o m p l e t e . V e r i f i c a t i o n   4 3 %   c o m p l e t e . V e r i f i c a t i o n   4 3 %   c o m p l e t e . V e r i f i c a t i o n   4 4 %   c o m p l e t e . V e r i f i c a t i o n   4 4 %   c o m p l e t e . V e r i f i c a t i o n   4 5 %   c o m p l e t e . V e r i f i c a t i o n   4 5 %   c o m p l e t e . V e r i f i c a t i o n   4 6 %   c o m p l e t e . V e r i f i c a t i o n   4 6 %   c o m p l e t e . V e r i f i c a t i o n   4 7 %   c o m p l e t e . V e r i f i c a t i o n   4 7 %   c o m p l e t e . V e r i f i c a t i o n   4 8 %   c o m p l e t e . V e r i f i c a t i o n   4 8 %   c o m p l e t e . V e r i f i c a t i o n   4 9 %   c o m p l e t e . V e r i f i c a t i o n   4 9 %   c o m p l e t e . V e r i f i c a t i o n   5 0 %   c o m p l e t e . V e r i f i c a t i o n   5 0 %   c o m p l e t e . V e r i f i c a t i o n   5 0 %   c o m p l e t e . V e r i f i c a t i o n   5 1 %   c o m p l e t e . V e r i f i c a t i o n   5 1 %   c o m p l e t e . V e r i f i c a t i o n   5 2 %   c o m p l e t e . V e r i f i c a t i o n   5 2 %   c o m p l e t e . V e r i f i c a t i o n   5 3 %   c o m p l e t e . V e r i f i c a t i o n   5 3 %   c o m p l e t e . V e r i f i c a t i o n   5 4 %   c o m p l e t e . V e r i f i c a t i o n   5 4 %   c o m p l e t e . V e r i f i c a t i o n   5 5 %   c o m p l e t e . V e r i f i c a t i o n   5 5 %   c o m p l e t e . V e r i f i c a t i o n   5 6 %   c o m p l e t e . V e r i f i c a t i o n   5 6 %   c o m p l e t e . V e r i f i c a t i o n   5 7 %   c o m p l e t e . V e r i f i c a t i o n   5 7 %   c o m p l e t e . V e r i f i c a t i o n   5 7 %   c o m p l e t e . V e r i f i c a t i o n   5 8 %   c o m p l e t e . V e r i f i c a t i o n   5 8 %   c o m p l e t e . V e r i f i c a t i o n   5 9 %   c o m p l e t e . V e r i f i c a t i o n   5 9 %   c o m p l e t e . V e r i f i c a t i o n   6 0 %   c o m p l e t e . V e r i f i c a t i o n   6 0 %   c o m p l e t e . V e r i f i c a t i o n   6 1 %   c o m p l e t e . V e r i f i c a t i o n   6 1 %   c o m p l e t e . V e r i f i c a t i o n   6 2 %   c o m p l e t e . V e r i f i c a t i o n   6 2 %   c o m p l e t e . V e r i f i c a t i o n   6 3 %   c o m p l e t e . V e r i f i c a t i o n   6 3 %   c o m p l e t e . V e r i f i c a t i o n   6 4 %   c o m p l e t e . V e r i f i c a t i o n   6 4 %   c o m p l e t e . V e r i f i c a t i o n   6 4 %   c o m p l e t e . V e r i f i c a t i o n   6 5 %   c o m p l e t e . V e r i f i c a t i o n   6 5 %   c o m p l e t e . V e r i f i c a t i o n   6 6 %   c o m p l e t e . V e r i f i c a t i o n   6 6 %   c o m p l e t e . V e r i f i c a t i o n   6 7 %   c o m p l e t e . V e r i f i c a t i o n   6 7 %   c o m p l e t e . V e r i f i c a t i o n   6 8 %   c o m p l e t e . V e r i f i c a t i o n   6 8 %   c o m p l e t e . V e r i f i c a t i o n   6 9 %   c o m p l e t e . V e r i f i c a t i o n   6 9 %   c o m p l e t e . V e r i f i c a t i o n   7 0 %   c o m p l e t e . V e r i f i c a t i o n   7 0 %   c o m p l e t e . V e r i f i c a t i o n   7 1 %   c o m p l e t e . V e r i f i c a t i o n   7 1 %   c o m p l e t e . V e r i f i c a t i o n   7 1 %   c o m p l e t e .        V   e   r   i   f   i   c   a   t   i   o   n       7   2   %

When I run these commands from cmd.exe, the output looks like this:
MACAddress         Name
34:F2:B3:A1:83:33  Broadcom 802.11n Network Adapter

I would use PowerShell normally, but that is not what I need here. I would like the output to look like this in the output file.
The output doesn't seem to care if I use setlocal enabledelayedexpansion endlocal, as the output is the same.
Thank you for your help!
EDIT
I created a blank Unicode file ( I have Windows 10 ), and copied it to a new file I used for the output file. Now, the spaces are gone, but for whatever reason, the variable created for the hostname outputs what appears to be Chinese characters:
潈瑳慮敭›䕄䭓佔ⵐ䩒䵔剄⁓਍MACAddress         Name
34:F2:B3:A1:83:33  Broadcom 802.11n Network Adapter

The hostname command was used as follows:
for /f "delims= tokens=*" %%i in ('hostname') do (
    set "nameHost=%%i"
)

Then, I changed tokens=* to tokens=2 and all of the characters were Chinese. Anyway, a work-around was to add the hostname to the filename instead, which resolves this issue. However, it would be ideal to learn how to have both ANSI and Unicode strings in the same file, without the spaces.
I saw a C++ article about this and the answer was to change the code; therefore, if that it true, I don't have the code for sfc or wmic, so am I SOL there, or is there a way to have both ANSI and Unicode strings in the same file without the spaces between each character?
Comment: The issue is likely that you are appending the unicode, _(UTF-16 LE, BOM)_, output from `WMIC` to a file already created as ANSI. It may therefore be a simple case of changing the order such that you output the unicode stuff first.
Answer: wmic nic where "name like '%%802%%'" get name,macaddress|more

should provide you with an ANSI version - the problem there is Unicode-output from WMIC.