Como posso substituir uma parte de uma string por ela mesma mais o caractere "~"?

Question: Como posso substituir uma parte de uma string por ela mesma mais o caractere "~"?
Estou fazendo da seguinte forma: só que quando a string tem dois números iguais como o 51 que vem logo após AP e o contido no 17513322  o Replace faz a troca nos dois locais sendo que só quero que faça o Replace no número completo.
Minha string deveria ficar da seguinte forma:

RUASANTA HELENA, 769~ AP 51~ BL H JD ALVORADA~ 17513322~

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string lista = "RUASANTA HELENA, 769  AP 51 BL H JD ALVORADA~ 17513322 ";

        var match = Regex.Match(lista, "[0-9]+");
        while (match.Success)
        {
            lista = lista.Replace(match.Value, match.Value + "~");
            match = match.NextMatch();
        }
        System.Console.Write(lista);
    }
}

Comment: Assim também deve funcionar: http://ideone.com/59v7or
Comment: @stderr, obrigado também funcionar.
Answer: Se o número completo sempre for seguido de um espaço, você pode usar o pattern "([0-9]+?)" e substituir pelo match que ocorreu dentro dos parênteses mais o ~ e um espaço(que deu match também):
string lista = "RUASANTA HELENA, 769  AP 51 BL H JD ALVORADA~ 17513322 ";
lista = Regex.Replace(lista, "([0-9]) ", "$1~ ");

Exemplo no DotNetFiddle.
Comment: Use `\d` jovem, `[0-9]` é feio :D
Answer: A pergunta cita RegEx e a resposta aceita deu uma boa solução. Eu prefiro fazer manualmente porque eu faço isso mais fácil do que eu faria com RegEx, mas sei que não é o caso de todo mundo. Se a performance for importante o RegEx nem sempre é uma boa opção. Quase todos algoritmos é possível fazer mais rápido se produzir manualmente. Foi o que eu fiz:
public static string MudaEndereco(string texto, char adicao = '~') {
    var resultado = new StringBuilder(texto.Length * 2);
    var anterior = '\0';
    foreach (var caractere in texto) {
        if (Char.IsDigit(anterior) && Char.IsWhiteSpace(caractere)) {
            resultado.Append(adicao);
        }
        resultado.Append(caractere);
        anterior = caractere;
    }
    return resultado.ToString();
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
O RegEx perdeu para o algoritmo manual em média de pelo menos por 4X. Teve casos de dezenas que eu desconsiderei, talvez por causa de coleta de lixo. 4X não é pouca coisa. Dependendo da máquina a diferença ficou em 6X ou mais. Não entendo tanto de RegEx, posso ter feito alguma coisa errada, mas fiz em cima do que foi respondido. Tentei algumas otimizações que o RegEx do .Net permite e só piorou :).
Eu usei até um critério que pode ter deixado mais lento porque eu não peguei só uma caractere branco, peguei qualquer caractere que seja considerado um branco, se o requisito não permite isso é só mudar para um simples ' '. A verificação de dígitos também está feita de forma que funciona onde os números estão representados de forma não comum na tabela Unicode, isso certamente também deixa mais lento.
Eu fiz um exemplo extra mais personalizável e o resultado foi praticamente o mesmo.
Note que eu dei uma otimizada no padrão do RegEx, o ? não fazia sentido ali e poderia usar \d. Então eu faria:
Regex.Replace(lista, "(\\d+) ", "$1~ ")

Então se a resposta tiver que ser RegEx este seria meu código.
Answer: Método String.Replace (String, String)

Retorna uma nova seqüência na qual todas as ocorrências de uma String
  especificada são substituídas por outra String especificada.

Sintaxe
public string Replace(
    string oldValue,
    string newValue
)

Exemplo
public class Example
{
   public static void Main()
   {
      String s = "aaa";
      Console.WriteLine("The initial string: '{0}'", s);
      s = s.Replace("a", a+"~");
      Console.WriteLine("The final string: '{0}'", s);
   }
}

Método String.Concat (String, String)

Concatena duas instâncias de String especificadas.

Sintaxe
public static string Concat(
    string str0,
    string str1
)

Exemplo
string str0 = "teste";
string str1 = "~";

str0 = string.Concat(str0, str1)

Boa sorte!
Comment: Com o String.Replace() eu precisaria saber o index de inicio e fim da string para pegar a parte especificar da string e fazer o replace. isso é complicado quando envolve muita informação em uma string a resposta do Daniel resolveu.


Problems that can be shown by "an epsilon of room".

Question: This might not be a question suitable here so apologies from posting it if so.
In Terence Tao's blog he refers to something called "An epsilon of room" and this seems to be a helpful way to prove for example inequalities in analysis. He goes on to say that

If one has to show that $X \le Y$, try proving that $X \le Y+ \varepsilon$ for any $\varepsilon >0$.

I tried to find examples online from where I could gather a collection of problems that can be shown by his proposed method, but there isn't much to find. Or perhaps most of the problems are "masked" in a way that I don't see this particular trick being used. If anyone knows some of these kind of problems I would appreciate if they could be posted here.
Comment: You could maybe add the big-list tag to this question.
Comment: This is just a special case of arguments done "by passing to limit". And it is not restricted to inequalities. For example, in linear algebra you often prove some property for diagonalizable matrices first, and then extend it to all matrices by passing to limit. Because every matrix is a limit of diagonalizable matrices. The property just has to behave continuously. That $\det(e^A)=e^{\text{tr}A}$ is proved this way. This is also used in measure theory a lot, something is first proved for step functions, etc.
Comment: This is not really a "give me some homework problems" site. It is instead a question-and-answer site.
Comment: It seems to me that any epsilon-delta proof of a limit fits the description, but maybe I'm misunderstanding the concept here.
Comment: @LeeMosher Well, I think this person may just be asking for statements that may be proven using the trick.
Comment: @LeeMosher Yes I see that the site is mostly for answering questions that can be answered pretty much in a "binary" sense. By this I mean that there isn't room for "hand waving". However as I see the sites main purpose is to educate and this is clearly an post that would be of help in that sense for many.
Comment: You can do the inverse and show that 0.99999.....=1 because there's no way to find an "epsilon of room" between them
Answer: Here are some statements that come to mind:

The Lindelöf's theorem and its variants
The theorem that every probability measure defined on a Polish space is inner regular
The theorem that the continuous extension of a Lipschitz-continuous function that had previously only been defined on a dense subset is again Lipschitz-continuous with the same Lipschitz constant
Answer: This happens frequently in the theory of elliptic and parabolic partial differential equations.
Here is a very classical example.
A $C^{2}$ function $u$ in an open set $\Omega$ is harmonic if its Laplacian vanishes everywhere, i.e. $-\Delta u(x) = 0$ for all $x \in \Omega$.
Maximum principle: If $u : \overline{\Omega} \to \mathbb{R}$ is continuous in $\overline{\Omega}$ and twice continuously differentiable in $\Omega$, then $\max\left\{u(x) \, \mid \, x \in \Omega\right\} = \max\left\{u(y) \, \mid \, y \in \partial \Omega\right\}$.
Proof:  It's convenient to argue by contradiction.  Suppose, then, that the conclusion is false, i.e. $\max\{u(z) \, \mid \, z \in \partial \Omega\} < \max\{u(x) \, \mid \, x \in \Omega\}$.
I will take you up on that offer of $\epsilon$ of room.  Consider the function $v_{\epsilon}(x) = \max\{u(x) \, \mid \, x \in \Omega\} - \epsilon \|x\|^{2}$.  $u - v_{\epsilon}$ has a maximum $x_{\epsilon}$ somewhere in $\overline{\Omega}$.  For $\epsilon$ small enough, $x_{\epsilon} \in \Omega$ --- otherwise, $u$ would attain its maximum somewhere on the boundary.  (We have "room" to work with.)  Thus, since $x_{\epsilon}$ is an local maximum (in the interior), I can apply the the second derivative test to find
\begin{equation*}
-\Delta u(x_{\epsilon}) + \Delta v_{\epsilon}(x_{\epsilon}) = -\Delta (u - v_{\epsilon})(x_{\epsilon}) \geq 0.
\end{equation*}
so $-\Delta u(x_{\epsilon}) \geq -\Delta v_{\epsilon}(x_{\epsilon}) = 2 \epsilon d$.  This is impossible since $u$ is harmonic.
With experience, one realizes there is a geometric interpretation of this proof that is perfectly suited to the intuition that "we have room," but it would be cumbersome to explain here.

Problems that can be shown by ”an epsilon of room”.


How to solve $\int \sqrt{1+\sin x}\, dx$?

Question: It's easy to get this:
$$\int \sqrt{1+\sin x}\, dx \\= \int \sqrt{ \sin^2{\frac{x}{2}} + \cos^2{\frac{x}{2}} + 2\sin{\frac{x}{2}}\cos{\frac{x}{2}}}\,\, dx  \\ = \int \left | \sin{\frac{x}{2}} + \cos{\frac{x}{2}} \right |\, dx \\= \sqrt{2} \int \left | \sin{\left ( \frac{x}{2} + \frac{\pi}{4} \right )} \right |\, dx$$
So, in fact, my question is how to solve the integrate $\int \left | \sin x \right| dx $.
Or how to deal with the integrate when have absolute in it?
Comment: Why absolute value makes it special you think ?
Answer: As zkutch has given how to calculate with absolute value here is another approach
To avoid confusion its better to do this we have $$\int \frac{\cos x}{\cos x}\sqrt{1+\sin x}dx=\int \frac{\cos x dx}{\sqrt{1-\sin x}}=-2\sqrt{1-\sin x}+C$$
Here in above integral i had put $1-\sin x=t$ which gave answer easily
Answer: Hint: $|\sin x|=(-1)^n \sin x$ for $\pi n \leqslant x < \pi (n+1)$, where $n=0, \pm 1,\pm2, \cdots$.
To keep antiderivative continuous in $x=\pi (n+1)$ you need to solve
$$\left((-1)^{n+1}\cos x +C_n\right) \Big|_{x=\pi (n+1)}=\left((-1)^{n+2}\cos x +C_{n+1}\right)\Big|_{x=\pi (n+1)}$$
taking some $C=C_0$.


Kernel density estimation integral of squared kernel

Question: For computing the mean integrated squared error of an estimated distribution, there is a term
$$
R(g) = \int_{-\infty}^{\infty}g(x)^2 \,\text{d}x,
$$
where $g(x)$ denotes the so-called kernel. No suppose that I have a gaussian kernel, i.e.,
$$
g(x) = \frac{1}{\sqrt{(2\pi)^d}} \exp \left\{-\frac{1}{2} \|x\|^2\right\},
$$
where $d$ denotes the dimension of the vector $x$ and $\|\cdot\|$ denotes the 2-norm, i.e. $\|x\|^2=x^T x$. Then, what is the value of $R(g)$?

