Multiplying by $1$ adds a solution to an equation

Question: I have a question, which is motivated by my book's solution to finding the inverse function of $f(x)=\frac{x}{1-x^2}$ with the domain of $f(x)$ restricted the open interval $(-1,1)$. The questions are stated at the bottom, but first is the book's solution:
Solution
$f(x)$ is injective and surjective, and hence it has an inverse, $f^{-1}(x)$.
$y=\frac{x}{1-x^2}$
$x=\frac{y}{1-y^2}$
$xy^2+y-x=0$
$y=\frac{-1\pm\sqrt{1+4x^2}}{2x}$
The negative solution is the right one, and then the book notices that $y=\frac{-1\pm\sqrt{1+4x^2}}{2x}$ excludes $x=0$ from the domain, but it should be in the domain since $0$ is in the image of $f(x)$, namely $f(0)=0$. It fixes this by rationalizing the numerator by multiplying by $1$ as follows:
$y=\frac{-1+\sqrt{1+4x^2}}{2x}\cdot \frac{-1-\sqrt{1+4x^2}}{-1-\sqrt{1+4x^2}} = \frac{2x}{1+\sqrt{1+4x^2}}$
Hence $f^{-1}(x)=\frac{2x}{1+\sqrt{1+4x^2}}$. $\blacksquare$
Question
Why is it that multiplying a function by $1$ will add a value for the graph of $f^{-1}(x)$? I can see why multiplying by $1$ will sometimes remove points on the graph, namely where the denominator is zero (e.g. multiply an equation by $\frac{x}{x}$ and it won't have a value at $x=0$), but how does it work here that multiplying by $1$ adds a point to the graph? Did it just get shifted somewhere else?
Comment: Seems pretty clear you'll have to extract a square root.  But why is that difficult?  The function $g:[-1,0]\to [0,1]$ given by $x\mapsto x^2$ has an inverse, namely $-\sqrt x$.  The other square root, namely $\sqrt x$ does not map you to the right interval.  Same phenomenon as in your example.  You have two possible square roots, and you must choose the correct one.
Comment: The technique underlying the quadratic formula does indeed give you all roots of a quadratic equation that lie *on the entire real line*. But maybe your needs are more specific. For instance, if you need to know only the roots that lie *on a specific subinterval of the real line*, then you'll have to check the roots given by the quadratic equation, and throw out any of them that do not line in the specified subinterval.
Comment: Please, limit to one question in each post. See [how to ask a good question](http://meta.math.stackexchange.com/questions/9959/how-to-ask-a-good-question#33671)
Answer: It's not quite the "multiplying by $1$" that expands the domain. Note that after doing the multiplication, we actually have
$$
y=\frac{4x^2}{2x\left(1+\sqrt{1+4x^2}\right)}.
$$
Here we still can't have $x=0$. The magic happens when we declare
$\frac{4x^2}{2x}=2x,$
which gets rid of the removable "hole" in the graph. So really, it's like in your own example, just in reverse: We started out with an $\frac xx$ in disguise, which we converted to a $1$. The multiplication is just a clever (and common) algebraic trick to clean up the expression.
As to why we got the hole in the first place, this happened when we used the quadratic formula. The formula is only suited to actual second degree polynomials, so we must assume that the leading term doesn't vanish when we use it. Really, we should split up in cases at that point in the proof: Either $x=0$ (which implies $y=0$), or we can solve for $y$ with the quadratic formula when $x\ne0$. Thus, another way to write the final answer would be simply
$$
f^{-1}(x)=\begin{cases}\frac{-1+\sqrt{1+4x^2}}{2x}&x\ne0 \\ 0 &x=0\end{cases}
.$$
Comment: Thank you, this clarifies all the questions I had.
Answer: TLDR;  There is a shorter more direct answer. It took me too long to write this one.  C'est la vie.
First of all let me comment on the textbook answer.
Although it derives a formula for the domain value ($f^{-1}(x)$) it does not define a function. This is because it has not specified its domain.
Furthermore, it introduces some confusion by swapping $x$ and $y$ from the very beginning, as if the domain variable had to be $x$. I suppose this is a sort of convention.
Finally, it does not encourage any understanding of why the adjustments have to be made at all, and how we should spot they are necessary when doing our own examples. [At least, from your explanation, it does not appear to do so.]
Now let's look at this problem afresh.  As a matter of course I would want to know what this function $f$ looks like.  Either I would sketch it by hand, or, these days, I would use a graphing calculator to see the shape of the function quickly.  Here is what the graph of
$y=\frac{x}{1-x^2}$
looks like:

It is now clear why the function ($f$) is restricted to the domain $-1 < x < 1$.  Moreover, the inverse looks like this (simply swap the x and y coordinates):

and now it is obvious that the unrestricted domain of $f$ would fail to have a function as an inverse, since the graph shows it would have to be multi-valued — not an option for a function.
So, from these graphs we can begin to see that $f$, restricted to the domain $(-1,1)$, does have a (single-valued) inverse function and that its domain is going to be the whole of the real number line.
Now we know exactly what the inverse function is: it is that function which given a real value, call it $y$, 'returns' the (unique) value $x\in (-1,1)$ such
that $y=\frac{x}{1-x^2}$.
In one sense this is a complete answer — I have told you exactly what the inverse is.  But that is not what the textbook wants you to do. It wants you to derive an algebraic formula for calculating the value of $x$ given that real number $y$.
Now that is another kettle of fish entirely.  In general it is not possible: not all (functions defined by) algebraic expressions have inverse (functions defined by) algebraic expressions.  But in this case we can derive one.  Let's see how:
If $y=\frac{x}{1-x^2}$ (and $x \in (-1,1)$) then we proceed as follows:
$\begin{align*}
 y & = \frac{x}{1-x^2} \\
 y(1-x^2) & =x \tag*{(notice that $1-x^2$ is never $0$)} \\
 y-yx^2 & =x \\
 \text{which rearranges to:} & {} \\
yx^2 + x -y &= 0.
\end{align*}$
Now the textbook 'solves' this quadratic equation (in $x$) using the standard formula.  You can clearly see that the value $y=0$ is excluded because the formula divides by $2y$. This is why the formula for the inverse cannot tell us the value when $y=0$.
Notice why the formula has two values for $x$: it is because the algebra (relating $x$ and $y$) doesn't care about the restricted domain of $f$.  It is telling us that there are two possible values of $x$ that the formula for $f$ maps to $y$.  It is up to us to determine which one we want.  In this case, we restrict ourselves to results in the interval $(-1,1)$ by choosing the formula:
$\displaystyle x = \frac{-1 + \sqrt{1+4y^2}}{2y}$
But this formula only works if $y\neq 0$ as we noted above. So a perfectly good 'solution' is:
$f^{-1}(y) = \begin{cases} \frac{-1 + \sqrt{1+4y^2}}{2y} & \text{if $y\neq 0$}\\
0 & \text{if $y=0$}\end{cases}$
How do we get a formula which works even when $y=0$?
The 'trick' used here is to change the formula to one that doesn't want to divide by zero when $y=0$. Obviously we don't want to change the values it produces when $y$ isn't zero, but maybe we can find an alternate formula which does just as well but manages not to become 'indeterminate' at that point.
The trick is a natural one to use when dealing with quadratic surds.  We remember the formula $(a-b)(a+b) = a^2 - b^2$.  So if we have something like $a-\sqrt{\text{thing}}$ then multiplying it by $a+\sqrt{\text{thing}}$ will produce something with squares of the two terms, i.e. $a^2 - \text{thing}$.
[Note: I'm assuming $\text{thing}$ is positive here.]
So let's see what this does to the numerator of our formula.  Oh, and while we're about it, we had better divide by this term as well, otherwise the values will get mucked up.  Here we go:
$\begin{align*}
\frac{-1 + \sqrt{1+4y^2}}{2y} & = \frac{-1 + \sqrt{1+4y^2}}{2y}\cdot \frac{-1 - \sqrt{1+4y^2}}{-1 - \sqrt{1+4y^2}} \\
{} & = \frac{(-1 + \sqrt{1+4y^2})\cdot (-1 - \sqrt{1+4y^2})}{2y(-1 - \sqrt{1+4y^2})} \\
{} & = \frac{1-(1+4y^2)}{2y(-1 - \sqrt{1+4y^2})} \\
{} & = \frac{-4y^2}{2y(-1 - \sqrt{1+4y^2})} \\
\text{which simplifies, } & \text{when $y\neq 0$, to:} \\
{} & = \frac{2y}{1 + \sqrt{1+4y^2}}
\end{align*}$
Notice that we only proved this when $y\neq 0$.  But, fortunately, this formula has no problem when $y=0$.  And it gives the right answer, too.  Lucky us.
Multiplying by $1$ didn't introduce any new values; we were lucky that the formula it led us to worked in the case $y=0$. That is all.
[NB: This 'technique' doesn't work most of the time.]


Full flag $Fl_{\mathbb C}(3)$

Question: How we can see that the full complex flag when $n=3$ is equivalent to one of these spaces:

$\{(u,v)\in \mathbb CP^2\times \mathbb CP^2 ; u\perp v\}$ and what is dimension over $\mathbb C$ here?
$\{(l,W); l\in Gr(1,3),W\in Gr(2,3),l\subset W\}$?

I know that the full flag $Fl_{\mathbb C}(3)= U(3)/(\mathbb S^1)^{\times 3}$ but I can't deduce that is the same as above spaces (or at least one of them)!
Comment: The second space is what is usually taken to be the _definition_ of the space of full flags.
Comment: But the definition I use is that the full flag is the space of all sequences $\{0\}=V_0 \subset V_1\subset...\subset V_n=\mathbb C^n$ with $dim V_j=j $ How we can see that both definitions are equivalent?
Answer: The right space is the second!
For completeness, let $\mathbb{V}$ be a complex vector space of dimension $n$; I recall that a flag of $\mathbb{V}$ is a strictly increasing sequence of vector subspaces of $\mathbb{V}$
$$
\{\underline{0}\}=\mathbb{V}_0<\mathbb{V}_1<\dots<\mathbb{V}_r\leq\mathbb{V}\,\text{where:}\,\forall i\in\{1,\dots,r\},\dim\mathbb{V}_i=m_i,\,dim\mathbb{V}_{i\displaystyle/\mathbb{V}_{i-1}}=d_i,
$$
the $r$-tuple $(m_1,\dots,m_r)$ is called signature of the flag; and if the signature is $(1,\dots,n)$ then the flag is called complete.
Let $\mathcal{F}(n;m_1,\dots,m_r)$ be the set of the  flags of $\mathbb{V}$ with signature $(m_1,\dots,m_r)$, let $F\in\mathcal{F}(n;m_1,\dots,m_r)$; by definition:
$$
F\equiv\mathbb{V}_0<\mathbb{V}_1<\mathbb{V}_2<\dots<\mathbb{V}_r\leq\mathbb{V}
$$
and let $\{e_1\dots,e_n\}$ be a basis of $\mathbb{V}$ such that:
$$
\forall i\in\{1,\dots,r\},\,\mathbb{V}_i=\langle e_1,\dots,e_{m_i}\rangle;
$$
then $\forall M\in\mathrm{GL}(n,\,\mathbb{C}),i\in\{1,\dots,r\},\,M\cdot\mathbb{V}_i=\langle M\cdot e_1,\dots,M\cdot e_{m_i}\rangle$ are well defined subspaces of $\mathbb{V}$; in particular, the flag
$$
\mathcal{F}(n;m_1,\dots,m_r)\ni M\cdot F\equiv\mathbb{V}_0< M\cdot\mathbb{V}_1<\dots<M\cdot\mathbb{V}_r\leq\mathbb{V}
$$
is well defined.
After all this, one can define the action
$$
\alpha:(M,F)\in\mathrm{GL}(n,\mathbb{C})\times\mathcal{F}(n;m_1,\dots,m_r)\to M\cdot F\in\mathcal{F}(n;m_1,\dots,m_r);
$$
one (easily) prove that $\alpha$ is a transitive action and therefore $\mathcal{F}(n;m_1,\dots,m_r)$ is in bijection with
$$
\mathrm{GL}(n,\mathbb{C})_{\displaystyle/P(d_1,\dots,d_r)},
$$
where $P(d_1,\dots,d_r)$ is the (closed) subgroup of $\mathrm{GL}(n,\mathbb{C})$ generated by the matrices of the following type
$$
\forall i\leq j\in\{1,\dots,r\},\,A_i^j\in\mathbb{C}_{d_i}^{d_j},\,\begin{pmatrix}
A_1^1 & A_1^2 & \dots & A_1^r\\
\underline{0}_{d_2}^{d_1} & A_2^2 & \dots & A_2^r\\
\vdots & \ddots & \ddots & \vdots\\
\underline{0}_{d_r}^{d^1} & \underline{0}_{d_r}^{d_2} & \dots & A_r^r
\end{pmatrix}.
$$
In particular, one can restrict the focus on the isometries of $\mathbb{V}$; one can define the action
$$
\widetilde{\alpha}:(M,F)\in\mathrm{U}(n)\times\mathcal{F}(n;m_1,\dots,m_r)\to M\cdot F\in\mathcal{F}(n;m_1,\dots,m_r)
$$
and as for $\alpha$, one prove that $\widetilde{\alpha}$ is a transitive action and therefore $\mathcal{F}(n;m_1,\dots,m_r)$ is in bijection with
$
\mathrm{U}(n)_{\displaystyle/\mathrm{U}(d_1)\times\dots\mathrm{U}(d_r)}$.
Is it all clear?
Furthermore: the first space is the space of (complete) orthogonal flag $\mathcal{F}^{\perp}(3;1,2,3)$ of $\mathbb{C}^3$.
Comment: We can associate a unique orthonormal basis to any complete flag by the Gram-Schmidt process, so, is "the space of complete orthogonal flags" really different from the space of complete flags?
Comment: They are different as sets.
Comment: But homeomorphic? @Armando j18eos
Comment: @テレビスクリーン If I am not wrong: these spaces are diffeomorphic as real manifolds!

Full flag $Fl_{\mathbb C}(3)$


Views Template Suggestions When There are Duplicate Filenames

Question: What does Drupal 6 / Views 2 do when there are two templates with the same filename in different directories?
I just ran into a situation where a row template was accidentally uploaded twice.  Typically, I make views subdirectory in my theme, and then a subdirectory per view inside that.  Due to a bad copy/paste, I ended up with
site/all/themes/mytheme/views/myview/views-view-unformatted--myview.tpl.php
site/all/themes/mytheme/views/myview2/views-view-unformatted--myview.tpl.php

My dev server was picking up the first template.  My live server was picking up the second template, despite being the same set of files as the dev server.  I didn't do the actual live deployment, but as far as I know, the rollout was an exact clone of the files.
I haven't been able to unravel how this actually happened, and would appreciate some insight.
Thanks.
Answer: You could look and see in your theme registry by dpm-ing in theme_registry_alter() or by turning on devel and visiting /devel/theme/registry and seeing what entry is pointing to what file.
If you don't want to do that on production you could do it locally first and then grab the production database locally.
I would imagine that the registry was rebuilt between the two sites and the first time it picked up one of the files and the second time the other since I don't know of a designed hierarchy for two files in the same level directories in a theme folder.
Don't upvote - this is a speculative answer.
Comment: I rebuilt the theme registry via `drush cc all` a million times on both dev and live when debugging this.  I don't think that was the problem.
Comment: Can you just remove the duplicate file ;)
Comment: Problem is fixed on live server.  This is more of an issue about *why* it happened.
Answer: I think I got to the bottom of this.
It looks like when you rebuild the theme registry, _theme_build_registry invokes phptemplate_theme via a hook.
phptemplate_theme calls drupal_find_theme_templates, which calls drupal_system_listing, which calls file_scan_directory.
file_scan_directory uses the PHP functions opendir and readdir to build the list.
No sorting takes place anywhere, so file_scan_directory returns in the order which readdir returns, which is typically in the order that the files were written to the filesystem.
So, for my problem, the issue boiled down to the dev server and live server writing out the template files in different orders, so the choice as to which to use was different.


Timeout em processamento

Question: Estou fazendo uma integração com SAT, quando não consigo a comunicação com o equipamento a aplicação trava. Existe alguma forma de eu estipular um tempo limite de espera para esse processo ser executado, cancelando a operação quando o timeout for atingido?
Comment: Quando não é possível fazer a comunicação, o processo fica travado no comando em que ativo o equipamento, sendo assim não tenho um retorno informando que a comunicação falhou.
Comment: Cara, depende do processo, poderia detalhar melhor qual processo você quer cancelar?
Comment: no caso estou fazendo uma integração com SAT, quando não consigo a comunicação com o equipamento a aplicação trava.
Gostaria de estipular um timeout e parar o processo de comunicação quando o tempo for atingido.
Comment: Vou editar sua pergunta, adicionando essas informações. Existe alguma forma de você verificar se a comunicação foi realizada com sucesso? Se sim, basta colocar em um timer, não?
Comment: Tente falar com o responsável do aparelho SAT, verifique o porque que ocorre esse travamento ao cancelar uma operação.
Answer: Faça com thread e defina um timeout para a thread, assim você fará a chamada ao SAT dentro da thread e caso ocorra qualquer problema, o timeout da thread será alcançado e o sistema sairá.

Timeout em processamento


Randomize database table result with LINQ

Question: from f in db.Table1
orderby Guid.NewGuid()
select f

this doesn't seem to work. how can i randomize results?
Answer: How about
SELECT TOP 1 column FROM table ORDER BY NEWID and skip the linq :)
Or try this:
var t = (from row in db.Table1 order by table1.random()
         select row).FirstOrDefault();

Answer: Maybe something like this works (not tested):
 (from f in db.Table1 select new { f, r = Guid.NewGuid()}).OrderBy(x => x.r)

Answer: Randomize whole list
db.Table1.OrderBy(x => Guid.NewGuid())

Get single Random
db.Table1.OrderBy(x => Guid.NewGuid()).FirstOrDefault();

Answer: I like to write an extension method for this.
IEnumerable<T> Randomize(this IEnumerable<T> list)
{
    T[] result = list.ToArray();
    Random random = new Random();

    for(int i = result.Length; i > 0; i--)
    {
        result[i] = random.Next(i);
    }

    return (result);
}


How can I find the authoritative DNS server for a domain using dnspython?

Question: As part of a tool I'm writing I want to have a diagnostic that will tell the user whether they have configured their domain's DNS correctly for a particular service. I want to query the authoritative DNS server for their domain so that I can bypass any cached results.
Answer: Here's my attempt at this. It uses the system's standard DNS server for looking up the root server for the top-level domain and for resolving the names of the various DNS servers along the chain, which I think is appropriate because those names would presumably change very infrequently.
import dns
import dns.name
import dns.query
import dns.resolver

def get_authoritative_nameserver(domain, log=lambda msg: None):
    n = dns.name.from_text(domain)

    depth = 2
    default = dns.resolver.get_default_resolver()
    nameserver = default.nameservers[0]

    last = False
    while not last:
        s = n.split(depth)

        last = s[0].to_unicode() == u'@'
        sub = s[1]

        log('Looking up %s on %s' % (sub, nameserver))
        query = dns.message.make_query(sub, dns.rdatatype.NS)
        response = dns.query.udp(query, nameserver)

        rcode = response.rcode()
        if rcode != dns.rcode.NOERROR:
            if rcode == dns.rcode.NXDOMAIN:
                raise Exception('%s does not exist.' % sub)
            else:
                raise Exception('Error %s' % dns.rcode.to_text(rcode))

        rrset = None
        if len(response.authority) > 0:
            rrset = response.authority[0]
        else:
            rrset = response.answer[0]

        rr = rrset[0]
        if rr.rdtype == dns.rdatatype.SOA:
            log('Same server is authoritative for %s' % sub)
        else:
            authority = rr.target
            log('%s is authoritative for %s' % (authority, sub))
            nameserver = default.query(authority).rrset[0].to_text()

        depth += 1

    return nameserver

import sys

def log(msg):
    print msg

print get_authoritative_nameserver(sys.argv[1], log)

Here's some sample output:
Looking up com. on 192.168.255.10
l.gtld-servers.net. is authoritative for com.
Looking up stackoverflow.com. on 220.127.116.11
ns1.p19.dynect.net. is authoritative for stackoverflow.com.
Looking up meta.stackoverflow.com. on 18.104.22.168
Same server is authoritative for meta.stackoverflow.com.
18.104.22.168

Answer: I came across Jon Colverson's answer, and it helped me understand the dnspython module and how to process the results (I guess all DNS modules have the same twisty maze of class structure ...)  I needed the TTL and the glue records, so I created my own adaptation.  I am posting it here in case somebody would find it useful; I do not intend to compete with Jon Colverson's excellent answer, just fill in some additional blanks.  The basic improvement is the use of name server information from the additional section of the answer, where available.  I suppose a server could put something else than glue records in the additional section, so perhaps this should still be enhanced to properly correlate the information from the additional section with the information in the answer section.  I also fetch and print all the name servers, not just the first one.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import dns.query
import dns.resolver
from dns.exception import DNSException

def query_authoritative_ns (domain, log=lambda msg: None):

    default = dns.resolver.get_default_resolver()
    ns = default.nameservers[0]

    n = domain.split('.')

    for i in xrange(len(n), 0, -1):
        sub = '.'.join(n[i-1:])

        log('Looking up %s on %s' % (sub, ns))
        query = dns.message.make_query(sub, dns.rdatatype.NS)
        response = dns.query.udp(query, ns)

        rcode = response.rcode()
        if rcode != dns.rcode.NOERROR:
            if rcode == dns.rcode.NXDOMAIN:
                raise Exception('%s does not exist.' % (sub))
            else:
                raise Exception('Error %s' % (dns.rcode.to_text(rcode)))

        if len(response.authority) > 0:
            rrsets = response.authority
        elif len(response.additional) > 0:
            rrsets = [response.additional]
        else:
            rrsets = response.answer

        # Handle all RRsets, not just the first one
        for rrset in rrsets:
            for rr in rrset:
                if rr.rdtype == dns.rdatatype.SOA:
                    log('Same server is authoritative for %s' % (sub))
                elif rr.rdtype == dns.rdatatype.A:
                    ns = rr.items[0].address
                    log('Glue record for %s: %s' % (rr.name, ns))
                elif rr.rdtype == dns.rdatatype.NS:
                    authority = rr.target
                    ns = default.query(authority).rrset[0].to_text()
                    log('%s [%s] is authoritative for %s; ttl %i' %
                        (authority, ns, sub, rrset.ttl))
                    result = rrset
                else:
                    # IPv6 glue records etc
                    #log('Ignoring %s' % (rr))
                    pass

    return result

import sys

def log (msg):
    sys.stderr.write(msg + u'\n')

for s in sys.argv[1:]:
    print query_authoritative_ns (s, log)

Answer: The other examples are fine but overly complex if you need just the nameservers. Example from
http://c0deman.wordpress.com/2014/06/17/find-nameservers-of-domain-name-python/ :
import dns.resolver

domain = 'google.com'
answers = dns.resolver.query(domain,'NS')
for server in answers:
    print server

Comment: That will only give you the nameserver for the top-level domain (or sub-domains if they have NS records). It won't tell you what the authoritative DNS server is for `www.example.org` and will raise a `dns.resolver.NoAnswer` exception.
Comment: Would I be right in thinking that might return cached results, though? In my case I specifically wanted to find the current server avoiding any caching, but there might be a significantly simpler way of doing that than the way I did it. :)
Answer: Im pretty sure this would do it.
import dns.resolver

domain = 'co.uk'

response = dns.resolver.query(domain, 'SOA')
if response.rrset is not None:
    print response.rrset

You could of course cleanup the response
import dns.resolver
import re

domain = 'co.uk'

response = dns.resolver.query(domain, 'SOA')

if response.rrset is not None:
    pattern= r'(%s)\.\s(\d{1,})\s(\w+)\sSOA\s(.*?)\.\s(.*?)\.\s(\d{1,})\s(\d{1,})\s(\d{1,})\s(\d{1,})\s(\d{1,})' % domain
    match = re.match(pattern, str(response.rrset))
    m_name, ttl, class_, ns, email, serial, refresh, retry, expiry, minim = match.groups()

output ='''
Main Name In Zone: {a},
Cache TTL: {b},
Class: {c},
Authoritive NS: {d},
Email Address: {e},
Last Change: {f},
Retry In Secs: {g},
Expiry: {h},
Slave Cache In Sec: {i}
'''.format(a = m_name, b = ttl, c = class_, d = ns, e = str(email).replace('\\', ''), f = serial, g = retry, h = expiry, i = minim)

print output

This produces
Main Name In Zone: co.uk,
Cache TTL: 600,
Class: IN,
Authoritive NS: dns1.nic.uk,
Email Address: hostmaster.nominet.org.uk,
Last Change: 1305857394,
Retry In Secs: 300,
Expiry: 2419200,
Slave Cache In Sec: 10800

Comment: Correct me if I'm wrong, but I believe those SOA results could still be cached on the resolver, though? It was bypassing the caching that made things more elaborate.
Answer: I ended up here because I needed to get an accurate return of ns in python ignoring the cache and starting from random servers.
I got a lot of help from your answers to build what is for me, the most useful version.
It allows me to know directly if a site belongs to a domain parking or not (e.g. freespt.com => ['ns1.bodis.com.', 'ns2.bodis.com.'])
I hope my code will be useful to you!
import random
import sys

import dns.resolver
import dns.name
import dns.message
import dns.query
import dns.flags

import re

NAMESERVERS = {
    '22.214.171.124': 'Cloudflare DNS',
    '220.127.116.11': 'Cloudflare DNS',
    '188.8.131.52': 'Google DNS',
    '18.104.22.168': 'Google DNS',
    '220.127.116.11': 'Quad9',
    '220.127.116.11': 'Quad9',
    '18.104.22.168': 'OpenDNS',
    '18.104.22.168': 'OpenDNS',
    '18.104.22.168': 'CleanBrowsing',
    '188.8.131.52': 'CleanBrowsing',
    '184.108.40.206': 'AdGuard DNS',
    '22.214.171.124': 'AdGuard DNS',
}

def rand_nameserver():
    """
    Choosing randomly one of the nameservers
    """
    return random.choice(list(NAMESERVERS.keys()))

def query_authoritative_ns(domain):
    """
    Dig recursively leaf to root and retrieve ns with cache bypassing.
    That will NOT only give you the nameserver for the top-level domain !
    It'll try sub-domains if they have NS records.

    It'll tell you what the authoritative DNS server is for www.example.org and will not raise a dns.resolver.NoAnswer exception.

    (quite similary to dig +trace)
    """

    trace = '### Querying authoritative ns for {d}:\n'.format(d=domain)
    result = None

    resolver = dns.resolver.Resolver(configure=False)
    name_server = rand_nameserver()

    # Setting-up random nameservers
    resolver.nameservers = [name_server]

    # Defining Timeout and lifetime
    # To not taking long time to skip to the next one records when it failed.
    resolver.timeout = 5
    resolver.lifetime = 5

    trace += '[NS records] [{d}] Used nameserver for DNS NS query is {fns} ({ns})'.format(
        d=domain,
        fns=NAMESERVERS.get(name_server),
        ns=name_server
    )

    ns = resolver.nameservers[0]

    # branches
    n = domain.split('.')

    for i in range(len(n), 0, -1):
        sub = '.'.join(n[i - 1:])

        trace += '\n[NS records] Looking up %s on %s' % (sub, ns)
        query = dns.message.make_query(sub, dns.rdatatype.NS)
        try:
            response = dns.query.udp(query, ns, port=53, timeout=5)

        except Exception as e:

            trace += '\n[NS records] [domain={d}] [subdomain={s}] Receive exception : {e}'.format(d=domain, s=sub, e=e)
            continue

        rcode = response.rcode()
        if rcode != dns.rcode.NOERROR:
            if rcode == dns.rcode.NXDOMAIN:

                trace += '\n[NS records] {sub} does not exist.'.format(sub=sub)
            else:

                trace += '\n[NS records] Error {err}'.format(err=dns.rcode.to_text(rcode))

            break

        if len(response.authority) > 0:
            rrsets = response.authority
        elif len(response.additional) > 0:
            rrsets = [response.additional]
        else:
            rrsets = response.answer

            # Handle all RRsets, not just the first one
        for rrset in rrsets:
            for rr in rrset:
                if rr.rdtype == dns.rdatatype.SOA:
                    try:

                        trace += '\n[NS records] Same server is authoritative for {sub}'.format(sub=sub)
                    except KeyError:
                        # Here, for '1337x.unblocked.team' it returns:
                        # "unblocked.team. 300 IN SOA ns1.koaladns.com. admin.unblocked.team. 2021070507 86400 10800 604800 300"
                        return (rrset.to_text().split(' ')[4::11], trace)

                elif rr.rdtype == dns.rdatatype.A:
                    try:
                        ns = rr.items[0].address

                        trace += '\n[NS records] Glue record for {sub}: {gl}'.format(sub=rr.name, gl=ns)
                    except KeyError:
                        # {<DNS IN A rdata: 188.8.131.52>: None}
                        # Glue Record with no data

                        trace += '\n[NS records] Glue record for {sub} contains None data !'.format(sub=rr.name)
                        # [<DNS ns18.above.com. IN A RRset: [<188.8.131.52>]>, <DNS ns17.above.com. IN A RRset: [<188.8.131.52>]>]

                        # ['ns17.above.com.','3600','IN','A','126.96.36.199','ns18.above.com.','3600','IN','A','184.108.40.206']
                        # And you extract correct ns by jumping arround the list
                        return (' '.join([e.to_text() for e in rrset]).split(' ')[0::5], trace)

                elif rr.rdtype == dns.rdatatype.NS:
                    authority = rr.target

                    try:
                        if sys.version_info.major == 3:
                            ns = resolver.resolve(authority).rrset[0].to_text()
                        else:
                            ns = resolver.query(authority).rrset[0].to_text()

                        trace += '\n[NS records] {ns} ({ns_ip}) is authoritative for {sub}; ttl {ttl}'.format(ns=authority, ns_ip=ns, sub=sub, ttl=rrset.ttl)
                    except dns.resolver.NoAnswer:

                        trace += '\n[NS records] Got no answer querying {ns}'.format(ns=authority)
                        continue

                    except dns.resolver.NoNameservers:

                        trace += '\n[NS records]  All nameservers failed to answer the query {ns}. Retrying with another nameserver.'.format(ns=authority)
                        return query_authoritative_ns(domain)

                    except dns.resolver.NXDOMAIN:
                        # 1337x.full-hd-torrent.net

                        trace += '\n[NS records] {ns} does not exist'.format(ns=authority)
                        continue

                    except (dns.resolver.Timeout, dns.exception.Timeout):

                        trace += '\n[NS records] [{d}] Timeout while querying {ns}, retrying with another nameserver.'.format(d=domain, ns=authority)
                        return query_authoritative_ns(domain)

                    result = rrset.to_text()

                else:
                    # IPv6 glue records etc
                    pass

    if result is not None:
        # Here, rrset can look like:
        # <DNS fp5u7c.top. IN NS RRset: [<justin.ns.cloudflare.com.>, <dora.ns.cloudflare.com.>]>
        # <DNS bypassed.works.prx2.unblocksites.co. IN NS RRset: [<ns2.parklogic.com.>, <ns1.parklogic.com.>]>
        return (re.split(r'NS |\n', result)[1::2], trace)

    return ([], trace)

domain = 'freespt.com'
ns_querying = query_authoritative_ns(domain)
trace = '### Results for ns query_authoritative_ns("{d}"): {ns}\n{trace}'.format(
    d=domain,
    ns=ns_querying[0],
    trace=ns_querying[1]
    )

print(trace)

This produces
### Results for ns query_authoritative_ns("freespt.com"): ['ns1.bodis.com.', 'ns2.bodis.com.']
### Querying authoritative ns for freespt.com:
[NS records] [freespt.com] Used nameserver for DNS NS query is Quad9 (18.104.22.168)
[NS records] Looking up com on 184.108.40.206
[NS records] m.gtld-servers.net. (188.8.131.52) is authoritative for com; ttl 41016
[NS records] a.gtld-servers.net. (18.104.22.168) is authoritative for com; ttl 41016
[NS records] b.gtld-servers.net. (184.108.40.206) is authoritative for com; ttl 41016
[NS records] j.gtld-servers.net. (126.96.36.199) is authoritative for com; ttl 41016
[NS records] i.gtld-servers.net. (220.127.116.11) is authoritative for com; ttl 41016
[NS records] c.gtld-servers.net. (220.127.116.11) is authoritative for com; ttl 41016
[NS records] f.gtld-servers.net. (188.8.131.52) is authoritative for com; ttl 41016
[NS records] l.gtld-servers.net. (188.8.131.52) is authoritative for com; ttl 41016
[NS records] g.gtld-servers.net. (126.96.36.199) is authoritative for com; ttl 41016
[NS records] h.gtld-servers.net. (220.127.116.11) is authoritative for com; ttl 41016
[NS records] d.gtld-servers.net. (188.8.131.52) is authoritative for com; ttl 41016
[NS records] e.gtld-servers.net. (184.108.40.206) is authoritative for com; ttl 41016
[NS records] k.gtld-servers.net. (184.108.40.206) is authoritative for com; ttl 41016
[NS records] Looking up freespt.com on 126.96.36.199
[NS records] ns1.bodis.com. (188.8.131.52) is authoritative for freespt.com; ttl 172800
[NS records] ns2.bodis.com. (188.8.131.52) is authoritative for freespt.com; ttl 172800


Sequences with strong inductional proof

Question: i have encountered an inductional proof example.Actually i know basic induction but i stuck in this question after basis step. Can anybody write the following steps by using STRONG induction. The question is:

The sequence $a_1, a_2, a_3,\ldots$ is defined by $a_1 = 1$, $a_2 = 1$, $a_3 = 1$, $a_n = a_{n−1} + a_{n−2} + a_{n−3}$ for $n \ge 4$. Using mathematical induction correctly, prove that
  $a_n < 2^n$ for all $n \in\Bbb Z^+$.
Answer: My attempt:
Base case: $n = 1,2,3,4$:
$1< 2$,
$1<4$,
$1<8$,
$3<16$
Now we assume that the statement hold for everything upto $n-1$, and prove $n$:
$$a_{n} = a_{n-1} + a_{n-2}+ a_{n-3} < 2^{n-1} + 2^{n-2} + 2^{n-3} = 2^{n-3}(1+2+4) = 7\cdot 2^{n-3} < 8\cdot 2^{n-3} = 2^n $$
Answer: Base: $n=4$. Obviously, $a_4=1+1+1=3<2^2=4.$
Assume the statement is true for k such that $k\leq n$. Let's prove it for $n+1.$
$a_{n+1}=a_{n}+a_{n-1}+a_{n-2}\leq 2^n+2^{n-1}+2^{n-2}=2^{n-2}(4+2+1)=2^{n-2}(7)<2^{n-2}8=2^{n+3}$.

Sequences with strong inductional proof


How can I record time now in RichTextBox in WPF application?

Question: Here is my codes,the main xaml.cs file:
//using statements...

namespace WpfAppTestRichTextBox
{
    public partial class MainWindow : Window
    {
        public Paragraph p = new Paragraph();

        public MainWindow()
        {
            InitializeComponent();
            Start();
        }

        // Initialize the richTextBox...
        public void Start()
        {
            Run r = new Run("");
            p.Inlines.Add(r);
            richTextBox.Document.Blocks.Add(p);
        }

        // Button Click and Start a new Thread to record time for each second.
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(ChangeText);
            th.Start();
        }

        public void ChangeText()
        {
           while(true)
           {
                this.Dispatcher.Invoke(new Action(() =>
                {

                    string time = System.DateTime.Now.ToString() + "\n";
                    Run r = new Run(time);
                    p.Inlines.Add(r);

                    System.Threading.Thread.Sleep(1000);

                }));
            }
        }
    }
}

