Behavior of the sequences as n tends to infinity

Question: I'm trying to figure out the behavior of some sequences in the following cases.
The next two can be found in Hardy's "A Course of Pure Mathematics" (p. 131).
If $\phi(n) \to +\infty$ and $\psi(n) \to -\infty$, then
1) $\lim_\limits{n \to +\infty} (\phi(n) + \psi(n)) = 0$ if $\phi(n) = n$ and $\psi(n) = -n$
2) $\lim_\limits{n \to +\infty} (\phi(n) + \psi(n)) = \infty$ if $\phi(n) = n^2$ and $\psi(n) = -n$
In the first case, if $n-n$ were simply numbers, then I could substract them and obtain a constant sequence which has the same limit. However, I'm considering this case as a limit, so I'm not quite sure I can operate with the expression under the limit as with simple numbers.
In the second case, I could make the following transformation $\lim_\limits{n \to +\infty} (n^2-n) = \lim_\limits{n \to +\infty} n^2 \cdot (1-\frac{1}{n})$, but as far as I understand, I can't use the property $\lim_\limits{n \to +\infty} x(n) \cdot y(n) = \lim_\limits{n \to +\infty} x(n) \cdot \lim_\limits{n \to +\infty} y(n)$ because $\lim_\limits{n \to +\infty} n^2 = +\infty$. So it's like in the case of, for example, $\lim_\limits{n \to +\infty} (\sqrt{n^2+n} - n)$ where the similar transformation $\lim_\limits{n \to +\infty} (n \cdot \sqrt{1+\frac{1}{n}} - n)$ leads me to the same indeterminate form $"\infty-\infty"$ (but here I can get rid of it with help of the conjugate multiplier $(\sqrt{n^2+n} + n$)).
So, I'm confused of how can I deal with the indeterminate form of type $"\infty-\infty"$ and would like to find a way to solve this by only using the basic properties of the limits.
Thanks!
Comment: Is there a typo on the first case? $\psi(n)=n$, no?
Comment: @WeierstraßRamirez sorry, there should be $\phi(n) + \psi(n)$ instead of substraction. Fixed it.
Comment: You can say $\lim x(n)y(n) = \lim x(n) \lim y(n)$ because $\lim y(n)$ exists and is finite and non-zero.  If the limit of the product existed and were finite, then $\lim x(n)$ would be the quotient of two limits that exist and are finite.  So $\lim x(n)y(n)$ must be infinite.
Comment: Can you use L'Hôpital's rule? Otherwise, you can prove that $\lim_{n\to \infty}c\cdot x(n)=c\lim_{x\to\infty}x(n)$ even if $x(n)\to \infty$, and then use the fact that $\lim_{n\to\infty}y(n)=1=c$
Comment: @RobertShore just explained this with more detail, thanks!
Comment: @RobertShore then, according to your logic, $\lim_\limits{n \to +\infty} (n \cdot \sqrt{1+\frac{1}{n}} - n) = 0$ which isn't correct... I thought myself it could work, but when I do this, it leads me to the wrong answer as $\lim_\limits{n \to +\infty} ( \sqrt{n^2+{n}} - n)=-\frac{1}{2}$...
Comment: No, because now you are trying to take the difference of two infinite limits.  My argument works only when all but (possibly) one of your limits exist and are finite (and sometimes you also need non-zero).  My logic does show that $\lim n \sqrt{1+ \frac 1n}$ is infinite, but that doesn't help you because $\lim n$ also is infinite.
Comment: @WeierstraßRamirez, I wouldn't like to use L'Hôpital's rule, just want to get the result explicitly by using the basic properties of limits. Moreover, if I follow that logic for $\lim_\limits{n \to +\infty} ( \sqrt{n^2+{n}} - n)$, I will get $0$ instead of $-\frac{1}{2}$ as  $\lim_\limits{n \to +\infty} ( n \cdot \sqrt{1+\frac{1}{n}} - n)=\lim_\limits{n \to +\infty} ( n - n) = 0$
Comment: @RobertShore, yeah, that's right. But I'm interested exactly in cases when I have a "substraction" of infinities.
Comment: Perhaps a similar technique from the one you are proposing is:

$$\lim_{n\to\infty}\phi(n)+\psi(n)=\lim_{n\to\infty}\frac{n^2(1-1/n^2)}{1+1/n}$$

Notice that this is of the form $\lim_{n\to\infty}x(n)y(n)$ where $y(n)=\frac{(1-1/n^2)}{1+1/n}$ and hence $\lim_{n\to \infty}y(n)=1$. Therefore, $\lim_{n\to\infty}x(n)y(n)=\lim x(n)=\infty$
Comment: @WeierstraßRamirez, yes, I guess this one will really work. So the only confusing case is $\lim \limits_{n \to \infty} (n-n)$. If I apply the same technique, there will still be the indeterminate form of "$\infty \cdot 0$", $\lim \limits_{n \to \infty} \frac{n \cdot (1-1)}{2}$.
Comment: Are you familiar with the formal definition of limit? Would like to include in an answer, perhaps.
Comment: @WeierstraßRamirez sure! Do you simply want to write $|n-n-0| < \epsilon$ and "prove" $\lim \limits_{n \to +\infty} (n-n) = 0$?
Comment: As in your example of $\lim (\sqrt{n^2-n}-n)$, those problems often are solved by converting them to a quotient that *is* in the necessary form.  In that case, multiply by $\frac{\sqrt{n^2+n}+n}{\sqrt{n^2+n}+n}$ and then divide top and bottom of the resulting fraction by $n$.
Answer: You may add the functions, so that $\phi(n) + \psi(n) = n - n = 0$ for all $n$.  Then take the limit.  That is exactly what $$\lim_{n\to\infty}( \phi(n)+\psi(n) ) $$ is defined to mean.
In the second case, again you are right:
$$\lim_{n\to\infty} (\phi(n) + \psi(n)) = n^2 - n. $$
At this stage you do not need to apply the limit of a product but simply note that once $n > 2$, $n^2 - n > n$ so the right hand side approaches $\infty$.
Does that answer your question?
Comment: yes, it makes sense. So, in the first case, I can at first take the sum of 2 functions and then evaluate the limit while this approach would be wrong $\lim \limits_{n \to +\infty} n - \lim \limits_{n \to +\infty} n$ because it leads me nowhere (I mean, I can apply the sum property of the limits but it won't give me an effect). I would like to clarify if my conclusion is correct.
Comment: Correct:  the approach fails in both cases, because neither $\phi$ nor $\psi$ have limits and then the limit of the sum (which is what you want) is not equal to the sum of the limits.  This is a case, by design, where the limit of the sum is easier to deal with than the sum of the limits.
Comment: Now it's clear. Thank you very much!
Answer: I will provide an answer with aims of explaining why the approach suggested in the comments does not work every time. I present three observations:

Let $\lim_{n\to\infty}f(n)\to\infty$ and $\lim_{n\to\infty}g(n)=c>0$. Then:

$$\lim_{n\to\infty}f(n)g(n)\to c\lim_{n\to\infty}f(n) \to \infty$$
(I can provide a formal proof below, if needed).

Let $\lim_{n\to\infty}f(n)\to\infty$ and $\lim_{n\to\infty}g(n)=0$. Then we cannot be conclusive about  $\lim_{n\to\infty}f(n)g(n)$, since it is of the form $0\cdot \infty$.
Consider the function
$$r(n;k)=n\sqrt{c+1/n}-n=n(\sqrt{k+1/n}-1)=f(n)\cdot g(n)$$

Where $f(n)=n$ and $g(n)=\sqrt{c+1/n}-1$. Notice that $\lim_{n\to\infty}f(n)\to\infty$ and $\lim_{n\to\infty}g(n)=\sqrt{k}-1$.
This means that for $k>1$, it is the case that:
$$\lim_{n\to\infty}f(n)g(n)\to (\sqrt{k}-1)\lim_{n\to\infty}f(n) \to \infty$$.
However, if $k=1$ the limit is of the form $0\cdot\infty$ and hence:
$$\lim_{n\to\infty}f(n)g(n)\neq (\sqrt{k}-1)\lim_{n\to\infty}f(n) =0$$.
Notice that $k=1$ represents the counter example you are providing, however for $n^2-n=n^2(1-1/n^2)$ this problem does not arise since $\lim_{n\to \infty}(1-1/n^2)=1\neq 0$ and hence
$$\lim_{n\to \infty}n(1-1/n^2)\to 1\cdot \lim_{n\to \infty}n\to \infty$$


Drupal Commerce age gate on Add to Basket?

Question: I'm building a Drupal Commerce store for a client and some of the products are alcohol which requires me to add a popup modal with some text about age laws when they click "add to cart".
How can I do this? I've seen the 'add to cart confirmation' module but I want to display custom markup and only for certain products. The other projects I've seen are in the sandbox and not well documented on how they are used.
Answer: First you can add a popup callback for certain products in the add to cart form alter.
e.g.
function my_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    // if this is the alcohol
    $form['submit']['#ajax'] = array('event' => 'click', 'wrapper' => 'age_check_popup', 'callback' => 'my_module_age_check');
}

function my_module_age_check($form, &$form_state) {
    ctools_include('modal');
    ctools_modal_add_js();
    $commands = array();
    $commands[] = ctools_modal_command_display('title', theme('my_module_age_block'));
    print ajax_render($commands);
    drupal_exit();
}

Then you'll need to handle the clicks in the popup to either add the product or cancel (just close the popup).
You could do this via hook_menu() callbacks or by rendering a form with buttons in the popup.
Edit:
Implement hook_theme() to create a new template file for your popup content.
e.g.
function my_module_theme($existing, $type, $theme, $path) {
    return array(
       'my_module_age_block' => array(
          'template' => 'my_module_age_block'
        ),
     );
 }

Then add a template file my_module_age_block.tpl.php and put your HTML content in here.
Comment: Thanks, this works but I'm not clear on how I set the content of the modal or add a button to continue adding to the cart.


Can I remote desktop from XP SP3 to Windows Server 2K8 R2?

Question: When I try I get an error message saying that my computer does not support Network Level Authentication.  I am doing remote desktop across a VPN from a PC on a different domain.
Is this possible?
Answer: Go to system properties, go to the "remote" tab and change the option to "Allow connections from computer running any version of Remote Desktop" to turn NLA off.  (On the server, that is)

Right click on computer and click properties
Click on the Remote settings link (left side) and you'll jump right to the remote tab of system properties, fyi.
Comment: Thank you.  Not quite sure why I didn't think of that.
Comment: Not a problem - I ran into this not two weeks ago so it was fresh in my mind.
Comment: Had the same problem late last year. The alternative it to update to something like Vista or Windows 7.
Answer: You are probably still using an older version of RDP client ... get the 6.x version and you should be good: http://www.microsoft.com/downloads/details.aspx?familyid=6E1EC93D-BDBD-4983-92F7-479E088570AD&displaylang=en
Comment: I tried installing that and it told me that the service pack on the machine was more recent than the update I was trying to install.


conditional independence in an integral

Question: Let $f(\cdot)$ denote a density. Measure theory aside, I know that $A$ and $B$ are conditionally independent given $C$ iff $f(a,b|c)=f(a|c)f(b|c).$ Also, $\int f(a,b|c)f(c) dc = f(a,b)$.
But is it true that $\int f(a,b|c)f(c) dc = \int f(a|c)f(b|c)f(c) dc = f(a)f(b)$? I don't think this is always the case, but I am not sure. If it is not true, are there any conditions under which it would be true?
Answer:
$\int f(a,b|c)f(c) dc = \int f(a|c)f(b|c)f(c) dc$

Generally this is false, but it is true if $A,B$ are conditionally independent given $C$.

$\int f(a|c)f(b|c)f(c) dc = f(a)f(b)$

Generally this is false, but it is true if $A$ is independent of $C$, and also $B$ is independent of $C$.

conditional independence in an integral


Domino SSL 301 redirect with www and non www

Question: With reference to this question How to do a 301 redirect from http to https in a domino server? My redirects are failing.
(gaps between protocol and : are because i dont have the rep to post multiple links)