My attempt:
I try to write the integral as a gaussian distribution (which is normalized) with covariance $\frac{1}{2}I$, where $I$ denotes the identity matrix, so the determinant of the covariance equals $2^{-d}$. The result is this:
\begin{align}
R(g) &= \int_{-\infty}^{\infty}g(x)^2 \,\text{d}x \\
&= \int_{-\infty}^{\infty} \frac{1}{(2\pi)^d} \exp \left\{ \|x\|^2 \right\} \,\text{d}x\\
&= \frac{\sqrt{2^{-d}}}{\sqrt{(2\pi)^d}} \int_{-\infty}^{\infty} \frac{1}{\sqrt{(2\pi)^d} \sqrt{2^{-d}}} \exp \left\{ \frac{1}{2} x^T \left(\frac{1}{2}I\right)^{-1} x \right\} \,\text{d}x\\
&=\frac{\sqrt{2^{-d}}}{\sqrt{(2\pi)^d}} = \frac{1}{2^d \pi^{d/2}}.
\end{align}
Is my approach correct?
Comment: @joriki Thanks, I did not know that. I changed the `||` to `\|`.
Comment: You can get a proper norm symbol using `\|` instead of the double `|`.
Answer: Your integral notation is  unorthodox – since you take norms and transposes of vectors, I take it that $x\in\mathbb R^n$ and the integral is over all $\mathbb R^n$, which is usually symbolized either by $\int_{\mathbb R_n}$ (or for some other volume $V$ by $\int_V$) or by $\int_{-\infty}^\infty\ldots\int_{-\infty}^\infty$, whereas your notation is the usual one for a one-dimensional integral over $\mathbb R$.
Assuming that I've interpreted the integral correctly, your approach is correct, and if this formula involving a general covariance matrix and its determinant is the first that occurs to you, that's fine. I personally would have found it slightly easier to substitute $x=\frac u{\sqrt2}$, thus transforming to the standard normal distribution and obtaining the factor of $2^{-\frac d2}$ from the Jacobian of the substitution.
This is of course also how the determinant formula is derived, so it's just a matter of what you're more familiar with whether you do it from first principles or from a formula for a specific substitution that this is a special case of.
Comment: Thanks for your reply, that is very useful. I really like your feedback regarding the notation so that I can improve on that. I also tend to think that your approach with the substitution is easier, but somehow it did not come to my mind. Thanks again for your time


Azure ARM - Live swapping of LB backend pool

Question: I am currently investigating the feasibility of swapping the backend pool of an Azure load balancer, whilst not interrupting the experience for those requests coming into the load balancer.
The reason being is to create a blue/green deployment strategy, where we create a new availability set (VMSS potentially) and update the load balancers backend pool to point to the new availability set.
I'd love to hear if anyone has had some experiences doing something like this in Azure.
Answer: Azure Load Balancer probe comes from 188.8.131.52. If you create a firewall rule on the VM to deny access to the probe port from that IP it will knock the VM out of the pool so no future connections will be routed to that VM (until the firewall rule is disabled). Existing connections from users continue unharmed.
I haven't tried your approach and don't know whether it will work. But you asked for our experience so I thought I would share that with you. I found it a great way to take a VM offline gracefully for maintenance from within the VM. And I was happy I didn't have to configure Azure PowerShell on the VM and a service principal to accomplish it.
Answer:
I am currently investigating the feasibility of swapping the backend
  pool of an Azure load balancer, whilst not interrupting the experience
  for those requests coming into the load balancer.

As far as I know, we can't live swapping of LB backend pool and  not interrupt those requests.
As a workaround, we can use powershell to upgrade Azure Vmss.
Here is the PowerShell script about update Azure Vmss instance (it does an update one VM instance at a time):
<code>$rgname = "vmss"
$vmssname = "vmss"
$newURI = "imageurl"
$instanceid = "1"
$vmss = Get-AzureRmVmss -ResourceGroupName $rgname -VMScaleSetName $vmssname
$vmss.virtualMachineProfile.storageProfile.osDisk.image.uri= $newURI
Update-AzureRmVmss -ResourceGroupName $rgname -Name $vmssname -VirtualMachineScaleSet $vmss
Update-AzureRmVmssInstance -ResourceGroupName $rgname -VMScaleSetName $vmssname -InstanceId $instanceId
</code>
Here a blog about upgrade an Azure VM Scale Set without shutting it down, please refer to this link.


Cleaning up after calling GetSystemMenu()

Question: I'm using Florian's wrapper class to call GetSystemMenu() to add a custom menu item to the system menu for an application.
I'm just curious as to whether there is any cleanup required for the handle returned by calling GetSystemMenu or the additional menu items. I don't see any mention of needing to call CloseHandle() or similar, so my current assumption is that this is not needed.
Answer: You shouldn't have to worry about it.
Check the MSDN docs for DestroyMenu:

A menu that is assigned to a window is automatically destroyed when the application closes.

In general, Windows should destroy the menu when your form is closed, which in turn will destroy your custom menu items.
Answer: I have had a look at the wrapper and my gut feeling is this:
The handle used within SystemMenu.cs is giving me a doubt...

private IntPtr m_SysMenu = IntPtr.Zero; // Handle to the System Menu

That handle, nowhere in the code is being explicitly closed or released...which leads me to think that there should be an IDisposable implementation within the code to close/release the handle...
What do you think?
Hope this helps,
Best regards,
Tom.
Comment: Sorry to be pedantic and nit-picky...but had to post my thought on it.
Comment: See Reed's answer.  It is probably deleted in DefWindowProc's handling of WM_NCDESTROY.
Comment: @Michael: Thanks... but can you clarify DefWindowProc in the aspect of .NET...or did you mean WndProc? (the protected override method commonly found in controls)


Access to Map values in Safari 7.1+

Question: Safari has support for ES6 Maps and Sets in version 7.1 and higher (MDN).
I'm using a Map in my application and at some point want access to the values. Calling the values() function on the map seems like the way to go and returns an Iterator. By calling next() on the returned Iterator, one should be able to iterate over the values. This works fine in Chrome, but Safari does something strange. It returns a Map Iterator when calling values(), but the returned iterator has no next() function.
m = new Map();
m.set(1, "test");
m.set("2", false);
it = m.values(); // returns Map Iterator
it.next(); // TypeError: undefined is not a function

Am I missing something obvious, or is the Safari implementation only partial?
Is there another way to get access to the values? Using the for..of construct is not an option because this is new syntax and is not supported in older browsers (for which I use the es6-collections shim).
Comment: Yes, this is a bug in Safari (7.1/8): https://github.com/paulmillr/es6-shim/issues/326
Comment: If it really is how you describe, then that's a bug.
Answer: This indeed seems to be a bug with Safari 7.1 and 8. I managed to work around this issue by first checking if the next function was available and if not, I used the for...of construct. Because this is invalid syntax pre-ES6, I had to wrap it in an eval statement:
m = new Map();
m.set(1, "test");
m.set("2", false);
it = m.values(); // returns an Iterator
if (typeof it.next === 'function') {
    v = it.next();
    // do something with v here
} else {
    eval("for (v of iterator) /* do something with v here */");
}

Comment: *" Because this is invalid syntax pre-ES6, I had to wrap it in an eval statement"* That doesn't seem to make sense. If the engine doesn't understand `for/of`,  using `eval` instead won't make a difference. It seems to me that the linter you may be using doesn't understand ES6, which is a separate problem.
Comment: @FelixKling It does make a difference. The for/of case only gets executed in Safari 7.1/8 which does support it. The other browsers make use of a polyfill that has a working iterator. I can't put the for/of in plain code because other browsers would complain about the invalid syntax and do nothing at all.
Comment: I see. Still. Using `eval` here is not a clean solution. I would probably use a library that polyfills the non-standard behavior. Core-js claims it does, but I haven't tested it in Safari.

Access to Map values in Safari 7.1+


Error starting a test with testacular

Question: I am trying out the angularjs tutorials on a 64 bit Windows 7 system because I find this framework quite interesting from what I read on its home page. I am a newbie to node.js and not experienced in Java-Script.
When running the tests, I get the following error. Can anybody find out what the problem is or give some hints how to determine that? I have a fresh Installation of node and added testacular with

npm install -g testacular

which worked fine from what was printed on the console window.
So here is the error message:

PS C:\Users\xx\Documents\Angular\angular-phonecat> .\scripts\test.bat
  INFO [testacular]: Testacular server started at http://localhost:9876/
  INFO [launcher]: Starting browser Chrome
  ERROR [testacular]: { [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' }
  Error: spawn ENOENT
      at errnoException (child_process.js:948:11)
      at Process.ChildProcess._handle.onexit (child_process.js:739:34)
Comment: Well, do you have `chrome` installed and in your path? The error is basically telling you that `child_process.spawn` threw `ENOENT` which usually means that the executable couldn't be found
Comment: Yep, Chrome is installed and I've added Chrome's application Folder to the PATH variable. Is there a way to find out what process node.js was trying to start?
Answer: Short answer:
Set env variable CHROME_BIN to full path to chrome.exe
The error msg is confusing, as the behavior of spawn got changed in Node 0.10, we need to update it (https://github.com/karma-runner/karma/issues/452)
Comment: Btw, the project has been renamed to Karma, so you might rather install `npm install karma`, as Testacular package won't be updated on NPM.
Comment: If you are running on Windows make sure you don't put quotes around the path even if there are spaces in it, just the full path to the exe like `C:/Program Files (x86)/Google/Chrome/Application/chrome.exe`.
Comment: @clav thanks for pointing that out, btw. with the latest Karma this is not an issue, as Karma checks for the quotes first and remove them if you use them...
Answer: Inserting 'PhantomJS' for the test browser in the karma configuration file on Windows Vista resulted in the same error message:  { [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' }
I ad-libbed on the advice above and inserted in the system path ("Environmental Variables") under "User variables for owner" PHANTOMJS_BIN with the value consisting of the path including phantomjs.exe (C:\Program Files\phantomjs-1.9.0-windows\phantomjs.exe)
All good, jasmine angularjs tests running now and much faster than with 'Chrome' or 'Firefox' as the test browser.

Error starting a test with testacular


Proving that the desired set exists

Question: Let $n_2$ be the binary form of $n\in\mathbb N$.  Define the function $F$ on $\mathbb N\times \mathbb N \to \{0,1\}$ by $F(n,i)=1$ if $i$ is less than the length of $n_2$ and the $(i+1)$th digit (counting from the right) of $n_2$ is $1$. Otherwise, $F(n,i)=0$.
Now let's make each natural number a set as follows. Nothing lies in $0$. Only $1$ lies in $1$. For all other $m\ne 0,1$, $n$ lies in $m$ iff $F(m,n)=1$. The problem is to show that for all $k$ and all $n_1,\dots, n_k$ there is a unique $N$ such that $N=\{n_1,\dots, n_k\}$. (There might be a slight confusion with the notation: at the beginning $n_2$ denotes the binary form of $n$, but here the indices don't denote binary or other forms.)
I guess this needs to be proved by induction on $k$? The base case presumably has to be $k=1$ (because the statement doesn't seem to be true for $k=0$), and it's clear. Now suppose we have a set $N_k=\{n_1,\dots, n_k\}$ and suppose we consider a $k+1$st number $n_{k+1}$. I don't really see how to consruct  a number $\{n_1,\dots, n_k, n_{k+1}\}$ out of $\{n_1,\dots, n_k\}$ and $N_k$... Any ideas?
Comment: The statement is true for $k=0$, because there is a unique $N$ such that $N=\{\}$, namely $N=0$.
Comment: You said that the case $k=1$ is clear, but can you explain that case? If $k=1$, then we're looking at a set $\{n_1\}$, but what number gives that set?  For example, which number gives the set $\{3\}$?
Comment: Anyway, welcome the Mathematics StackExchange!  I have an answer ready, but I'm not sure that I understand the question correctly, so I hope that your reply to my last comment will clarify.  (But mostly, the question seems clear, and you've explained what you tried and how it failed.)
Comment: @TobyBartels Oops, I oversimplified things in my head, I only thought about the case $k=1$ and $n_k=n_1=1$. But for $k_1=3$, I guess we could take $N$ to be 100 in binary. And in general for $k_1=n$ we can take the number 1000...00 with $n-1$ zeros after 1.
Comment: Oops I mean $n_1$ instead of $k_1$.
Comment: OK, good, you get the set $\{3\}$ by taking a number which is $100$ in binary; specifically, that's the number $2^3=8$.  And you get the set $\{4\}$ by taking a number which is $1000$ in binary; specifically, that's the number $2^4=16$.  Now do you see how you could get the set $\{3,4\}$?
Comment: I'm asking more questions, because I think that if you see how make $\{3,4\}$, then you'll see how to make any set, which will be more valuable than reading my answer about it.  But you've also confirmed that I understand the question correctly, so I'll post my answer this weekend in any case.
Answer: I don't like using the same symbol for a number and for its associated set, especially since the elements of that set are themselves numbers.  So I'm going to put a bar over the number to indicate the set.  (But I'll come back to this in an appendix.)  Then the goal is to prove that for all $ k $ and all $ n _ 1 , \ldots , n _ k $, there is an $ N $ (the actual number) such that $ \overline N $ (the associated set) is $ \{ n _ 1 , \ldots , n _ k \} $.
You wrote the definition so that $ 0 $ and $ 1 $ are special cases, but if I use the same definition for them as for the other numbers, then I still get $ \overline 0 = \{ \} $ but I get $ \overline 1 = \{ 0 \} $ instead of $ \overline 1 = \{ 1 \} $ as you wrote.  So I think that this is a mistake, whether made by you or by whoever posed the question to you.  And besides, I can't solve the problem without making this change, since there is no other $ N $ that I can use to get $ \overline N = \{ 0 \} $, whereas there is another $ N $ (namely, $ 2 $) that gives $ \overline N = \{ 1 \} $.  (Also, there's an application of this idea for which it's important that $ x < N $ whenever $ x \in \overline N $, so we wouldn't want $ 1 \in \overline 1 $.)
With this understanding, here are the first few sets: $$ \eqalign { \overline 0 & = \{ \} \text , \\ \overline 1 & = \{ 0 \} \text , \\ \overline 2 & = \{ 1 \} \text , \\ \overline 3 & = \{ 0 , 1 \} \text , \\ \overline 4 & = \{ 2 \} \text , \\ \overline 5 & = \{ 0 , 2 \} \text , \\ \overline 6 & = \{ 1 , 2 \} \text , \\ \overline 7 & = \{ 0 , 1 , 2 \} \text , \\ & \; \vdots } $$
For example, $ 6 $ in base $ 2 $ is $ 1 1 0 $, so (counting from the right) the $ 1 $st digit is $ 0 $, the $ 2 $nd digit is $ 1 $, the $ 3 $rd digit is $ 1 $, and there are no other digits (although you could take them to also be $ 0 $ if you wanted to).  So the $ ( i + 1 ) $th digit is $ 1 $ precisely when $ i $ is $ 1 $ or $ 2 $.  Thus, $ \overline 6 = \{ 1 , 2 \} $.  (Or if this is wrong, then I haven't understand your description of the problem correctly.)
You could also start counting the digits with $ 0 $ instead of $ 1 $ to avoid having to do $ i + 1 $, but I guess that starting on the right is already one unusual aspect of the counting, so they didn't want to add another.  Still, it's worth noticing that the first digit (from the right) tells you whether or not $ 0 $ belongs to the set, the next digit tells you whether or not $ 1 $ belongs to the set, etc.
Anyway, to reverse this, that is to find the number $ N $ starting with a set $ \overline N = \{ x _ 1 , \ldots , x _ k \} $, you need to find a number whose $ ( i + 1 ) $th binary digit is $ 1 $ precisely when $ i $ belongs to the set.  And that digit contributes $ 2 ^ i $ to the value of the number.  Therefore, assuming that the $ k $ numbers $ x _ 1 , \ldots , x _ k $ are all distinct (no repetition), $$ N = \sum _ { j = 1 } ^ k 2 ^ { x _ k } \text . $$  That is, add up $ 2 ^ x $ for each element $ x $.  For example, starting with $ \{ 1 , 2 \} $, we get $ N = 2 ^ 1 + 2 ^ 2 = 6 $.
So for every (natural) number, we get a set of numbers; and for every (finite) set of numbers, we get a number.  Depending on how much detail you want in your proof, you could prove this by induction on $ k $; that's natural since summation is defined by induction.  But I think that the summation formula will probably satisfy whoever's asking you.  Or if this is something that you thought of on your own, then hopefully this satisfies you!

Appendix:
I said before that I don't like using the same symbol for the number $ N $ and the set $ \overline N $.  And if you write $ 6 = \{ 1 , 2 \} $ outside of the context of this question, then people will probably not like that.  (They may say that it's nonsense, because a number is not a set; or they may say that it's wrong, because really $ 6 = \{ 0 , 1 , 2 , 3 , 4 , 5 \} $; but they almost certainly will not say that it's correct.)  However, if we instead write $ \overline 6 = \{ \overline 1 , \overline 2 \} $, then nobody can object, because we're defining what $ \overline N $ means.  (The fact that $ x < N $ whenever $ \overline x \in \overline N $, allows you to prove that this is a consistent way to define a family of sets; $ \overline 1 \in \overline 1 $ is not allowed in a well-founded set theory such as ZFC.)
So instead of saying that a number is a set whose members are also numbers, we're defining a family of sets (one for each number), each of whose members are also sets in this family.  Then these are actually a famous family of sets called the hereditarily finite sets.  (Finite since they're all finite, hereditarily finite because also their members are finite, their members' members are finite, etc.  Formally, a set is hereditarily finite if and only if it's finite and all of its members are hereditarily finite; and while this looks circular, it's valid as a definition by induction on the set-membership relation in a well-founded pure set theory such as ZFC.)
If you're founding all of mathematics on pure set theory, then you want to have a way to define numbers as sets.  The most common way, named after von Neumann, is to use $ N = \{ x \; | \; x < N \} $; that's what people would be thinking of if they say that $ 6 = \{ 0 , 1 , 2 , 3 , 4 , 5 \} $.  An earlier method, named after Zermelo, is to use $ N = \{ N - 1 \} $ (with $ 0 = \varnothing $ as an exception to get started); then $ 6 = \{ 5 \} $.  But now we can see that the way you wrote things before, where the numbers are the sets, is yet another way to define numbers as sets, although a little more complicated to explain.  And while von Neumann's and Zermelo's methods turn every natural number into a hereditarily finite set, your method turns the natural numbers into all of the hereditarily finite sets, so it's nice.  (Von Neumann's method is nice in another way, in that it generalizes smoothly to certain infinite numbers, the transfinite ordinal numbers.  Zermelo's is nice in that it's minimal; it consists of the smallest and simplest sets that can do the job.  So they all have their charms.)
So now I'm back to saying that OK, $ 6 = \{ 1 , 2 \} $; but only if you're founding all of mathematics (or at least arithmetic) on pure set theory in this new way.

Proving that the desired set exists


How to run a PHP script using a Cron job

Question: I'm having a PHP script which I want to run every 2 minutes using a Cron job in Ubuntu. I'm getting the following error:
bash: */2: No such file or directory

I've completed all steps below to set up a Cron job.
Please help me to resolve the error, I don't understand what I'm doing wrong.
1) Write this command in my terminal: where is php
Output:
php: /usr/bin/php /usr/bin/X11/php /usr/share/php /opt/lampp/bin/php /usr/share/man/man1/php.1.gz
2) Run a PHP script every 2 minutes:
*/2 * * * * /usr/bin/php  /opt/lampp/htdocs/kyrill/filetest.php
Output:
bash: */2: No such file or directory
Comment: first: have you add the path correctly to the cron? second: have you add at the very top of your script the script type? in your case should be like this #!/usr/bin/php
Comment: olso add php **** php /usr/bin/......
Comment: @alvaro if i want to run php on terminal then i have write this command on terminal php /opt/lampp/htdocs/kyrill/filetest.php and it execute it successfully
Answer: Seems like you are executing the crontab directive.
Execute
 crontab -e

to edit your cron jobs. Then add this line at end of the file
 */2 * * * * /usr/bin/php /opt/lampp/htdocs/kyrill/filetest.php

Comment: yes i will directly run on terminal but when i apply your approach it gives me something like this error E486: Pattern not found: 2 * * * *
Comment: Follow this link, could help you https://www.digitalocean.com/community/tutorials/how-to-use-cron-to-automate-tasks-on-a-vps
Comment: are you using vim?
Comment: Seems that you are using vim, follow this link to get help https://www.digitalocean.com/community/tutorials/installing-and-using-the-vim-text-editor-on-a-cloud-server
Answer: try
0/2 * * * * curl http://[your_id:port]/kyrill/filetest.php

Comment: No, please, don't add an extra layer of obfuscation. You don't need Internet to run a local command.
Comment: with this also it is showing the same error bash: 0/2: No such file or directory
Comment: Would you mind to set it * * * * * curl http://[your_id:port]/kyrill/filetest.php ?
Comment: no i dont i have any but it is also not working given the same bash error


SELECT em duas tabelas diferentes com variáveis de mesmo nome

Question: Tenho a seguinte consulta a ser feita:
<code>"SELECT DISTINCT
        andamento_processual.licenciamento_cod,
        andamento_processual.inter_simplificada_cod,
        andamento_processual.inter_pretendida_cod,
        andamento_processual.processo_numero,
        andamento_processual.processo_situacao,
        licenciamento.licenciamento_empreendimento_nome,
        empreendimento.empreendedor_nome_empreendimento,
        intervencao_amb_pretendida.inter_pretendida_cod,
        intervencao_amb_pretendida.intervencao_nome_empreendedor, <---
        intervencao_amb_simplificada.inter_simplificada_cod,
        intervencao_amb_simplificada.intervencao_nome_empreendedor <----
        FROM
        andamento_processual
        LEFT OUTER JOIN licenciamento ON andamento_processual.licenciamento_cod = licenciamento.licenciamento_cod
        LEFT OUTER JOIN empreendimento ON licenciamento.licenciamento_empreendimento_cod = empreendimento.empreendimento_cod
        LEFT OUTER JOIN intervencao_amb_pretendida ON andamento_processual.inter_pretendida_cod = intervencao_amb_pretendida.inter_pretendida_cod
        LEFT OUTER JOIN intervencao_amb_simplificada ON andamento_processual.inter_simplificada_cod= intervencao_amb_simplificada.inter_simplificada_cod
        WHERE
        andamento_processual.processo_numero";
</code>
Meu problema é que existem duas variáveis de mesmo nome só que em tabelas diferentes, coloquei uma setinha apontando para elas. Quando coloco para exibir na tabela, só mostram os resultados da "intervencao_amb_simplificada.intervencao_nome_empreendedor".
Tentei fazer da seguinte forma, dentro do WHILE:
<code>if($inter_simplificada_cod){

        $nomeSimplEmpreendedor = $row['intervencao_nome_empreendedor'];

      }else if($inter_pretendida_cod){

        $nomePretEmpreendedor = $row['intervencao_nome_empreendedor'];

      }
</code>
Mas não funcionou! Tem como eu resolver isso sem trocar o nome da variável nas duas tabelas?
Comment: Posso estar com a vista meio ruim mas as linhas que você apontou tem o mesmo nome de campo mas são de tabelas diferentes.
Comment: é porque uma variável esta salva na tabela "intervencao_amb_pretendida" e outra na "intervencao_amb_simplificada", eu coloquei banco, mas são tabelas. Estava errado, arrumei aqui
Answer: Você precisa usar um alias no segundo nome para poder retorná-lo:
<code>    SELECT DISTINCT
        andamento_processual.licenciamento_cod,
        andamento_processual.inter_simplificada_cod,
        andamento_processual.inter_pretendida_cod,
        andamento_processual.processo_numero,
        andamento_processual.processo_situacao,
        licenciamento.licenciamento_empreendimento_nome,
        empreendimento.empreendedor_nome_empreendimento,
        intervencao_amb_pretendida.inter_pretendida_cod,
        -- abaixo, mudando o nome utilizando 'as'
        intervencao_amb_pretendida.intervencao_nome_empreendedor as intervencao_nome_empreendedor_pretendida,
        intervencao_amb_simplificada.inter_simplificada_cod,
        -- abaixo mudando o nome sem usar o 'as'
        intervencao_amb_simplificada.intervencao_nome_empreendedor intervencao_nome_empreendedor_simplificada
    FROM
        andamento_processual
        LEFT OUTER JOIN licenciamento ON andamento_processual.licenciamento_cod = licenciamento.licenciamento_cod
        LEFT OUTER JOIN empreendimento ON licenciamento.licenciamento_empreendimento_cod = empreendimento.empreendimento_cod
        LEFT OUTER JOIN intervencao_amb_pretendida ON andamento_processual.inter_pretendida_cod = intervencao_amb_pretendida.inter_pretendida_cod
        LEFT OUTER JOIN intervencao_amb_simplificada ON andamento_processual.inter_simplificada_cod= intervencao_amb_simplificada.inter_simplificada_cod
    WHERE
        andamento_processual.processo_numero
</code>
Com isso, você irá receber no resultset de retorno ambas os valores.
Comment: FUNCIONOU, não sabia que dava pra fazer assim. MUITO OBRIGADO!


Enviar texto de múltiplos "select" para o mesmo "input text"?

Question: Dado o código:

var select = document.getElementById('meuSelect');
var input = document.querySelector('input');

select.addEventListener('change', function() {

  var option = this.children[this.selectedIndex];
  input.value = option.innerHTML;
});
<select id="meuSelect">
    <option value="a">Alfa</option>
    <option value="b">Beta</option>
    <option value="g">Gama</option>
</select>

<input type="text" />

(cedido por @Sergio referência)
O código realiza a função com um select, a pergunta é : Como obter o mesmo resultado, porém com múltiplos select, onde cada opção selecionada será enviada ao mesmo input, formando por exemplo uma frase, onde cada select é uma palavra que compõe a frase? Desculpem se não fui claro.
Por exemplo:

<select id="meuSelect1">
    <option value="a">Alfa</option>
    <option value="b">Beta</option>
    <option value="g">Gama</option>
</select>
<select id="meuSelect2">
    <option value="a">Delta</option>
    <option value="b">Épsilon</option>
    <option value="g">Digama</option>
</select>
<select id="meuSelect3">
    <option value="a">Zeta</option>
    <option value="b">Eta</option>
    <option value="g">Teta</option>
</select>
<input type="text" />

Como proceder no javascript?
Comment: `input.value += option.innerHTML;` ?
Comment: Somente com 3 selects?
Comment: @David No caso serão mais, porém mais do que 1 como exemplo já me serve para adaptar por aqui...
Answer: Ao utilizar o input.value = option.innerHTML;, toda vez que clicar em uma nova palavra do select, seu input ira receber um novo valor, mas o que queremos é concatenar os valores para formar uma frase, certo?
Conforme comentado pelo @Diego, recomendou utilizar o operador encurtado +=, que seria a mesma coisa de fazer:
input.value =  input.value + option.innerHTML;

Tabela com mais exemplos
operador    significado
x += y      x = x + y
x -= y      x = x - y
x *= y      x = x * y
x /= y      x = x / y
x %= y      x = x % y
x <<= y     x = x << y
x >>= y     x = x >> y
x >>>= y    x = x >>> y
x &= y      x = x & y
x ^= y      x = x ^ y
x |= y      x = x | y

Ou seja, para resolver seu problema, adicionei o operador e ainda mais um espaço no final, pois como no select são palavras, achei interessante.

var select = document.getElementById('meuSelect');
var input = document.querySelector('input');

select.addEventListener('change', function() {

  var option = this.children[this.selectedIndex];
  input.value += option.innerHTML + ' ';
});
div {
  display: inline-block;
}

  Palavras

  <select id="meuSelect">
      <option selected></option>
      <option value="a">Alfa</option>
      <option value="b">Beta</option>
      <option value="g">Gama</option>
  </select>

  Frase

  <input type="text" id="frase" />

Com a edição e 3 select:

var select1 = document.getElementById('meuSelect1');
var select2 = document.getElementById('meuSelect2');
var select3 = document.getElementById('meuSelect3');

var input = document.querySelector('input');

select1.addEventListener('change', function() {

  var option = this.children[this.selectedIndex];
  input.value += option.innerHTML + ' ';
});

select2.addEventListener('change', function() {

  var option = this.children[this.selectedIndex];
  input.value += option.innerHTML + ' ';
});

select3.addEventListener('change', function() {

  var option = this.children[this.selectedIndex];
  input.value += option.innerHTML + ' ';
});
<select id="meuSelect1">
    <option selected></option>
    <option value="a">Alfa</option>
    <option value="b">Beta</option>
    <option value="g">Gama</option>
</select>
<select id="meuSelect2">
    <option selected></option>
    <option value="a">Delta</option>
    <option value="b">Épsilon</option>
    <option value="g">Digama</option>
</select>
<select id="meuSelect3">
    <option selected></option>
    <option value="a">Zeta</option>
    <option value="b">Eta</option>
    <option value="g">Teta</option>
</select>
<input type="text" />
Comment: Já respondeu a pergunta, minimizar o código fica por minha conta...Vlw bro nota 10...
Comment: e Diego F Editei a pergunta, tornando explícito o objetivo, pois diferente da oportuna resposta, possui 3 select, como procedo no javascript? Desde já agradeço a atenção.
Comment: De maneira bem simples, adicionei mais 2 eventos, porém esses 2 eventos retornando para o mesmo `input`, talvez tenha alguma forma dinâmica de fazer isso para todos os select de um form por exemplo, mas ai seria mais complexo :)
Comment: estou com uma dificuldade neste código, pode me ajudar? Como eu devo proceder para que exista um título dentro do select ? Por exemplo: "Marcas" seria o título e "a,b,c" as opções. O que ocorre é que seu eu retirar o "selected" para mostrar a 1º opção como um título, quando eu clico ele realiza a função, porém ele trás a 1º e a opção selecionada... Exemplo no input ele trás "Marca c", pode dar um help?
Comment: Cara desconsidere, eu havia mudado o evento "change " para "click", com change funciona ok! vlw