I add the new Run() to the Paragraph and expect the content of the richTextBox will be refreshed.But it blocks in while() and print nothing in richTextBox.
How can i solve this?
Answer: The problem is that you have your sleep inside the dispatcher thread. Did you intend to place it after the dispatcher invoke?
while(true)
{
    this.Dispatcher.Invoke(new Action(() =>
    {
        string time = System.DateTime.Now.ToString() + "\n";
        Run r = new Run(time);
        p.Inlines.Add(r);
    }));
    System.Threading.Thread.Sleep(1000);
}

Thread.Sleep

Suspends the current thread for the specified amount of time.

Dispatcher.Invoke dispatches the code inside the block to run on the UI thread. Putting the sleep in there Suspends the UI thread essentially causing it to freeze up.
UPDATE: A better solution would be to use a dispatcher timer.
public partial class MainWindow : Window
{
    private DispatcherTimer _timer = new DispatcherTimer();
    public Paragraph p = new Paragraph();

    public MainWindow()
    {
        InitializeComponent();
        _timer.Interval = new TimeSpan(0, 0, 1);
        _timer.Tick += _timer_Tick;
    }

    private void _timer_Tick(object sender, EventArgs e)
    {
        string time = System.DateTime.Now.ToString() + "\n";
        Run r = new Run(time);
        p.Inlines.Add(r);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Run r = new Run("");
        p.Inlines.Add(r);
        richTextBox.Document.Blocks.Add(p);
        _timer.Start();
    }
}