http ://example.com
https ://example.com
http ://www.example.com
http ://www.example.com/old-page

All urls above should 301 redirect to https://www.example.com

Incoming URL pattern: /*
Redirect to this URL: https ://www.example.com/*

and

Incoming URL pattern: /old-page
Redirect to this URL: https ://www.example.com/*

I have redirect TCP to SSL set to yes on the website doc.
And I have the IP address, example.com and www.example.com entered in "Host names or addresses mapped to this site" on the website doc.
But when I have the rule as suggested in the question linked above I get into a loop with all urls.
I did have 2 site docs for www and non www redirecting fine but since implementing SSL these are ignored.
Answer: I think the problem is that in order for SSL to work in Domino for multiple host names you need multiple IP addresses - see my answer to a question on that topic here: https://serverfault.com/a/375106/108199
Let's say we start with example.com. What happens is: http://example.com redirects to https://www.example.com (as expected because Domino can see the host name in the request). When Domino then processes the encrypted https://www.example.com it doesn't know what internet site doc to use other than the one containing the IP address of the request. That internet site doc is set to redirect which Domino then does - and that kicks of the loop.
Comment: OK let me step back a bit. I removed the domains from the "Host names or addresses mapped to this site" section so the only thing entered here is the server IP address. Added the rule
    Incoming URL pattern: /*
    Redirect to this URL: https://www.example.com/*
which results in a loop!!
Comment: Well, yes since all requests now go to that internet site doc which redirects to itself. Right?
Comment: Yes, that was my understanding. However the post http://serverfault.com/questions/463976/how-to-do-a-301-redirect-from-http-to-https-in-a-domino-server suggested that the redirect rule would fix the ssl redirect to become a 301 instead of a 302 (which was my first goal before getting into non www and www.) - Does this mean that the answer in the other post is not correct? How can we perform a https 301 redirect? Thanks for your help Per.
Comment: The answer might be correct. Since you want to redirect from https to https you need two IP addresses (and thereby two internet site docs - one for each IP address) if Domino should be able to distinguish between the two. That's my understanding of Domino and the version of SSL that it uses


.load nao funciona se elemento já estiver carregado

Question: Estou com o seguinte problema.
estou usando .load para executar uma ação apos o carregamento de um iframe
<code>$(document).ready(function() {
   $('iframe').on('load',function()
   {
       $('#diviframe').fadeTo(200,1);
   });
});
</code>
Tudo funciona muito bem, exceto se o iframe carregar antes do codigo.
cheguei a essa conclusão por que testei com iframe com apenas com uma palavra (para carregar mais rapido) e com varios textos (para demorar um pouco mais para carregar).
alguem tem alguma ideia de como resolver isso?
Answer: O problema é que o código jQuery está a ser executado antes da iframe completar o carregamento.
Para garantir que esse código jQuery é executado após a iframe estar carregada, é necessário usar o $(document).ready. Exemplo:
<code>$(document).ready(function() {
    $('iframe').on('load',function() {
        $('#diviframe').fadeTo(200,1);
    });
});
</code>
Fica a nota que, se está a usar jQuery e não houver uma razão para a existência da iframe, talvez o melhor seja carregar o conteúdo por ajax. Exemplo:
<code>$(document).ready(function() {
    $('iframe').load('http://yoursite.tld/pagina', function() {
        $('#diviframe').fadeTo(200,1);
    });
});
</code>
Além disto, importa referir que
<code>$('iframe').load(...)
</code>
e
<code>$('iframe').on('load', ...);
</code>
funcionam da mesma forma. Aliás, o .on() é recomendado e existe a partir da versão 1.7 do jQuery (ver http://api.jquery.com/on/)
Comment: Obrigado pela resposta, mas apesar de eu não ter especificado, o codigo ja se encontra dentro de ready. É necessario o iframe pois o objetivo é upload sem refresh. Pelos testes que fiz, acredito que é o iframe que esta sendo carregado antes do codigo, pois só nao funciona quando o iframe carrega muito rapido.
Comment: Ok. Então talvez seja melhor fazer o seguinte: Retirar o código da página que inclui a iframe e colocar o $('#diviframe').fadeTo(200,1); dentro de um $(document).ready na própria vista (página) da iframe.
Assim, o seu código só depende da iframe.


Como montar par de array key vaue para inserir na tabela?

Question: $key = "id,name";
$val = "'$lastid','$autor'";
...
if ($email){
   $key .= ",email";
   $val .= ",'$email'";
}
...
$keys = \explode(',', $key);
$vals = \explode(',', $val);
$arr  = array_combine($keys,array_fill(0,count($keys),$vals));
....
//O array montado fica assim:
// INSERT INTO autores (id, name, email) VALUES (:id, :name, :email)

$insok = $pdo->insert($arr);
if (!$insok) {
    $error = "Erro ao inserir dados
".print_r($conn->errorInfo());
}

echo $error; // mostra o seguinte resultado

//array(3) { [0]=> string(5) "00000" [1]=> NULL [2]=> NULL }

Gostaria de saber como resolver esse erro:
Answer: É só simplificar, não precisa daquele array_fill() basta chamar o array_combine() com $keys e $vals. Se for utilizar prepared statements não inclua aspas simples no valores.
Troque:
$arr  = array_combine($keys,array_fill(0,count($keys),$vals));

Por:
$arr  = array_combine($keys, $vals);

Seu array ficará dessa forma:
Array
(
    [id] => '10'
    [name] => 'fulano'
)

Comment: Olá, muito obrigado pela rápida resposta. O problema realmente estava nas aspas simples. O correto é:

$key = "id, name";
$val = $id. "," .$cauthor;

E também simplifiquei o array_combine() como vc falou.

Funcionou ok.

Um abraço.
Comment: @user1818765 com `array_fill()` fica assim: `Array
(
    [id] => Array
        (
            [0] => '10'
            [1] => 'fulano'
        )

    [name] => Array
        (
            [0] => '10'
            [1] => 'fulano'
        )

)`


Does the FLAC audio format have multiple quality settings?

Question: I am writing an encoding software and dealing with uncompressed wav and flac formats. My question is, flac is supposed to be a lossless format, similar to wav but compressed. However, certain softwares such as JRiver's Media Center offer a 'quality' setting for encoding flac files. Does taht mean they are offering to reduce quality pre-encoding or am i missing something in the flac standard?
Answer: The quality parameter for FLAC refers to the quality of compression, not audio. The audio will stay lossless but you get a better compression with higher quality. Higher quality will take more time to compress however.
See docs http://wiki.jriver.com/index.php/Encoding_Settings

Free Lossless Audio Codec (FLAC): FLAC is a popular lossless, freely
  available open source encoder. [2] Quality Settings: 0 - 8. Sets the
  quality of compression (and not sound, which is lossless), 8 meaning
  most compressed/time/effort.


PHP - Extensions - no-debug-non-zts-xxxxxxxx

Question: I am compiling php extensions (memcached and xdebug), and when I run make install, they keep getting installed into /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626. So a few questions:

What does no-debug-non-zts-20090626 even mean, and why is it the default?
Is it good practice to edit the php.ini file and set the extension_dir directive to the aforementioned directory? Or should I compile each module with a PREFIX=/usr/local/php/extensions? So when I do make install, they are put into a custom extensions directory, then I can add extension=/usr/local/php/extensions/memcached.so lines to my .ini files.
Is there ever a risk when compiling a new module, that it will go in a different directory than the directory in question #1?
Answer: "no-debug-non-zts-20090626" means that it's built without the debug flag, and without ZTS, which is the acronym PHP uses to indicate internal thread saftey.  The datestamp is used to identify the internal API version.  I'm pretty sure that one identifies PHP 5.3.
Instead of compiling these yourself and thus causing these questions to need answers, you probably want to really look for precompiled versions of these modules provided by your OS distribution or a trusted third party.  Memcached and xdebug are amazingly common extensions, and chances are that they're already easily available to you.
Failing that, you probably want to use the pecl tool to download, compile and install these for you.  These tools exist for good reasons.
Comment: I see, so if I flip debug and zts flags and recompile php, then phpize memcached, upon make install of memcached, it will be installed into debug-zts-20090626?
Comment: Quite possibly, yes.
Comment: You were right about the 20090626 part, it matches the same date for `PHP Api Version` when I do a phpize.
Answer: Ended up not custom configuring the location of the module, instead I just created extension .ini files which each load the extension using the full module uri:
; memcached.ini
extension=/path/to/php/lib/php/extensions/no-debug-non-zts-20090626/memcached.so

This way, when I do make install, I don't have to do any symlinking etc.
One a sidenote, If I don't use the full module uri within the custom .ini file, then PHP cannot find the module, which is odd because if I add the following to php.ini, it works fine:
; php.ini
extension=memcached.so

Anyway, got it to work.
Answer: Check if libraries are found:
ldd /usr/lib/php/extensions/no-debug-non-zts-xxxxxxxx/memcached.so

Outbuildings:
yum -y install gcc make automake autoconf gcc-c++ flex bison
yum remove libmemcached
/usr/bin/pecl uninstall memcached
wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz
tar -xvzf libmemcached-1.0.18.tar.gz
cd libmemcached-1.0.18
./configure
make && make install
/usr/bin/pecl install memcached-2.2.0
echo "extension=memcached.so" >/etc/php.d/memcached.ini
service httpd restart
/usr/bin/php -i | grep memcached
echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php

Check logs:
tail -f /var/log/httpd/error_log


Integrating $dS/S = \mu dt$

Question:
Integrating $dS/S = \mu dt$ between time $0$ and time $T$ we get $S_T = S_0e^{\mu T}$, for $S_0$ and $S_T$ stock prices at time $0$ and $T$.

I'm trying to figure out how they came to this conclusion.
So if I do $\int_o^{T} dS/S$ I get $\ln (T) + C$ and integrating $\int_0^{T}\mu dt$ I get $\mu T + C$. Setting them equal to each other and raising $e$ to both sides I get $T = e^{\mu T}$. Finance notation notwithstanding, did I do something wrong in my calculations?
Comment: The integral $\int_0^T\frac{dS}{S}$ is improper and diverges; (you should not get a $+C$ if you are doing a *definnite* integral!) But since $S$ is a function of $T$, that integral should be from $S(0)$ to $S(T)$, not from $0$ to $T$. Likewise, when you integral $\int_0^T\mu\,dt$ you should not get a "$+C$"; that should jsut be $\mu T$.
Answer: $S$ does not change from $S=0$ to $S=T$, it changes from $S_0$ to $S_T$. And definite integrals don't have constants of integration. So you should have:
$$\begin{align*}
\frac{dS}{S} &= \mu \\
\int_{S_0}^{S_T}\frac{dS}{S} &= \int_0^T\mu \,dt\\
\ln|S|\Bigm|_{S_0}^{S_T} &= \mu t\Bigm|_0^T\\
\ln|S_T|-\ln|S_0| &= \mu T\\
\ln\left|\frac{S_T}{S_0}\right| &= \mu T\\
\left|\frac{S_T}{S_0}\right| & = e^{\mu T}\\
\frac{S_T}{S_0} &= e^{\mu T} \quad\text{(since }S_T,S_0\text{ are positive)}\\
S_T &= S_0e^{\mu T}.
\end{align*}$$

Integrating $dS/S = \mu dt$


Office 2010 activation from domain group policy

Question: We just found out that an windows 7 image that we had applied to about 1,800 laptops has a bit of a problem.  When Students log in for the first time an lauch word, they are prompted to activate office but can't because they done' have admin rights.
Here is a script that runs the activation"
c:\windows\system32\cscript C:\"Program Files (x86)\Microsoft Office\Office14\OSPP.VBS" /act
My question is this, if I run this under another account on the individual laptops, does that script effect all the user profiles?  If NOT can I run this script from a domain Group Policy and have it run even though the user does NOT have admin rights?
Thanks in advance.
Zyper Thanks for your answer but I'm little fuzzy about how to post this via group policy and run it as a "system" user.  When you say "system" are you refering to the computer configuration or the user configuration?
Comment: At the risk of sounding condescending (which is not my intention, but speaking from personal experience) you could have saved yourself a lot of headaches by testing this deployment before going live with 1800 machines.
Comment: Oddly enough we did and it ran fine.  What I think happened was the wrong HD shipped to the manufacture.  Lucky for me there were only a couple minor problems.
Answer:
My question is this, if I run this under another account on the individual laptops, does that script effect all the user profiles?

Yes, activation is per machine, not per user.

If NOT can I run this script from a domain Group Policy and have it run even though the user does NOT have admin rights?

I believe that if you run it as a start up script  (runs as the SYSTEM user) and not a logon script it should work.
Comment: I was going to post essentially the same answer, but I'll give you a one up instead.
Comment: Zypher.  Thanks for your help.  So where do put this in the GPO?  I'm a little fuzzy as to where to place the script to run it as "system".  Do you mean under the computer configuration?
Comment: Any  start up or shutdown script is run under the `SYSTEM` account since there is no active user to associate with the action. This is opposed to Logon and Logoff scripts which run as the logged in user.You can find the setting at: `Computer Configuration->Policies->Windows Settings->Scripts`
Comment: So would I be right in assigning the GP to machines rather then users?
Comment: You are Correct Sir.
Answer: If you have that many installations then KMS is something you should (already) have in place.
http://blogs.technet.com/b/office2010/archive/2009/08/24/volume-activation.aspx
Comment: The KMS server solution is what you are looking for. This also applies to virtual desktop solutions so users aren't prompted for activation during their initial logins.


Qual o mais rápido is_null($y) ou $y == null?

Question: Qual o mais rápido is_null($y) ou $y == null?
Comment: @WallaceMaxters exato, se a comparação pode ser estrita, por que não faze-la no sistema todo? Com um sublimetext da vida e uma consulta por regex você encontra todos locais que necessita editar.
Comment: Particularmente, em alguns casos, preocupar com microotimização é desnecessário. É como uma frase que eu vi por aí a fora "... alguns programadores descobrem que o `for` é um milionéssimo de segundo mais rápido para iterar com array do que o `foreach` e monta uma palestra falando que não devemos usar `foreach`..."
Comment: @WallaceMaxters existem casos que é o contrario, ao menos nos últimos testes que fiz de micro-optimização `foreach` foi mais rápido.
Comment: PauloCosta é provável que a diferença seja impercepitivel, no entanto eu prefiro usar `$y === null` (com três sinais de `=`), pois a comparação é estrita.
Comment: No geral, @GuilhermeNascimento, a regra que eu uso é a seguinte: "começou com ===, então agora tem que ir no sistema todo. Feio é ter uma parte de um jeito e outra, de outro".
Comment: Alguma das respostas lhe ajudou? Ou há problemas nelas? Comente informando ao autor qual a duvida em tentar usar a solução proposta. Se alguma das respostas lhe resolveu o problema, marque-a como correta clicando em ✓
Answer: Segurança das Expressões
A pergunta que realmente deve-se fazer é a seguinte, "Qual é mais seguro de se usar?". Por exemplo, as expressões a seguir:
"oi" == null    => false
""   == null    => true
0    == null    => true
null == null    => true

is_null("oi")   => false
is_null("")     => false
is_null(0)      => false
is_null(null)   => true

"oi" === null   => false
""   === null   => false
0    === null   => false
null === null   => true

Otimização
A diferença entre === e is_null é praticamente irrelevante, a não ser que você tenha cerca de dois milhões de expressões como essa em um script para necessitar de uma otimização significativa.
Um dos comentários na documentação do PHP diz o seguinte (em tradução livre):

Micro otimização não vale a pena.
Você tinha que fazê-lo dez milhões de vezes a notar uma diferença, um pouco mais de 2 segundos
$a===NULL; Durou: 1,2424390316s
is_null($a); Durou: 3,70693397522s
Diferença = 2,46449494362s
Difereça/10.000.000 = 0,000000246449494362ns
O tempo de execução entre === NULL e is_null é menos do que 250 nanosegundos. Vá otimizar algo que valha a pena.

Obs.: Fiz alguns testes e os vários resultados não passaram de 100 nanosegundos, e a média de diferença fica entre 20 ~ 50 nanosegundos.

Conclusão
Se deseja realmente otimizar e ter segurança no seu código, dê preferencia à comparação com o operador triplo:
$y === null

Porém não vale a pena ficar vasculhando o código procurando otimizar essas expressões (a não ser que procure pelo operador simples ==). Pois a diferença é tão insignificante, que o tempo seria melhor investido caso estivesse limpando/melhorando o código ou estudando.
Mais detalhes sobre expressões lógicas: https://pt.stackoverflow.com/a/69576/8493
Mais detalhes sobre operadores lógicos: http://php.net/manual/pt_BR/language.operators.comparison.php
Answer: Tudo depende do que você quer verificar, não deve ser olhado somente a performance. Por exemplo:

<?php

$str1 = "";
$str2 = null;
$str3 = 0;

var_dump(is_null($str1)); // retorna false
var_dump(is_null($str2)); // retorna true
var_dump(is_null($str3)); // retorna false

var_dump($str1 == null); // retorna true
var_dump($str2 == null); // retorna true
var_dump($str3 == null); // retorna true

?>

Answer: A sua pergunta tem rasteira porque o resultado nunca é o mesmo para:
is_null($y) ou $y == null

para comparar deve de o fazer sobre:
is_null($y) ou $y === null

Aqui sim os resultados serão semelhantes. É importante referir que tem situações onde a aplicabilidade do operador === é impossível. Em casos que seja necessário utilizar em callbacks apenas o is_null pode ser utilizado.
Numa resposta directa à pergunta no que respeita à performance:
A diferença não é relevante.
Mas:
Ambas são abordagens diferenciadas para o mesmo problema.
Porque...

is_null é uma função que no caso do PHP é executa um C. Em resultado é obtida alguma latência.
No caso do PHP a diferença é mínima porque por se tratar de uma linguagem de script baseada em C a interpretação do código $y === null irá na mesma sempre originar chamadas de métodos C em qualquer um dos casos.

Opinião:
Eu aplico de acordo com a situação, mas escolheria sempre $y === null pois é um operador base e por esse motivo nuclear... pelo que o PHP tende a resolver com menos esforço certamente.
Answer: Não existe nenhuma diferença entre is_null and === null.
A unifica diferença e que is_null se trata de uma função e por consequencia,
1° A chamada da função faz ela ficar mais lenta,  mas isso falanto de um tempo relativamente insignificante.
2°  Por se tratar de uma função você pode usa-lá de callback, exemplo:

  array_map('is_null', $array);

Na documentação do php existe um teste de  benchmarking com 10 milhões de iterações que  acaba concluindo  da seguinte forma,  a comparação de uma variável com um operador é muito mais rápido, então não use is_null a menos que precise de um callback.
Php - Manual
Comment: +1 . A função `is_null`, embora por ser uma função é mais lenta que uma expressão (não é um construtor da linguagem, mas é uma função mesmo), é excelente usá-la como callback. Ela poderia ser usada em `array_map`, `array_filter` e afins :)
Answer: $y == null.
Em questão de performance não é tão relevante a diferença, porém se usado com frequência, realmente vale mais apena usa-lo.
Comment: Por quê ele é mais rápido? Se puder melhorar sua resposta, ela certamente irá ajudar mais pessoas que, assim como eu, não entendem nada de php.


Fetching HTML table elements into an array

Question: I need to fetch lessons from an online timetable(for a school) into an array. So i can insert the data into my database. The online timetable(url: roosters-hd.stenden.com) looks like this:
 On the left hand we see the times, and on top the schooldays (Mo, Tu, We, Th, Fr). Very basic.
Each lesson contains 6 values that i need to fetch.

Besides that, I also need to fetch the [startDate] and [endDate]. Time is based on which row the lesson-cell is at, and how much rowspan it has. Date can be calculated by adding column number onto the start date(printed on top).
So in the end the array would look something like this:
[0] => Array
        (
            [0] => Array
                (
                    [Name] => Financiering
                    [Type] => WC
                    [Code] => DECBE3
                    [Classroom] => E2.053 - leslokaal
                    [Teacher] => Verboeket, Erik (E)
                    [Class] => BE1F, BE1B, BE1A
                    [StartDate] => 04/06/2013 08:30:00
                    [EndDate] => 04/06/2013 10:00:00
                )
                etc.

Because my lack of experience in fetching data, I will properly end up with a highly inefficient and inflexible solution. Like should i use XML-parser? Or Regex? Any ideas on how to tackle this problem?
Comment: please **not** regex! http://stackoverflow.com/a/1732454/2170192
Comment: yes not regex, regex is for parsing strings it is very powerful but still it should not be used for this kind of parsing. Also link you posted returns 400 bad request. It would be good to see live example, you can put it in jsfiddle.net
Comment: Fixed link.
I don't have any example right now, since i'm not sure where i should start. With that i mean, the correct efficient way of fetching the data.
Answer: The regex way:

<?php
$html = file_get_contents('the_url.html');

$clean_pattern = <<<'LOD'
~
  # definitions
    (?(DEFINE)
        (?<start>                             )
        (?<end>           (?>[^<]++|<(?!!--))*  )

        (?<next_cell>     (?>[^<]++|<(?!td\b))*]*+>  )
        (?<cell_content>  [^<]*+                           )
    )

  # pattern
    \g<start>
        \g<next_cell>     (?<Name>      \g<cell_content>   )
        \g<next_cell>     (?<Type>      \g<cell_content>   )
        \g<next_cell>     (?      \g<cell_content>   )

        \g<next_cell>     (?<Classroom> \g<cell_content>   )
        \g<next_cell>

        \g<next_cell>     (?<Teacher>   \g<cell_content>   )
        \g<next_cell>
        \g<next_cell>     (?<Class>     \g<cell_content>   )
    \g<end>
~x
LOD;

preg_match_all($clean_pattern, $html, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo <<<LOD
    Name: {$match['Name']}
    Type: {$match['Type']}
    Code: {$match['Code']}
    Classroom: {$match['Classroom']}
    Teacher: {$match['Teacher']}
    Class: {$match['Class']}

LOD;
}

The DOM/XPath way:
$doc = new DOMDocument();
@$doc->loadHTMLFile('the_url.html');
$xpath = new DOMXPath($doc);
$elements = $xpath->query("//*[comment() = ' START OBJECT-CELL ']");
$fields = array('Name', 'Type', 'Code', 'Classroom', 'Teacher', 'Class');
$not_needed = array(10,8,6,1,0);
foreach ($elements as $element) {
    $temp = explode("\n", $element->nodeValue);
    foreach ($not_needed as $val) { unset($temp[$val]); }
    array_walk($temp, function (&$item){ $item = trim($item); });
    $result[] = array_combine($fields, $temp);
}
print_r ($result);

Comment: @JasperJ: rubular is for ruby not for php, the best test you can do is IN YOUR CODE! Otherwise, you can use http://regex.larsolavtorvik.com/ which is designed for php.
Comment: I tried your raw pattern in Rubular, but it doesn't seem to match anything. http://rubular.com/r/xwfwYKy13S .
Comment: Right, stupid me. I tried preg_match_all($raw_pattern, $data, $out); With data being file_get_content from url. But still no success (php 5.3.26). But I will wait for updates.
Comment: I like your xPath version. Still I need to be able to calculate start and end date. Is there any way to fetch: column name/number, row name/number and rowspan of the cell?
Comment: @JasperJ: I have just see that you need start and end date time.


Disagreement between normality tests and histogram graphs

Question: My data consist of compaction measurements from 3 different cell types (X,Y, and Z). My goal is to know whether there are "significant" differences between these measurements, so I have tested for:

Whether my samples are normally distributed

using the Shapiro–Wilk test
using the Jarque-Bera test
plotting qqnorm graphs
plotting histograms

Whether the samples come from the same distribution

using two-sample Kolmogorov–Smirnov test (K–S test) and comparing X vs Y, X vs Z, and Y vs Z
using Kruskal–Wallis comparing X, Y, and Z together

My data consist of 232 measurements for X, 284 for Y, and 124 for Z. The Shapiro-Wilk and Jarque-Bera tests in R always give me p<0.05, which I accept as not being normally distributed. However, when I plot histograms I get a normal-like distribution.

The qqnorm plots also don't look that skewed, but maybe this is just my inexperience in interpreting qqnorm graphs (this is my first time making them).

Because of the supposedly non-normal distribution, I compared my data using KS test and Kruskal-Wallis, which always give me the result that my population Z is drawn from a different distribution compared to X and Y. However, I do not know if this is true, as R always reports for my two-sample Kolmogorov–Smirnov tests:
<code>Warning message:
In ks.test(dataX, dataY) : cannot compute correct p-values with ties

Warning message:
In ks.test(dataX, dataZ) : cannot compute correct p-values with ties

Warning message:
In ks.test(dataY, dataZ) : cannot compute correct p-values with ties
</code>
probably because the samples have different sizes.
I'd like to know what you think about it, and whether I should consider using more parametric tests rather than the non-parametric ones I've used, or whether the tests I've used are valid regardless of the normality of the data. Also, my measurements seem to differ very little among themselves, for example:
<code>---Summary stats for WT cells
Min.    1st Qu. Median  Mean    3rd Qu. Max.
0.1450  0.3720  0.5000  0.5598  0.7102  1.9290

---Summary stats for Df cells
Min.    1st Qu. Median  Mean    3rd Qu. Max.
0.0550  0.4030  0.5445  0.5857  0.7210  1.5350

---Summary stats for Dp cells
Min.    1st Qu. Median  Mean    3rd Qu. Max.
0.0670  0.4790  0.6255  0.6782  0.7897  2.0160
</code>
Here's a boxplot of the data:

Green=X, Blue=Y, Red=Z
So I'm unsure about the conclusions I may derive from them.
Comment: Both the qq plots and the histograms look pretty skewed to me.  Look at the right tails on the latter.  Normally I think it's best to just trust your eyes, since 1) the issue of whether or not a distribution is normal often isn't terribly important (what usually matters is how far it deviates from normal), and 2) normality tests typically reject the null if you an appreciable amount of data.  However, in this case I'd say your distributions are not normal.
Comment: You may want to add a diagonal line to your qqplots with `abline(b=1)`. If your data are in fact normal, the dots should lie on that line, so it will make it much easier to see any deviations from normality.
Comment: I haven't looked at the images: this is a general comment. Among all the tools commonly available to assess distributions, including histograms, kernel density estimates, QQ plots, boxplots, and even dot density plots, as well as the formal tests of distribution, histograms are perhaps the crudest and most arbitrary of them all (for reasons well documented in the literature). In the event of an apparent disagreement between a conclusion drawn from a histogram and a conclusion drawn through the *correct* application of any of these other methods, I would automatically favor the other method.
Comment: Thank you very much for these comments. I tried using the abline but it didn't work for me, supposedly I need to standardize my data for comparing against the 45 degree line. I used qqline instead (explained in my other comment on Charlie's answer) and it seems to be pretty in alignment with that qqline.
Comment: To aid in the reading of QQ-plots, I really like the Stabilized Normal Probability Plot (ref):   https://www.smu.edu/-/media/Site/Dedman/Departments/Statistics/TechReports/TR-165.pdf; https://www.jstor.org/stable/2335939?seq=1; or https://www.tandfonline.com/doi/abs/10.1080/00224065.1989.11979171?journalCode=ujqt20 (The last one is an adaptation to BASIC that includes the information for plotting lines for various $\alpha$ values.
Answer: It appears that your data can only take on positive values. In this case, the hypothesis of normality is often rejected. Normally distributed random variables range from positive to negative infinity, so only positive values would violate this. You could try taking the log of the observations and seeing whether these are normally distributed.
If your data follow a normal distribution, then the points in your QQ-plot should lie on a 45-degree line through the origin. Your plots do not look like that at all.
The KS test is giving an error because the distributions being tested are presumed to be continuous. In this case, the probability of witnessing two observations with the exact same value is 0. Your data set contains ties, invalidating this assumption. When there are ties, an asymptotic approximation is used (you can read about this in the help file). The error that you are receiving has nothing to do with data sets with different sizes.
In your post, you never specified the question that you are trying to answer--with sufficient precision, anyway. Do you really want to test that the distributions are the same? Would it be sufficient to test that the means are the same?
Unless you are willing to assume that the variables follow some distribution, there isn't much of an alternative to the KS test if you want to test for the distributions being the same. But there are several ways to test for differences in means.
Comment: No, what you provided was very not normal like. When you take the logs, many of the points lie on the 45-degree line. This suggests that the center of the distributions look normal-ish, but the patterns shown in the QQ-plots of the logs are consistent with a positive skew.
Comment: Thank you very much Charlie, you gave me great advice regarding my problem. I'll assume my data follows some distribution, so I guess the KS test with ties (thanks for this tip) is my only alternative. Because the mean is sensitive to outliers, I decided to test median values, which seem more robust, so would a Wilcoxon Signed-Ranks Test be useful? Finally (sorry for this much bothering!) I tested log values with qnorm and plotted qqline as well for each
Comment: qqnorm(logx);qqline(logx,col=2)

And I get the following:

http://i49.tinypic.com/2jexoiv.png
http://i49.tinypic.com/2day3di.png
http://i50.tinypic.com/sbrimh.png

I read qqline passes through the 1st and 3rd quartiles of my sample, because otherwise for comparing against a 45 degree line wouldn't be useful as this is standardized, and for using it I'd have to standardize my own values. Is this correct? Or is it safe to assume my data (log val) is normally distributed? Also I don't know why using logs would be useful, how is it related to my original hypothesis testing?

Thank you so much!!
Comment: Your links aren't working for me. Sometimes the log of a positive-only variable looks more normal-like (it undoes the skew in the data).
Comment: Does this mean the original (non-log) samples distribution is more normal-like? Here are the images. Thanks!! [link]http://img832.imageshack.us/img832/9397/screenshotat20130125115.png
[link]http://imageshack.us/a/img37/9397/screenshotat20130125115.png
[link]http://imageshack.us/a/img189/9397/screenshotat20130125115.png


The definition of the crossed product of a ring and a monoid

Question: I know the  definition of crossed product of a ring and a group. But when I consider the definition of the crossed product of a ring and a monoid, I can not understand exactly  the definition on page 27 of the book "Ring Constructions and Applications" by Andrei V. Kelarev. I want to know if the set $\bar{S}$ can be replaced directly by the monoid $S$, and if this replacement seems to make sense? that is to say, we only need to consider the finite sums of each term of R*S as the form of  $r_{s}s$? Any help would be helpful. Thank you very much!
Answer: Fast answers
You can write elements of $M$ without bars in the crossed product, just as long as you don't forget that they don't multiply according to the rules of the monoid $M$.
Yes, you only take finite sums of the $r_s s$: there's no reason to expect infinite sums are defined. The ring is, by definition, the free module on the elements $\{\overline m\mid m\in M\}$, and that can be expressed by finite linear combinations only.
Elaboration
The crossed product $(R,M,\tau,\sigma)$ is a construction generalizing both skew monoid rings and twisted monoid rings.
Twisted monoid rings
In the usual monoid ring $R[M]$, $M$ injects directly in as a submonoid, and its monid multiplication matches the multiplication in $R[M]$. But in a twisted monoid ring $(R,M,\tau)$, the set $M$ still injects into the twisted ring, but $M$ is not usually a submonoid of $R$ because its product doesn't match.
That is why the overlines are used for the images of $M$ in $(R,M,\tau)$: they don't want you to look at $a,b\in M$ and say "ah, well if I multiply these inside the twisted group ring I get $ab$." The overlines are added to remind you that they are multiplied differently: $\overline{a}\overline{b}=\tau(a,b)\overline{ab}$.
(By the way, there is either a typo in the googlebooks preview I'm reading, or else the resolution is bad, because it looks like $\overline{ab}=\tau(a,b)\overline{ab}$, but that doesn't make sense. See page 13 of Passman's Algebraic structure of group rings instead.)
Skew monoid rings
A skew monoid ring $(R,M,\sigma)$ generalizes a monoid ring again by not assuming that the elements of $R$ commute with the elements of $M$: that is, $mr=\sigma(r)m$ where $\sigma$ is a ring homomorphism of $R$ into itself. In this skew ring, you can still write elements of $M$ without bars because they are multiplied in $(R,M,\sigma)$ and in $M$ exactly the same way.
Crossed products
This is what you get when you do twisting and skewing simultaneously. It's inadvisable to drop the bars from the elements of $M$ because of the twisting.
Comment: Now I know that the symbol bar means that the multiplication in the crossed product of a ring and a monoid is different to that of the usually multiplication.Thank you very much!


Copiar conteúdo de um div ao clicar em um botão

Question: Tenho um encurtador de URL, onde há listagem com todos os links gerados.
O que eu preciso, é criar um botão ao lado, em que, quando a pessoa clique em cima dele, copie automaticamente a div que contém o link encurtado.
Tô tentando algo assim:
window.onload = function() {
document.getElementById("link").innerHTML = document.getElementById("btCopia").innerHTML;
}

O HTML está assim

teste1.1

COPIAR

A sintaxe não está Ok, alguém já fez algo parecido, talvez com Jquery?
Comment: Pode postar a parte HTML relevante?
Comment: Editei a pergunta.
Comment: Felipe: queres copiar `teste1.1` e mudar o `COPIAR` para ser `teste1.1`? tens outros campos onde queres fazer o mesmo? com ids também?
Answer: Boa noite, talvez eu esteja falando mais do mesmo mas acho válido ressaltar que, levando em consideração o fato do Felipe não apresentar no código dele o uso de Jquery, e o Anmaia recomendar, gostaria de propor só mais dois detalhes na proposta do Anmaia, sendo eles:
1 - Incluir o CDN na sua pagina:

2 - A inclusão do Ready do Jquery no código de exemplo:

http://api.jquery.com/ready/
No mais acho que é só isso mesmo.
Answer: Para fazer o mesmo com jQuery é o seguinte:
$("#link").text($("#btCopia").text())

Esse trecho de código vai copiar o valor de btCopia para link.
Sugestão
Modifique o seu html e javascript para capturar isso de uma forma mais fácil. Você está usando o onload em seu javascript, talvez o código a seguir melhore sua implementação:

[Valor do link]

[Esse valor deve ser copiado para #link]

<button id="btCopiar">Copiar</button>

Dessa forma, toda vez que você clicar no botão btCopiar o conteúdo de paraCopiar vai para link.
Comment: Apenas os elementos filhos do elemento que possui o id `btCopia`?
Comment: @Patrick veja se a sugestão em minha resposta te ajuda.


Basic Complex Analysis Questions

Question: A few quick questions from an older text on complex analysis:
$|e^{it}|^2=e^{it}\cdot\overline{e^{it}}=e^{it}\cdot e^{-it}$
I'm not sure about the notation $|e^{it}|^2$, but I'm assuming it indicates the magnitude of the vector squared?  If so, I'm having trouble getting to the next part, $e^{it}\cdot\overline{e^{it}}$, which seems to be $e^{it}$ times its complex conjugate?
A separate question, this line of reasoning: if $z=x + iy$ then $e^z=e^xe^{iy}$ and therefore $|e^z|=e^x.$
Can't grok how that follows.
Text: Rudin, Real and Complex Analysis, 1970, p. 3
Comment: It is just $|z|^2 = z*\bar{z}$, nothing extraordinary or tricky.
Comment: If $y\in\mathbb R$, then $\lvert e^{iy}\rvert=1$
Answer: For your second question, note that
$\displaystyle |z \times w| = |z| \times |w|, ~: ~z,w \in \Bbb{C}.$
The above result may be manually verified by setting
$\displaystyle z = (x + iy), w = (u + iv)$
and then comparing
$\displaystyle |~(x + iy)(u + iv)~|$ with
$\displaystyle \sqrt{x^2 + y^2} \times \sqrt{u^2 + v^2}.$
Further, as indicated by the answer of José Carlos Santos, any complex number of the form $e^{i\theta}$ is some element of the unit circle.
Therefore, for all $\displaystyle \theta, ~|e^{i\theta}| = 1.$
Answer: If $z\in\Bbb C$, and if $a,b\in\Bbb R$ are such that $z=a+bi$, then\begin{align}z\cdot\overline z&=(a+bi)(a-bi)\\&=a^2+b^2\\&=\sqrt{a^2+b^2}^2\\&=|z|^2.\end{align}
Besides, if $y\in\Bbb R$, then\begin{align}|e^{yi}|&=|cos(y)+\sin(y)i|\\&=\cos^2(y)+\sin^2(y)\\&=1.\end{align}
Answer: Given $z=x+iy$ we have that $z \overline{z} = (x+yi)(x-yi)=x^2 + xyi - xyi -(yi)^2 = x^2 + y^2$ which is the magnitude squared.

Basic Complex Analysis Questions


A question about rearranging order of sequence

Question: Let $a$ be limit point of sequence of $\{x_n\}$ ,let $\{y_n\}$ be a sequence obtained by rearranging the order of the term of $\{x_n\}$ adding a finite or infinite number of additional terms .prove that $a$ is limit point of $\{y_n\}$
I don't have any idea of all the sides please help me
Comment: @MeesdeVries,,i was miss the class
Comment: @MeesdeVries..can you help it i was studying but i dont understand concept
Answer: Consider the definition of a limit point: A point $x \in \mathbb{R}$ is a limit point of a numerical sequence $(a_n)$ if, $\forall \epsilon > 0, \{n: |a_n - x| \leq \epsilon\}$ is infinite.
So in your problem setup, there are infinitely many terms in $x_n$ that are arbitrarily close to $a$. To make it concrete, let's arbitrarily pick an $\epsilon^* > 0$. Since $a$ is a limit point of $(x_n)$, there are infinitely many terms in $x_n$ s.t. $|x_n - a| \leq \epsilon^*$.
Let $S = \{x_n: |x_n - a| \leq \epsilon^*\}$.
What is the intersection of $S$ and the set of elements of $y_n$?
Comment: @ken47..sorry youe answer is dufficulty to undertand
Comment: Let's make this even more concrete. The fact that $a$ is a limit point of the sequence $(x_n)$ means that there are infinitely terms of $(x_n)$ such that $|x_n - a| \leq 1$. In other words, there are infinitely many terms that are within 1 unit of $a$.

But this is not just true for 1. The definition of a limit point says that you can pick any positive number, called $\epsilon$, and there will be infinitely many terms of $(x_n)$ that are within $\epsilon$ units of $a$.


Is there any way to load a template dynamically inside of a static navbar template based on the current url?

Question: Hi I'm new to django and I'm trying to make a site with it. My project structure is currently like so:
project/
    manage.py
    project/
        __init__.py
        settings.py
        urls.py
        myapps/
            __init__.py
            main/
                __init__,models,views,urls,etc...
                static/
                    main/
                templates/
                    main/

I'm using html5boilerplate with all the css, javascript and images are located in
myapps/main/static/main/

And all of my templates reside in
myapps/main/templates/main/

With unique names. When the user hits the main page they load up a slightly modified index.html (renamed to boilerplate.html) that came with html5bp:

{% load static %}
...

    {% include "main/index.html" %}

...

I'm using index.html as my static sidebar but I have it in a separate template in case I want to change it down the line and it separates the boring stuff from the fun stuff (who likes looking at bp code?).

    ...

    {% include /*SOMETHING HERE*/ %}