Cron jobs not working anymore

Question: Cron jobs were working for months in the past but recently I had a high server load and now cron jobs aren't executing my php files (the same ones that were working before). When I check the cron log I see this which I believe has something to do with the issue:
(CRON) EXEC FAILED (/usr/sbin/sendmail): Resource temporarily unavailable
What do I need to do to fix this problem? I am running CentOS 7.
EDIT: I marked this as answered as I thought a process hanging was causing this issue. Today, I woke up and the same issue occurred. I wonder what could be causing this.
In the cron log, I see:
Oct 11 05:01:01 run-parts(/etc/cron.hourly)[25431]: starting 0anacron
Oct 11 05:01:01 run-parts(/etc/cron.hourly)[25444]: finished 0anacron
Oct 11 05:01:01 run-parts(/etc/cron.hourly)[25431]: starting 0yum-hourly.cron
Oct 11 05:01:01 run-parts(/etc/cron.hourly)[25450]: finished 0yum-hourly.cron
Oct 11 05:01:01 CROND[25434]: (CRON) EXEC FAILED (/usr/sbin/sendmail): Resource temporarily unavailable
Oct 11 05:01:01 CROND[25429]: (apache) MAIL (mailed 71 bytes of output but got status 0x0001

UPDATE:
I noticed two things that look off in my mail log.
Oct  8 14:01:39 postfix/local[12886]: 5180C2D098A5: to=<email@example.com>, orig_to=<N>, relay=local, delay=1.1, delays=0.07/0.01/0/1, dsn=5.1.1, status=bounced (unknown user: "n")
Oct  9 04:19:10 postfix/local[12452]: C8F762D012D6: to=<email@example.com>, orig_to=<apache>, relay=local, delay=0.22, delays=0.13/0.02/0/0.07, dsn=5.2.0, status=bounced (cannot update mailbox /var/mail/root for user root. cannot open file: Is a directory)

Comment: Seems out of resource. Check yours limits, file descriptors, max process, etc.
Comment: @FedericoSierra I've increased the `limits.conf` and also `sysctl.conf` but I am still getting the same error in cron log. What user does cron use? I've increased for `apache` user which is the user that executes my php files. Maybe something with sendmail?
Comment: Look in your sendmail or message logs to see if there are any relevant messages. Take appropriate action.
Comment: @lain I am checking the `mail` and `messages` log but most of it has to do with `postfix` and not `sendmail`. I do notice a lot of queued mails (600+) but that is with postfix, not sure if postfix and sendmail are one of the same?
Comment: okay restarting apache fixed the problem so now I have to investigate why apache is preventing my crons to stop working.
Comment: "cannot update mailbox /var/mail/root for user root. cannot open file: Is a directory)" So /var/mail/root is a directory, not a file?
Answer:
(CRON) EXEC FAILED (/usr/sbin/sendmail): Resource temporarily
  unavailable

This isn't a cron problem. from exec(3):

 The execl(), execle(), execlp(), execvp() and execvP() functions may fail
 and set errno for any of the errors specified for the library functions
 execve(2) and malloc(3).

From execve(2):

 [ENOMEM]           The new process requires more virtual memory than is
                    allowed by the imposed maximum (getrlimit(2)).

From malloc(3):

   ENOMEM
       Memory allocation error.

On most UNIX systems, any runaway process can consume enough resources to cause normal virtual memory allocations by non-runaway processes to also fail.
This is not a cron problem, it's a system resource, utilization, or tuning problem.
Comment: OP, I'm guessing your C7 box is a VPS or containerised system without swap.  When load increases, and no memory is available to fulfil cron's requests, what's a system to do?

Cron jobs not working anymore


Equivalent topology definitions

Question: Given any two absolute values on an arbitrary field k, one defines the absolute values to be equivalent if they define the same topologies. I am having trouble understanding how the following definitions of equivalent topologies T1 and T2 are the same.

Every set open under T1 is open under T2
Every T1-open ball contains a T2-open ball centered at the same point and vice versa.
Every T1-open set contains a T2-open set, and vice versa.

1 iff 2 is clear, but I'm having trouble with 2 iff 3.
In particular, say we fix e>0 and x, and consider the ball centered at x with radius e under T1. Why can't every arbitrarily small ball centered at x under T2 not be fully contained in the set. It seems that this could still occur while an arbitrarily shaped T2- open set is contained in the ball centered at x with radius e under T1.
Comment: Because it contains an open set w.r.t. $T2$ and therefore an open ball w.r.t. $T2$.
Comment: right, but why does that ball have to contain the original center x, why can't it just constantly jump around the center no matter how small e is.
Comment: I see what you mean now.  Let me think about it.
Comment: Thanks; I was thinking it would be some consequence of writing open sets as (infinite) unions of open balls centered at each point, but I can't quite figure it out.
Comment: Well I'm convinced you need to use the field properties.  My suggestion is to try proving it first for $p=0$ which should be easier.  Then see if you can generalize it.
Comment: I'll see if I can do it that way -- strange, I thought it would be trivial
Answer:
Do you ask why 2. requires a $T_2$-ball centered at the same point? You suppose that just a ball containing that center is enough? Or you suppose that just any ball jumping around $x$ is required?

If you have such a ball containing $x,$ no matter whether $x$ is its center or not, it definitely implies the existence of an open ball centered at $x.$ So, your condition is sufficient not necessary. cf. [Example 2.2, p. 232]{Analysis I, Herbert Amann}
If you have many $T_2$-balls that don't contain $x,$ what are they for? when we need one open ball centered at $x$ for all such points $x$ to show their containing set is also an open set in $T_2,$ by definition of open set. If you have many such balls but none containing $x,$ the definition is not satisfied.

Do you ask why can't every arbitrarily small $T_2$-ball centered at $x$ be fully contained in the $T_1$-ball?

If there is one such ball, it is already sufficient, why need more? there is an upper bound of the radius (in order to have the balls contained in the set, which is to be shown to be open in $T_2$), and consequently all smaller balls are contained in the $T_1$-ball, and so if the "arbitrarily small" that you want surpasses this upper bound, it doesn't hold.

Equivalent topology definitions


MySQL: Display only 200 characters from total value

Question: I have a MySQL table with a field named description, with a record like this:

Former cop Brian O'Conner partners with ex-con Dom Toretto on the opposite side of the law.Since Brian and Mia Toretto broke Dom out of custody, they've blown across many borders to elude authorities. Now backed into a corner in Rio de Janeiro, they must pull one last job in order to gain their freedom. As they assemble their elite team of top racers, the unlikely allies know their only shot of getting out for good means confronting the corrupt businessman who wants them dead. But he's not the only one on their tail. Hard-nosed federal agent Luke Hobbs never misses his target. When he is assigned to track down Dom and Brian, he and his strike team launch an all-out assault to capture them. But as his men tear through Brazil, Hobbs learns he can't separate the good guys from the bad.

How can I display first 200 characters of it? Like this:

Former cop Brian O'Conner partners with ex-con Dom Toretto on the opposite side of the law.Since Brian and Mia Toretto broke Dom out of custody, they've blown across many borders to elude authorities.
Answer: SELECT LEFT(description, 200)
FROM yourtable

relevant docs here.
Answer: Try this:
SELECT SUBSTR(description, 1, 200)
FROM your_table

You can find docs here
Answer: SELECT * FROM table ...
Then in PHP just:
echo substr($desc, 0, 200); //1st 200 characters

DOC
Comment: hey neal thanks please also answer this question too
http://stackoverflow.com/questions/7979513/mysql-multiple-row-as-comma-separated-single-row-separate-with
Comment: @SumitBijvani you tagged your question [tag:php], i gave you a php relevant answer
Comment: @Neal the third arg is the length not the ending offset. So 200 should be there ;)
Answer: SELECT SUBSTRING(`description`,1,200) as description FROM table