Comment: I've added more details to my answer.
Comment: It works for me!But I thought it just sleeps 1000 ms .Why the Sleep() statement can blocks the UI Thread?
Answer: first of all, changing your method to async would be a good idea, but to answer your question, it is possible that your UI is just not refreshing due to the method never ending or giving control back to the caller. Try forcing a refresh:
 if (richTextBox.InvokeRequired)
 {
      richTextBox.Invoke(new MethodInvoker(delegate
      {
          richTextBox.Refresh();

       }));
 }
 else richTextBox.Refresh();
 Application.DoEvents();

If that doesn't work then try doing things like running in debug mode and checking the value of p at certain times, or try altering the value of the textbox.Text directly to see where your actual bug is


How to write a scala spark code to connect to Multiple cloud platforms(Azure,AWS) with Design Pattern or OOP

Question: I want to write a spark Scala code in GenericWay where it can connect to azure Blob storage or S3 or some other storage in another cloud to read the data. Want to write it as an Extendable and Wrapper way.
Expectation : implementation using design pattern or OOPs concepts.
Thoughts: Correct me If iam Wrong
CloudService as Interface;
implementation of cloudService as Azure
implementation of cloudService as AWS S3
implementation of cloudService as AWS Redshift

Calling Interface will dynamically invoke related implementation.