Now whenever a user is redirected to a new page I just want to resolve the destination url and change the include tag to include a completely different template. So I figured I'd have to pass the requested url to a view function and return a template from that, but I am unsure how to do this or if it would work. Sorry if this is a repeat question from somewhere, I did look and couldn't find anything relevant.
Answer: You're thinking about this the wrong way round: you should use template inheritance. Your view should render the specific template for that URL, but each template should in turn extend index.html which provides the sidebar and the rest of the structure.
Comment: Ok so I just read up on this. Just to be clear I should have index.html extend boilerplate.html, and instead of including index.html in boilerplate.html, I should use a {% block content %}? Then for my other pages I just extend index.html, replace the /*SOMETHING HERE*/ line with another {% block content %}?


React Router *Not Found* rendered first before main routes

Question: i am working on a huge project and i have an authorization system where Logged in users can access certain routes while the Not Found component, served on Logged Out Users. The problem is, when a user is marked as logged in and has a valid token and then proceed into a page (e.g /account), the component Not Found is rendered first and a second later the component account is rendered correctly.
I have an async componentDidMount where i validate my token and if it's valid, i set the state of isLogged: true. Also on each route in my switch i am checking the the state of isLogged and only then i send the corresponding component.
My async componentDidMount
{/* Username is from localstorage */}