That will start at position 1 and go 200 characters, and return the field as 'description' which is easier for mysql_fetch_assoc()
Comment: Marco, that's incorrect (I just tested it on my db to be sure before posting). also, from the MySQL docs:
For all forms of SUBSTRING(), the position of the first character in the string from which the substring is to be extracted is reckoned as 1.
Answer: It is better to get the substring from the database rather than getting the whole string into PHP and then slicing it:
SELECT SUBSTRING(description, 0, 200) FROM TABLE_NAME


Override core permissions used for visualizing a page

Question: Is there is a way (without using any external module) to override the core drupal 7 pages access permissions , for example and by default you will not be able to access /admin/structure/taxonomy/tags page without having (Administer vocabularies and terms) permission , but I want the users to be able to access it if they have for example (Edit terms in Tags) permission
Answer: You can make it by writing a custom module that implements hook_menu_alter().
function mymodule_menu_alter(&$items) {
  $items['path/to/change']['access arguments'] = array('permission name');
}


Ear Training: How to figure out the key signature and chords used in a song

Question: I have just started learning music but i find it very difficult to recognize the chords used in a song and its key signature when it seems to be far too easy a task for other students.
Is there any specific exercises/tricks to getting a better ear for the not-so-gifted in this department?
Comment: A trick I heard of once is to hunt (by humming) a single note that seems to fit the music no matter what chord changes are happening.  This note will often be echoed in the melody or accompanying instruments or will fit especially well during the chorus.  Most of the time this note is the Key note.
Answer: What I do is not caring for the key signature. Not at the beginning at least. To a beginner, I would suggest to do likewise.
Let's say you hear a song in F major, with this chord progression: I-IV-V-VI-V-I.
If you don't know the key signature, just play the progression in any key, and it would be the same. It's far more difficult to find the progression rather than the key. After you've successfully found the progression, you can compare it with the original song (while you play piano/guitar) and see what the key is.
Now, as far as the chord progression, I would suggest to you to try and focus on the bass of the chords'. Follow the movement of the bass, because that is what gives the chord its name. You can start by simply identifying intervals rather than chords. After you've gotten better at intervals, you'll be able to recognize the movement of the bass and then you should focus on the quality of the chord.
For instance: You hear a C major chord, and the bass moves to F. What is the quality of the chord? Major? Minor? Diminished?
After you've found the  quality, you should try and think: "In the C major scale, what kind of chord could there be with F as a bass and the quality X?"
Answer: I'm sure there have been very similar questions posed here, however - The final chord in most songs is the key, or root chord. This needs to be established first. As Shev. says, the bass will often play that root note, so it becomes easy to find.
It will also tell if a song's in major or minor. Having found that, by matching it with a chord played on an instrument simultaneously, a set of chords to complement that will be necessary. Working from the major perspective, I,ii,iii,IV,V,vi will be the list to take chords from. As in Cmaj., say. C, Dm, Em, F, G, Am will be the most commonly used chords. The first 'main' chord will often be the key chord, too. So, if it is, then the next chord, if also major, will be a 50/50 between F or G. If the progression moves to a minor, there's a 33% chance of just guessing. Not bad odds either way!
I feel this is maybe easier to do whilst listening to the song, rather than taking a random key and trying to play the song in that key - unless, of course, one only knows a few chords that fit in a key.
Start with simple songs - Happy B'day, Jambalaya are a couple. Bear in mind that usually the two most prevalent chords are I and V - two chord songs generally only use those.
Key signature is really a different issue - you maybe just meant key?
Comment: Thank you for the answers...I am also trying the ear trainer pro s/w...but I have a long way to go with that. There are no short cuts to getting a good ear I guess....unless you are one of those god gifted ones
Comment: Just listen to the radio, etc., and try out these ideas with each and every song. You will find they'll bear fruit, sooner or later.


How do you show that $e_{I}^{*}(e_{J}):=\delta_{I,J}$ is a basis for $(\Lambda_{k}V)^{*}$, $\Lambda_{k}V:= V^{\otimes k}/A$?

Question: In Tu's book "Geometry" there is the following statement on page 171:

I would like to show that $span\{e_{I}^{*} \}=(\Lambda_{k}V)^{*}$. For some reason I get completely confused by all the indices. I tried the following so far, which is I think more or less the same as in the case of $V^{*}$, which is often done in a first course in linear algebra
Question:
How do I get the inidices right in the following computations?
Let $\phi\in(\Lambda_{k}V)^{*}$. Then $\phi(v_{1}\wedge...\wedge v_{n})=\phi((\sum v_{i_{1}}e_{i_{1}})\wedge...\wedge(\sum v_{i_{n}}e_{i_{n}}))$. Then I would use the multilinearity of $\phi$. Then
$\phi((\sum v_{i_{1}}e_{i_{1}})\wedge...\wedge(\sum v_{i_{n}}e_{i_{n}}))=\sum_{I} v_{i_{1}}...v_{i_{n}}\phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})$, $I:=(i_{1},...,i_{n})$.
This is where I get stuck, because I think that's not the right way of writing it down.
Next I would look at $\sum \phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})e_{I}^{*}$ and evaluate it on $v_{1}\wedge...\wedge v_{n}$. Hence,
$\sum_{I} \phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})e_{I}^{*}(v_{1}\wedge...\wedge v_{n})$
$=\sum_{I} \phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})e_{I}^{*}((\sum v_{j_{1}}e_{j_{1}})\wedge...\wedge(\sum v_{j_{n}}e_{j_{n}}))$
$=\sum_{I,J} v_{j_{1}}...v_{j_{n}}\phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})e_{I}^{*}(e_{j_{1}}\wedge...\wedge e_{j_{n}})$
$=\sum_{I,J} v_{j_{1}}...v_{j_{n}}\phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})\delta_{I,J}$                 (Again, I am not sure about the indices.)
$=\sum_{I} v_{j_{1}}...v_{j_{n}}\phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})$.
From which I would conclude that
$\phi=\sum_{I} \phi(e_{i_{1}}\wedge...\wedge e_{i_{n}})e_{I}^{*} $
Thank you very much in advance!
Answer: $(e_J)_J$ Forms a basis for the space. For each $J$, $e_J^{*}$ is a linear map $\Lambda^{k}(V)^{\vee}\rightarrow \mathbb{R}$  defined by its action on the basis then extended linearly. Namely, $e_J^*(e_K)=0$ if $J=K$ and 0 otherwise.
More generally, if $V$ is finite dimensional with basis $e_1,...,e_n$, then the dual basis, $(e_j^*)_j$ are defined as above. Namely, $e_j^*(e_i)=\delta_{i,j}$. Once you show that the dual basis, in this general case, is infact a basis, then you get what the author wrote for free.
Comment: Thanks for the answer, but that is not the answer I am looking for. I am aware of that too. It was meant as a little execise in dealing with multi-linear functions and multi-indices.


Remove fields from dialog window

Question: How can I remove fields from the CKEditor dialog window?
In my case, I need to remove the "Caption" field from the "Table Properties" window. How can I do that?
Answer: The solution is simple: remove the caption tag from the allowed HTML tags in "/admin/config/content/formats" :-)

Remove fields from dialog window


Mocha, go to the next file after timeout

Question: I'm running my test files with script
"test": "node_modules/.bin/mocha *.test.js

but in the first test I'm sending to my Node.js server while(1); and causing it to timeout, simultaneously failing that test. That's the intended behaviour but how do I make mocha run the rest of the files after that?
Answer: There is an issue in Mocha's repository for your case.
Infinite loops seem to escape timeouts #1609

TL:DR
This is not possible in mocha(because of how node works).
You can read the interesting discussion about this problem.
The reason it blocks all the code is because of how node works.
The code is executed line by line totally in syncronous way.
The async magic happens with the node event loop .
But when you run infinite  loop the event loop will be blocked because only one event can run at a time, and this event will never end:)
Comment: Yep.  Busy waits are death in Node


How to sort an arraylist of type class with respect to two elements(two columns) in it