Suggest Other Ways or Please extend my Thoughts
Thanks in Advance
Comment: You could have a look at [Benji](https://zengularity.github.io/benji/) (I'm contributor of) which provides abstraction for Object storage operations (now for S3/Google, planned for Azure).
Comment: for S3 you can use https://doc.akka.io/docs/alpakka/current/s3.html
Answer: I think you are looking for the Strategy pattern.
Suppose the succession of operations is connect, read and cleanup (free resources, close connections and so on).
Then you have
trait CloudService {
    def connect()
    def read()
    def cleanup()

}

with implementations for every cloud system you use. This is the Strategy.
class AWSCloudService extends CloudService {
    ...

}

This are the concrete Strategy implementation.
To use them, you need a Context, which is a class that  will get a Strategy implementation and call the methods:
class CloudReader {
def readFromCloud(  service : CloudService ) {
    service.connect()
    service.read()
    service.cleanup()
}

}
For more information on the Strategy desing pattern:
https://en.wikipedia.org/wiki/Strategy_pattern
Comment: Suppose I'm getting config as s3 .how to call relevant implementation ?
if I call trait will trait handles what to call .?
Comment: The trait only defines the operations. To call the Concrete Strategy implementations you need something like a factory.
Comment: exactly expecting Factory pattern


PHP static initializer

Question: I'd like to access a static field of a class in a static function, but the field is still <Uninitialized>. How can I initialize this field?
<?php
final class StaticTest {
    private static $lookup = array(123, 456, 789);

    public static function compute() {
        return StaticTest::$lookup[0];
    }
}

echo 'result: ' . StaticTest::compute();
?>

As you can see in the following picture taken from the Eclipse PDT debugging the static field $lookup is <Unitialized>.
Comment: [It works just fine](http://3v4l.org/F3YNE).
Answer: Edit your code to this and it should work as you desire:
<?php
  final class StaticTest{
    protected static $instance;
    private $lookup = array(123, 456, 789);

    public function compute() {
      return $this->lookup[0];
    }

    public static function get(){
      if (!isset(self::$instance))
        self::$instance = new self();
      return self::$instance;
    }
  }
  echo 'result: ' . StaticTest::get()->compute();

To explain myself here, it's always better to use the concept where you only specify that you want to use the property of object and don't care about creating the object.
It is done automatically (it object doesn't exist in memory it is created, if it exists it is called).
I can't really explain this better. I'm no braniac. I only use this concept as a substitution for application global variables.
Hope it helps!
Comment: Thank you! It is another solution, but in my case of a simple CRC16 algorithm I think it is not neccessary to use the singleton pattern for it.
Answer: The error is happening because you are trying to call a private variable while not calling self to access it.
I have given the below code a test and it seems to work. Oddly, I have also given your code a test, and that seems to work fine also.
To get around this, in your compute function, you should use this return self::$lookup[0]; instead of return StaticTest::$lookup[0];.
Another way around this would be to change the private static $lookup = array(123, 456, 789); to public static $lookup = array(123, 456, 789);. Doing this, your code would work fine, but is not the recommended way.
Doing this, it should return the result you want. Think of it similar to non static classes, to access parameters (private or public) inside of a non-static class you can use $this->, where as in a static class, you should use self:: instead. Also, not that using self:: to access a variable requires the $ to be present, where as using $this-> does not.
The answer provided by Dejv would also work, but involves using a singleton type class, which is definitely not needed for this procedure as it is instancing a new class each time, completely ignoring how static variables and functions can work.
Hope this answers your question.
Comment: Thank you! With `self::$lookup[0]` it works fine :)I saw the use of `self` to access a static member in the manuel, but it was called in a non-static function so I assumed that `self` is the aquivalent to `this` in Java :) And another hint is missing in the PDT: Suspending the return statement and looking for the variable value, Eclipse displays always ``. The variable gets initialized only after a first access, like `$result = self::$lookup[0];`. That was confusing to me as a PHP beginner :)

PHP static initializer


Troubleshooting 5.5.0 smtp; 503 Bad sequence of commands (Microsoft SMTP + Exchange 2003)