async componentDidMount() {
  if ((USERNAME != "") && (USERNAME != null)) {
    const logged = await checkTheToken({'Username': USERNAME}).then((result) => {
      if(result.status == 202) {
         this.setState({isLogged: true});
         this.setState({checking: false});
      };
    });
  }
}

This is the Router (* supposing we are trying to access /user page. Notice i use react-router, react-router-dom ^4.1.1* )
   if (this.state.checking) {
        return null;
   } else {
   return (
     <Router>
        <Switch>
            {/* This is Not Rendered First and Not Found rendered before FALSLY */}

            {this.state.isLogged && <Route exact path="/user" component={() => (<User isLogged={this.state.isLogged} username={USERNAME} />)} />}

            {/* This is Rendered First and Not Found is not rendering at all CORRECTLY */}

            <Route exact path="/test" component={() => (<Test isLogged={this.state.isLogged} />)} />

            <Route component={() => (<NotFound isLogged={this.state.isLogged} />)} />
        </Switch>
     </Router>
   );

I think the problem is in the {this.state.isLogged && ...} because if we try to access /test the component is rendered correctly without Not Found rendering first.
Also, I tested all the lifecycle methods
Comment: Have you tried doing the auth check  in `componentWillMount`, your component has already rendered before it gets to `componentDidMount`.
Comment: I tested all the lifecycle methods
Comment: You probably need to add a state field like `checking` that defaults to `true`. And when you have got a response either success or error set `checking` to `false`. In your render `if(this.state.checking) return null;`.
Comment: i've updated my question based on your comment. Home is not rendered at all now
Comment: Which is `Home`? You need to move the `this.state({checking: ..` outside the `if(result.status...)` and you also need to put it where you catch if the request has errors. as `checking` needs to be set to `false` regardless of the response from your auth check. If you are not getting any errors and it definitely setting state then the code looks fine. I don't think you need to have the `async`/`await` on your `componentDidMount` function either since we are using state to manage the asynchronous nature of your auth check.
Answer: I think you're right and the issue comes from {this.state.isLogged && ...}
Lets take it step by step.
First this.state.isLogged is falsy. It does mean that <User isLogged={this.state.isLogged} username={USERNAME} /> is not currently in the ReactRouter configuration.
We can guess that ReactRouter will match the default component (<Route component={() => (<NotFound isLogged={this.state.isLogged} />)} />) since /user is not in its configuration.
The actual behavior is then correct.
The fastest way to archieve your goal would be to move the token check into your child component with something like this :
async componentDidMount() {
  if ((USERNAME != "") && (USERNAME != null)) {
    const logged = await checkTheToken({'Username': USERNAME}).then((result) => {
      if(result.status !== 202) {
        history.push('/not-found')
      } else {
        this.setState({isLogged: true});
        this.setState({checking: false});
      };
    });
  }
}

Rendering function would like this :
render () {
 if(!this.state.isLogged) return
 return
...

}

The main problem with this aproach is that it would require all your authenticated components to implement this.
You'll also need to factorize the code into a service to avoid multiple calls.
A 2nd approach would be to fatorize this into a proxy component that do the check like this :
<Router>
    <Switch>
        <Route component={Authenticated}>
           <Route exact path="/user" component={() => (<User isLogged={this.state.isLogged} username={USERNAME} />)} />
        </Route>
        <Route exact path="/test" component={() => (<Test isLogged={this.state.isLogged} />)} />
        <Route component={() => (<NotFound isLogged={this.state.isLogged} />)} />
    </Switch>
 </Router>

This component will now be the one who carry the token check.
Rendering function would look like this :
render () {
 if(!this.state.isLogged) return
 return {this.props.children}
}

Main problem here is that you can't easily share between your component the "this.state.isLogged"
If you want to share and update mutiple component using some global state, i highly suggest you to give a look at Redux.
Since redux can have a hard learning curve, if you only need to share this single value, you could try some things using the observable pattern. (Example : observable service, observable service + connector )
All my code example are not tested and are here to guide you in the right direction. In my opinion there is a lot of way to archieve what you want, sadly i can only tell you why it currently do not work and i hope i gave you enough clues to find a solution adapted to your use case.
Comment: And a 2nd example on how to make a connector for your service https://jsfiddle.net/qcdmuzac/2/
Comment: Thanks for the answer! I moved the checkToken on each corresponding component. As a result, each component on ComponentDidMount has to check for isLogged user. I dont think if this is optimized (possibly not) but it works. I prefer to avoid multiple calls to db when i load my component and i prefer to pass the value from one component to another through props but i think is the only way.

Regarding the 2nd approach, i have react router v4 and i cannot add nested Routes on my Router. I tried to downgrade the Router but i receive multiple errors let me know if you want to update the question
Comment: As you said i have to factorize the code into a service. I'll check it.


Powershell -or isn't working -or I'm using it wrong.

Question: I've tried to use it both ways and it deleted the files no matter what. Basically if any of the variables are true I don't want it to delete the file, but it does anyway. I know that $Paper= MN and it still deletes the file. I'm obviously doing something wrong.
if(!$Paper.equals("MN") -or !$Paper.equals("NJ") -and $extension.equals(".txt")){
Remove-Item $File.FullName -Force -Recurse
write-host $File " has been removed."
}

if($Paper -ne "MN" -or $Paper -ne "NJ" -or $extension -eq ".txt"){
Remove-Item $File.FullName -Force -Recurse
write-host $File " has been removed."
}

Answer: The issue is that you need to change all the -or to -and for both examples. Because otherwise it will always evaluate to true.
Comment: yep. good catch. !$Paper.equals("MN") -or !$Paper.equals("NJ") always evaluates to true.
Comment: Yeah, I think what his train of thought was `If(!($Paper.equals("MN") -or $Paper.equals("NJ")) -and $extension.equals(".txt"))` but didn't have the parenthesis in there to group his -or's together for the -Not statement.
Answer: Lets put your first if in a truth table:
!$Paper.equals("MN") i will call that NOT A
!$Paper.equals("NJ") i will call that NOT B
$extension.equals(".txt") i will call that C
your expression is   NOT A OR NOT B AND C = delete
so here is the table:
A  B  C  delete
0  0  0  0
0  0  1  1
0  1  0  0
0  1  1  1
1  0  0  0
1  0  1  1
1  1  0  0
1  1  1  1

Now looking at this, you should notice, that you are deleting the file when atleast one expression is not true and the file is a txt.
What you wanted to achieve is to use some brackets,
!($Paper.equals("MN") -or $Paper.equals("NJ")) -and $extension.equals(".txt")
New truth table:
NOT(A OR B) AND C = delete
A  B  C  delete
0  0  0  0
0  0  1  1
0  1  0  0
0  1  1  0
1  0  0  0
1  0  1  0
1  1  0  0
1  1  1  0

We could apply De'Morgans law here and turn

NOT(A OR B) into NOT A AND NOT B

So it will become

NOT A AND NOT B AND C

!$Paper.equals("MN") -and !$Paper.equals("NJ") -and $extension.equals(".txt")

Comment: Ok I see what you're saying.if(!$Paper.equals("MN") -and !$Paper.equals("NJ") -or $extension.equals(".txt")){
Remove-Item $File.FullName -Force -Recurse
write-host $File " has been removed."
} I would still use a -or when checking the extension because I want it to delete .txt files no matter if the first two conditions are true or not. Right? Sorry sending from my phone.
Comment: Yes. I misunderstood you then.
Answer: "Basically if any of the variables are true I don't want it to delete the file,"
Okay.
if ( ( $Paper.equals("MN"), $Paper.equals("NJ"), $extension.equals(".txt") ) -notcontains $true )
  { Remove-Item $File.FullName -Force -Recurse }