Question: I'm having an arraylist(arrList) of type 'class'(Info).The class 'Info' is having two properties called 'case' and 'step' of type long. I need to sort the arraylist in ascending order by comparing both the properties in class Info.
<code>//scrambled list
arrList={[#case,#step],[2,1],[1,4],[2,2],[1,2],[1,3],[1,1],[2,3],[2,4],.....}

//Output I need
arrList={[#case,#step],[1,1],[1,2],[1,3],[1,4],[2,1],[2,2],[2,3],[2,4],...}

</code>
I'll make it more clear.For example,
Case 1 is having Steps 1,2,3,4 &Case 2 is having Steps 1,2,3,4
So, here I need the arraylist like case and step sorted together([1,1] ,[1,2],[1,3]...)
I tried with the code given below.
<code>        for (int i = 0; i < arrList.size(); i++) {
            for (int j = i+1; j < arrList.size(); j++) {
                long tmp1Case=arrList.get(i).getCase_ID();//case id value --i
                long tmp1Step=arrList.get(i).getStep_ID();//step id value --i

                long tmp2Case=arrList.get(j).getCase_ID();//case id value --j
                long tmp2Step=arrList.get(j).getStep_ID();//step id value --j

               if (tmp1Case>=tmp2Case && tmp1Step>tmp2Step ) {
                    Info tmp = new Info();
                    tmp = arrList.get(i);

                    arrList.get(i).setStep_ID(arrList.get(j).getStep_ID());
                    arrList.get(i).setCase_ID(arrList.get(j).getCase_ID_ID());

                    arrList.get(j).setStep_ID(tmp.getStep_ID());
                    arrList.get(j).setCase_ID(tmp.getCase_ID());
                }
            }

        }

//printing the arraylist ...

</code>
Output is wrong. Help me out. Thanks in advance
Answer: The easiest way to do it is to make Info implement comparable.  Then you just have to implement the compareTo function that handles your cases and will return 0 if they are the same 1 if the the comparison is greater than and -1 if it's less than.  Than you can just use Collections.sort(arrList) https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
Answer: Assuming you have java 8 or higher and further assuming you have the getters for both properties:
<code>arrList.sort(Comparator.comparing(Info::getCase_ID).thenComparing(Info::getStep_ID));
</code>
Comment: It shows error : cannot find method sort(Comparator)


Why use mutual information if it is just a function of correlation?

Question: (This question differs from a similarly titled one because mine focuses instead on the analytical solution of mutual information as a function of correlation, its usage, and its seeming pointlessness as a replacement to correlation.)
The closed-form analytical solution for mutual information (a scalar) between two jointly Gaussian distributed random variables $X$ and $Y$ is $$I(X,Y) =-\frac{1}{2}\ln(|\rho|)$$ where $\rho$ is the joint correlation matrix between $X$ and $Y$.

If $I(X,Y)$ can pick up non-linear co-dependencies that correlation can't, why do I not see this indicated anywhere in the above formula?
If $I(X,Y)$ is just a re-expression of correlation as shown above, what's the point of even switching to mutual information from correlation?
Is $I(X,Y)$'s advantage of picking up full co-dependencies that correlation can't only apparent for joint non-Gaussian variables, where the above analytical solution does not apply?
Comment: Isn't that for when the bivariate distribution is *jointly* Gaussian? Two Gaussian distributions can be uncorrelated yet most definitely not independent.
Comment: thanks for the correction
Answer: When a bivariate distribution is jointly Gaussian, it means that the dependence structure is correlation.
Therefore, mutual information and correlation magnitude between the marginals become synonyms.
Note, however, that the mutual information does not give you the direction of correlation (nor should it).
Comment: When the bivariate distribution is not jointly Gaussian, then correlation doesn't tell the whole story. You might be interested in this answer: https://stats.stackexchange.com/a/30205/247274. There's a relationship between mutual information and copula.
Comment: Then your $\frac{1}{2}\log(\vert\rho\vert)$ formula does not apply.
Comment: When the bivariate distribution is bivariate Gaussian, Pearson correlation is the parameter of the Gaussian copula. Pearson correlation captures all of the dependence structure, so all of the mutual information. Mutual information would be more useful when there is a funkier dependence structure, say an X shape instead of a slash or backslash.
Comment: and non-Gaussian joints? what about them
Comment: when the analytical solution no longer applies, then does the non-analytical stand-alone formula for mutual information suddenly have an upper hand over correlation? i.e. is it no longer a function of correlation whatsoever?
Comment: Even if there is a relationship, what good is mutual information if it is just merely equal to the entropy of a bivariate copula? why should the measurement of a joint distribution's dependence structure using copula be overhauled by measuring that same dependence structure's entropy? what is the added value
Comment: The mutual information summarizes the copula in a single number, which is easier to manage and perhaps easier to estimate.
Comment: But Spearman's rank correlation and Kendall's tau do too, so what? And actually mutual information is the most difficult to estimate of all of them
Comment: When you say mutual information and correlation are synonyms for a Gaussian joint distribution, you're not saying that they are *equivalent* are you? since $I(X,Y) =-\frac{1}{2}\ln(|\rho|)$, which is not equivalent
Comment: No, they're not equal, but if you know one, you know the (magnitude of) the other.


GNU Make dynamically created variable name

Question: This is my make recipe, I'm passing nonle value *, although bamboo_nonle_password variable is having password, still function is failing
validatevar.%: $(if $(IS_BAMBOO),)
        @echo "\n################################################################################"
        @echo ">>> validatevar"
        @echo ">>> Start: Validate bamboo variables "
ifndef bamboo_$*_password
        @echo "Bamboo variable bamboo_$*_password is empty"
        exit 1
endif
ifndef bamboo_$*_server
        @echo "Bamboo variable bamboo_$*_server is empty"
        exit 1
endif
        @echo "<<< Done: validatevar"
        @echo "################################################################################\n\n"

Comment: why is this extra comma here, `validatevar.%: $(if $(IS_BAMBOO),)` ? perhaps you can have 1 or 0, so that you can do like `IS_BAMBOO=1` like that.
Comment: yeah, that is also possible, anyhow it still works, I will change that in my code. but the real problem is in the generating variable name dynamically i.e generating bamboo_$*_password variable name.
Answer: You crazy person :)
Make will expand the recipe just before it wants to execute it.
At this point make knows what the % corresponds to,
and so can ensure $* is set appropriately.
Unfortunately, the ifndef…endif pair is evaluated as the makefile is read,
not as the recipe is expanded.
This suggests the answer:
use macros.
Maybe $(origin …) or $(flavor …) in something like
validatevar.%:
    @echo
    $(if $(filter undefined,$(origin bamboo_$*_password)),@echo "Bamboo variable bamboo_$*_password is undefined")
    $(if $(filter undefined,$(origin bamboo_$*_password)),exit 1)

Naturally you can tidy this up a bit.
Maybe:
die-if-undefined = $(if $(filter undefined,$(origin $1)),$(error "$1" is undefined))

validatevar.%:
    $(call die-if-undefined,bamboo_$*_password)
    $(call die-if-undefined,bamboo_$*_server)
    @echo
    @echo

Two things to note:

The whole of the recipe is expanded in one go, before any of the lines are executed.
The upshot of this is that it doesn't matter where you expand the $(error) assertions.
I have put them at the top.
ifndef also detects empty variables, as well as undefined ones. You may wish to adjust die-if-undefined to take account of this (and rename it to die-if-empty).

(This would all be a lot easier if make would only take a --error-undefined-variables parameter,
just to match the existing --warn-undefined-variables parameter.)


Cannot Enter Credentials Over UAC Prompts During Remote Assistance

Question: We are using SonicWALL firewall devices throughout our network. We use the SonicWALL Virtual Assistance tool for remote desktop assistance. Since our systems are not in a workgroup and are on a domain, we face problems when the UAC prompts appear.
As a workaround, we edited the UAC policies such as switching to secure desktop-disable, Allowing UI Acess applications to prompt for elevation without using secure desktop-Enable, etc. The ultimate result was we are able to see the UAC prompt on the remote user system, but we are not able to interact with it and are not able to enter credentials to it.  I can see the password being entered if it is done by the local user. However, we cannot interact with the UAC prompt window remotely. Is there any solution for this?
Answer: One possible solution is to use SCCM. When using remote tools in SCCM you can type in the UAC prompt.
Answer: Enabling the following group policy option on workstation computers may allow you to remotely interact with UAC prompts. This is needed for Microsoft's built-in remote assistance facilities.
Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Security Options\User Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktop
Answer: No there is no solution for this. This is the intention of the UAC dialog that there is no interaction possible. So malicious code or malicious people can't run any code as administrator.


Fazer logout quando browser fechar ou sessão finalizar

Question: Estou desenvolvendo um sistema que armazena no banco de dados quando usuário faz login e logout. Porém, a função de logout só é chamada quando o usuário clica em sair.
Queria saber se tem como chamar a função de logout quando o browser fechar ou a sessão finalizar.
Comment: Se a solução linkada acima ou resposta abaixo não resolver, queira [edit] a postagem detalhando melhor as peculiaridades e requisitos do seu caso.
Answer: Você poderia tentar utilizar a função 'onunload'

outra alternativa:


Converting XML element into string and again string to XML file in python

Question: How would I convert an XML element into string and a string back to XML format using xml.elementtree in web2py ?
Thanks !
Answer: Using the standard library, you'd use the StringIO writer and the parseString function:
>>> from StringIO import StringIO
>>> from xml.dom.minidom import parseString
>>> e = parseString('<foo/>')
>>> out = StringIO()
>>> e.writexml(out)
>>> s = out.getvalue()
>>> print(s)
<?xml version="1.0" ?><foo/>
>>> e2 = parseString(s)

Answer: Use parseString to get xml element from string and toxml to make string out of xml element. Something like this.
from xml.dom.minidom import parseString

dom = minidom.parseString(content)
...
# do some changes to dom here
return dom.toxml()


How to restrict access to a specific node to to an individual user

Question: I am trying to see if I can put together a D9 site for this person how designs custom 3D images and animations. I'm working on a way to have him sell the files once completed, but first I need a way for him to preview the file for the client while he's working on it. For this to work, I need a way to restrict viewing of the node/image so only the logged in client can see it.I looked at the modules that I thought might work, and so far only Taxonomy Access Control comes close, but I'm not sure if it does what I need. Does anybody have any ideas what might be what I'm looking for?
Answer: Here is a relatively easy way to do this without writing code.
Assumptions

There is one designer who has multiple clients.
The designer should have access to everything, while each client should only have access to that client's designs from the designer.

How to implement

Give the designer all content administrator permissions. This will let the designer create, update, and delete content as needed.
Create a custom content type and name it however you like (for this example, we'll call it Designs).
Set up accounts for clients with the authenticated role.
Give the authenticated role permission to "view own content" for the Designs content type.  Do not give authenticated users the permission to edit or delete Designs content (or, more broadly, all of their own content).
When the designer creates a Design node for a client, in the admin UI, assign the client as the author of the node.

Because the client is the node author, they will be able to view the content (since it is their own content, because they are assigned as the author) but nothing else (based on the permissions configured above).
Comment: That sounds a lot easier than what I tried. I installed Node Access module and set it up similar to how you described. I'm not sure which would work the best in the long run, but you way sounds much less complicated.


Camel Iterator or How to use Camel Splitter but keep body unchanged

Question: I want to iterate String with a delimiter "," and then send message to several endpoint. The problem is if I use Splitter, it would replace the body content of my message.
from("switchyard://ICamelServiceProcess")
.process(new Processor() {
String recipients = "abc";
recipients += "," + "bcd";
exchange.getIn().setHeader("recipients", recipients);
}
.to("switchyard://ICamelServiceRoute");

In Service ICamelServiceRoute, I want to iterate through header.recipients value with delimiter "," and then create a file with a named of each iteration.
Could you please tell me some solution.
Thank you.
Comment: You should be able to do this with a [recipient list](http://camel.apache.org/recipient-list.html).
Comment: I did take a look at recipient list, routing slip, splitter. The problem with recipient is I must create before-hand many services. Now I try to use recipient list point to the same service. Like this:
recipients += "," + "switchyard://ICamelServiceRoute?operationName=routeMessage";
The different between recipient is to use different parameter. But I dont know how to pass parameter. Could you tell me how?
Comment: I am not sure I understand your question. I understood that you would like to create a varying number of files, the file name representing a "recipient", all files with the same contents, the contents being the body of your exchange. Is that not correct?
Comment: That's correct. Until now, I have no clues to solve this. Can you help me, please?
Comment: So why does the recipient list not work for you? Is it because you need to do things in switchyard?
Comment: After many hours trying many things, I realized my sillinest. Thanks Ralf, I can solve this problem.
Comment: Kindly update the answer you fix that will useful for others.
Answer: You can save the original body in a exchange property before the splitter, and restore it from the property when finish splitter. With Camel 2.15 or latter
<setProperty propertyName="originalBody">
    <simple>${body}</simple>
</setPropery>
<split>

</split>
<setBody>
    <simple>${exchageProperty[originalBody]}</simple>
</setBody>

All exchange properties will be deleted when finish the camel context execution. Note that you can save Java Object in exchange properties, but only until the camel context ending


How do I translate a views field to lowercase and with spaces replaced with dashes but not make it a link?

Question: I've got a link that surrounds some code (jquery hexagons). I'd like to be able to just print out the link.
The solution
Firstly, 2 copies of the 'studio name field'. The second set to 'rewrite as link' with the translations.
Secondly, 'exclude from display' both fields.
Thirdly. Custom text to print out the hexagon.

[field_studio_name]

        [field_studio_address]

[field_studio_name]

        [field_studio_address]

If I use the 'rewrite as link' replacement then I get
 <a href="/studio/">

If I use the raw version I am stuck with

Here is a fiddle with a views export that demonstrates the problem.
Comment: Can you please add what field you have and what you want in output. I will send export file of view.
Comment: Hi @PankajYogi The 'custom text' is what I want. It is easy to show, I'll attach an export.
Answer: You want link all output with studio/my-studio .First convert My studio to lowercase then rewrite as link  custom text.
Think My studio is [field_studio_name_1] .Convert this to lowercase. Then rewrite as link custom text like this .
Comment: ah - of course. You can rewrite in the link text too. Nice.
Comment: Is it working ?
Comment: Yes - nicely https://www.yogahive.com.au/students/find-the-right-yoga-class-for-you
Comment: Great Is that Your personal account on drupal.stackexchange ?


Good text on Clinical Trials?

Question: I'm an undergraduate statistics student looking for a good treatment of clinical trials analysis. The text should cover the fundamentals of experimental design, blocking, power analysis, latin squares design, and cluster randomization designs, among other topics.
I have an undergraduate knowledge of mathematical statistics and real analysis, but if there's a fantastic text that requires a bit higher level of statistics or analysis, I can work up to it.
Answer: I would definitively recommend Design and Analysis of Clinical Trials: Concepts and Methodologies which seems actually the most complete one given your request.
Statistical Issues in Drug Development also covers a broad range of concepts but is less oriented toward design of experiment. Statistics Applied to Clinical Trials includes more technical stuff, but mainly focus on crossover trials and applications in epidemiology. And there is always the most famous Rothman, Modern Epidemiology, which provides valuable help for interpretation and examples of application of clinical biostatistics. Finally, The Design and Analysis of Clinical Experiments is more centered onto the analysis of specific experimental settings, but it does not address other points and is a bit older.
Answer: It's difficult to go past Piantadosi's Clinical Trials: A Methodologic Perspective at least as a starting point. It is quite comprehensive and covers the topics you want and much more - including ethics, history, reporting, fraud, meta-analyses, randomisation, phases, stopping rules etc. - at an advanced undergraduate to early post-grad level.
The few times I was frustrated with it (the 1st edition anyway) where when it lacked sufficient detail - eg the derivations for sample size calculations. A comprehensive starting point!
Answer: Experimental Design for the Life Sciences, by Ruxton & Colegrave, is a nice book and is aimed primarily at undergraduates.
Answer: I was using "Fundamentals of Clinical Trials" when I was in PhD program.

Good text on Clinical Trials?


Como usar um contador em variável global?

Question: Clique para testar!
O meu objectivo é que a variável count obtenha o valor que vai acumular na função arrayVec1, mas ao invés disso obtenho sempre o resultado 0.
Alguém me pode dizer como consigo passar o valor para fora da função e atribuir à variavel global?
Código:

//cout if exits
var count=0;

var vec = new Array();
var vec1= new Array();
var tag1="wedding ball evening gown";
arrayVec();

function arrayVec() {
$.getJSON("http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?",
        function (jd) {
            for (var i = 0; i < jd.items.length; i++) {
                vec.push(jd.items[i]);
            }
            arrayVec1();
        });
}

function arrayVec1() {
 for (var i = 0; i < vec.length; i++) {
         $.getJSON('http://www.flickr.com/services/feeds/photos_public.gne?tags='+"ball"+'&format=json&jsoncallback=?',
         function (jd) {
            for (var i = 0; i < jd.items.length; i++) {
                  if (tag1 ===  jd.items[i].tags) {
                    count++;
                   }
            }

        });

    }
}

alert(count);
Comment: Possivel duplicata: http://pt.stackoverflow.com/q/60852/129
Comment: Possivel duplicata também: http://pt.stackoverflow.com/q/58566/129
Answer: Ana, o problema é que o $.getJSON é assincrono.
O valor de count vai ser mudado como tu esperas mas depois do teu alert. Ou seja, o $.getJSON vai correr paralelamente, assincrono, e vai dar resposta depois de script ter chamado o alert.
Tens de usar o count dentro dessa callback do $.getJSON. Podes por exemplo testar:
setTimeout(function(){
    alert(count);
}, 1000);

e vais ver que esse 1 segundo de espera já vão mostrar o count com o novo valor.
O count vai ter o valor final na linha a seguir a este loop:
for (var i = 0; i < jd.items.length; i++) {

Se quiseres podes é chamar uma função depois desse loop. Da mesma maneira que funcionaria colocar o alert(count); aí, dentro dessa callback.
Exemplo: http://fiddle.jshell.net/d4h0ykj9/2/


Differentiating products and quotients

Question: I am studying maths as a hobby and have come across this problem:
Differentiate with respect to x:
$\frac{(x^2 + 1)(x - 1)^2}{(2x - 1)}$
Now if we say  $u =(x^2 + 1)$ and $v = (x - 1)^2$ and $w =(2x + 1)$ I would know how to find $\frac{dy}{dx}$ if the problem was $y = uv$ or $y = \frac{u}{v}$ but I cannot solve this, which involves 3 elements.
I have tried multiplying out the numerator to get a single equation but still cannot get the right answer.
The book answer is $\dfrac{2x(x - 1)(3x^2 - 3x + 2)}{(2x - 1)^2}$
I have eventually boiled it down to this:
$$\frac{dy}{dx} = \frac{ (2x-1)\{(x-1)^2\cdot 2x + 2(x^2+1)(x-1)  \} - 2(x^2+1)(x-1)^2 }{(2x-1)^2}$$
Comment: If you wish to use chain rule, take $w = \frac{1}{2x+1}$. Now you have $y = uvw$ and $y' = u'vw + uv'w +uvw'$
Answer: HINT:
Use logarithmic differentiation.
$$y=\frac{(x^2 + 1)(x - 1)^2}{(2x + 1)}$$
$$\ln y=\ln(x^2 + 1)+2\ln(x - 1)-\ln(2x+1)$$
$$\frac 1y \frac{dy}{dx}=\frac{2x}{1+x^2}+\cdots\cdots$$
This is particularly useful when you have multiple functions multiplied/divided or if in powers.
Comment: It's likely that the derivative of a logarithm has not yet been covered, given the nature of the problem and the OP's unfamiliarity when both the product and quotient rules are used together. Later, however, logarithmic differentiation is certainly one way of approaching this.
Comment: @DaveL.Renfro I understand. I'll let this be as it is, since another answer has been added addressing OP's needs
Answer: Just apply the rules as you need to. To make the procedure more clear, I'll use $u,v,w$ for the pieces in your problem (you can use the original pieces and actually perform the indicated differentiations).
The overall form is a fraction, so first use the quotient rule:
$$\left(\frac{uv}{w}\right)' = \frac{(uv)'w - (uv)w'}{w^2}$$
Then in the numerator, you see $(uv)'$, which needs the product rule
$$(uv)' = u'v + uv'$$
So put it together to get
$$\left(\frac{uv}{w}\right)' = \frac{(u'v + uv')w - (uv)w'}{w^2}$$
and simplify as needed. You typically may need to rearrange the result to get it to match the form of the answer in the book, but that shouldn't be too hard.

Addendum: Check your work. I see $(2x+1)$ in the original denominator, but you have $(2x-1)$.
Comment: Add the book's answer and your work at the top so we can see where you went wrong
Comment: Note that you seem to have $(2x-1)$ in the denominator, but the original problem has $(2x+1)$, so one of them must be wrong
Comment: I worked with your expression and was able to reduce it to the book's answer. Are you still having trouble? Note that you can factor a $2(x-1)$ out of the expression in curly braces $\{\cdots\}$, so it will factor out of the whole numerator. Then work **carefully** with what's left in the numerator.
Comment: Thanks MPW. I solved it using your method.  Took me ages but I now feel I have a much better understanding.

Differentiating products and quotients


Prolog: How to perform term expansion on input from shell?

Question: I am writing a module A which defines term_expansion/2. As a side-effect, when it becomes imported by module B, the terms defined in module B will be expanded as described in module A. However, I did not manage to also expand the terms which come from shell, after a user has loaded B using ?- [B]. in an interactive session.
How do I manipulate the queries/directives which come from shell and call them instead?
Example:
If the user types
?- my_append("AB", "CD", L).

I want to expand the my_append-term to something like this (but not restricted to it) which is then called after expansion:
?- extra_args(A0, A1), my_append_with_extra_args(A0, A1, "AB", "CD", L).

To be clear: The term-expansion/-manipulation itself is not the problem – what I need to know is the hook which can I use/redefine like term_expansion/2.
Comment: just import module A from REPL: `?- [a].`
Comment: @CapelliC A solution, which does not require the user to remember always importing `A` before starting a session, would be preferable.
Answer: The predicate I was looking for is expand_query/4.
Comment: Does a simple `goal_expansion/2` rule not suffice? This way, you could use the goal also within your programs, not only from the query.
Comment: @mat `goal_expansion/2` triggers too often. Performing a simple `?- append("a","b",L).` triggers it four times, instead of one time. Also, it is triggered during the `term_expansion/2`-process – and that is not what I am looking for.
Comment: @mat Surprisingly, I still haven't found a way to [expand Prolog queries](https://stackoverflow.com/questions/46614561/implementing-partial-evaluation-in-swi-prolog) using `goal_expansion/2`. Is this possible somehow?


break line issue in javaScript?

Question: I am receiving a comments from service.
If I get this comment "hello world" it is printing as it is but when I receive Comments like this
"hello
world" then I am receiving nothing I write a function for it but it also doesn't work
function NextLineFix(Call) {

        return Call.replace("\n", '
');
    }

Can any body help please....!
Answer: Perhaps you also have carriage return characters in the string ('\r')? Does this work better for your issue:
Call.replace("\r", "").replace("\n", "
") ?

Answer: try this:
function NextLineFix(Call) {
    return Call.replace(/[\r\n]/gi, '
');
}

Comment: In this function i am unable to print "" means i want to print the whole text "hello" including "" how can i achieve this can you please solve this????
Comment: try this: return '"' + Call.replace(/[\r\n]/gi, '') + '"';
Answer: Try it with \r\n instead of \n and then do the replace , see if that helps
Comment: Can you check to see what is in call variable? Does it contain the hello world? or does it show unterminated string constant?
Comment: it has "hello world" and remains hello world no change occur

break line issue in javaScript?


Parâmetro pelo Ajax

Question: Estou precisando passar alguns argumentos pelo Ajax, a princípio o código apresenta erro de sintaxe.
            var comeco = $("data_filtroe").val();
            var fim = $("data_filtrod").val();
            jQuery.ajax({
                type: "get",
                url: "status_relatorio.php",
                data: "comeco="+comeco+" && fim="+fim,
                success: function(data){
                    document.querySelector('#status_dia').innerHTML = data;
                }
            });

Código PHP("status_relatorio.php"):
<?php
session_start();
$con = mysql_pconnect("localhost","root","eeep_#2017");
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
mysql_select_db("alunos",$con);
setlocale( LC_ALL, 'pt_BR', 'pt_BR.iso-8859-1', 'pt_BR.utf-8', 'portuguese' );
date_default_timezone_set( 'America/Fortaleza' );
$data_inicio = $_GET['comeco'];
$data_fim = $_GET['fim'];
$data="";
for ($i=$data_inicio; $i <= $data_fim; $i++) {
    if($data==""){
        $data = "data = ".$i;
    }else{
        $data = "and data = ".$i;
    }
}
if($data_inicio==$data_fim){
$data = "data=".$data_inicio;
}
$sql = "select * from ocorrencias where '$data' order by curso, nome_aluno asc";
$resultado = mysql_query($sql,$con);
$cont = 0;
$falta = 0;
$falta_justificada = 0;
$fardamento_incompleto = 0;
$es_autorizada = 0;
$indis = 0;
while($linha1 = mysql_fetch_array($resultado)){
    $cont++;
    if($linha1['tipo']=="Falta"){
        $falta++;
    }
    if($linha1['tipo']=="Falta Justificada"){
        $falta_justificada++;
    }
    if($linha1['tipo']=="Fardamento Incompleto"){
        $fardamento_incompleto++;
    }
    if($linha1['tipo']=="Entrada/Saída Autorizada"){
        $es_autorizada++;
    }
    if($linha1['tipo']=="Indisciplína"){
        $indis++;
    }
}
        echo "

                Faltas: ".$data_inicio."
                Faltas Justificadas: ".$falta_justificada."
                Fardamentos Incompletos: ".$fardamento_incompleto."
                Entradas/Saídas Autorizadas: ".$es_autorizada."
                Indisciplína: ".$indis."
                Total: ".$cont."

";?>

Comment: Continuou sem dar certo. Erro : Notice: Undefined index: comeco in C:\xampp\htdocs\Sistema - Controle Geral de Alunos\status_relatorio.php on line 11

Notice: Undefined index: fim in C:\xampp\htdocs\Sistema - Controle Geral de Alunos\status_relatorio.php on line 12
Comment: Eu fiz isso... código de receber... $data_inicio = $_GET['comeco'];
 $data_fim = $_GET['fim'];
Comment: @CarlosHenrique Dá uma olhada na minha resposta e nos meus comentários nela. Utilize `$_POST["comeco"]`, `$_POST["fim"]`.
Comment: Outra coisa... Há inúmeros erros em seu código. O mais grave é que você está utilizando a extensão `mysql` que foi removida completamente no PHP 7 e depreciada  desde a versão 5.4 do mesmo.
Comment: Outra coisa... É bem mais fácil, simples, rápido e prático você realizar uma consulta separada da outra baseado no `tipo de falta que você quer`... Ou utilizar `COUNT()` e `GROUP BY`.
Comment: @GodfreytheKing Não posso usar a função group by, porque preciso mostrar exatamente todos os valores.
Comment: Como eu disse... Você pode utilizar `COUNT()` baseado no tipo que vc deseja e agrupá-los. Você tem 5 tipos diferentes, certo? É só você contar as linhas que possuem o `tipo X` e agrupar nesse tipo, contas as linhas que possem o `tipo Y` e agrupar. Dessa forma, o `SELECT` vai retornar apenas 5 linhas.
Answer: De acordo com a documentação do jQuery você precisa enviar dados no formato PlainObject, String ou Array.

data Type: PlainObject or String or Array Data to be sent to the
  server. It is converted to a query string, if not already a string.
  It's appended to the url for GET-requests. See processData option to
  prevent this automatic processing. Object must be Key/Value pairs. If
  value is an Array, jQuery serializes multiple values with same key
  based on the value of the traditional setting (described below).

Escreva o código abaixo:
        // Supondo que "data_filtroe" é uma classe.
        // Se for um ID, utilize $("#data_filtroe").val();
        var comeco = $(".data_filtroe").val();
        // Supondo que "data_filtrod" é uma classe.
        // Se for um ID, utilize $("#data_filtrod").val();
        var fim = $(".data_filtrod").val();
        jQuery.ajax({
            method: "POST",
            dataType: "json",
            url: "status_relatorio.php",
            data: { "comeco": comeco, "fim": fim },
            success: function(data){
                document.querySelector('#status_dia').innerHTML = data;
            }
        });

Lembrando que:

GET - Busca, requer, solicita dados de algum lugar especificado.
POST - Envia os dados para serem processados em algum lugar especificado.
Comment: Não deu certo, não apareceu nada.
Comment: `data: { "comeco": comeco, "fim": fim }` este trecho está enviado as duas variáveis para o script PHP `status_relatorio.php`. No PHP, você deverá recuperar as variáveis através de `$_POST["comeco"]` e `$_POST["fim"]`. E por fim, no seu arquivo PHP, para devolver algum tipo de informação para a requisição `Ajax`, você deve fazer `echo json_encode("Olá mundo, estou saindo do PHP e voltando ao JS");`
Comment: O código não retorna nada, quando uso esse código.
Comment: Editei minha resposta, dê uma olhada. E também poste o código PHP na sua pergunta.

Parâmetro pelo Ajax


Mostrar data na MessageBox C#

Question: tenho um vetor de datas com os valores já inseridos, porém queria mostrar os valores um a um, então criei um "for" que fizesse isso
DatasIndisponíveis é o meu vetor de datas, com os valores já alocados;
string mens;
 for (int i = 0; i <= 5; i++)
  {
   mens += @DatasIndisponiveis[i].ToString();
  }
 MessageBox.Show(@mens,"Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);

Ele simplesmente não executa a Messagebox logo depois de receber o valor do formato data ( Parece que como a data vem no formato dd/mm/yyyy ele não consegue usar as "/")
Answer: porque dos @ no nome das variáveis ?
se você tem um array de datas, ficaria assim:
DateTime[] datas = new DateTime[5];
string msg = "";
for(int i =0; i< datas.Lenght; i++)
     msg += datas[i].ToShortDateString()+"\r\n";

MessageBox.Show(msg);

Comment: O "@" nas variáveis era alguns testes que esqueci de retirar. Pois bem, fiz como você descreveu e mesmo assim continuou meu erro. Meu array está declarado por [List DatasIndisponiveis = new List();]
Comment: As barras não importam na string. Poste seu código completo como está por favor
Answer: Estou criando um sistema Hoteleiro, para isso preciso saber se não há uma reserva durante o período de check in e check out, então eu explodo a distancia entre as datas (08 ao 10 vira 08-09-10) caso haja alguma reserva neste período eu adiciono valor a uma variável chamada reserva e também esse mesmo dia no array datas indisponíveis, lá na frente eu realizo o teste, o problema é que eu quero mostrar todas os valores dentro do array em uma linha só(ex: "Há reserva nos dias 21,22,23,24,25,26)
Segue o código:
// FUNÇÃO PARA COMPARAR AS DATAS DO CHECK IN E DO CHECKOUT
    public List<DateTime> retornadata(DateTime start, DateTime end)
    {
        var dates = new List<DateTime>();

        for (var dt = start; dt <= end; dt = dt.AddDays(1))
        {
            dates.Add(dt);
        }

        return dates;
    }

Agora o código de inserção das datas
try              {
                    DateTime start = dtpCheInR.Value;
                    DateTime end = dtpCheOutR.Value;
                    List<DateTime> DatasIndisponiveis = new List<DateTime>();
                    List<DateTime> datas = retornadata(start, end);
                    int reservas = 0;
                    foreach (var data in datas)
                    {
                        string stringSQL = "SELECT * FROM reserva JOIN quarto on (quarto.IdQ = reserva.IdQ) WHERE quarto.NumeroQ= " + txtQuartoR.Text+ " AND CAST('"+ data.ToString("yyyy-MM-dd") +"' AS DATE) BETWEEN reserva.CheckinR and reserva.CheckoutR";

                        MySqlCommand comandoSQL = conectabanco.CreateCommand();
                         comandoSQL.CommandText = stringSQL;

                        comandoSQL.Connection = conectabanco; //usar a conexao mComm
                        MySqlDataReader dadosNumQuarto = comandoSQL.ExecuteReader();
                        try
                        {

                            dadosNumQuarto.Read();

                            NumQ = dadosNumQuarto["NumeroQ"].ToString();

                            dadosNumQuarto.Close();

                        }
                        catch (Exception)
                        {
                            // Caso ele não tenha encontrado valor ele cai neste catch que possibilita o fechamento do comando de leitura já aberto.
                            dadosNumQuarto.Close();
                            // throw;
                        }
                        if ((NumQ != null)&&(NumQ!=""))
                        {
                            DatasIndisponiveis.Add(data);
                            reservas++;

                        }
                        NumQ = "";
                    }

                    if(reservas > 0)
                    {
// O Erro acontece aqui, ele simplesmente trava

                        for (int i = 0; i < reservas; i++)
                        {
                            msg += @DatasIndisponiveis[i].ToShortDateString() + "\r\n";
                        }
                        MessageBox.Show(msg, "Erro Nova reserva", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                    else
                    {
//Realizo o insert aqui ( já funcionando)
                      }

Mostrar data na MessageBox C#


can i adopt model property in the view asp.net MVC

Question: here is my code
@{
            var splitResult = (ViewBag.Linguas.ToString()).Split(','); }
            @foreach (var x in splitResult)
            {

                    @Html.LabelFor(model => model.title_PT, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.title_PT, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.title_PT, "", new { @class = "text-danger" })

                @x
            }

ok, as you can see i am splitting the viewbag.linguas. the outcome is PT and EN for example, i want to use the foreach to create dynamicaly fields for all the language I allow in the database.
I want to change the name model => model.title_pt to model=> model.title_x
Any suggestions
Thanks
Answer: You can use Html.Editor instead and pass your property name to it
@Html.Editor("model.title_" + x , new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessage("model.title_" + x, "", new { @class = "text-danger" })