Question: Note: this question has changed.  Originally I believed it had something to do with BDAT.
An external party is trying to send us a message to a valid address and they're getting an NDR:
<code><sender.it #5.5.0 smtp;503 Bad sequence of commands>
</code>
Note that this message is coming from the sender's side.
I'm looking at my SMTP logs and am finding:
<code>#Fields: date time c-ip cs-username cs-method cs-uri-stem cs-uri-query sc-status sc-win32-status sc-bytes cs-bytes
2009-11-24 19:38:26 22.214.171.124 sender.it RCPT - +TO:+<email@example.com> 250 0 0 28
2009-11-24 19:38:26 220.127.116.11 sender.it BDAT - - 250 0 0 9
2009-11-24 19:38:26 126.96.36.199 sender.it BDAT - - 250 0 42 9
2009-11-24 19:38:26 188.8.131.52 sender.it BDAT - - 250 0 42 9
2009-11-24 19:38:26 220.127.116.11 sender.it QUIT - sender.it 240 11188 0 37
</code>
The message never reaches Exchange.  No record of anything from the sender in the message tracking log. I'm also running GFI MailEssentials 14 and there is no record of this message in its logs.  No Exchange-related errors or warning in the event logs.  Queues are normal.
Where do I go from here?  This user is not able to send mail to my domain.  I'm not having any other reported incoming email issues at this time...everything seems to be flowing like normal.
Comment: I had a similar issue and found that our TrendMicro was quarantining the message right after the SMTP accepted it. By doing this, the Message Tracking didn't see it as well. Maybe you have a 3rd party software that is doing some sort of policy checking - profanity, credit card, etc. It also may have had a file type set up to quarantine.
Answer: If the server responds to the ehlo command and lists Chunking, then it supports BDAT. To test your server, telnet to it on port 25 and issue the ehlo command. It will then list which of the ESMTP commands that it supports. If Chunking is in the list then BDAT is not the problem. Because this is Exchange you should see that it supports the full ESMTP command set and Chunking because AFAIK, this is the default for Exchange.
Your log file doesn't have enought info to tell what the problem is. You need to modify the log file parameters to include status codes so that you can see what the status is for each command (log file entry) and determine what the problem is.
Comment: Good suggestion.  I believe I may have jumped the gun thinking it had something to do with BDAT.  I've enabled status codes in my logs and will have the user resend.
Comment: I edited my question to include new log entries.  Everything looks like it's succeeding.  However, the message doesn't seem to get any further than the SMTP server.
Comment: Yep, based on the logs it looks like it's making it into SMTP and past the SMTP filtering (if you have any enabled). My next suggestion would be to use the Message Tracking tool to see if it's getting filtered by the Intelligent Message Filter.
Comment: No record of the message in Exchange.  I have a spam filter integrated into Exchange and it's not showing this message coming in either.  I'll keep digging.
Comment: Check the badmail folder on the Exchange server to see if the message is in there. If it is then it means that the sender is being filtered by Sender Filtering.
Comment: At this point I would start eliminating things. Can you temporarily eliminate GFI from the equation? Then, the next step would be to disable the various SMTP filters (located in Global Settings>Message Delivery) and see if the email comes through. If it does, then re-enable them one at a time, sending a test email each time until it stopes working again. When it does then you'll know that the last filter you enabled is the cause. Not to worry about opening yourself to any risk, the filters control spam only and not relaying, etc.
Comment: Good ideas, but I'm not sure if I can demand that much participation by the sender.  Bad mail folder is empty.  BTW, I updated the question with the error message he's getting in the NDR.
Comment: That's a strange ndr and a strange problem because based on your logs your server is receiving the message. The 250 status codes mean success and the 240 status code is the normal status code for ending the smtp session after the message has been received. the ndr doesn't correlate to the logs. i'm at a loss to think of anything else except to try and rule things out as suggested in my earlier comment. if you can manage to get some cooperation from the sender then follow my suggestions and see where it leads. keep us posted on your progress and if i think of anything else, i'll post back.
Answer: The Exchange Best Practices Analyzer will check to see if the server supports BDAT (their writeup on this particular test can be found here: http://technet.microsoft.com/en-us/library/aa997593.aspx).  Not sure if disabling the CHUNKING and BINARYMIME verbs will help, but if you want to try it for purposes of receiving that particular e-mail from the Italian provider, instructions are here: http://support.microsoft.com/?kbid=257569


Setting up cron at specific time

Question: Even though this is simple, i just want to make sure. How do you run a cron schedule every 15minutes from 12pm to 12am
is it:
<code>*/15 12-00 * * * php mycommand.php
or
*/15 12-24 * * * php mycommand.php
</code>
Thanks,
Comment: Hour is 0-23 I believe, so the first would be correct, else there'd be 25 hours in a day
Answer: Both are actually valid I believe. Though 12-00 looks more accurate as far as I'm concerned.
Check Here
Comment: based from your link both said are working. haha. but will just follow your advice 12-00.thanks :D

Setting up cron at specific time


Using $g(x)=1$ for the quotient test of convergence of improper integrals

Question: Is it ok to set $g(x)=1$ for the quotient test of convergence of improper integrals?
I find it easily solves many problems, for example, show if the following converge or diverge:
$\displaystyle\int^{\infty}_1\frac {\arctan x}{x\ln ^2(1+x)}dx$
So, $g(x)=1$, $\displaystyle\lim_{x\to\infty} \frac {f(x)}{g(x)}=\lim_{x\to\infty} \frac {\arctan x}{x\ln ^2(1+x)}= 0$ ($\arctan x$ is bounded and the denominator tends to zero).
Since $\displaystyle\int^{\infty}_1 1dx$ converges so does the given.
Comment: The integral $\int_1^\infty 1\,dx$ does not converge.
Comment: @AndréNicolas oh I see I mixed it up with integrals of this kind: $\int ^1_0$...
Answer: The integral $\int_1^\infty 1\,dx$ does not converge. so the procedure will not work in this case.
A good $g(x)$ here would be $\frac{1}{(1+x)\ln^2(1+x)}$, whose integral converges by a direct calculation.


Difference between {... | ...} and {... : ...}

Question: Is there a difference between the following two set related notations:
$$\{~\dots~:~\dots~\}~\text{vs.}~\{~\dots~|~\dots~\}?$$
I take it they both mean "such that" but I was wondering why some authors prefer one to the other, maybe there is a historical background to it?
Comment: I usually prefer the latter, but in some texts use the former (esp. when the conditions are full of $|x|$ and $y\mid z$)
Comment: Note that "such that" is not what the symbol _means_, but merely how the notation is _pronounced_. The _meaning_ of the symbol $\{x\mid \phi(x)\}$ is the unique set $y$ with the property $\forall x(x\in y\leftrightarrow \phi(x))$.
Comment: What is the difference between $]a,b[$ and $(a,b)$ and why do some authors prefer one to the other?
Comment: @HagenvonEitzen In a paper I was making up for a conference proceeding volume, the separator was $|$, $:$ or $;$, with no apparent reason, except for the fact that the paper had three authors.
Comment: @AsafKaragila Same here, I guess. I was raised with the former, but mostly use the latter (esp. because you need \left and \right to get good  spacing with the former), but am unhappy with it if I need ordered pairs in the same text ... :)
Comment: @Hagen: Easy fix, $\langle a,b\rangle$.
Comment: @AsafKaragila I knew you'd say that, but I often use that for dot product :)
Comment: @Hagen: What's wrong with $a\cdot b$, then?
Answer: it's exactly the same. But if you need a "such that " twice, it's better to use $\mid$ and then $:$. For example,
$$\{y\mid \exists x\in \mathbb R: y=f(x)\}$$
Comment: why is $| \ldots :$ better than $:\ldots |$?
Comment: Well, graphically it looks better :-)
Answer: They are the same, but there are occasion where one would be less practical to use. For example the $|$ sign has uses that makes $|$ non-practical for set building. For example $\{P|ab: P\in X\}$ (ie the set of distances to the line $ab$ for points in $X$) and $\{f|_A: f\in X\}$ (ie the set of restrictions to $A$ for functions in $X$) would be less obvious if you used $|$ sign instead of $:$ sign. There are other uses for the $:$ sign to (fx mappings which would lead to constructs like $\{f:\mathbb R\to \mathbb Z|\, f(-x)=f(x)\}$) so if there's risk of running into these cases the author should select the notation that results in the least confusing set-building notation.
Answer: There is no difference between both notation. One author may prefer the first one, the other the second one. See https://en.wikipedia.org/wiki/Set-builder_notation for more details.


Making sure the cookie path does not include language code

Question: I'm in the process of setting up a site to support 4 languages. One of the changes I made started to redirect /user to /[lang-code]/user, which in turn means Drupal's session cookie path now contains the language code. With the language code in the path, authenticated users do not stay logged in when they change languages.
Is there a simple way to avoid having Drupal add the language code to the cookie session path?
Answer: The problem in this case was solved by setting the cookie path in settings.php:
<code>ini_set('session.cookie_path', '/subdir');
</code>
The site is running in a sub-directory (which may or may not have mattered), and the initial value used in the settings file has lacked the leading / (which mattered a great deal).


Trying AJAX autocheckboxes example; getting Notice: Undefined index: #ajax in ajax_form_callback()

Question: I'm using the exact code found within the examples module function ajax_example_autocheckboxes though I have changed the function and callback names. When I change the select dropdown the field goes gray for a second as the AJAX process kicks off; but no checkboxes appear. I don't think it matters, but my form is in a block defined in my custom module.
I'm getting this in my recent log messages:
Type    php
Date    Wednesday, March 21, 2012 - 12:24
User    me
Location    http://localhost.com/system/ajax
Referrer    http://localhost.com/node
Message Notice: Undefined index: #ajax in ajax_form_callback() (line 379 of C:\Users\me\Documents\www\localhost.com\includes\ajax.inc).
Severity    notice
Hostname    127.0.0.1

UPDATE: I tried the examples module (ajax examples) in a clean D7 install and get 503 errors trying to open the example pages; now I'm investigating my hosting environment (xampp) will update once resolved.
UPDATE2: Installed a bitnami drupal stack & tested ajax examples; everything works as expected which points to an issue with my xampp environment.
FYI xampp details:

    ###### ApacheFriends XAMPP version 1.7.7 ######

  + Apache 2.2.21
  + MySQL 5.5.16 (Community Server)
  + PHP 5.3.8 (VC9 X86 32bit thread safe) + PEAR
  + XAMPP Control Panel Version 2.5 from www.nat32.com
  + (BETA) XAMPP Control Panel Version 3.0.2 by Steffen Strueber (not in the USB & lite version)
    see http://www.apachefriends.org/f/viewtopic.php?f=16&t=46743
  + XAMPP Security
  + OpenSSL 1.0.0e
  + phpMyAdmin 3.4.5
  + ADOdb 5.14
  + Mercury Mail Transport System v4.62 (not in the USB & lite version)
  + FileZilla FTP Server 0.9.39 (not in the USB & lite version)
  + Webalizer 2.23-04 (not in the USB & lite version)
  + Perl 5.10.1 (not in the USB & lite version)
  + Mod_perl 2.0.4 (not in the USB & lite version)
  + Tomcat 7.0.21 (not in the USB & lite version)
Comment: Are you able to post the code you're currently using? The example module you're using works fine if memory serves so the problem is probably something to do with the function name changes
Comment: @Clive lmk if you want the block code too.
Comment: removed my code from post; see update in post.
Answer: Reinstall XAMPP! if that doesn't fix it, try a different stack:

Bitnami
Acquia
MAMP

So installing the Bitnami Drupal stack and testing successfully there indicated a problem with my XAMPP install. Also wanted to try the Acquia stack, was ok, ended up going back to XAMPP.


Probability questions involving chance of drawing particular poker hands.

Question: I am trying to design a program to calculate the probability of getting a set of poker hands, but I've been having trouble finding where to start. It would really help me out if someone could assist me with a couple of simple probability questions, and then I should be able to figure out the rest on my own.
Here are the questions I would like help with:
Please note that the cards "in hand" must be used for the final "hand":
1.) With a 51 card deck, if you already have the 10 of clubs in hand, what is the probability that you will draw at least one more 10 from the deck after drawing 20 more cards?
2.) With a 51 card deck, if you already have the 10 of clubs in hand, what is the probability that you will get a royal flush (same suit, 10-J-Q-K-A) after drawing 25 more cards?
3.) If you already have a 3 of hearts in hand, what are the odds that you will be able to get a straight (any 5 card sequence with 2-3-4-5-6-7) if the deck only has two 5s and three 6s, after drawing 20 more cards (deck only has 48 cards left in this case)?
Any suggestions/guidance is very much appreciated!
Comment: Have you had any thoughts yourself?
Comment: @Henry I have. I took a course on statistics a couple of years ago, but I can't find any of my notes. I believe it is quite easily calculated. The only problem is that it's a little too specific to find relevant examples online.
Comment: What do you mean by "be able to get"? Is this just a roundabout way of saying "get", or something more involved?
Comment: @joriki Yes, sorry. I fell out of the "math question" persona there for a second xD
Comment: Use the search box in this web to find questions about cards. Im not sure but I think there is a tag for it, for cards. Just put in the search box "poker", press ENTER and enjoy.
Comment: @Masacroso I've tried that, but I can't seem to find any that involve using ~20 cards and only paying attention to the ones you need, etc. That's what I meant when I said the problem is "a little too specific to find relevant examples online".
Answer: For 1, to fail you have to draw your $20$ cards out of the $48$ non-$10$s.  The chance of that is $\frac {48 \choose 20}{51 \choose 20}$, so the chance of success is $1-\frac {48 \choose 20}{51 \choose 20}$  You are correct, the others are similar.
Comment: Is the 20 in the top "combination" also due to the amount of cards you draw? If so, are there any circumstances where this number would differ from the bottom "combination"'s?
Comment: Yes it is.  You have to select $20$ cards out of the $48$ acceptable ones.  "Any circumstance?", yes.  Say I want the chance of drawing exactly $2$ kings and $3$ tens out of $13$ cards.  It is $\frac {{4 \choose 2}{4 \choose 3}{44 \choose 8}}{52 \choose 13}$  You have to read and think about the problem.
Comment: I see. Thanks! One problem, though.. I've been told that $\frac {47 \choose 16}{51 \choose 25}$ is the answer to the second question, but I can't seem to find the reasoning behind this. Do you understand it?
Comment: I don't see where that comes from.  Do you want the chance of a club royal flush or any royal flush?  The second is rather harder.
Comment: I'm looking for a club royal flush, I guess. It seems to make sense to me that it would be $\frac {{1 \choose 1}{1 \choose 1}{1 \choose 1}{1 \choose 1}{47 \choose 21}}{51 \choose 25}$ which equals $\frac {47 \choose 21}{51 \choose 25}$. Does that make sense to you?
Comment: I think I finally get this, now. Thanks for all of the help and patience!!
Comment: Yes, I agree with that.