Dependency Injection if service exists

Question: Is there any way to use dependency injection in a conditional way, i.e. only if a service exists similar to \Drupal::hasService().
I have a created a service in module A and in module B I have an EventSubscriber that should use the service from module A, but only if present of course.
Static I would do sth. like:
    if (\Drupal::hasService('module_a.my_service')) {
      \Drupal::service('module_a.my_service')->mymethod();
    }
Is there any possibility to do this when injecting the service?
Comment: If it depends on it, when would it not be available?
Comment: When the module A is not installed. It's optional. I have a couple of helper services in module A that are all optional, e.g. debugging, logging and notification functionalities.
Comment: Just add some logic to your static `create` method which checks `$container->has('service')`, and pass null to the constructor for those that are missing. Then check the service is an instance of the class you expect it to be before you use it
Comment: But I don't recommend that approach because it anchors to the wrong thing. Dependency injection doesn't really work as a concept if the dependencies are optional. There are probably better practice ways to structure your code to base the decision on whether the module is installed or not, which is the real trigger, and not on whether a service exists
Comment: I see, you might be right, I'll check if I can restructure the code. Maybe additional submodules which implement the service calls and do not perform any check are better.
Answer: One possible way to handle this situation is for your Module B to define a default, stub service with the same type signature (ie, Interface) as the one you need).  Use that in the YAML.  Then, in your Module A, you can alter the service to the one that the module provides.
That said, I do agree with the comments that you may be bypassing one of the benefits of DI, and creating a tight coupling between your two modules.  Read the linked article to see when it is appropriate.  Core uses it for the language and workspaces subsystems.

Dependency Injection if service exists


What is "Carry the bat" in Cricket?

Question: I have heard the terminology "Carry the bat" in Cricket. What does it mean? When it is used?
Answer: "Carry the bat" is used when an opener (a batsman who play at number 1 or 2)  remains not out after the team is all out.
From Wikipedia:

In cricket, the term carry the bat (or carry one's bat) refers to an opening batsman who is not dismissed ("not out") when the team innings is closed.

Here the term is used when the innings is closed due to all players are out or retired out or unable to bat.
The term is not used when the innings is except above reasons. E.g. declaring the innings, win the match etc.
The term is used like this:

Rahul Dravid carries the bat for 146.

See the list of carrying the bat in:

Test
ODI
Answer: It basically means that the batsman was at bat for the entire inning and, since he never got out, he "carried the bat" the entire time (as opposed to handing it over to another batsman once he was out).

What is "Carry the bat" in Cricket?


Powder Problems Snowboarding

Question: This is a big issue that I am having when I am doing snowboarding runs on powder. Usually, when there is fresh powder from overnight or accumulation during the day, I tend to "trip over" and lose my balance over accumulated powder debris. What type of skills/drills can I do to make sure that this does not happen ?
I am able to do powder turns just fine in green level but when at times, It is really easy for me to pick up speed and lose control where I just trip over. When it gets to blue and black runs, I tend to really have this issue of tripping over since the snow is much deeper. While at really steep runs, I tend to do a turn (say toe turn) and while switching to my heel turn, I tend to traverse horizontally with my board and fall on my butt. Could someone provide some advice on how I can get better ?
I also tried to lean back but didnt exactly shift the bindings to the back (but could this really make that large of a difference) ?
Thanks
Answer: I always found that having my bindings set slightly back on the board (leaving you with more tip length than tail length) makes a big difference in deeper powder. It gives you a little more confidence in being able to keep your nose out of the powder and "hydroplane" ("snowplane" ?) on the surface. I always rode the Burton EST bindings on the rail system whenever I could so I could shift them just slightly without much effort. You can always have a separate board set up for powder but that kind of requires you to commit to one or the other for the day.
Also, whereas you want to keep your weight a little bit forward on groomed slopes, you want to shift your weight slightly backwards in your stance. Nothing extreme, because that will also yield problems, but only as much as you would shift forward on groomed stuff.
One last thing that's helped me, and I'm not sure its a common thing or just something I've come across, if you start feeling yourself sinking in, do a gentle dip-and-jump thing. Kind of mimicking the motion you would do to start your spring at the end of a diving board. I think it sort of compacts the snow under you just slightly, ushering your board back up over the top of that and back up around the surface.
Most importantly in powder however, is be sure of your terrain under the surface. Powder is a ton of fun and a great place to learn (always nicer dumping it backwards in powder than on packed down slopes). Just know it's a lot different from hoping off a chairlift and bombing the main lines.

Powder Problems Snowboarding


Why is the weak* topology not in general metrizable?

Question: A Banach space is a topological group under addition. The dual is a topological group under the weak$^*$ topology. The weak$^*$ topology is weaker than the operator norm topology, so is it first-countable? It is also Hausdorff. (Seems intuitively obvious, might require the Hahn-Banach Theorem to make rigorous). So by the Birkhoff-Kakutani Theorem it should be metrizable. But I believe this is only the case for the finite-dimensional case. Where is my reasoning wrong?
Comment: First countability doesn't transfer to stronger or weaker topologies. Discrete topology and trivial topology are both always first countable and any topology is between the two.
Comment: "The weak* topology is weaker than the operator norm topology, so is first-countable" is, except in the finite-dimensional case, wrong.
Answer: If a topological space is metrizable, then it has to be first countable.
It turns out that, if $X$ has uncountable base (as a linear space), then the weak$^*$ topology of $X^*$ is not first countable. See
The weak$^*$ topology on $X^*$ is not first countable if $X$ has uncountable dimension.
But, even if the dimension of a normed space is $\aleph_0$, then its dual shall coincide with the dual of the completion of $X$, which will have dimension $2^{\aleph_0}$, and hence the weak$^*$ topology of $X^*$ will not be first countable, as well.
Comment: Is the weak* topology on $X^*$ induced by the completion of $X$ the same as the weak* topology on $X^*$ induced by $X$?
Comment: If and only if $X$ is complete. I'm sure that was a rhetorical question by @DavidMitra, but just in case somebody doesn't know: if $Y$ is a (linear) subspace of the completion of $X$ such that $\lambda\lvert_Y = \mu\lvert_Y \implies \lambda = \mu$ for $\lambda,\mu\in X^\ast$, then the dual space of $X^\ast$ with the weak* topology induced by $Y$ is $Y$, so no two such subspaces induce the same weak* topology on $X^\ast$.
Comment: Please explain more about when "the dimension of a normed space is ℵ 0 " part. Reading above result, I can not understand it or give me a reference about it.
Comment: Dear @DanielFischer or others also who could give me a hand : what happens if $X$ is not Banach? I am not sure why this is neccessary (or convenient) in the above argument. Thank you.
Comment: What happens if $X$ is not Banach? Can't we say also that then its dual has an uncountble dimension? @DavidMitra Thank you.
Comment: Dear @Yiorgos, could you please give a reference of where can I read that the dimension of continuous dual is also always strictly bigger than that of the original space? And what happens if $X$ is not Banach?


Show that $E|X-Y| = \int_{\mathbb{R}}[F(t) + G(t) - 2H(t,t)]dt $

Question: Assume $X$, $Y$ random variables with joint distribution function $H$ and their respective marginals $F$ and $G$.
I'm trying to show that:
$$E|X-Y| = \int_{\mathbb{R}}[F(t) + G(t) - 2H(t,t)]dt $$
My approach: So far I know that
$$ E|X-Y| = \int\int_{\mathbb{R}^2}|x-y| \text{d}H(x,y)$$
from where we can straightforwardly try to reduce the integral to
$$ \int_{-\infty}^{\infty}\int_{-\infty}^{x}(x-y) \text{d}H(x,y)  + \int_{-\infty}^{\infty}\int_{x}^{\infty}(y-x) \text{d}H(x,y) $$
However, I'm not sure how to proceed from here, that is, how to think about working with the $\text{d}H(x,y)$ term and how to properly take it out.
Firstly, I'm not even sure if in general case we can take the $h(s,t)$ part out, where $H(x,y) = \int_{-\infty}^{x}\int_{-\infty}^{y}h(s,t)dsdt$, since $X$ and $Y$ are not necessarily continuous? Even if we could, I can't see how to properly proceed.
On the other hand, by going backwards,
$$ E|X-Y| = \int_{\mathbb{R}}[F(t) + G(t) - 2H(t,t)] dt = \int_{-\infty}^{\infty}\left(\int_{-\infty}^{t}dF(s) + \int_{-\infty}^{t}dG(s) - 2\int_{-\infty}^{t} \int_{-\infty}^{t} dH(s,j)\right)dt$$
It also feels like something in the likes of
$$ \int_{-\infty}^{t}dF(s) = \int_{-\infty}^{\infty} \int_{-\infty}^{t}dH(s,j),$$
might hold, but again, I'm not entirely sure how to work with distribution functions when they are in the integral measure part.
Any hints/ideas would be appreciated!
Answer: By the very definition of the distribution function, we have
$$\begin{align*} F(t)+G(t)-2H(t,t) &= \mathbb{P}(X \leq t) + \mathbb{P}(Y \leq t) - 2 \mathbb{P}(X \leq t, Y \leq t) \\ &= \bigg( \mathbb{P}(X \leq t, Y \in \mathbb{R}) - \mathbb{P}(X \leq t, Y \leq t) \bigg) \\ &\quad + \bigg( \mathbb{P}(Y \leq t, X \in \mathbb{R}) - \mathbb{P}(Y \leq t, X \leq t) \bigg) \\ &= \mathbb{P}(X \leq t, Y>t) + \mathbb{P}(Y \leq t, X>t)\end{align*}$$
for any $t \in \mathbb{R}$. This implies
$$F(t)+G(t)-2H(t,t) = \mathbb{P} \left( \min\{X,Y\} \leq t, \max\{X,Y\}>t \right). \tag{1}$$
Applying Tonelli's theorem and using the elementary identity
$$|x-y| = \max\{x,y\} - \min\{x,y\}$$
we find
$$\begin{align*} \int_{\mathbb{R}} \mathbb{P}(\min\{X,Y\} \leq t < \max\{X,Y\}) \,dt &= \mathbb{E} \left( \int_{\mathbb{R}} 1_{\{\min\{X,Y\} \leq t < \max\{X,Y\}} \, dt \right) \\ &= \mathbb{E} \left( \int_{\min\{X,Y\}}^{\max\{X,Y\}} \, dt \right) \\ &= \mathbb{E}(\max\{X,Y\}-\min\{X,Y\}) \\ &= \mathbb{E}(|X-Y|); \end{align*}$$
combining this with $(1)$ this proves the assertion.


Como resolver problema de "Access-Control-Allow-Origin"

Question: Não estou sabendo resolver o problema de Access-Control-Allow-Origin. O que fazer para funcionar corretamente?

function calc() {

 var cepDestino = document.getElementById( 'cepDestino' ).value;
 if(cepDestino.trim() != ""){
  var request = new XMLHttpRequest();

  request.open('GET', 'http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep='+cepDestino, true);

  request.onload = function() {
   if (request.status >= 200 && request.status < 400) {
    var data = JSON.parse(request.responseText);
    document.getElementById('bairro').value(data.bairro);
    document.getElementById('cidade').value(data.cidade);
    document.getElementById('estado').value(data.estado);
   } else {
    // Não deu certo
   }
  };

  request.onerror = function() {
    // A conexão nem sequer deu certo
  };

  request.send();
 }
}

  CEP Destino
  <input class="input" type="text" name="cepDestino" id="cepDestino" >

 -

 -

  <input class="button" type="button" id="calcular" value="Calcular" onclick="calc();">

Comment: @PedroCamaraJunior Eu não estou usando jquery. Não tem nada haver meu problema com esse existente.
Comment: Descuple, marquei a pergunta errada: Duplicada relacionada http://pt.stackoverflow.com/questions/3183/requisi%C3%A7%C3%A3o-ajax-cross-domain-com-javascript-puro-sem-apis
Answer: Esta API tem como parâmetro o tipo de retorno, para trabalhar com CORS e JSON, você deve especificar formato=jsonp na URL do request.
Fora isto, temos outros problemas, o primeiro é o envio sincrono do AJAX, raramente isto é uma boa ideia.
uma tag
 não possui uma propriedade value, e mesmo que tivesse ela não é um método e sim uma propriedade, em todo caso você deve setar o textContent da div.

function calc() {

 var cepDestino = document.getElementById( 'cepDestino' ).value;
 if(cepDestino.trim() != ""){
  var request = new XMLHttpRequest();

  request.open('GET', 'http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=' + cepDestino + '&formato=jsonp', false);

  request.onreadystatechange = function() {
   if (request.status == 200 && request.readyState == 4) {
    var data = JSON.parse(request.responseText);
    document.getElementById('bairro').textContent = data.bairro;
    document.getElementById('cidade').textContent = data.cidade;
    document.getElementById('estado').textContent = data.estado;
   } else {
    // Não deu certo
   }
  };
  request.send();
 }
}
label {
 width: 100%;
 display: inherit;
 font-weight: bold;
 font-size: 3em;
 margin-top: 41px;
}
.input, #descricao {
 width: 100%;
 height: 111px;
 font-weight: bold;
 font-size: 4em;
 text-align: center;
 border-radius: 5px;
 background-color: #ECF0F1;
}
.button {
 width: 100%;
 font-size: xx-large;
 height: 116px;
 background-color: #2CC36B;
 border-radius: 5px;
 margin-top: 76px;
}

  CEP Destino
  <input class="input" type="text" name="cepDestino" id="cepDestino" />

 -

 -

  <input class="button" type="button" id="calcular" value="Calcular" onclick="calc();">


pegar evento click dentro do html dentro de uma varivel javascript

Question: Como eu pego o evento do click de codigo html dentro de uma constante criada no javascript, por exemplo como no codigo abaixo:
function mostrarDados(){
    resultado.innerHTML = '';
    for (let i = 0; i < usersDB.length; i++) {
        const e = usersDB[i];
        const usuario = `

${e.nome}

${e.email}

${e.endereco}

${e.bairro}

${e.cidade}

${e.telefone}

${e.data}

        `;
        resultado.innerHTML += usuario;
    }

}

O que estou tentando fazer criar uma function editar o conteudo do localstorage, mas não estou pegando parametro na function, isso é possivel fazer?

Deixa eu melhor a pergunta, por exemplo:
ao criar a const usuario dentro dela tem a tag 'a' coma class btn-editar, ao criar o addEventlistener pegando a class btn-editar quando clico no btn editar no navegador não funciona.
Vou colocar todo o codigo se minha duvida fica mais clara.
const btnCadastrar = document.querySelector('#btn-cadastrar');
const modal = document.querySelector('.modal');
const formulario = document.querySelector('.formulario');
const salvar = document.querySelector('.salvar');
const cancelar = document.querySelector('.cancelar');
const fechar = document.querySelector('.btn-fechar');
const resultado = document.querySelector('.resultado');
const btnEditar = document.querySelector('.btn-editar');

const nome = document.querySelector('#nome');
const email = document.querySelector('#email');
const endereco = document.querySelector('#endereco');
const bairro = document.querySelector('#bairro');
const cidade = document.querySelector('#cidade');
const telefone = document.querySelector('#telefone');
const data = document.querySelector('#data');

const usersDB = localStorage.getItem('Usuarios') ?
    JSON.parse(localStorage.getItem('Usuarios')) : [];

btnCadastrar.addEventListener('click', function(){
    modal.classList.add('show');
    modal.classList.remove('hide');
    formulario.classList.add('show-form');
    formulario.classList.remove('hide-form');
});

fechar.addEventListener('click', function(){
    modal.classList.add('hide');
    modal.classList.remove('show');
    formulario.classList.add('hide-form');
    formulario.classList.remove('show-form');
    formulario.reset();
});

cancelar.addEventListener('click', function(){
    modal.classList.add('hide');
    modal.classList.remove('show');
    formulario.classList.add('hide-form');
    formulario.classList.remove('show-form');
    formulario.reset();
});

salvar.addEventListener('click', function(){
    gravarDB();
});

function editar(){
    alert('Teste');
}

// btnEditar.addEventListener('click', function(){
//     alert('eric');
// });

function gravarDB(){
    const newId = usersDB.length +1;
    const pegaItems = {
        id: newId,
        nome: nome.value,
        email: email.value,
        endereco: endereco.value,
        bairro: bairro.value,
        cidade: cidade.value,
        telefone: telefone.value,
        data: data.value
    }
    usersDB.push(pegaItems);
    localStorage.setItem('Usuarios', JSON.stringify(usersDB));

    mostrarDados();
    formulario.reset();
}

function mostrarDados(){
    resultado.innerHTML = '';
    for (let i = 0; i < usersDB.length; i++) {
        const e = usersDB[i];
        const usuario = `

${e.nome}

${e.email}

${e.endereco}

${e.bairro}

${e.cidade}

${e.telefone}

${e.data}

        `;
        resultado.innerHTML += usuario;
    }

}

mostrarDados();

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='https://firstname.lastname@example.com/css/boxicons.min.css' rel='stylesheet'>
    <link rel="stylesheet" href="./assets/css/style.css">
    <title>CRUD</title>

                    Cadastrar

                    <form class="formulario hide-form">

Cadastro de Clientes

                                    <input id="nome" type="text" placeholder="Nome Completo">

                                    <input id="email" type="email" placeholder="email">

                                    <input id="endereco" type="text" placeholder="Endereço">

                                    <input id="bairro" type="text" placeholder="Bairro">

                                    <input id="cidade" type="text" placeholder="Cidade">

                                    <input id="telefone" type="text" placeholder="Telefone">

                                    Data
                                    <input id="data" type="date" id="data">

                                    Salvar

                                    Cancelar

                    </form>

Comment: Não entendi a pergunta. A julgar pelo código, você gostaria de saber como adicionar eventos a código HTML gerado dinamicamente?
Comment: Depois que os elementos criados dinamicamente existirem no DOM – ou seja, depois do seu loop `for` – é possível atrelar event listeners a eles normalmente.
Answer: Pelo que entendi, você deseja ativar a função "editar()" quando o botão de edição for clicado e enviar o evento para saber qual foi o índice do botão de edição clicado.
Uma abordagem seria utilizar o evento onClick para enviar o evento. Segue um exemplo:
function mostrarDados(){
resultado.innerHTML = '';
for (let i = 0; i < usersDB.length; i++) {
    const e = usersDB[i];
    const usuario = `

${e.nome}

${e.email}

${e.endereco}

${e.bairro}

${e.cidade}

${e.telefone}

${e.data}

    `;
    resultado.innerHTML += usuario;
}

}
Agora lá na função que vai ser chamada:
function editar(e){
  console.log(e.target);
  console.log(e.id);
}

Dê uma olhada no console.log(e.target);, ele possui uma série de atributos que você pode utilizar. Por exemplo, é possível obter o texto que está dentro do botão, a posição do mouse e muito mais. Depois, confira a documentação sobre eventos do JavaScript em https://developer.mozilla.org/en-US/docs/Web/API/Event para mais informações.


How do I add ajax callback to a form element which is created in a foreach loop

Question: Please see the following code:
foreach ($formaddresses as $key => $val) {
  // Add edit buttons to custom client-side created addresses.
  if (!isset($val['accountnumber'])) {
    $form['orderinfo']['billshipaddresses']['billingaddresses'][$key]['#description'] = 'Edit';
    $form['orderinfo']['billshipaddresses']['shippingaddresses'][$key]['#description'] = 'Edit';
  }
}

Here this loop is creating some anchors in my form.
I just need to attach/add '#ajax' callback to it.
How can I achieve this?
Something like the following code:
$form['orderinfo']['billshipaddresses']['shippingaddresses'] = [
  '#type' => 'radios',
  '#title' => 'Shipping Address',
  '#options' => $formaddressesOptions,
  '#default_value' => '',
  '#ajax' => [
    'callback' => '::buildShipBillAddresses',
    'wrapper' => 'shippingaddresses',
    'event' => 'change'
  ],
];

Here we can see if the above radio is change then an ajax callback will work and will call this method buildShipBillAddresses
Thanks!
Answer: Actually, the anchor element to which you want to add an AJAX callback isn't a form element. The Ajax API page says how to trigger AJAX for a link.

Add class 'use-ajax' to a link. The link will be loaded using an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax JavaScript processes the page, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

This means that for a link, the following code would work.
foreach ($formaddresses as $key => $val) {
  // Add edit buttons to custom client-side created addresses.
  if (!isset($val['accountnumber'])) {
    $form['orderinfo']['billshipaddresses']['billingaddresses'][$key]['#description'] = 'Edit';
    $form['orderinfo']['billshipaddresses']['shippingaddresses'][$key]['#description'] = 'Edit';
  }
}

The module needs to define two routes for those links. I cannot tell you the code for those route callbacks, but they should render the Edit form to make it appear on that form.
Answer: This isn't really a Drupal question so much as a PHP question, but to answer your question:
foreach ($formaddresses as $key => $val) {
  // Add edit buttons to custom client-side created addresses.
  if (!isset($val['accountnumber'])) {
    $form['orderinfo']['billshipaddresses']['billingaddresses'][$key]['#ajax'] = [
      'callback' => '::buildShipBillAddresses',
      'wrapper' => 'shippingaddresses',
      'event' => 'change'
    ];
  }
}


Combobox Ajax PHP Nao retorna nada

Question: Nao consigo retornar nada .. quando testo em vez do campo cidade e apago ai ele retorna mas com o nome da cidade ele nao retorna
tem limite de dados para um CMB?
$(document).ready(function() {
    $('#carrEst').change(function(e) {
        $('#carrCid').empty();
        var id = $(this).val();
        $.post('../include/carrCid.php', {ufid:id}, function(data){
            var cmb = '<option value="">Selecione a Cidade</option>';
            $.each(data, function (index, value){
                cmb = cmb + '<option value="' + value.cidadeid + '">' + value.cidaden + '</option>';;
            });
            $('#carrCid').html(cmb);
        }, 'json');
    });
});

PHP
if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
 $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest") {
$conexao = mysqli_connect('localhost', 'root', '', 'rhsystem') or
 die(mysqli_error($conexao));
$ufid = filter_input(INPUT_POST, 'ufid', FILTER_SANITIZE_NUMBER_INT);
//$ufid = 48;
if ($ufid) {
    $query = mysqli_query($conexao, "SELECT idCidade, cidade FROM tbCidade WHERE fkEstado =" . $ufid . "");
    $linhas = array();
    while ($jm = mysqli_fetch_array($query)) {
        $linhas[] = array(
            "cidadeid " => $jm["idCidade"],
            "cidaden" => $jm["cidade"],
        );
    }

    echo json_encode($linhas);
 }

}
HTML
<!DOCTYPE html>

        TODO supply a title

            Estado *

                <select id="carrEst" >
                </select>

            Cidade *

                <select id="carrCid" >
                </select>