How to Check or Uncheck all Items in VB.NET CheckedListBox Control

Question: I need to select and unselect all items in a VB.NET CheckedListBox control, what is the best way to do this?
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        With clbCheckedListBox

        .Items.Add("Select/UnSelect All")
        .Items.Add("Enero")
        .Items.Add("Febrero")
        .Items.Add("Marzo")
        .Items.Add("Abril")
        .Items.Add("Mayo")
        .Items.Add("Junio")
        .Items.Add("Julio")
        .Items.Add("Agosto")
        .Items.Add("Septiembre")
        .Items.Add("Octubre")
        .Items.Add("Noviembre")
        .Items.Add("Diciembre")

        .SelectedIndex = 0

    End With

End Sub

    Private Sub clbCheckedListBox_ItemCheck(sender As Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck

    If e.Index = 0 Then

        If e.NewValue = CheckState.Checked Then

            For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
                Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Checked)
            Next

        ElseIf e.NewValue = CheckState.Unchecked Then

            For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
                Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Unchecked)
            Next

        End If

    End If

End Sub

After Hours the above code work fine for me !
Comment: Please mark the appropriate answer.
Comment: Blech. No enumeration support??
Answer: Do you mean something like this:
Dim checked As Boolean = True   ' Set to True or False, as required.
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
    CheckedListBox1.SetItemChecked(i, checked)
Next

Here I'm just looping through all the CheckedListBox Items and setting their checked state.
Answer: Ricardo, perhaps this might be what you are looking for:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim items$() = New String() {"Select/UnSelect All", "Enero",
     "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
     "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}
    For Each Str As String In items : clbCheckedListBox.Items.Add(Str) : Next
End Sub ' Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs)

Private Sub clbCheckedListBox_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
    If e.Index = 0 Then
        Dim newCheckedState As CheckState = e.NewValue
        For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
            Me.clbCheckedListBox.SetItemCheckState(idx, newCheckedState)
        Next
    End If
End Sub

Comment: I know this is marked as the answer, but you're starting at index 1 and SetItemCheckState won't work in any code I've ever worked in, only SetItemChecked works.
Comment: @Keith: yes it intentionally skips the first item because the first item is 'Select/UnSelect All'.
Comment: And i tested that code before i posted it. so i know that code worked for me. Keith, does SetItemCheckState not work for u in WinForms or WPF? I used a WinForm project. i used VS 2010 since in my opinion, the later VS 2012 and 2013 were downgrades. but i don't think the VS version wud matter. I know i used .NET 4 environment (i think .NET 4.5). sometimes that matters with MS quirks. maybe u might want to compare ur environment that doesn't work with SetItemCheckState to my environment.
Comment: @Keith, i do know that if i only want states of checked or unchecked, then i'd prefer to use the SetItemChecked() method that u share works for u. SetItemCheckedState() is for 3 states, not 2: Checked, Unchecked, and Indeterminate. Keith, i wud check 3 things: 1: your environment is WinForms, 2: your control is a `CheckedListBox` and 3: you are using .NET 4.5 or later.
Answer: If button.Text = "Select All" Then
    For i As Integer = 0 To checklist.Items.Count - 1
        checklist.SetItemChecked(i, True)
    Next
    Button.Text = "Deselect All"
Else
    For i As Integer = 0 To checklist.Items.Count - 1
        checklist.SetItemChecked(i, False)
        Button.Text = "Select All"
    Next
End If

Answer: To check all CheckedListBox Item:

For i As Integer = 0 To CheckedListBox1.Items.Count - 1
     CheckedListBox1.SetItemChecked(i, True)
Next

To uncheck all CheckedListBox Item:

For i As Integer = 0 To CheckedListBox1.Items.Count - 1
     CheckedListBox1.SetItemChecked(i, false)
Next

Answer: I found that clbCheckedListBox.clearSelection() works well for unselecting all.
Comment: @Trey You mean `.ClearSelected()`? My VisualStudio 2017 with .NET target framework 4.5 doesn't accept your suggestion. And just for the records: This does NOT uncheck the items, just unselect them.
Comment: Welcome to SO Trey :-). Generally it is not a great idea to add to questions that are this old and already have an accepted answer. Further, answers are encouraged to write more than just a single line - otherwise maybe a comment would be better. Finally, please try format contributions correctly as it helps with legibility; in this case the code can be formatted (I will go ahead and edit so you see what I mean).
Answer: Added a separate checkbox called "Select All". On checking and unchecking of this checkbox items of a checklistbox can be selected or unselected. So you can call this Kb() function anywhere in your code:
Private Sub ChkSelectAll_Click(sender As Object, e As EventArgs) Handles ChkSelectAll.Click
    Kb(ChkSelectAll.CheckState)
End Sub

Private Sub Kb(ByVal Key As Boolean)
    For i As Integer = 0 To ChkLstServices.Items.Count - 1
        ChkLstServices.SetItemChecked(i, Key)
    Next
End Sub

Answer: Put this code in the SelectedValueChanged event.
Private Sub clbCheckedListBox_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles ContrListCheckBox.SelectedValueChanged
    If clbCheckedListBox.SelectedIndex = 0 Then
        If clbCheckedListBox.GetItemChecked(0) = False Then
            For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1

                Me.clbCheckedListBox.SetItemChecked(idx, False)
            Next
        Else
            For idx As Integer = 1 To ContrListCheckBox.Items.Count - 1

                Me.clbCheckedListBox.SetItemChecked(idx, True)
            Next
        End If
    ElseIf clbCheckedListBox.SelectedIndex > 0 Then
        If clbCheckedListBox.CheckedItems.Count = clbCheckedListBox.Items.Count - 1 And clbCheckedListBox.GetItemChecked(0) = False Then
            clbCheckedListBox.SetItemCheckState(0, CheckState.Checked)
        End If
        For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1

            If clbCheckedListBox.GetItemChecked(idx) = False Then
                clbCheckedListBox.SetItemCheckState(0, CheckState.Unchecked)

            End If
        Next
    End If
End Sub

Other solutions are correct but if you want to deselect another checkbox inside the CheckBoxList or empty the CheckBoxList without the Select All checkbox
the top checkbox will remain checked and it is not logical so the above code should solve this problem.
Answer: Another option would be to bundle the check/uncheck events - of two buttons, for example - into one handler and use the value of sender to set the check state:
Private Sub clbCheckedListBox(
    ByVal sender As Object,
    ByVal e As EventArgs) Handles btnAll.Click, btnNone.Click

    For i As Integer = 0 To clbApis.Items.Count - 1
        clbApis.SetItemChecked(i, sender Is btnAll)
    Next i
End Sub


What is imitation between two voices on an eighth note upbeat figure?

Question: On the Wikipedia page on BWV 578, a technique devised by Corelli is mentioned.

The fugue's four-and-a-half measure subject is one of Bach's most recognizable tunes. The fugue is in four voices. During the episodes, Bach uses one of Arcangelo Corelli's most famous techniques: imitation between two voices on an eighth note upbeat figure that first leaps up a fourth and then falls back down one step at a time. (em mine)

I can't understand the last sentence. I somewhat understand the last bit about the fourth, but the part about imitation is a bit beyond me. Could someone rephrase that part in simpler language and explain it?
Answer: Luke, part of the cause for your confusion stems from the poor grammar in the Wikipedia article.  I actually had to read the highlighted excerpt twice to make sure that I understood it correctly.
A fugue, begins with what is called a subject, an identifiable motive or phrase that serves as a calling card for the piece - drawing the listener's attention during highly complex parts and creating cohesion throughout a piece.
After the subject is stated, it is followed by what is called an answer in another voice.  An answer may be done through imitation, which means exactly as it sounds (think "monkey see / monkey do").
A fugue cannot continue until all of the voices have entered the music (much like the way you would spin tops consecutively and watch them all spin.)
The last sentence that you highlighted indicates a phrase that ascend by the interval of a perfect-fourth and then descends by step back downward to the original pitch.
A musical example of this would be jumping upward from C -> F, and then "falling" (descending by step) back down to C:  F -> E -> D -> C
Regarding the "eighth note" comment, the author could have meant one of two things:

That the ascending / descending figure only occurs on a succession of upbeats.
That the ascending / descending figure begins on an off beat with an eighth note rhythm.

It is hard to say without context of looking at the score with the specific measure numbers.
I would also like to add that the Wikipedia article cited is quite, quite flimsy, and a very poor representation of analysis for one of Bach's most famous fugues.  I would highly suggest looking into other materials if you are in fact interested in learning more about the work.
Hope that helps.
Answer: Imitation is when a voice directly repeats an idea that was just stated in another voice.  It does not have to start on the same not.  So in this case, imagine two parts that take turns playing a fourth up and steps going down.
Imitation is closely related to sequences, which is when you repeat a melodic fragment several times, usually going up or down a scale. ex. (CFED)(DGFE)(EAGF)


No Web API Controller on Amazon EC2 instance

Question: I have a web application running on IIS 7 on Windows Server 2008 R2 (Datacenter edition) and built using Visual Studio 2010. When I deploy the website project to my local IIS server or the production IIS server hosted on a hosting service's VPS, the API Controller can be accessed via /api/notifications/, which is done via an AJAX call from a webpage. The problem is, on an identical setup on the Amazon EC2 instance, none of the API Controllers work, they all result in a 404 not found response. I checked that the same version of the .NET framework is installed everywhere, that IIS is running the same handler mappings, modules, ISAPI filters, Request Filtering, and ASP settings are all identical. Ran failed request tracing on the EC2 instance and got no asp related errors. Everything is up to date. I tried adding:
<modules runAllManagedModulesForAllRequests="true" />

and also tried adding:
<handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*"
         type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified"
         requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

To the appropriate places in the web.config file and still no api controllers. Normally, the website gets deployed to the "wwwroot" folder and everything else works, so I also tried deploying to a virtual directory by creating an application and accessing /Test/api/notifications/ still results in a 404 (while I can access the rest of the site at /Test/).
I tried re-registering the framework via this post: http://www.aheil.de/2012/11/05/fixing-asp-net-mvc-4-web-api-404/
I made sure that "Allow unlisted file name extensions" was checked in the IIS config.
Any ideas why this isn't working on the EC2 instance?
Comment: Is it an MVC application? Do you have the correct MVC framework installed?
Comment: @MattHouser It is not an MVC application. It's built from a Visual Studio 2010 website project. The API Controller code is inside the App_Code directory.
Answer: The problem was that .NET Framework 4.5 was installed on all the dev machines but not on the Amazon EC2 Windows Server 2008 R2 server. Installing .NET 4.5 apparently also updated old 4.0 assemblies (in particular, I suspect System.Net.Http and System.Web.Http), and because the webapp was built against the 4.5 versions of these 4.0 assemblies the Web API Controller wouldn't initialize when deployed on the EC2 server.
Solution: make sure that the framework assemblies are the same on the EC2 server as they are on the dev machines:

Install .NET 4.5 on the EC2 server
Uninstall .NET 4.5 on the dev machines.

Also a lot of useful information in this MSDN thread


What do imaginary components of frequencies represent in Fourier?

Question: I'm a Biology Ph.D. student with some math literacy (multivariable calc, discrete math, linear algebra, quantum chemistry) under my belt, so apologies if my knowledge is substandard for the work I'm trying to do.  I am currently looking at some time series of environmental data sampled every 20 minutes (temperature, etc). With help from a Geology professor, I am teaching myself some time-series analysis techniques and had some quick questions about the Fourier Transform.
My understanding: F.T. involves plotting your time series in the complex plane in polar coordinates, and averaging your points into a vector. Changing a multiplier (radians per timepoint) changes the vector, because… no correlation would cause the points to average out to zero, but any 'resonance' would cause the data to pull the vector off of 0.
The point where I'm having trouble, theoretically, is understanding what the imaginary component of the frequencies represents. I understand that in negative frequencies, imaginary components are odd and reals are even. I also understand that when you're looking at the One-sided power spectrum, you end up using the magnitude of the vector to determine power. This also makes sense to me.
Is having an imaginary component to the data just an incidental happenstance that results from utilizing the complex plane? Using this makes sense to me in that you're taking advantage of Euler's equations (which I'm sure helps with a lot of the math), but is there any sort of real-world meaning to imaginary components of frequencies?
Also, my conceptual understanding of Fourier comes from using my data, which does not have an imaginary component to it. How does plotting the data in the complex plane work when you start thinking about an input with both real and imaginary components?
Comment: If you are talking about the complex plane as $\mathbb{C}^1$, then I can tell you this. $\mathbb{C}^1\cong\mathbb{R}^2$. This allows you to simplify two sets of variables, $(x,y)\in\mathbb{R}^2$ to just one in $\mathbb{C}^1$.
Comment: Also, the frequency $\xi$ is usually real, giving us the Fourier transform of a function $f:\mathbb{R}^1\to\mathbb{C}^1\cong\mathbb{R}^2$ as $$\hat{f}(\xi) = \int_{-\infty}^\infty f(x)\ e^{- 2\pi i x \xi}\,dx$$
Answer: The easier way to think of the Fourier transform of a function is in terms of magnitude and complex argument (corresponding to the "polar" representation $r e^{i \theta}$ rather than the "rectangular" representation $a + bi$).
To try to put things in the terms you've used: let $x(t)$ be the time series, and let $X(\omega)$ be the Fourier transform.  The magnitude $|X(\omega)|$ at a particular frequency $\omega$ measures the power of the "resonance" of the time series with the reference oscillation $e^{i\omega t}$.  Along those lines, $\angle X(\omega)$ (the argument) tells you the phase of the oscillation with which $x(t)$ oscillates the strongest.
Comment: Thanks for answering my question, and for following along with the coarse nonmathematical language I am using. I guess thinking of it in terms of the real and imaginary components is somewhat flawed in that they are the cartesian coordinate representation of a polar coordinate vector that we use to find the power and phase. Does this sound correct?
Comment: I wouldn't say that thinking of it in terms of real and imaginary components is "flawed".  It is, however, generally more difficult less useful to do so.  I think there may be some physical interpretation of the real and imaginary components, probably having to do with the extent of constructive/destructive interference with a reference real-oscillation $\cos(\omega t)$.


Magento REST API OAuth

Question: Magento ver. 18.104.22.168
I'm new to Magento, REST and oauth. I want to be able to use the Magento REST API to be able to modify an online store with an inhouse Customer Management System. I have been able to set up Magento easily enough, but I'm struggling with REST, specifically with the oauth.
I am currently running Magento on MAMP 2.1.1 on OSX 10.7.5. I was able to install OAUTH using these directions: Installing PHP OAuth in MAMP environment
Following the Magento tutorial I am using the Firefox RESTClient to test OAuth. I have set up Roles and a Consumer in Magento, and put the keys in the corresponding fields in RESTClient.
When I post to
http://localhost:8888/store/oauth/initiate?oauth_callback=http://localhost:8888/store/oauth_admin.php

I get the reponse
oauth_problem=signature_invalid&debug_sbs=QiIiTo3WGTZLTOhyIest9B5+l5s=

Using the test PHP script on Magento ( http://www.magentocommerce.com/api/rest/introduction.html )
<?php
/**
 * Example of products list retrieve using admin account via Magento REST
API. oAuth authorization is used
 */
$callbackUrl = "http://localhost:8888/store/oauth_admin.php";
$temporaryCredentialsRequestUrl =
"http://localhost:8888/store/oauth/initiate?oauth_callback=" .
urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://localhost:8888/store/admin/oAuth_authorize';
$accessTokenRequestUrl = 'http://localhost:8888/store/oauth/token';
$apiUrl = 'http://localhost:8888/store/api/rest';
$consumerKey = 'obscured';
$consumerSecret = 'obscured';

session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) &&
$_SESSION['state'] == 1) {
   $_SESSION['state'] = 0;
}
try {
   $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION
: OAUTH_AUTH_TYPE_URI;
   $oauthClient = new OAuth($consumerKey, $consumerSecret,
OAUTH_SIG_METHOD_HMACSHA1, $authType);
   $oauthClient->enableDebug();

  if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
   $requestToken =
$oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
       $_SESSION['secret'] = $requestToken['oauth_token_secret'];
       $_SESSION['state'] = 1;
       header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' .
$requestToken['oauth_token']);
       exit;
   } else if ($_SESSION['state'] == 1) {
       $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
       $accessToken =
$oauthClient->getAccessToken($accessTokenRequestUrl);
       $_SESSION['state'] = 2;
       $_SESSION['token'] = $accessToken['oauth_token'];
       $_SESSION['secret'] = $accessToken['oauth_token_secret'];
       header('Location: ' . $callbackUrl);
       exit;
   } else {
       $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
       $resourceUrl = "$apiUrl/products";
       $oauthClient->fetch($resourceUrl);
           $productsList = json_decode($oauthClient->getLastResponse());
           print_r($productsList);
       }
    } catch (OAuthException $e) {
       print_r($e);
    }
    ?>

I get the following error:
Notice: Undefined index: state in /Applications/MAMP/htdocs/store/test.php on line 23