Codigo para salvar no banco JavaScript
  $("document").ready(function () {

  $("#btngravar").click(function () {

    $.post("../include/cadfunc.php", {oper: "1", nome: $("#txtnome").val(),cpf: $("#txtcpf").val(),
        endereco: $("#txtendereco").val(),  cep: $("#txtcep").val(),complemento: $("#txtcomplemento").val(),bairro: $("#txtbairro").val(),
        dtNasci: $("#dtaNascimento").val(), sexo: $("#cmbSexo").val(), email: $("#txtemail").val(),dtaAdm: $("#dtaAdmissao").val(), UF: $("#carrDpto").val(),
        cidade: $("#carrCid").val(), dpto: $("#carrDpto").val(), cargo: $("#carrCarg").val(), salario: $("#txtsalario").val(), status: $("#carrStatus").val()} ,function (data) {
        var items = [];
        i = 0;

        alert(data.tipo);

    });

});

});
Codigo PHP
<?php
  include "conexao.php";

$oper = $_POST["oper"];

switch ($oper) {
 case 1:
inserir($_POST["nome"],$_POST["cpf"],$_POST["endereco"],$_POST["cep"],
$_POST["complemento"],$_POST["bairro"],$_POST["dtNasci"],$_POST["sexo"],
$_POST["email"],$_POST["dtaAdm"],$_POST["UF"],$_POST["cidade"],
$_POST["dpto"],$ _POST["cargo"],$_POST["salario"],$_POST["status"],$conn);
    break;

default:
    $data = '{"tipo": "sucesso"}';
    echo $data;
 }

 function inserir($nome,

 $cpf,$endereco,$cep,$complemento,$bairro,$dtNasci,$sexo,$email,$dtaAdm,
 $UF,$cidade,$dpto,$cargo,$salario,$status,$conn) {
        $sql = "CALL InserirFunc ( '".$nome."', '".$cpf."', '".$endereco."',

    '".$cep."', '".$complemento."', '".$bairro."', '".$dtNasci. "',
 '".$sexo."',  '".$email."',' ".$dtaAdm."', ".$UF.", ".$cidade.", ".$dpto.",
 ".$cargo.", ".$salario.", ".$status.")";

        mysqli_query($conn,$sql);

    $data = '{"tipo": "sucesso"}';

    echo $data ;

  }

?>

Comment: Olá Somdesp, teria como você postar os códigos ao invés de imagens? facilita para o pessoa poder testar e te ajudar.
Comment: pronto ..primeira vez que faço uma postagem aqui nao estava conseguindo fazer por codigo agora consegui
Comment: Existe alguma cidade com acentuação por a caso?
Comment: sim..varias cidades
Comment: Tente colocar assim: `"cidaden" => utf8_encode($jm["cidade"])`
Comment: Agora funcionou .. Muito obrigado
Answer: Consegui achar uma solução
Mudei o JavaScript
$(function(){
$('#carrDpto').change(function(){
    if( $(this).val() ) {
        $('#carrCarg').hide();
        $('.carregando').show();
        $.getJSON('../include/carrCarg.php?search=',{carrDpto: $(this).val(), ajax: 'true'}, function(j){
            var options = '<option value=""></option>';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].carrCarg + '">' + j[i].nome + '</option>';
            }
            $('#carrCarg').html(options).show();
            $('.carregando').hide();
        });
    } else {
        $('#carrCarg').html('<option value="">-- Escolha um Departamento --</option>');
    }
});
});

E o PHP
header('Cache-Control: no-cache');
header('Content-type: application/xml; charset="utf-8"', true);

 include 'conexao.php';

 $carrEst = mysqli_real_escape_string($conn, $_REQUEST['carrEst']);

 $cidades = array();

  $query = mysqli_query($conn, "SELECT idCidade,nomeCidade FROM tbCidade
 WHERE fkEstado =  " . $carrEst . " ");

while ($row = mysqli_fetch_assoc($query)) {
$cidades[] = array(
    'carrCid' => $row['idCidade'],
    'nome' => utf8_encode($row['nomeCidade']),
    );
}

echo( json_encode($cidades) );

Combobox Ajax PHP Nao retorna nada


Executing 2 (similar) commands using sudo giving same exact output

Question: Here is my shell script where I'm trying to execute a command as sudo
#! /bin/sh

# Initialize values of arguments
SUDO_USER=""
SUDO_PWD=""
CMD_OR_SCRIPT=""

if ! options=$(getopt -u -o : -l sudoUser:,sudoPwd:,cmd: -- $@)
then
    echo "Wrong option given :: $1"
    exit 1
fi

set -- $options

while [ $# -gt 0 ]
do
    case $1 in
        --sudoUser)
                SUDO_USER="$2"
                shift
                ;;

        --sudoPwd)
                SUDO_PWD="$2"
                shift
                ;;

        --cmd)
                CMD_OR_SCRIPT="$2"
                shift
                ;;

    esac
    shift
done

if [ "$CMD_OR_SCRIPT" != "" ]; then
    if [ "$SUDO_USER" != "" ]; then
        if [ "$SUDO_PWD" != "" ]; then
            echo $SUDO_PWD | sudo -k -S -u $SUDO_USER $CMD_OR_SCRIPT
        else
            sudo -u $SUDO_USER -k -S $CMD_OR_SCRIPT
        fi
    else
        if [ "$SUDO_PWD" != "" ]; then
            echo $SUDO_PWD | sudo -k -S $CMD_OR_SCRIPT
        else
            sudo $CMD_OR_SCRIPT
        fi
    fi
fi

when i run the command as-
./execSudoScript.sh --sudoUser root --sudoPwd pass --cmd ls

I get the contents of current directory as output as expected. But if I run the command as-
./execSudoScript.sh --sudoUser root --sudoPwd pass --cmd ls /opt

I still get the contents of current directory, instead of getting the contents of /opt. Is it the space after ls that is causing htis? How do I fix this?
Answer: The problem is that your script only accepts one argument after --cmd. That means that your command can only have one token in it.
I suggest that you take all positional arguments as the command to run, and pass that to sudo using "$@". For that to work, you will need to avoid shifting off all the non-option arguments like you're currently doing.
For example, you might do this:
while [ "$#" -gt 0 ]; do
    case "$1" in
    --sudoUser)
        SUDO_USER="$2"
        shift 2;;
    --sudoPwd)
        SUDO_PWD="$2"
        shift 2;;
    *)
        break;;
    esac
done

then, for the rest of your script, replace all instances of $CMD_OR_SCRIPT with "$@" (the double-quotes are required). Also, do not specify --cmd when running your script. Thus, for your sample usage, you should use:
./execSudoScript.sh --sudoUser root --sudoPwd pass ls /opt

At the OP's request, here's an edited version of the whole script:
#!/bin/sh

# Initialize values of arguments
SUDO_USER=""
SUDO_PWD=""

while [ "$#" -gt 0 ]; do
  case "$1" in
  --sudoUser)
    SUDO_USER="$2"
    shift 2;;
  --sudoPwd)
    SUDO_PWD="$2"
    shift 2;;
  *)
    break;;
  esac
done

if [ -n "$SUDO_USER" ]; then
  if [ -n "$SUDO_PWD" ]; then
    echo "$SUDO_PWD" | sudo -k -S -u "$SUDO_USER" "$@"
  else
    sudo -u "$SUDO_USER" "$@"
  fi
else
  if [ -n "$SUDO_PWD" ]; then
    echo "$SUDO_PWD" | sudo -k -S "$@"
  else
    sudo "$@"
  fi
fi


Replace full path with one string if

Question: I have a lot of paths in one file and i need to change paths with specific string IF there is .jpg, .pdf
For example:
I have right now lines like those:
images/2015/somename.jpg
images/2012/somefile.pdf

2015/2012 could be 1997 or 2010 etc - random year numbers.
I would like to change those lines with sed (if possible)  like this
images/somename.jpg
files/somefile.pdf

I tried like so:
echo "images/2015/image12345.jpg" | sed 's/images[^0-9]*[^0-9]/\/images/;' - no result
Or maybe awk will be good tool for this job?
Comment: Why are you matching on non-numbers when your middle component contents are all numbers?
Comment: I just tried something to make it work. I'm not good with sed - sorry
Comment: You want to match and remove `/####` so match that.
Answer: $ cat file
images/2015/somename.c
images/123/somename.jpg
1234/2015/somename.jpg
images/2015/somename.jpg
images/2012/somefile.pdf

$ awk '/\.(jpg|pdf)$/ {sub("/[0-9]{4}/","/")} 1' file
images/2015/somename.c
images/123/somename.jpg
1234/somename.jpg
images/somename.jpg
images/somefile.pdf

Comment: Ed Morton, i got it now - thank you!
Now i have to adjust it to make it work as needed.
Answer: With gnu-sed: sed -r '/\.(jpg|pdf)$/s#/[0-9]+/#/#'
/\.(jpg|pdf)$/: Matches lines ending with .jpg or .pdf
/[0-9]+/: Matches any sequence of just digits between slashes
Example:
$ echo "images/2015/image12345.jpg" | sed -r '/\.(jpg|pdf)$/s#/[0-9]+/#/#'
images/image12345.jpg

Replace full path with one string if


Dúvida com consulta no SQL Server

Question: Eu possuo a seguinte consulta no SQL Server, para me retornar uma lista de cidades que eu necessito.
select IDCidade as "ID",

       case UF when 'RS' then '1'
       when 'SC' then '2'
       when 'PR' then '3'
       when 'SP' then '4'
       when 'RJ' then '5'
       when 'MG' then '6'
       when 'ES' then '7'
       when 'BA' then '8'
       when 'MS' then '9'
       when 'MT' then '10'
       when 'GO' then '11'
       when 'DF' then '12'
       when 'TO' then '13'
       when 'AM' then '14'
       when 'AC' then '15'
       when 'RO' then '16'
       when 'RR' then '17'
       when 'PA' then '18'
       when 'AP' then '19'
       when 'MA' then '20'
       when 'PI' then '21'
       when 'RN' then '22'
       when 'CE' then '23'
       when 'SE' then '24'
       when 'AL' then '25'
       when 'PB' then '26'
       when 'PE' then '27'
       else '28' end as "ESTADO",

       case Nome when 'CidadeNome' then 'Não Informado'
       else UPPER(LEFT(Nome,1))+LOWER(SUBSTRING(Nome,2,LEN(Nome))) end as "NOME"

from cidades

where IDCidade in ( select IDCidade from empresas )

Porém, esta listagem está me mostrando alguns valores de cidades duplicados, que foram inseridos errado no banco. Quero saber como retornar os valores dessa consulta, sem que existam nomes de cidades duplicados. Tentei usar um distinct no para o campo Nome mas ele manteve a mesma quantidade.
Qual a maneira correta de se fazer esta consulta?
Comment: Tem certeza de que há denominações repetidas para localidades? Lembre-se de que no Brasil há várias localidades homônimas (geralmente em estados diferentes).
Answer: Se há localidades repetidas, então me parece que o primeiro passo é retirá-las da tabela. Para encontrar os possíveis casos de repetição em uma mesma unidade da federação, o código abaixo pode ser útil.
-- código #1
with LocalidadeUF as (
SELECT Nome, UF, IDCidade,
       Qtd= Count(*) over (partition by lower(Nome), lower(UF))
  from cidades
)
SELECT Nome, UF, IDCidade
  from LocalidadeUF
  where Qtd > 1
  order by lower(Nome), lower(UF);

De posse do resultado da consulta, avalie com cuidado os casos indicados como repetição. Após, basta apagar as linhas que considerar repetidas. É claro que isto depende de saber se o código de cidade está em uso ou não em outra tabela (integridade referencial).
Após efetuar a limpeza de dados, basta reexecutar o código que transcreveu.

Mas, se não for permitido apagar as linhas repetidas, segue solução de contorno.
-- código #2
with cidades2 as (
SELECT Nome, UF, min(IDCidade) as IDCidade
  from cidades
  group by lower(Nome), lower(UF)
)
SELECT IDCidade as "ID",
       case UF when 'RS' then '1'
       when 'SC' then '2'
       ...
       when 'PE' then '27'
       else '28' end as "ESTADO",

       case Nome when 'CidadeNome' then 'Não Informado'
       else UPPER(LEFT(Nome,1))+LOWER(SUBSTRING(Nome,2,LEN(Nome))) end as "NOME"
  from cidades2
  where IDCidade in (SELECT distinct IDCidade from empresas);

Neste caso o IDCidade a ser considerado será o menor utilizado, para linhas duplicadas.
Comment: Funcionou perfeitamente José. Agradeço o tempo disposto !

Dúvida com consulta no SQL Server