Notice: Undefined index: state in /Applications/MAMP/htdocs/store/test.php on line 29
OAuthException Object ( [message:protected] => Invalid auth/bad request (got a 401,         expected HTTP/1.1 20X or a redirect) [string:private] => [code:protected] => 401     [file:protected] => /Applications/MAMP/htdocs/store/test.php [line:protected] => 31 [trace:private] => Array ( [0] => Array ( [file] => /Applications/MAMP/htdocs/store/test.php [line] => 31 [function] => getRequestToken [class] => OAuth [type] => -> [args] => Array ( [0] => http://localhost:8888/store/oauth/initiate?oauth_callback=http%3A%2F%2Flocalhost%3A8888%2Fstore%2Foauth_admin.php ) ) ) [lastResponse] => oauth_problem=signature_invalid&debug_sbs=c3Pb0LJa26al02LJh9hSubXlBs8= [debugInfo] => Array ( [sbs] => GET&http%3A%2F%2Flocalhost%3A8888%2Fstore%2Foauth%2Finitiate&oauth_callback%3Dhttp%253A%252F%252Flocalhost%253A8888%252Fstore%252Foauth_admin.php%26oauth_consumer_key%3D41rv8qwkai1og9yp6ragyew5rag5e9oj%26oauth_nonce%3D10898187885101843ed45b24.99726561%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1359053886%26oauth_version%3D1.0 [headers_sent] => GET /store/oauth/initiate?oauth_callback=http%3A%2F%2Flocalhost%3A8888%2Fstore%2Foauth_admin.php&oauth_consumer_key=41rv8qwkai1og9yp6ragyew5rag5e9oj&oauth_signature_method=HMAC-SHA1&oauth_nonce=10898187885101843ed45b24.99726561&oauth_timestamp=1359053886&oauth_version=1.0&oauth_signature=F36aIxyET2XEVXDCJxm4jxGsRPg%3D HTTP/1.1 User-Agent: PECL-OAuth/1.2.3 Host: localhost:8888 Accept: */* [headers_recv] => HTTP/1.1 401 Authorization Required Date: Thu, 24 Jan 2013 18:58:06 GMT Server: Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/0.9.8r DAV/2 PHP/5.2.17 X-Powered-By: PHP/5.2.17 Content-Length: 70 Content-Type: application/x-www-form-urlencoded [body_recv] => oauth_problem=signature_invalid&debug_sbs=c3Pb0LJa26al02LJh9hSubXlBs8= [info] => About to connect() to localhost port 8888 (#0) Trying ::1... connected Connected to localhost (::1) port 8888 (#0) Connection #0 to host localhost left intact Closing connection #0 ) )

As far as I can tell I've done everything correctly, going so far as to completely wipe Magento and doing a fresh install after figuring out how to get Oauth installed. I have no idea what to do next and any help would be greatly appreciated, thanks.
Answer: I learned you can't include the port number of a URL for an Oauth Request. The port number gets stripped, so when the keys are compared, they don't match. Changing the port to 80 (so that it doesn't have to be included in the url) solved the problem.
Comment: I hit this and was also healed by moving to port 80, THANK YOU! Some notes for other searchers: I was using MAMP PRO on Mac OS X, which defaults to port 8888, which I had left as-is when I installed Magento. The base REST API was working. I was using Python with rauth and OAuth1Service. Further hint: When this line failed: request_token, request_token_secret = service.get_request_token(...), I tried using: raw = service.get_raw_request_token(...) and then print "RAW Request Token reply: " + str(raw), and I was seeing "", but I had carefully checked Roles under Web Services.
Comment: But what is the solution. I mean if I cannot for some reason change the port number, then what should i do?
Comment: You have to find some way to make the connection on Port 80 (http) or 443 (https)
Comment: Port number must be stripped (normalized) when doing OAuth 1.0 signature. After doing this, I was able to connect to Magento as if the service were on port 80.
Answer: Just override Mage_Oauth_Model_Server::_validateSignature(), on line 52 (magetno CE 1.8.1)
$this->_request->getHttpHost()

and make it :
 $this->_request->getHttpHost(!Mage::getIsDeveloperMode())

This way, if you are in developer mode (set it by SetEnv in your vhost <Directory /> part), the method won't strip the port number, plus it won't change the production environment behavior.
++

Magento REST API OAuth


Effect of illness on vocal range

Question: My usual vocal range is F2-A4. During a recent illness, my range was temporarily reduced to F2-C4. Why does throat irritation seem to affect only my high notes?
Comment: Strange, sometimes it would even expand my range. :/ Sometimes shrink.
Answer: Probably due to thickening of the vocal chords due to swelling.  I've often found that when I get a throat problem, my range is lower.  I can't hit my highest notes and can hit lower notes than usual.  (I'm a rather high baritone, by the way; I've sung lead in a barbershop quartet and second tenor in a choir.)

Effect of illness on vocal range


Solve matrix equation $\mathbf{X} + \mathbf{X}\mathbf{M} + \mathbf{M}\mathbf{X} = \mathbf{C}$

Question: I'm having some trouble solving the matrix equation
$$\mathbf{X} + \mathbf{X}\mathbf{M} + \mathbf{M}\mathbf{X} = \mathbf{C}$$
for $\mathbf{X}$, where

$M_{ij} = m_im_j$ (and therefore symmetric)
$m_i$ is vector of length $=1$,
$\mathbf{X}$ is symmetric
Trace$(\mathbf{X})=0$
Matrices are $3 \times3$

I've been doing some research, and my post is relatively similar to this post. However, $\mathbf{M}$ seems to have at least one zero eigenvalue, implying the suggested solution in the post will not work.
How can I proceed? (My linear algebra is a bit rusty)
Thank you very much for your time!
Comment: @AlexSilva symmetric matrices don't necessarily commute, e.g.
$$
M = \pmatrix{1&1\\1&1}, \quad X = \pmatrix{1&0\\0&2}
$$
Comment: https://en.wikipedia.org/wiki/Sylvester_equation
Comment: @Omnomnomnom, You're right! Thanks.
Answer: With a careful reading of the page on Sylvester's equation, we can apply the vectorization operator to both sides of your equation to obtain
$$
\operatorname{vec}(X) + (M \otimes I_3) \operatorname{vec}(X) + (I_3 \otimes M)\operatorname{vec}(X) = \operatorname{vec}(C) \implies\\
[I_9 + M \otimes I_3 + I_3 \otimes M]\operatorname{vec}(X) = \operatorname{vec}(C)
$$
which is to say that, at worst, we can obtain the solution by solving 9-variable linear system of equations.  Note that, in the above, $\operatorname{vec}(X)$ is the column-vector given by
$$
\operatorname{vec}(X) = (x_{11},x_{21},x_{31},x_{12},x_{22},x_{32},x_{13},x_{23},x_{33})^T
$$
We can guarantee that the matrix $I_9 + M \otimes I_3 + I_3 \otimes M$ will be invertible since it is positive definite, so we can indeed guarantee the unique solution
$$
\operatorname{vec}(X) = [I_9 + M \otimes I_3 + I_3 \otimes M]^{-1} \operatorname{vec}(C)
$$
Notably, we have done nothing with the information that $X$ is symmetric and trace free. However, if the above is implemented correctly, then our unique solution $X$ should satisfy these conditions.

Idle observations:
We can easily find an orthogonal matrix $P$ whose first column is $m = (m_1,m_2,m_3)^T$ (or at least have a computer do so).  That is, we can find a $P$ which satisfies $Pe_1 = m$ and $P^TP = I$, where $e_1 = (1,0,0)^T$.  With that, we can note that $M = mm^T$ and rewrite the equation as
$$
X + XM + MX = C \implies\\
X + X(Pe_1)(Pe_1)^T + (Pe_1)(Pe_1)^TX = C \implies\\
X + (XP)(e_1 e_1^T)P^T + P(e_1e_1^T)(P^TX) = C \implies\\
P^TXP + (P^TXP)(e_1 e_1^T) + (e_1e_1^T)(P^TXP) = P^TCP
$$
So, if we perform the substitution $Y = P^TXP$, $D = P^TCP$, $N = e_1e_1^T$, then it suffices to solve the system of equations
$$
Y + YN + NY = D
$$
where in this equation, we always have
$$
N = \pmatrix{1&0&0\\0&0&0\\0&0&0}
$$
Comment: Thank you very much for taking the time and laying out  your answer in such detail. As said, my linear algebra  is a bit rusty, so I appreciate very much your effort. I'll be studying it over the weekend once I have time. Thank you!
Comment: I finally had the time to go through the derivation for my problem using your explanation. It worked nicely. Thank you very much!


Do finite additivity and countable subadditivity imply countable additivity?

Question: Given a Measure Space and f a positive set function on the sigma-algebra of the space (not identically infinite), how could I prove that f is a measure given the hypothesis above?
I've tried both by contradiction and induction, but I struggle a bit with the intuition.
Answer: Yes.
Finite additivity implies the next inequality:
$$
\mu \left(\bigsqcup\limits_{i = 1}^{\infty} A_i \right) \geq \sum\limits_{i = 1}^{\infty} \mu(A_i)
$$
Indeed,
$$
\mu \left(\bigsqcup\limits_{i = 1}^{\infty} A_i \right) = \mu \left(\bigsqcup\limits_{i = 1}^{N} A_i \right) + \mu \left(\bigsqcup\limits_{i = N+1}^{\infty} A_i \right) \geq \mu \left(\bigsqcup\limits_{i = 1}^{N} A_i \right)  = \sum\limits_{i = 1}^{N} \mu(A_i)
$$
Taking limits of both sides of the inequality finishes the proof.
Obviously, countable subadditivity (or also called $\sigma$-subadditivity) implies the opposite inequality.
Combining the ideas above, it can be concluded that a finite additivity and a countable subadditivity do imply a countable additivity.


Does the logic behind objects matter?

Question: When working on the early stages of a console-based Python remake of the classic game 'Snake', someone submitted a patch to spawn food at random locations. The code defined a Food class which worked fine, but the logic behind it seemed a little weird.
I think we should delete the food once it's been consumed, then create another one. However, this person simply moves the food to a new random location once it's been consumed. While the latter seems illogical to me, it seems to do the exact same thing, maybe even more efficiently.
My question is: Would it be better to use the former logic, or the later, or am I simply nit-picking over nothing?
This all started at: https://bugs.launchpad.net/snakes-game/+bug/628180
Answer: I believe both solutions are fine. Relocating the food to another location is brobably less error prone in memory management terms, but due to garbage collection, you shouldn't care about that too much.
I'd argue, while instantiating a new food object is more logical, and closer to the real life model, relocating is more efficient.
Comment: +1: Good concise explanation, but Jason's answer goes into more detail about the practical implications of the solutions.
Answer: Either is fine - within certain common-sense boundaries.
The latter approach will save re-allocating the object, so recycling it in this way will be more efficient - the gain is likely to be irrelevant in your particular example though unless heap fragmentation is a concern (e.g. on an embedded app with very limited RAM).
The danger with recycling is that the object may retain some vestige of its former state, so may not behave in the same manner as a new object would - in your case the logic is simple, so there is little danger, but with more complex objects this could become significant.
So in general I'd suggest the "create a new object" approach (it follows the principle of "least surprise", and will be less likely to confuse other programmers who come to work on the code) unless there are performance implications (e.g. on an embedded application like a phone where you have very limited resources and don't want a fragmented heap), in which case the "re-use an existing object" may be a smart solution.
Comment: Thanks, very in-depth explanation. Answers my question perfectly.
Answer: The main issue as far as OOP is concerned isn't so much whether the food re-instantiates vs. relocates, but rather that this behavior remain transparent outside of the object.  The game engine should be telling the object "you've been eaten" and such, but how the object handles that internally shouldn't be known to the game engine.  If, internally, the object maintains a singleton of "food" and the "consume" method simply re-forms the food object with new values, that's fine.  That's all internal to the implementation of "food" and just shouldn't be known outside of that class.
Comment: +1 for the good explanation of basic object-orientated logic, but some of the other answers were more in-depth  about my particular question.

Does the logic behind objects matter?


Proving density of $\mathbb{Q}^n$ in $\mathbb{R}^n$

Question: I'm looking for a relatively simple way to prove that $\Bbb {Q}^n$ is dense in $\Bbb{R}^n$ given $\Bbb Q$ is dense in $\Bbb R$
Thanks
Comment: Every ball with centre $x$ contains a "cube" with centre $x$.
Comment: To get a rational point $(r_1,\dots,r_n)$ within $\epsilon$ of $(x_1,dots,x_n)$ it is enough to make $|x_i-r_i|\lt \frac{\epsilon}{\sqrt{n}}$ for all $i$.
Comment: Start with $n=1$.
Answer: Let $U \subseteq \mathbb{R}^n$ be open and nonempty, and let $x = (x_1, x_2, \cdots, x_n) \in U$. By openness there exists $\varepsilon > 0$ such that
$$B(x; \varepsilon) = \{ y \in \mathbb{R}^n : \lVert x-y \rVert < \varepsilon \} \subseteq U$$
For each $1 \le i \le n$ pick $q_i \in \mathbb{Q}$ such that $x_i \le q_i < x_i + \frac{\varepsilon}{\sqrt{n}}$; such a $q_i$ exists by density of $\mathbb{Q}$ in $\mathbb{R}$. You need to show that $q = (q_1, q_2, \cdots, q_n) \in U \cap \mathbb{Q}^n$, so that $U \cap \mathbb{Q}^n \ne \varnothing$.


Is this a valid uniqueness up to isomorphism?

Question: I've shown around for a couple of times asking more or less same "uniqueness up to isomorphism"-related questions. Unfortunately, have to ask yet another one.
Say, there are distinguishable $A, B, C$ sets along with $f : A \mapsto B$ and $g : B \mapsto C$. Those conditions are sufficient to build up unique $h : A \mapsto C, h = g \circ f$.

1) May I state that $A$ and $B$ are "unique up to isomorphism" since there is a way to map them both to the same $C$?
2) May I state that maps $g$ and $h$ are "unique up to isomorphism" because of the fact that both resulting to the same $C$?
3) Finally, does the term "isomorphism" always equal to the "bijection"? Could any of the "unique up to isomorphism" be safely replaced with "unique up to bijection"?
Comment: Saying that $A$ is isomorphic to $B$ has nothing to do with $C$! Also, $\text{Hom}(X,Y)\neq \emptyset$ for all non-empty sets $X,Y$, thus between any two sets, there is always a map.
Comment: Are $f,g$ assumed to be isomorphisms or merely functions?  In what sense do you mean that $h$ is "unique"?
Comment: This question is not at all clear.  "isomorphisms" are the same as "bijections" only if we are in a category in which this holds.  If you are in a category in which the objects have more structure then an "isomorphism" will be expected to respect that additional structure.
Answer: The answer is no to all three questions.

$A$ and $B$ are isomorphic. You say that an object is unique up to isomorphism when it is completely determined by some (universal) property, up to isomorphisms (i.e. there could be another object with the same properties, but it would have to be isomorphic to the first one).
This question doesn't really make any sense to me.
This is a more interesting question. You are probably used to work in categories where the objects have underlying sets and where the morphisms are morphisms of the underlying sets. This is not always the case, so the answer is no. Also in the case where the objects have underlying sets and the morphisms are morphisms of sets respecting some additional structure, this is certainly not true (e.g. not all bijections between groups are isomorphisms...)
Comment: $A$ and $B$ aren't isomorphic if all we know is that they both map into $C$!
Comment: Just to clarify. By saying that the $A$ is isomorphic to the $B$.. is it just because of mapping to the $C$? Does not make much sense to me then: there is a mapping from empty set to an any other $S$. So all of them are isomorphic?
Comment: @SerejaBobolubov $A$ and $B$ are isomorphic because, and only because, of the existence of a certain type of morphism $f$ from $A$ to $B$. Specifically, the morphism has an inverse morphism from $B$ to $A$ (inverse with respect to composition). So there is no mention of a third object $C$ at all.
Comment: @PeterSmith Oh, right, I misread. I thought that $f,g$ were supposed to be bijective in the OP.
Comment: I think your last sentence could be a bit nuanced; there are a lot of cases where the morphisms are just functions preserving some structure where it *is* true that isomorphisms are exactly the bijections that preserve the structure. For example every bijective group homomorphism is an isomorphism. A better counterexample would be topological spaces or partially ordered sets; not every continuous or order-preserving bijection is an isomorphism.


Laravel HasManyThrough relationship while including Trashed items

Question: I want to include soft deleted items with HasManyThrough relationship,
I tried adding ->withTrashed(); to it, but then I got this error:

BadMethodCallException Call to undefined method
  Illuminate\Database\Eloquent\Relations\HasManyThrough::withTrashed()

Is it possible to force Laravel skip that where table.deleted_at is null in a relationship?
Comment: Can you please post your code regarding your relationship here?
Comment: Could you plz add your models / controller ?
Answer: This is an old question, but responding for anyone that has the same issue.
if your are using HasManyThrough and want to fetch also the soft deleted records. there is a scope in the HasManyThrough relationship that can include them.
You should use it like follow :
$yourModel->yourHasManyThroughRelation()->withTrashedParents()->withTrashed();

Answer: Should work the way you are trying.
I made an example to make it more clear to understand:
Group::with('users')->get();
And in the Group model:
public function users()
{
    return $this->hasManyThrough(User::class, UserGroup::class, 'group_id', 'id', 'id', 'user_id')->withTrashed();
}