Convert List of DateTime entries to custom summary List

Question: Punches = new List<TimeClock>(); // Populated from database ...
Existing List:
[Employee] - [DateTime] - [Action]
x1 - y1 - in
x2 - y2 - in
x1 - y3 - out
x3 - y4 - in
x1 - y5 - in
x3 - y6 - out
x2 - y7 - out
x1 - y8 - out
x2 - y9 - in
x2 - y10 - out

Desired List format:
[Employee] - [Start] - [End] - [Hours]
x1 - y1 - y3 - z1
x1 - y5 - y8 - z2
x2 - y2 - y7 - z3
x2 - y9 - y10 - z4
x3 - y4 - y6 - z5

I'm trying to take a List of employee/time/action and flatten it into a summary list of employee/start/end/duration with each employee having 1 line per corresponding in/out times.
I'm not sure how to create the new list, or if I should even call it a List? I'm coming from PHP where I would use an Array to build the employee's summaries but I'm not sure how to do this in C#.
The code below is how I've managed to get the summary of hours worked per Employee from the main List, I thought I could use a similar structure/loop for making the summary list but again I'm not sure how exactly, I've also tried using struct to define a list... someone point me in the right direction please!
    ///
    /// Populates HoursWorked List
    ///
    public void PopulateHoursWorkedList()
    {
        // Get list of time clock punches
        PayPeriodPunches = new List<TimeClock>();

        if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            using (var db = new Database())
            {
                // Load with Employee
                DataLoadOptions dlo = new DataLoadOptions();
                dlo.LoadWith<TimeClock>(tc => tc.Employee);
                db.LoadOptions = dlo;

                PayPeriodPunches = db.TimeClockPunches
                    .Where(cp => cp.ClockPunchDateTime >= PayPeriodSelected.BeginDateTime
                                && cp.ClockPunchDateTime <= PayPeriodSelected.EndDateTime)
                    .OrderBy(cp => cp.ClockPunchDateTime)
                    .ToList();
            }

        // Get unique list of employees and sum of hours worked
        HoursWorkedList = new List<EmployeeHoursWorked>();
        foreach (TimeClock tcp in PayPeriodPunches)
        {
            if (!HoursWorkedList.Exists(e => e.Employee == tcp.Employee))
            {
                EmployeeHoursWorked ehw = new EmployeeHoursWorked();
                ehw.Employee = tcp.Employee;
                HoursWorkedList.Add(ehw);
            }
        }

        foreach (EmployeeHoursWorked ehw in HoursWorkedList.ToList())
        {
            Employee e = ehw.Employee;
            // This employees punches
            List<TimeClock> thisEmpPunches = PayPeriodPunches
                .Where(pp => pp.Employee == e)
                .OrderBy(pp => pp.ClockPunchDateTime)
                .ToList();

            bool hasClockedIn = false;
            bool hasClockedOut = false;
            int i = 0;
            DateTime dts = new DateTime();
            DateTime dte = new DateTime();
            TimeSpan dur = new TimeSpan();

            foreach (TimeClock tcp in thisEmpPunches)
            {
                if (tcp.ClockAction == ClockAction.In)
                {
                    dts = tcp.ClockPunchDateTime;
                    hasClockedIn = true;
                    i = 1;
                }

                if (tcp.ClockAction == ClockAction.Out)
                {
                    dte = tcp.ClockPunchDateTime;

                    // Was clocked In: Use previous clock-in time
                    if (i == 1)
                    {
                        dur = dte - dts;
                    }
                    else
                    {
                        // Not clocked in, never clocked in, assume clocked in since beginning of PP
                        if (!hasClockedIn)
                        {
                            dts = PayPeriodSelected.BeginDateTime;
                            dur = dte - dts;
                        }
                    }

                    // Update employee hours worked duration
                    int index = HoursWorkedList.FindIndex(z => z.Employee == e);
                    EmployeeHoursWorked tmp = HoursWorkedList[index];
                    tmp.HoursWorked += dur;
                    HoursWorkedList[index] = tmp;

                    hasClockedOut = true;
                    i = 2;
                }

            }

            if (i == 1)
            {
                // Employee never clocked out, assume end of PP (or now if sooner)
                if (DateTime.Now < PayPeriodSelected.EndDateTime)
                {
                    dte = DateTime.Now;
                }
                else
                {
                    dte = PayPeriodSelected.EndDateTime;
                }

                // Update employee hours worked duration
                dur = dte - dts;
                int index = HoursWorkedList.FindIndex(z => z.Employee == e);
                EmployeeHoursWorked tmp = HoursWorkedList[index];
                tmp.HoursWorked += dur;
                HoursWorkedList[index] = tmp;
            }

        }

    }

Answer: Ok, thanks rubber ducky. Was able to use the loop after all, just had to think out loud...
Note the parts with the following blocks of code:
EmployeeClockSummary ecs = new EmployeeClockSummary();
ecs.Employee = e;
ecs.ClockInTime = dts;
ecs.ClockOutTime = dte;
HoursSummaryList.Add(ecs);

Works:
///
/// Populates HoursSummary List
///
public void PopulateHoursSummaryList()
{
    HoursSummaryList = new List<EmployeeClockSummary>();

    // Get list of time clock punches
    PayPeriodPunches = new List<TimeClock>();

    if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))
    using (var db = new Database())
    {
        // Load with Employee
        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<TimeClock>(tc => tc.Employee);
        db.LoadOptions = dlo;

        PayPeriodPunches = db.TimeClockPunches
                .Where(cp => cp.ClockPunchDateTime >= PayPeriodSelected.BeginDateTime
                            && cp.ClockPunchDateTime <= PayPeriodSelected.EndDateTime)
                .OrderBy(cp => cp.ClockPunchDateTime)
                .ToList();
    }

    // Get unique list of employees and sum of hours worked
    HoursWorkedList = new List<EmployeeHoursWorked>();
    foreach (TimeClock tcp in PayPeriodPunches)
    {
        if (!HoursWorkedList.Exists(e => e.Employee == tcp.Employee))
        {
            EmployeeHoursWorked ehw = new EmployeeHoursWorked();
            ehw.Employee = tcp.Employee;
            HoursWorkedList.Add(ehw);
        }
    }

    foreach (EmployeeHoursWorked ehw in HoursWorkedList.ToList())
    {
        Employee e = ehw.Employee;
        // This employees punches
        List<TimeClock> thisEmpPunches = PayPeriodPunches
            .Where(pp => pp.Employee == e)
            .OrderBy(pp => pp.ClockPunchDateTime)
            .ToList();

        bool hasClockedIn = false;
        bool hasClockedOut = false;
        int i = 0;
        DateTime dts = new DateTime();
        DateTime dte = new DateTime();
        TimeSpan dur = new TimeSpan();

        foreach (TimeClock tcp in thisEmpPunches)
        {
            if (tcp.ClockAction == ClockAction.In)
            {
                dts = tcp.ClockPunchDateTime;
                hasClockedIn = true;
                i = 1;
            }

            if (tcp.ClockAction == ClockAction.Out)
            {
                dte = tcp.ClockPunchDateTime;

                // Was clocked In: Use previous clock-in time
                if (i == 1)
                {
                    dur = dte - dts;

                    EmployeeClockSummary ecs = new EmployeeClockSummary();
                    ecs.Employee = e;
                    ecs.ClockInTime = dts;
                    ecs.ClockOutTime = dte;
                    HoursSummaryList.Add(ecs);
                }
                else
                {
                    // Not clocked in, never clocked in, assume clocked in since beginning of PP
                    if (!hasClockedIn)
                    {
                        dts = PayPeriodSelected.BeginDateTime;
                        dur = dte - dts;

                        EmployeeClockSummary ecs = new EmployeeClockSummary();
                        ecs.Employee = e;
                        ecs.ClockInTime = dts;
                        ecs.ClockOutTime = dte;
                        HoursSummaryList.Add(ecs);
                    }
                }

                // Update employee hours worked duration
                int index = HoursWorkedList.FindIndex(z => z.Employee == e);
                EmployeeHoursWorked tmp = HoursWorkedList[index];
                tmp.HoursWorked += dur;
                HoursWorkedList[index] = tmp;

                hasClockedOut = true;
                i = 2;
            }
        }

        if (i == 1)
        {
            // Employee never clocked out, assume end of PP (or now if sooner)
            if (DateTime.Now < PayPeriodSelected.EndDateTime)
            {
                dte = DateTime.Now;
            }
            else
            {
                dte = PayPeriodSelected.EndDateTime;
            }

            EmployeeClockSummary ecs = new EmployeeClockSummary();
            ecs.Employee = e;
            ecs.ClockInTime = dts;
            ecs.ClockOutTime = dte;
            HoursSummaryList.Add(ecs);

            // Update employee hours worked duration
            dur = dte - dts;
            int index = HoursWorkedList.FindIndex(z => z.Employee == e);
            EmployeeHoursWorked tmp = HoursWorkedList[index];
            tmp.HoursWorked += dur;
            HoursWorkedList[index] = tmp;
        }

        if (HoursSummaryList.Any())
        {
        }
    }
}

Answer: So I was able to make a flattened list a lot easier by simply modifying the LINQ query to use GroupBy:
foreach (var empInOuts in PayPeriodPunches
    .OrderBy(x => x.ClockPunchDateTime)
    .GroupBy(x => x.Employee))

New:
    ///
    /// Populates HoursDuration List
    ///
    public void PopulateHoursDurationList()
    {
        HoursDurationList = new ObservableCollection<EmployeeClockSummary>();

        try
        {
            // Punches grouped by Employee
            foreach (var empInOuts in PayPeriodPunches
                .OrderBy(x => x.ClockPunchDateTime)
                .GroupBy(x => x.Employee))
            {
                int empCount = 0;
                foreach (var empPunch in empInOuts)
                {
                    if (empPunch.ClockAction == ClockAction.In)
                    {
                        // Clock In
                        HoursDurationList.Add(new EmployeeClockSummary
                        {
                            Employee = empPunch.Employee,
                            ClockInTime = empPunch.ClockPunchDateTime
                        });
                    }
                    else
                    {
                        // Clock Out
                        if (empCount == 0)
                        {
                            // This emp first punch is clock out (emp was clock in on previous pp)
                            HoursDurationList.Add(new EmployeeClockSummary
                            {
                                Employee = empPunch.Employee,
                                ClockOutTime = empPunch.ClockPunchDateTime
                            });
                        }
                        else
                        {
                            // Add clockout to previous clock in entry
                            var last = HoursDurationList[HoursDurationList.Count - 1];
                            last.ClockOutTime = empPunch.ClockPunchDateTime;
                            HoursDurationList[HoursDurationList.Count - 1] = last;
                        }
                    }
                    empCount++;
                }
            }
        }
        catch (Exception e)
        {
        }

        // Check for any missing ClockOuts ie still clocked in, ClockIns ie was clocked in at start
        ObservableCollection<EmployeeClockSummary> tempList = new ObservableCollection<EmployeeClockSummary>();
        foreach (var x in HoursDurationList)
        {
            var change = x;

            if (change.ClockOutTime == DateTime.MinValue
                || change.ClockOutTime == null)
            {
                // Set clock out date to now (or pp end if now passed it)
                // as they are still clocked in
                if (DateTime.Now > PayPeriodSelected.EndDateTime)
                {
                    change.ClockOutTime = PayPeriodSelected.EndDateTime;
                }
                else
                {
                    change.ClockOutTime = DateTime.Now;
                }
            }

            // Set clock in date to beginning of PP
            // as they were already clocked in when it started
            if (change.ClockInTime == DateTime.MinValue
                || change.ClockInTime == null)
            {
                change.ClockInTime = PayPeriodSelected.BeginDateTime;
            }

            tempList.Add(change);
        }

        // Group by Employee
        HoursDurationList = tempList;
        HoursDurationListView = new ListCollectionView(HoursDurationList);
        HoursDurationListView.GroupDescriptions.Add(new PropertyGroupDescription("Employee"));

    }


Extract all confirmed transactions from a bitcoin block using python

Question: I want to extract all confirmed transactions from the bitcoin blockchain. I know there are repos out there (e.g. https://github.com/znort987/blockparser) but I want to write something myself for my better understanding.
I am have tried the following code after having downloaded far more than 42 blocks and while running bitcoind (minimal example):
from bitcoin.rpc import RawProxy

proxy = RawProxy()
blockheight=42
block = proxy.getblock(proxy.getblockhash(blockheight))
tx_list = block['tx']

for tx_id in tx_list:
    raw_tx = proxy.getrawtransaction(tx_id)

This yields the following error:
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/donkeykong/.local/lib/python3.7/site-packages/bitcoin/rpc.py", line 315, in <lambda>
    f = lambda *args: self._call(name, *args)
  File "/home/donkeykong/.local/lib/python3.7/site-packages/bitcoin/rpc.py", line 239, in _call
    'message': err.get('message', 'error message not specified')})
bitcoin.rpc.InvalidAddressOrKeyError: {'code': -5, 'message': 'No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries. Use gettransaction for wallet transactions.'}

Could anyone elucidate what I am misunderstanding?
For reproduction:

python version: Python 3.7.3
I installed the bitcoin.rpc via: pip3 install python-bitcoinlib
bitcoin-cli version: Bitcoin Core RPC client version v0.20.1
Answer: Running the client as bitcoind -txindex solves the problem as it maintains the full transaction index. I should have spent more attention to the error message...
Excerpt from bitcoind --help:
-txindex
       Maintain a full transaction index, used by the getrawtransaction rpc
       call (default: 0)


How many olympic gold medal ties have there been?

Question: Simone Manuel tied for the gold with Penny Oleksiak in the 100m freestyle during the 2016 Summer Olympics. I have never seen this before, and was curious how often it happens. I tried to find information, and in fact the first article I linked to says that there was a tie in this same event in 1984, but I can't find a list of other events where this has happened, within swimming and beyond.
All I found were articles like about a downhill skiing gold medal tie between Tina Maze and Dominique Gisin in 2014, and one that addresses this incident and lists the ties from only the Winter Olympics.
Does anyone know how many gold medal ties there have been in Olympic history, in both the summer and winter games?
Comment: There was a 3-way tie for silver for the Mens 100m Butterfly.  PHELPS (USA), LE CLOS (S. Africa), CSEH (Hungary)  https://www.rio2016.com/en/swimming-mens-100m-butterfly-final
Answer: Summer Olympic Games: 27 gold medal ties. (The source below says 26 times as of 2014...so the Manuel/Oleksiak tie would be 27 -- looking for a better source).
Winter Olympic Games: 8 gold medal ties.


Show: If the adjoint of T is -T, all eigenvalues are purely imaginary

Question: Homework question.
Let $V$ be a finite dimensional inner-product space over $\mathbb{C}$.  Let $T \in L(V,V)$ satisfy $T^*=-T$.  Show that all eigenvalues of $T$ are purely imaginary, i.e., if $\lambda$ is an eigenvalue of $T$, then $\lambda = ia$ with $a \in \mathbb{R}$.

I can recall a proof we did in class that if $T$ is self-adjoint then all eigenvalues are real, and the basic gist of it was let $\lambda$ be an eigenvalue, then lambda is equal to its complex conjugate.  I understand this; it implies that if $\lambda = a+bi = a-bi$ then $b = 0$.
It follows (in my mind, at least) that I need to show that given that $T^* = -T$ that $\lambda = -\lambda$.
I'm kind of stuck here, though.  I've tried adapting the proof I have for self-adjoint operators, but I'm unable to do it without having the conjugate in the result, which is not what I want. (that seems to imply that all eigenvalues are 0, I don't think that's true).
Answer: An alternative proof of this, probably not as enlightening but I like it: if $T^* = -T$, then $iT$ is self-adjoint (why?) and so the eigenvalues of $iT$ are real. It then follows that the eigenvalues of $T$ are purely imaginary. (again, why?)
Answer: Showing that $\lambda=-\lambda$ would only let you say that $\lambda=0$, not that $\lambda$ was imaginary, so that is not what you need to show.
Instead, look at what exactly was originally done for $S$ symmetric and $\lambda,v$ an eigenpair:
$$\lambda \langle v,v\rangle =\langle Sv,v\rangle=\langle v,Sv\rangle = \overline{\langle Sv,v\rangle} =\overline{\lambda \langle v,v\rangle}=\overline{\lambda}\langle v,v\rangle.$$
The first equality is by linearity, the second by $S=S^*$, the third by conjugate symmetry of the inner product, the fourth by linearity again, and the last by $\overline{ab}=\bar{a}\,\bar{b}$ along with the fact $\langle v,v\rangle$ is purely real and so is invariant under complex conjugation. From this we deduce $\lambda = \lambda^*$.
So what happens if instead $T=-T^*$?
Answer: Suppose $\lambda$ is an eigenvalue, and $v$ a corresponding eigenvector of unit length. Then $$\langle v,Tv\rangle = \langle T^*v,v\rangle = -\langle Tv,v\rangle = -\overline{\langle v,Tv\rangle}.$$
Since $\langle v,Tv\rangle = \lambda$, we have $\lambda = -\overline{\lambda}$, from which it follows that $\lambda$ is purely imaginary.
Comment: Yes, I've found this result. But doesn't this imply that $\lambda = 0$?  It seems that if $-\lambda = \overline\lambda$, then that's like saying that $-a+bi = a-bi$, which would only be true if $a = b = 0$.  Am I missing something?
Comment: @Precision: $-\lambda=-(a+bi)=-a\color{Red}-bi,$ not $-a+bi$.
Comment: You are missing something. It implies $a+ib = -a+ib$ from which you can conclude $a=0$, hence imaginary.
Comment: Ah... yeah.  Well, that's awkward.  Makes so much sense now, thank you.


Integrating $ (\cos ^3 x - \sin^3 x)^{-1}$

Question: $$I=\int \frac{dx}{\cos^3 x-\sin ^3 x}=\int \frac {(\cos x-\sin x) dx}{(\cos x -\sin x)^2 (1+\sin x \cos x)}=\int \frac{2(\cos x-\sin x)dx}{(1-\sin 2x)(2+\sin 2x)}$$
$$\implies I=\frac{2}{3} \int (\cos x - \sin x) {\left(\frac{1}{1-\sin 2x}+ \frac{1}{2+\sin 2x}\right)}dx$$
$$\implies I=\frac{2}{3} \int (\cos x - \sin x) {\left(\frac{1}{2-(\sin x+ \cos x)^2}+ \frac{1}{1+(\sin x+\cos x)^2}\right)}dx.$$
Let us use $\sin x+\cos x=t$. Finally,we get
$$I=\frac{2}{3}\int\left( \frac{1}{2-t^2}+\frac{1}{1+t^2}\right)dt=\frac{1}{3\sqrt{2}} \log \left|\frac{\sqrt{2}-(\sin x+\cos x)}{\sqrt{2}+(\sin x+\cos x)}\right|+\frac{2}{3}\tan^{-1}(\sin x+\cos x)+C.$$
Looking at a solution, it looks natural and perhaps unique. The question is: How else it can be done.
Comment: Probably this is the simplest way to integrate it.
Comment: The standard-but-tedious use of the Weierstrass substitution, $t = \tan(x/2)$, probably applies.
Comment: One may also substitute $x=\sin^{-1}y$, then try an [Euler sub](https://en.wikipedia.org/wiki/Euler_substitution). The result is$$-\frac23\int\left(\frac2{z^2+2z-1}+\frac{z^2+2z-1}{z^4-2z^3+2z^2+2z+1}\right)\,dz$$
Answer: One possible way is the write
$$\frac 32 \frac{1}{\cos ^3(x)-\sin ^3(x)}=\frac{\cos (x)-\sin (x)}{1+(\sin (x)+\cos (x))^2}+\frac{\sec
   ^2\left(\frac{x}{2}\right)}{ 2- \left(\tan
   \left(\frac{x}{2}\right)+1\right)^2}$$
The first integral is obvious and the second is simple.
Answer: In general, with the substitution $t=\sin x+\cos x$
\begin{align}
&\int\frac{1}{\cos^{2n+1}x-\sin^{2n+1}x}\ dx\\
=& \ \frac{2^n}{1+2n}\int \bigg( \frac{1}{2-t^2}+2\sum_{k=1}^n(-1)^{k}\frac{\cos a_k \cos^{n-1}2a_k}{\sec 2a_k+1-t^2} \bigg)dt\\
\end{align} with $a_k=\frac{\pi k}{2n+1}$.


Restrict content access by term reference in profile

Question: What I would like to accomplish is to have the following.  Please let me know if anyone is aware of modules that can accomplish this already or what direction I should take developmentally to accomplish this.  Thanks.
Nodes
All nodes are tagged with terms from a particular vocab through the use of a taxonomy reference field.  The nodes are only accessible to specific users that have permissions to view the tagged terms.
Taxonomy
I have one vocab that I am working with for all of this control and it is enabled for all content.
Users
All users are tagged with terms from a particular vocab through the use of a taxonomy reference field added to their profiles.  This field should only be editable by a certain administrative roles.  Additionally, the user will only be able to access content on the site that is tagged with the terms set in this field.
Answer: Turns out I went with Access by Terms module after finding that the Term Access module did not work for me.  Access by Terms also has permissions the make the field editable by certain roles in the profile and nodes, so that takes care of administration requirements too.
Answer: As per your requirement you can use Term Access module or its related modules.
From module's project page:

... controls node access based on taxonomy term fields. When the nodes taxonomy terms and the user taxonomy terms match, the user is awarded certain permissions.
Comment: This does deal with the issues surrounding user access to matching nodes.  It does however not cover dealing with the field level permissions that would be needed to keep users from editing the field on their profiles (this should be left to administrators [or really a set of roles]).  However, I have opened issue with the field permissions module to see if they will add field level permissions per entity.  If they don't I will code a custom module to handle the field level permissions per entity.  Awarding to you since the answer takes care of most of the difficulty.  Thanks!
Comment: Actually after testing that module I found that it "simply does nothing" after configuration.  I assume there is something busted in code as this is a pretty default install.  I switched to http://drupal.org/project/abt and everything seems to be working.  ABT seems to differ as described here: http://drupal.org/node/1498354 and it works.


FCrDNS With Separate Host and Mail Server

Question: I have an "A" record on my DNS which points to an IP, specifically the IP my website is hosted on. I use a separate IP for my email server. This causes my emails to fail the Forward Confirmed Reverse DNS test because of the following:

My email server IP is looked up. It points to my domain name.
My domain name is looked up. It points to the IP in my "A" record,
which is different from my email server IP.
The test fails.

Is there any way to pass this test while retaining independence of host and email server? Can I have two "A" records?
Comment: Why don't you just fix the incorrect PTR record?
Comment: @MichaelHampton Could you please advise me on how to do that a bit more?
Answer: The reverse DNS PTR record for the IP address of the mail server is expected to point to the canonical hostname of this host (or whatever is applicable if the host has multiple addresses).
It sounds in the question that this PTR record simply points to the wrong name.
Eg, if your mail server hostname is zeus.example.com the PTR is expected to point to zeus.example.com. Which domain names it handles mail for is not really a factor (eg it could be handling mail for example.com and foo.example).
Comment: @JohnRoberts That sounds like unorthodox naming to begin with. If that name resolves to the address of some other host, that just makes it even more problematic.
Comment: My mail server host name is the same as my domain name. Is that what is causing the issue?
Comment: The reason I did it is because I wanted the sender of my emails to be "email@example.com" instead of "email@example.com". Is that not possible if my email server IP is different from my website hosting IP?
Comment: @JohnRoberts As I noted in my answer, the hostname of the mail server and the domain names it handles mail for have no actual relation.
Comment: So the only way for me to pass FCrDNS would be to change my email server host name to something like zeus.example.com instead of example.com?
Comment: @JohnRoberts The way to have a forward-confirmed reverse dns entry is to have the reverse dns `PTR` record point to a name which resolves back to that same IP address.  For consistency it sounds like you would want to change the configured hostname to match this same name.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31917/discussion-between-john-roberts-and-hakan-lindqvist).
Answer: You should use the MX option instead of the A RR. The MX (Mail Exchanger) is the name of the server which is responsible of the mails for your domain. When a mail server want to send you an email, it use first the MX record, then the A record if no MX is found.
You can define the PTR record accoringly
Comment: I specifically want my emails to pass the FCrDNS test. Will modifying the MX record help with that?
Comment: Yes, modifying the MX record is what you need to do.
Answer: For FCrDNS you need

dig +short mx example.com -> must result in the name of your mail server
dig +short a [the mail server name from line 1] -> must result in an IP
host [the IP from line 2] ->  must result in the same name as line 1.

If I understand correctly, you have one IP for your web server and one IP for your mail server. Is the mail server dedicated to you, or do you share it? If it is your server, do you control its rDNS? If yes, the normal setup would be
example.com IN A [webserver IP]
www.example.com IN A [webserver IP]
mail.example.com IN A [mailserver IP]
example.com IN MX mail.example.com.

If you do not control the rDNS of your mail server, then it probably already has a name like mail.yourisp.com. In this case do not use mail.example.com but
example.com IN MX mail.yourisp.com

Comment: What if I already have other MX records (I send email from Zoho as well, and this is where I want to receive all my mail. The email server is meant to be send only). Is it possible to add another MX record in this case? Can I send email from multiple servers?
Comment: MX indicates the server everyone on the Internet should use to send a mail to your domain. It MUST run an MTA server program such as postfix, exim, sendmail, Exchange, it MUST be configured for your domain, and if you have several then they must work very closely together. The mail servers that you use for SENDING your mails from do not have to be related, or even in your domain. There is an anti-spam setting called SPF that can list all the mail server IPs that are allowed to send mail from your domain, but otherwise it's not important. You really need to provide more information!
Comment: So as far as my mail server is concerned, I don't want to receive any email on it. I just want to be able to use it for sending. I wouldn't use MX then, right?


User register and login test

Question: I am trying to register and log in users via the Services module 7.0-3.11 on Drupal 7.36.
The endpoints are declared from the following code.
$endpoint = new stdClass();
$endpoint->disabled = FALSE; /* Edit this to true to make a default endpoint disabled initially */
$endpoint->api_version = 3;
$endpoint->name = 'user_service';
$endpoint->server = 'rest_server';
$endpoint->path = 'user_api';
$endpoint->authentication = array(
  'services' => 'services',
);
$endpoint->server_settings = array(
  'formatters' => array(
    'json' => TRUE,
    'bencode' => FALSE,
    'jsonp' => FALSE,
    'php' => FALSE,
    'xml' => FALSE,
  ),
  'parsers' => array(
    'application/json' => TRUE,
    'application/vnd.php.serialized' => FALSE,
    'application/x-www-form-urlencoded' => FALSE,
    'application/xml' => FALSE,
    'multipart/form-data' => FALSE,
    'text/xml' => FALSE,
  ),
);
$endpoint->resources = array(
  'user' => array(
    'operations' => array(
      'retrieve' => array(
        'enabled' => '1',
      ),
      'index' => array(
        'enabled' => '1',
      ),
    ),
    'actions' => array(
      'login' => array(
        'enabled' => '1',
      ),
      'logout' => array(
        'enabled' => '1',
      ),
      'token' => array(
        'enabled' => '1',
      ),
      'request_new_password' => array(
        'enabled' => '1',
      ),
      'register' => array(
        'enabled' => '1',
      ),
    ),
    'targeted_actions' => array(
      'password_reset' => array(
        'enabled' => '1',
      ),
    ),
  ),
);
$endpoint->debug = 1;

I am using basic PHP code for the testing purpose. Please have a look at the GIST.
The problem is that, while I run the test page, I can see it registers a new user and outputs the following.
stdClass Object
(
    [uid] => 14
    [uri] => http://vote-app.dd:8083/user_api/user/14
)

But while I try to log in with the same user (as per the code) it outputs the following error.

Error
  ["Wrong username or password."]

I need some help on this. Am I missing something?
I also checked https://www.drupal.org/node/1491754 and other Drupal pages for this too.
Answer: Found the solution. Just for future references for others and me as well :-)
There is an issue in Services module Wrong username and password, just after a creation of a user where someone faced the same problem. User login just registration. So as it stated,

If you are anonymous user and register a user your register form does not have password field at all. It has only username and email fields. All instructions are sent by email (with token to log in and set the password). So register call actually does not set the password.

This is actually true. If I go to the admin and change the password again then it's working. So the solution is to alter two variables,
variable_set('user_email_verification', FALSE);
variable_set('user_register', TRUE);

This will now allow the users to register by themselves.

User register and login test


Can music time signatures really be irrational?

Question: In  this video around the 5 minute mark, the presenter mentions that "irrational units of time cannot exist because of Planck's constant", and therefore music time signatures like 2:√2 cannot be perfectly performed in the real world (he used Conlan Nancarrow's Study 32 as an example).
Does this mean that the "units of time" are in a way discrete, i.e. there is a smallest unit of time and all others will be multiples of it, similar to the natural numbers and the unit 1? And does this imply that, whenever a music piece with an irrational time signature is performed by electronic means or a player piano, what is really happening is just a very good rational approximation of the signature? i.e. if the signature was π:1 (Pi:1), then it would really be something like 3927:1250? Am I understanding this all wrong?
Comment: The statement "irrational units of time cannot exist because of Planck's constant" is incorrect; it _assumes_ that space and time are discrete. It is still an open question in Physics whether space-time can be quantized.
Comment: Technology doesn't play music. People do. And analog music technology with continuous time bases is still widely available and widely used.
Comment: @topomorto One person's preference: I *never* want a computer over a human when it comes to music. Unless you mean an analog computer like a step sequencer or LFO or gate source, etc. I suppose a minimoog model D is kinda like an analog computer.
Comment: @BogdanSimeonov 'philosophically' I think that's true, but I would guess that the variation in the speed of sound in different temperatures and densities of air, and variations in the speed of firing of neurons in our brains, would cause bigger timing inaccuracies than any current technological limitations.
Comment: @Todd Wilcox, technology certainly plays music. I know people who've written LSTMs using Deep Learning that write Bach Chorales. Not great ones so far, but pretty good all things considered. I know this is anathema to many (myself included, really, but for reasons of anxiety about these technologies that go far beyond music), but it happens, and genies generally don't go back in bottles.
Comment: Possible duplicate of [(1/√π)/√⅔ as a time signature?](https://music.stackexchange.com/questions/16376/1-%e2%88%9a%cf%80-%e2%88%9a%e2%85%94-as-a-time-signature)
Comment: @prooffreader - the quote 'genies generally don't go back in bottles' is priceless! Excellent, made my day! Off topic, but hey ho.
Comment: Best not to learn about music from random people on YouTube :)
Comment: @DavidBowling very interesting. Still, computers do work only in approximations, right? I realise that a very good approximation won't really make a difference, though.
Comment: @BogdanSimeonov the fact that computers (usually) work in approximations is a different concept (and limitation) to the idea of the Planck time.
Comment: @topomorto I was just thinking that if space-time was indeed continuous, we still wouldn't have the technology needed to truly play in a "irrational"  time signature.Is this true?
Comment: @ToddWilcox if we're purely talking *precision*, you want a computer on a discrete time base over a human on a continuous time base any day of the week!
Comment: @David Bowling, I think people are confusing Planck time as an assertion that time is quantized, whereas if my understanding is correct, it just can't be _proven_ that time _isn't_ quantized, which is of course not the same thing.
Comment: @ToddWilcox If I understand correctly we're only talking measurable timing *precision* here, nothing to do with artistic preference, or whether (or in what cases) spot-on  timing actually sounds better. It's true that not *all* computer tech is more precise timing-wise in all cases than all human players, but almost all modern sequencers will be.
Answer: This is so over-hyped as to be irrelevant for any practical purposes. The wavelength of the highest pitch sound that humans can hear is about 16mm. That is about 1,000,000,000,000,000,000,000,000,000,000,000,000 times longer than the Planck wavelength, i.e. the distance light travels travels in one Planck unit of time.
Even taking into account the approximations made by current computer systems (for example, representing numbers approximately to "only" about 16 digits of precision) the accumulating timing errors would be barely perceptible in a piece of music with a duration of a million years.
In fact the commonest use of "irrational time signatures" in music theory are not mathematically irrational numbers at all - they are simply fractions with denominators which are not powers of two, for example 4/3 (which means the length of a bar is a quarter note - 3/3 - plus one note from a triplet of 8th-notes.)
Comment: "*the approximations made by current computer systems (for example, representing numbers approximately to "only" about 16 digits of precision) *" That's not true. Floats are not the only way of representing and using numbers in computers. There are many systems that can use arbitrary large precision, depending on the needs of the programmer.
Comment: _4/3 (which means the length of a bar is a quarter note - 3/3 - plus one note from a triplet of 8th-notes.)_  Uh... shouldn't that be a whole note, plus one note from a triplet of half-notes?
Comment: @ypercubeᵀᴹ Software isn't the bottleneck, and the sample precision / bit width does not matter. Only the final sample rate matters. Realistically, this is where the final bound on time quantization is. There's 384kHz sound cards on the market but virtually nobody would have one, not even in a studio. Even if you built your own, and assumed infinite bandwidth, the fastest DAC you could buy would still have settling times well above the Planck period. And, of course, the whole general topic is still irrelevant pedantry, only academically interesting at best. :)
Answer: He's just showing off.
There's a few major reasons why what he describes doesn't matter.  First and foremost, sheet music is a guide.  It's not actually the music.  You are always expected to put your own experience into the notes before they get called music.  Thus, you would never want to play an exact transcription of the black toner on the page.  It wouldn't be music.
Beyond that, let's pretend you want to play such a piece.  You in theory cannot, because you cannot properly play the irrational ratios.  But can you play any song?  It turns out that, by that standard, you can't.  Let's say you want to play a quarter note at 100BPM.  Let's say you want to play an A.  100BPM is 0.6 seconds per quarter note.  The frequency of A is 440Hz, so you'd have 264 oscillations in that quarter note.  Now let's play a B after that.  B is 493.88...Hz.  Uh o.  Now I need 296.328... oscillations.  But if I stop right there, I'm not actually at the end of a cycle.  I have to use a "windowing function" to stop the note when it's amplitude is not 0.  This causes an infinite series of harmonics to be unleashed.  It's no longer a pure B.
So if I try to hold myself to the standards put forth in this video, I can play a quarter note A at 100BPM, but I cannot play a quarter note of B.  The standards set are simply too high to permit a B to be played.
So go out there and play real music, using the sheet music as a guide.  Plank's Constant, Avagadro's Number, and all the other useful numbers in science will be there to back you up.
Answer: I'll give this another spin:

Can music time signatures really be rational?

Which I'd answer: no, not really. Rationality is a mathematical concept, depending on an exact, axiomatic notion of numbers. Now, sure, any ordinary piece of music will use a rational signature given by integer numbers on paper, or in the DAW you use. Time is conceptually divided in a rational way in these compositions.
But is the conceptual level really what the music is? I wouldn't be sure. To the listener, music is first just fluctuations in the air pressure field. Our brains do a remarkable job of disassembling that mess again... they will notice that there are certain individual voices. They will perceive that these voices are somehow synchronised, that there are some scales of repetition etc.. If they know something about music they'll usually also be able to guess from that again what the numbers on the sheet were that the composer wrote.But this is not quite an objective, reproducable process. Upon close investigation, you will find out that any human performance has slight tempo etc. fluctuations intrinsic in it. And, which may be more surprising, even a purely electronic, "exact" sequenced piece, when analysed from the audio mix, will seem to have such fluctuations, on a much smaller scale. The reason is actually mathematically akin to the quantum-mechanical Heisenberg uncertainty relation†: whenever you pack information into any sort of waves (be it electromagnetic radio waves or acoustic sound waves), you must make a tradeoff of frequency accuracy vs time accuracy. In exact terminology, transients in signal that has a frequency-bandwidth fU can have a time-accuracy of at most ≈ 1⁄fU.
Human hearing has a bandwidth of <20 kHz. Signals in that range have in principle a time certainty of at most 50 μs. In fact, humans can determine signal time only to about 3 ms... but whatever the exact numbers, there is in principle a limit to the precision. Therefore, it can never be possible to objectively distinguish a piece in 4⁄4 time from one in 4.00000001⁄4, or in fact from the irrational cosh(2.0634371)⁄4.
So why can we still be sure a given piece is in 4⁄4 time, and not in cosh(2.0634371)⁄4? Occam's razor. The simplest possible model that fits – within the available accuracy – the observed data, is the one that brings us closest to understanding what's going on.
Now there's an interesting detail: what do I mean by "the simplest possible model"? Simplicity can't really be defined, it is different for every human what seems simple and what seems complicated. In information theory, there exists a thing called Kolmogorov complexity. It's a tricky quantity, in fact it can't be computed – but it's still well-defined and can be decently approximated by the shortest program someone will send in to a given challenge on CodeGolf.StackExchange.
For example, 4⁄4 has a complexity of at most three characters or 24 bits, whereas the number 2.0634371 alone has a complexity of at least 30 bits.
But there are examples that are less clear-cut. In particular, there are some irrational numbers whose complexity we should consider rather low. The number π has a complexity of, like, one character, whereas the rational 3.1416 has already more than 16 bits complexity.
Therefore I would argue that a piece in π⁄4 should be considered to be in π⁄4 time, not in 3927⁄5000.

Can music time signatures really be irrational?

Yes they can, in every sense that the concept of time signatures can make sense at all.

†These uncertainty-effects actually have little to do with quantum fluctuations, physically – they're just mathematically analogous, but the physics is only classical mechanics.Theoretically speaking, quantum mechanics does put an even more fundamental bound on how exactly we can measure time: time-uncertainty times energy-uncertainly must be larger than the Planck constant. (This can be seen as the reason why particle-physics experiments need to put in such enormous energies: some of the particles they're studying there have extremely short life-times, which can only be resolved by allowing for enormous energy-fluctuations.)Applied to music, there is an energy-uncertainty of at least the average thermal energy that particles have at body temperature: Δ E ≥ k · Δ T = k · 37°C = k · 310 K ≈ 4.3×10-21 J. If you calculate the time-uncertainty from that, you get 1.5×10-13 s. Now, that's a time scale we can actually resolve with high-tech equipment (e.g. femtosecond lasers), way longer than the Planck time. But it's still many orders of magnitude smaller than the time-uncertainty due to classical effects, which I discussed above.
Comment: Referring to time and frequency is a nice way to understand the mathematical part of the Heisenberg uncertainty relation, but I don't think it does any good to refer to quantum mechanics here. Anyone who knows what it's about knows it already, anyone who doesn't know quantum mechanics will get an unhelpful explanation of it, and anyone who has a misconception of quantum mechanics will just misunderstand something.
Answer:
Can music time signatures really be irrational?

One thing that is worth noting is that the term irrational time signature uses 'irrational' in a different sense to the normal mathematical meaning. https://en.wikipedia.org/wiki/Time_signature#Irrational_meters.
Another thing is that I don't think there would be a commonly-understood way of notating music using standard notation in a time signature that was irrational in the normal, mathematical sense. I could be wrong there, but for the rest of my answer I'll talk about irrational ratios of time 'in general'.

"irrational units of time cannot exist because of Planck's constant"

They can exist 'conceptually', and be represented in numbers. It may not be possible to make something actually happen for that length of time - I'll let the physicists argue about that one!

.... therefore music time signatures like 2:sqrt2 cannot be perfectly performed in the real world

I think this statement is misleading for two reasons.
Firstly, Even if our timing resolution were limited by the Planck time, then we could still play pieces perfectly whose event lengths were exact multiples of the Planck time.
Secondly, in our actual real world, timing resolution is limited in all sorts of ways that are not related to the Planck time - so the Planck time wouldn't actually be the limiting factor in many (or any?) real-world situations.

Does this imply that , whenever a music piece with an irrational time signature is performed by electronic means or a player piano, what is really happening is just a very good rational approximation of the signature? i.e. if the signature was pi:1, then it would really be something like 3927:1250 ?

Well, it is true that a digital computer will need to represent an irrational number with a rational approximation. However, this approximation could be as precise as necessary - it could even be much more precise than the resolution of Planck's time!
Comment: @BogdanSimeonov that depends on the musical tempo - you could always define your tempo such that it was. Remember that note values aren't absolute amounts of time.
Comment: Every time the composer writes _rit._, or a performer interprets the music, this argument becomes pretty meaningless.
Comment: i don't know what the exact value of planck time is, but I'm pretty sure sqrt2 would not be an integer multiple of it .
Comment: @BogdanSimeonov ....though you're right, it's only pieces whose event lengths were exact multiples of the Planck time that could be played perfectly, not all pieces.
Comment: @Bogdan Simeonov, It's difficult to get a lot of precision in Planck time for obvious reasons (damn you Heisenberg). but let's call it a quarter note in x/4 at a tempo of 1000000000000000000000000000000000000000000.
Answer: It's wrong.
Planck time is not a "tick" in the universe; events are not aligned on tick boundaries.  Rather, it is a duration that is the smallest that can be measured as being before or after other times.
If you measure the time of some event, there will be uncertainty as to the exact measurement.  The tightest measurement possible (when the conjugate value is completely uncertain) is Planck's time.
So, given a piece of music of finite length, you draw your notes and measures with fuzzy lines having some tolerance to them.  You can then always choose a rational number such that the needed time points where you draw your theoretical lines are always within the tolerances of the measured lines.
Answer: As a practical answer: with completely computerized music (through probably not in traditional DAWs, which try to save you from "bad decisions" like this), you can come up with music that is not technically irrational, but so close to it, the human ear could certainly not tell the difference (e.g. if you wanted pi/4, it could easily give you 3.14159265358979323846264338327950288419716939937510/4). Whether you'd want to do that, I leave to your artistic vision.
Answer: An amusing question.
More relevant than Planck's constant is, as leftaroundabout mentions, Heisenberg's uncertainty principle: you could never measure a piece of music accurately enough to say whether the time signature was irrational.
There is also a mathematical problem.  Even if we move to a dream universe in which space and time are infinitely divisible, exact measurements are possible, and we live forever; we still could never say whether a piece of music was in π / 4 time or just a very close rational approximation to it.
Irrational numbers arise in music elsewhere: intervals.  In a just tempered scale a perfect fifth has a frequency ratio of 1.5.  So, the waveform of a perfect fifth will repeat every 2 wavelengths of the lower note. In a well tempered scale, the interval (in the dream universe that I just mentioned) would have a ratio of 2^(7/12) which is irrational.  So, its waveform will never repeat.  It will start looking very much like the just tempered perfect fifth but gradually the phase of the two notes will shift.  It will never quite repeat but it will come arbitrarily close to doing so.
Topo morto mentions irrational meters which was interesting and new to me.  These are not irrational in the mathematical sense; they just don't have a denominator which is a power of 2 as is usual.  Despite being a mathematician, this terminology does not upset me: I don't feel a need to impose mathematical definitions of terms on to other disciplines.  Anyway, even within mathematics, terms might be defined quite differently in different contexts or from author to author.
Answer: The 'Planck's constant' reference is just thrown in to sound clever, to dazzle us with science.
Experimental composers seem to use non-standard time signatures to indicate tempo relationships - the sort of thing where three quintuplet quavers in the old tempo add up to a double-dotted minim in the new one.  And I'm only slightly exaggerating!
My feeling is the same as when CERN discover yet another fundamental particle - yes, your analysis may come close to explaining the observed facts, but there MUST be a simpler way to describe it!
Answer: Generally, the composer tries to make it easier for the player to understand and play. Time signatures like 3927/1250 would certainly not be used in regular music, due to the fact that

It unnecessarily complicates things
There is no need
It makes it extremely hard or impossible for the player to play (therefore needing an electric music software to play)

Lastly, no matter what the numerator of the time signature is, the denominator must be a power of 2. This is because 1 represents a semibreve, 2 represents a minim, 4 represents a crotchet, 8 represents a quaver, 16 represents a semiquaver, and so on.
Since experimental music chooses sometimes to ignore these rules, they may contain some of these exotic time signatures, but the whole purpose would just to fit in the theme of experimentation. However, they would all use an electronic software. Although irrational units of time (for the extreme experimenters) do not exist because of Plank's constant as mentioned in the video, obviously one experimenter could develop a piece with an approximation of the irrational number.
There is some music with non-integer numerators in time signatures, however they are simple to understand and easy to play.
For example, the time signature (4 1/2)/4 (without parenthesis, of course) dictates measures of four quarter notes then an eigth note. An example of a piece utilizing this is Touch Piece, for piano, by Gardner Read.
Comment: "the denominator [of the time signature] must be a power of 2." That is not correct.  See scores by Adès, Boulez, Cowell, Ferneyhough, etc, etc.
Comment: @ScottWallace It's no more "childish" than claiming that most contemporary visual art could have been done by a five-year-old kid. But feel free to have a closed mind about such things if it makes you feel happy!
Comment: Sure, irrational durations can exist.  But they are useless and an affectation.  You might just as well say that a note must be played "yellow" or "apolitical".  It's childish "conceptual" art.
Comment: @alephzero- I beg to disagree.  Composing with an irrational time signature, which cannot be performed or perceived in any meaningful way, is childish, because it is claiming coolness based on nothing.
Comment: @prooffreader - then the question is: then why would you even want to do that? Seems pretty pointless to bring the irrational number to the denominator, and even having an irrational number in the time signature in the first place!
Comment: @alephzero, I'd just like to point out that when you have a rational number in the numerator and an irrational number in the denominator, the exact same ratio can always be equivalently expressed as a fraction with an irrational number in the numerator and an rational number in the denominator. Some examples: 2/sqrt(2) == 2*sqrt(2)/2; 4 / ln 2 = e^4 / 2.
Comment: @prooffreader: your second example is wrong: 4/ln 2 is nowhere near e^4/2. Of course a/b (with rational a) can always be expressed as c/d (with rational d): take for instance d=1 and c=a/b. But I don't think this is what you meant, and it seems your comment is based on a misconception.
Comment: Yes, my 4/ln 2 comment was clearly a poor example; I'm too lazy to solve this expression, but I suspect ln(2) = 2*arccoth(3) could be useful to change the number so that the rational part is in the numerator.
Comment: @Scott Wallace - I agree, as I mentioned in my answer, it is for the extreme experimental composers - these time signatures unnecessarily complicate things and are definitely not needed.
Comment: @AnselChang, I'm not going to comment on the point of using irrational numbers at all, if that's someone's artistic vision, fine. It just makes more sense to me in most situations to stick with the convention of natural numbers (generally but not necessarily a multiple of 2) in the denominator.
Answer: Interestingly no one thinks about what the two numbers in a time signature mean. The second note tells us which note is 1 beat. The first number tells us, how many beats are in one bar.
Thus the meter 2:4, 2:8 2:16 are all the same. Clearly also 2:3 would be the same meter, and finally even 2:Sqrt(2) is the same meter.
If we want an irrational time signature, the first number must be an irrational number.
Now lets make an example with an irrational time signature.: Sqrt(2):4, with a tempo 60bpm. Thus one bar is Sqrt(2) seconds long - which makes perfect sense.
Btw.: Plancks constant has nothing to with that problem.
Conclusio: There are irrational time signatures.


Prove $\mathbb{Q}(\sqrt3)$ is a field

Question: Prove that $\mathbb{Q}(\sqrt3) = \{a + b\sqrt{3} | a, b \in \mathbb{Q}\}$ is a field assuming addition and multiplication is commutative since $\mathbb{Q} \subset \mathbb{R}$.
In my book, I have a list of field axioms, but I am not so sure on how to prove each one.
Any help is much appreciated, but I would like it if someone could please explain rather than just posting a solution.
Thank you
Comment: The only point that's hard to prove is that every element of $\mathbb{Q}[\sqrt{3}]$ has a multiplicative inverse in $\mathbb{Q}[\sqrt{3}]$.  And even that's not hard, because of a high school trick called rationalizing the denominator.
Comment: The hardest part is showing inverses, which is contained within [this question](https://math.stackexchange.com/q/2155538/9754). A similar question that addresses some definition-understanding issues is [this question](https://math.stackexchange.com/questions/670236/prove-that-mathbb-c-is-a-field). And [this question](https://math.stackexchange.com/questions/162027/prove-that-k-is-a-field) is also essentially related.
Answer: Since:

$\mathbb{Q}[\sqrt3]\subset\mathbb R$;
$0,1\in\mathbb{Q}[\sqrt3]$;
$x,y\in\mathbb{Q}[\sqrt3]\implies x+y\in\mathbb{Q}[\sqrt3]$;
$x,y\in\mathbb{Q}[\sqrt3]\implies x\times y\in\mathbb{Q}[\sqrt3]$,

all that remains to be proved is:

$x\in\mathbb{Q}[\sqrt3]\implies-x\in\mathbb{Q}[\sqrt3]$;
$x\in\mathbb{Q}[\sqrt3]\setminus\{0\}\implies\frac1x\in\mathbb{Q}[\sqrt3]$.

This is easy: $-(a+b\sqrt3)=-a-b\sqrt3$ and$$\frac1{a+b\sqrt3}=\frac{a-b\sqrt3}{a^2-3b^2}.$$
Comment: How can I show 0 and 1 are in the field?
Comment: @Hat By noting that $0=0+0\times\sqrt3$ and that $1=1+0\times\sqrt3$.
Answer: It's easy to see $\Bbb Q[\sqrt 3]$ is closed under addition, for if
$a_1 + b_1\sqrt 3, a_2 + b_2\sqrt 3 \in \Bbb Q[\sqrt 3], \tag 1$
then clearly
$(a_1 + a_2) + (b_1 + b_2)\sqrt 3 \in \Bbb Q[\sqrt 3]; \tag 2$
similarly we have
$(a_1 + b_1\sqrt 3)(a_2 + b_2\sqrt 3) = (a_1 a_2 + 3b_1 b_2) + (a_1b_2 + a_2 b_1)\sqrt 3 \in \Bbb Q[\sqrt 3]; \tag 3$
all the rules about associativity, commutativity, and distributivity are inherited from $\Bbb R$, in which $\Bbb Q[\sqrt 3]$ may be considered to
"live".  Also, if $a + b \sqrt 3 \in \Bbb Q[\sqrt 3]$, $-a - b\sqrt 3 \in \Bbb Q[\sqrt 3]$, and clearly $1 \in \Bbb Q[\sqrt 3]$, so all we really need to do is show that $(a + b\sqrt 3)^{-1} \in \Bbb Q[\sqrt 3]$.  But
$\dfrac{1}{a + b\sqrt 3} = \dfrac{a - b\sqrt 3}{(a - b\sqrt 3)(a + b\sqrt 3)} = \dfrac{a - b\sqrt 3}{a^2 - 3b^2}  = \in \Bbb Q[\sqrt 3], \tag 4$
which works since $a^2 - 3b^2 \ne 0 $ for $a, b \in \Bbb Q$, since $\sqrt 3$ is irrational.
Answer: Hint:
$$
\frac{1}{a+b\sqrt{3}}=\frac{a}{a^2-3 b^2}-\frac{b}{a^2-3 b^2} \sqrt{3}.
$$
Answer: With respect to addition, verifying the axioms is straightforward. (I hope)
You would also have to verify group axioms with respect to multiplication.

Multiplicative identity. Is $1\in Q(\sqrt{3})$ true? (Yes, it is)
Inverses - Consider $a+b\sqrt{3}$, $a,b\in\mathbb Q$. Do there exist $c,d\in\mathbb Q$ such that
$$(a+b\sqrt{3})(c+d\sqrt{3}) = 1? $$
Associativity of multiplication (should be obvious)

One way of showing existence of inverses is as follows:
$$(a+b\sqrt{3})(c+d\sqrt{3}) = (ac +3bd) + (cb+ad)\sqrt{3} = 1 + 0\sqrt{3} $$
We want to find $c,d$ such that
$$ac+3bd = 1\quad\mbox{and}\quad bc + ad = 0 $$
what do you do?

Prove $\mathbb{Q}(\sqrt3)$ is a field


Show that $\exists c\in (0,1)$ such that $e^{f'(c)}=f(c)+1.$

Question:
Question: Let $f:[0,1]\in\mathbb{R}$ be a continuous function satisfying $\int_0^1f(x)dx=0$ and $f(0)f(1)>0$. Assume further that $f'$ is continuous on $(0,1)$. Show that $\exists c\in (0,1)$ such that $$e^{f'(c)}=f(c)+1.$$

My solution: It is given that $f(0)f(1)>0\implies f(0)>0,f(1)>0$ or $f(0)<0, f(1)<0$. Let us assume WLOG, that $f(0)>0,f(1)>0$.
Now since $\int_0^1f(x)dx=0$ and $f(0)>0,f(1)>0$, thus we must have a point $a\in (0,1)$ such that $f(a)<0$. Now since $f$ is continuous on $[0,1]$, therefore by IVT we can conclude that $\exists c_1\in (0,a)$, such that $f(c_1)=0$ and $\exists c_2\in(a,1),$ such that $f(c_2)=0$. From this we can conclude, there exists at least two distinct roots of $f$ in $(0,1)$. Therefore we are sure to have a point $b,0<b<1$ such that $f(x)>0, \forall x\in (0,b)$ and $f(b)=0$. Also we are sure to have a point $a,0<a<e<1$, such that $f(x)<0, \forall x\in(a,e)$ and $f(e)=0$.
Now consider the interval $[0,b]$. We have $f(0)>0$ and $f(b)=0$. Thus by MVT, we can conclude that $\exists c_3\in (0,b)$, such that $$f'(c_3)=\frac{f(b)-f(0)}{b-0}=-\frac{f(0)}{b}<0.$$ Now since $c_3\in (0,b)\implies f(c_3)>0.$
Again consider the interval $[a,e]$. We have $f(a)<0$ and $f(e)=0$. Thus by MVT, we can conclude that $\exists c_4\in (a,e)$, such that $$f'(c_4)=\frac{f(e)-f(a)}{e-a}=-\frac{f(a)}{e-a}>0.$$ Now since $c_4\in (a,e)\implies f(c_4)<0.$
Now let $g(x):=e^{f'(x)}-f(x)-1, \forall x\in(0,1).$ Observe that $g$ is continuous on $(0,1)$.
We have $g(c_3)=e^{f'(c_3)}-f(c_3)-1.$
Now $f'(c_3)<0\implies e^{f'(c_3)}<1$ and $f(c_3)>0\implies f(c_3)+1>1\implies -f(c_3)-1<-1.$
Thus $e^{f'(c_3)}-f(c_3)-1<0\implies g(c_3)<0.$
A similar reasoning shows that $g(c_4)>0$.
Thus by IVT, we can conclude that $\exists c\in(c_3,c_4)\subseteq(0,1)$, such that $g(c)=0\implies e^{f'(c)}=f(c)+1.$
Does this solution works fine? And is there a more better solution?
Comment: Looks fine. You seem to have an impressive supply of questions based on standard theorems of differential calculus. +1
Answer: WLOG, we suppose $f(0)>0,f(1)>0$. Define
$$F(x):=e^{f'(x)}-f(x)-1, \forall x\in(0,1).$$
On the one hand,
$\int_0^1f(x)dx=0$
implies $f$ can attain its Minimum value at some point $x_0\in(0,1)$,
such that $f(x_0)<0,$ and $f'(x_0)=0$(Fermat's lemma).
So
$$F(x_0)=-f(x_0)>0.$$
On the other hand, $f(0)>0,f(x_0)<0$ implies that: the zeros set
$$\{x\mid x\in[0, x_0], f(x) =0\}\ne \emptyset.$$
(by intermediate value theorem)
Thanks  @ Paramanand Singh for pointing out that: the zeros set
$$\{x\mid x\in[0, x_0], f(x) =0\}$$
has  minimum  and maximum element no matter it is finite set and infinite set.(Proof can be found Intermediate value theorem and supremum)
Let $$x_1=\max\{x\mid x\in[0, x_0], f(x) =0\},$$
and obviously $x_1\in(0, x_0)$.
So $f(x_1)=0$ and $f(x)<0$ for $x\in(x_1,x_0)$ .
Consider the derivative $f'(x_1)$, we know that
$$f'(x_1)=\lim_{x\to x_1^+}\frac{f(x)-f(x_1)}{x-x_1}
=\lim_{x\to x_1^+}\frac{f(x)}{x-x_1}\leq 0.$$
If $f'(x_1)=0$, take $c=x_1$, we can get $e^{f'(c)}=f(c)+1$.
If $f'(x_1)<0$, then $F(x_1)=e^{f'(x_1)}-1<0$,
by intermediate value theorem, we can conclude that $\exists\  c\in(x_1,x_0)\subset(0,1)$,
such that
$$F(c)=0\iff e^{f'(c)}=f(c)+1.$$
Comment: Why did you treat the case of infinitely many zeroes separately? If $f$ is continuous on $[a, b] $ with $f(a) f(b) <0$ then the set $A=\{x\mid x\in[a, b], f(x) =0\}$ is non-empty and possesses a least as well as a greatest member. Some proofs of IVT show this without mentioning it explicitly.
Comment: It is possibile there are infinite zeros in $[a,b]$, and the following proof is different when finite zero between infinite zeros! IVT only give the existence of zero, for this question, only existence is not enlugh for the proof! and $\max\{x\mid x\in[a, b], f(x) =0\}$ and $\min\{x\mid x\in[a, b], f(x) =0\}$ may  not exist! @Paramanand Singh
Comment: well the truth is that those max and min always exist. some of the proofs of IVT show the existence of these min and max
Comment: Maybe you are right! If likes you say, the proof is easy and no need to discuss the infinite zers case!!  But in general, the textbook only gives the existence of zero! And can you give me some references??
Comment: there is no need to prove the existence of max and min. rather you can just state that there is a biggest zero $x_1$ in interval $(0,x_0)$. thus your case 1 actually is sufficient. I will give a +1 anyway.
Comment: Thank you for your pointing out existence of   min and max zeros and your  +1!
Answer: If such $c$ doesn't exist, either always $e^{f'}>f+1$ or always $e^{f'}<f+1$. Whenever $f=0$, the former means $f'>0$ always and the latter means $f'<0$ always. However $f$ must change sign at least twice, and this is impossible.
Comment: Why $f$  changes sign at least twice  is impossible? Give you an example $f(x)=\cos(2\pi x),x\in[0,1],$ this function changes sign twice!!
Comment: @Riemann: $f$ has same signs at $0,1$ and integral of $f$ is $0$ so it has a sign different from $f(0)$ somewhere in $(0,1)$. Thus $f$ changes sign at least twice. If $a, b$ are first and last zero of $f$ then $f'$ has same sign at $a, b$ and this is not possible.
Comment: Nice and short proof. +1 I hope my understanding (mentioned in previous comment of mine) of your proof is correct.
Comment: Thank you for your nice comment @Paramanand Singh
Comment: @ParamanandSingh That's right. If $f'$ maintains the same sign everytime $f=0$, then $f$ cannot change sign twice.


Why is the mid-afternoon break in a Test Match called the "tea break"?

Question: Since when the break between the second and third session of any day of a test match started getting referred to "tea break"?
Although the term is like it has become part of the cricket rule book, it could have been referred to "drinks break" or "coffee break" but who decided it to be referred to as what we know today.
Answer: Since forever, effectively.
The important point here is that you have the wrong meaning of tea - it is not about the drink, but the meal, and in particular "afternoon tea", a light meal taken between lunch and the evening meal. Afternoon tea became established in England in the late 19th century, approximately concurrently with the first Test Match in 1877; as such it was natural to call the mid-afternoon break in the matches a "tea break".


google maps for iphone with PhoneGap

Question: I have an app built in HTML5 + PhoneGap,
in the application has a map of the Google-maps,
on an Android The application works fine,
I moved it to the iphone it also runs but it hangs when it should deal with google maps.
My link to the google map looks like this:

Do I need another link?
Comment: Did you add `maps.googleapis.com` to the whitelist, along with any other servers accessed as a result?
Comment: Where there is a white list? Where to add? I'm new in iphone ..
Answer: Add maps.googleapis.com to ExternalHosts in Cordova.plist. This is a whitelist of servers that the app is allowed to access.
Check the debugging log for whitelist violation errors if the problem persists, and add any other servers as necessary.
Comment: @HodayaShalom No, just `maps.googleapis.com`. Only that. Um, I used XCode's plist editor which takes care of XML… the whitelist is an array of strings.

google maps for iphone with PhoneGap


Hypotesis test to multi categorical data

Question: I want to verify if the difference in a temperature between three groups: smokers, no smokers and ex smokers. What is the most appropriate test?
(data is non-normal)
Comment: What about some good old ANOVA? ANOVA can be fairly robust for moderate violation of normality.
Comment: @QmmmmLiu: A possibility, of course (+), but OP _explicitly stated_ data non-normal. And I have no way to judge whether to trust ANOVA for the data that matter. // For my fake shifted-gamma data, `oneway.test` gave about the same P-values as K-W; t.test for Gp2 vs. Gp 3 has larger P-value than Wilcoxon signed rank, but still significant.
Comment: @BruceET Yes. I wonder if there's any sensitivity analyses of sorts that can help determine if the extent of normality violation warrant the use of nonparametric tests. I roughly remember that normality violation would render inflated type I error for ANOVA. But I thought that nonparametric test can have low power. So I was wondering if there's some sort of pre-analysis one can do to help decide between the two.
Comment: To OP, what do the data look like per each category? Do they look like they'd share the same distribution?
Comment: @QmmmmLiu. I look for outliers and aggressive skewness, but I know of nothing more systematic or reliable than that--before the fact. If trying ANOVA, I Iook at residuals from ANOVA model, then junk the ANOVA if I don't like what I see. Not sure whether to call this is a recommendation or a confession. // You seem to want to avoid K-W, a phobia I do not share.
Comment: @BruceET thanks. That helps a lot. I also found an article with simulation studies that seems to suggest K-W can be overall advantageous in this situation too. https://onlinelibrary.wiley.com/doi/full/10.1111/j.2044-8317.2012.02047.x
Answer: You have three levels in the categorical variable about smoking (Current, Never, Former) and obtain (presumably nonnormal) data for $r$ subjects at each level. I'd use a Kruskal-Wallis test to see if the medians differ among levels.
Fake shifted-gamma data and boxplots:
set.seed(718)
x1 = rgamma(10, 5, 1/5);  x2 = 2+rgamma(10, 5, 1/5);  x3 = 15+rgamma(10, 5, 1/5)
x = c(x1, x2, x3);  g = as.factor(rep(1:3, each=10))
median(x1); median(x2); median(x3)
[1] 20.92121
[1] 28.15298
[1] 36.45878

boxplot(x ~ g, col="skyblue2", pch=20)

The 'notches' in the sides of the boxes are approximate nonparametric confidence
intervals for individual group population medians.
Test of significance:
A Kruskal-Wallis test finds significant differences among medians at significance
level $\alpha = 0.005.$
kruskal.test(x ~ g)

    Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 11.507, df = 2, p-value = 0.003172

Paired comparisons. One method to check for differences between pairs of groups (levels) would be to
use the 'notches' in the boxplots, which are calibrated for pairwise comparisons (overlapping notches indicate no significance). A more formal method would be to use two-sample Wilcoxon (rank sum) tests. The difference between Groups 1 and 2 is not
significant an any reasonable level because of the P-value $0.22 > 0.05:$
wilcox.test(x1, x2)

    Wilcoxon rank sum test

data:  x1 and x2
W = 33, p-value = 0.2176
alternative hypothesis: true location shift is not equal to 0

But the difference between Groups 2 and 3 is highly significant with P-value 0.002 (computation not shown). In this particular instance, paired comparisons
from boxplot notches and from Wilcoxon tests agree.


Joint probability distribution question

Question: A regular tetrahedron has four faces of different colours: blue, red, green and yellow. The
tetrahedron is repeatedly rolled. In each roll the four faces are equally likely to occur.
Let the random variable G denote the roll in which the green face occurs for the first time, and
let the random variable Y denote the roll in which the yellow face occurs for the first time.
Compute P(Y > n) and P(Y > n, G > n).
I obtained Y~ Geometric(1/4) and P(Y>n)=(3/4)^n, which makes perfect sense so far. However, the solution for P(Y > n, G > n)= (1/2)^n which doesn't make sense to me.
I had two guesses: P(Y>n, G>n)=P(Y>n)*P(G>n) [by independence] and so is equal to (3/4)^(2n)
Second guess was: P(Y>n, G>n)=P(Y>n)*P(G>n|Y>n)=P(Y>n)*P(G>n intersection Y>n)/P(Y>n)= P(G>n intersection Y>n) = P(Y>n, G>n)=P(Y>n)*P(G>n) [by independence]
Any help would be greatly appreciated.
Comment: "*By independence*"  Why would you think that the event that $Y>n$ is independent of the event that $G>n$?  It should be obvious that it is not, since if we were to continue further, $P(Y>n,G>n,B>n,R>n)$ is very obviously zero, not $P(Y>n)\times P(G>n)\times P(B>n)\times P(R>n)$ which is nonzero.  Obviously... at least one of the colors had to have been rolled on the first roll.
Answer: If you need more than $n$ rolls to see the first yellow, and you need more than $n$ rolls to see the first green, then what do you know about the colors for rolls 1 through $n$?
Comment: @jeff123 $P(Y>n,G>n)=P(Y>n)\cdot P(G>n\mid Y>n) = \left(\frac{3}{4}\right)^n\cdot \left(\frac{2}{3}\right)^n=\left(\frac{2}{4}\right)^n$ where the conditional probability was calculated directly by imagining that since no yellow was rolled in the first $n$, that the die "*effectively had only three equally likely sides during this time instead of four*", one of which was green.
Comment: Thinking about it this way makes sense. Since the first n rolls were not yellow and were not green, they must have been a sequence of blues and reds. The probability of getting either a blue or a red in a single roll is 2/4=1/2, and we shall have n rolls of having either blue or red, and so (1/2)^n.
Comment: However, is there a way to obtain (1/2)^n from P(Y > n, G > n)?
Comment: I think JMoravitz has given the correct answer. Notice also that the second guess in your original question was essentially a repeat of your first guess, except that you made a detour in the middle.
Comment: Thank you!! Can't believe I complicated it so much

Joint probability distribution question


asp.net mvc authentication cookie issue

Question: I'm trying to implement a "remember me" feature using ASP.NET MVC. It uses a customized authentication process as defined below.
Web.config:
    <authentication mode="Forms">
        <forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
    </authentication>

Code to persist cookie:
public void SignIn(string userName, bool createPersistentCookie) {
    int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);

    HttpContext.Current.Response.Cookies.Add(cookie);
    FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}

Code to retrieve cookie:
        if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
            cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        }

The current code checks for Session for authentication. I'd like to add the ability to get the userName from cookie as well. I have 2 questions:

What do I need to do in order to retrieve the cookie?
How do I decrypt the cookie to obtain the userName?
Answer: To get the cookie:
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

Decrypt it with:
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData

Comment: Thanks, that works great. I also realized that I needed to remove the code FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

asp.net mvc authentication cookie issue


LDAP module + Windows AD

Question: I have a large AD setup which has not been configured in the ideal fashion, the base DN:
dc=davinci,dc=mydomain,dc=local

Now the existing structure of our AD looks something like:
@ 1122 Logan
  Accounting
  Aquarius
    Alejandro
    Mike
    Justin
  Aerospace
  Distribution
  Engineering
@ 2150 Logan
  Uniflyte
@ 1480 Church

Trying to test the authentication of the user Alejandro (old network guy was being funny when he gave me a user name).
Here is my Server Property Dump:
Server Properties:
sid = Davinci
numeric_sid = 1
name = Employees
status = 1
ldap_type = ad
address = davinci
port = 389
tls = 0
followrefs = 0
bind_method = 2
basedn = Array ( [0] => dc=davinci,dc=cadorath,dc=local )
binddn =
user_dn_expression = cn=%username,%basedn
user_attr = samaccountname
account_name_attr =
mail_attr =
mail_template =
picture_attr =
unique_persistent_attr =
unique_persistent_attr_binary = 0
ldap_to_drupal_user =
testing_drupal_username = Alejandro
testing_drupal_user_dn = cn=Alejandro,ou=@ 1122 Logan,dc=davinci,dc=mydomain,dc=local
grp_unused = 0
grp_object_cat =
grp_nested = 0
grp_user_memb_attr_exists = 0
grp_user_memb_attr =
grp_memb_attr =
grp_memb_attr_match_user_attr =
grp_derive_from_dn = 0
grp_derive_from_dn_attr =
grp_test_grp_dn =
grp_test_grp_dn_writeable =
search_pagination = 0
search_page_size = 1000

I enter in my password for non-anonymous search (Windows login password)...
Testing Drupal DN:

cn=Alejandro,ou=@ 1122 Logan,dc=davinci-1,dc=cadorath,dc=local

Drupal logs report:
LDAP bind failure for user userdn=, pass=XXX.

Where does the userdn get constructed???
I still cannot login to drupal with Windows login details...D7 is running in the same domain as Davinci so I assume I missing something in the syntax of connection string???
Comment: Which version of the ldap module are you using?  This is working for me similar to the answer from tenken.
Answer: The ldap config page for users and fields has a user_dn entry you can set.
Comment: I visit: admin/config/people/accounts/fields and see an "ldap_user_current_dn" field but its hidden and locked for modification? How does this supposed to work?
Comment: hmmm, on my setup(s) its usually not inactive. It lets you set the DN needed for some LDAP configurations. On a Windows LDAP box (I never got to fully work), I was using the following based on sysadmins request `firstname.lastname@example.com,%basedn`

LDAP module + Windows AD


GitLab Backups Auto Cleanup

Question: I have scheduled GitLab backups through crontab which backs up gitLab data everyday at 2 AM.
The problem I have is cleaning up of backup files automatically. Backups files have now been piling up and I want to automate this task.
Uncommenting the following lines in 'gitlab.rb' doesn't help.
gitlab_rails['backup_keep_time'] = 604800
For your info, my GitLab has been installed with omnibus package on CentOS 7.
Answer: After editing gitlab.rb, you need to run gitlab-ctl reconfigure to make your changes take effect.
Comment: Thanks mate, I really appreciate that. New to Gilab and Linux environment so going through lot of troubles.
Comment: I now have another issue,  'gitlab-ctl reconfigure' fails with following message: Recipe Compile Error in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/default.rb
 NameError
  ---------
  uninitialized constant Module::SSLCertificateFile

  Cookbook Trace:
  ---------------
    /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/default.rb:35:in `from_file'
Comment: Sounds like a problem in your config file. You could try to run it with an empty file (or everything commented out).
Comment: When you say config file, do you mean gitlab.rb?
Comment: Yes, that is the one.

GitLab Backups Auto Cleanup


Upgrading certificate template schema

Question: I need to update one of my Active Directory Certificate Services (ADCS) certificate templates from schema v2 to v3, to support KSP providers. It seems that I can only do this by cloning the template (only then I get an option to select KSP).
Is it possible to do it in situ? If so, how?
Answer: You have to duplicate existing certificate template and configure as per your needs. This is the only supported way to get V2/V3/V4 template schema version.
Comment: Thanks, that's what I suspected - just didn't have any confirmation. As a side question, do you have any documentation about configuring templates via XML?
Comment: No. Microsoft does not support certificate template modification outside of Certificate Templates MMC snap-in. I had a support case with them and was told this.

Upgrading certificate template schema


Swift: How to move button position that added in Storyboard

Question: I have added one button into one UIViewController in storyboard. Now I just want to try how can I move the origin x and y of that button from code so I write this code below
<code>    @IBOutlet weak var testBtn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    testBtn.frame = CGRectMake(0, 0, 200, 10)

}
</code>
but The button not move. Do you know why?
Comment: It's probably because you're running that code too soon. Try implementing `viewDidAppear:` and put your button-moving code into that.
Comment: @matt I thought the outlets are already connected in `viewDidLoad`, so the example from above should work
Comment: Did you connect your outlets? Do you use AutoLayout?
Comment: @MariusFanu The outlets are connected, but the views are not yet laid out (this happens just before `-viewDidLayoutSubviews`), so @matt is probably right (given that autolayout is enabled)
Comment: @Alladinian that makes sense, I looked the lifecycle of a VC
loadView -> viewDidLoad -> viewWillAppear
-> viewWillLayoutSubviews -> viewDidLayoutSubviews -> viewDidAppear. So those frame are probably overwritten.
Comment: @matt is right, viewDidAppear is what you are searching for I believe.
Answer: You need to place it in viewDidAppear. Even viewWillLoad if not late enough.. Here is a good way to set it with little hassle:
<code>override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    // Put the coordinates you want instead of x: 0, y: 0
    testBtn.center = CGPointMake(0, 0)
}
</code>
Remember that if you override this method, you must call super at some point in your implementation as recommended in the apple documentation. While not obligatory, it should relieve many problems ;)
Comment: It is obligatory _because_ it is an override call. Read carefully. Say the words one at a time. "If you _override_ this method, you _must_ call `super`." That is Apple talking. Obey!
Comment: No need to, it's standard declaration
Comment: Instead, you could simply do an edit on the answer... And you can take the down vote out now, it's rectified :)
Comment: Excellent, thanks for fixing that. Very important to set a good example for beginners.
Comment: It is not obligatory as it is an override call. If you want to eliminate default behaviour from viewDidAppear, you would not call super.viewDidAppear on it now would you..
Comment: while it is not necessary to call super when overriding functions in general, in this particular case documentation explicitly states to call super when overriding viewDidAppear, therefor it is obligatory in the case of this function.  Not calling super could cause your app to miss behave.


DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data()

Question: DrupalTemporaryStreamWrapper::stream_open call failed in file_unmanaged_save_data()
I do not identify the problem. Could anyone help me?
Answer: You can solve this by setting up temporary path i.e.
Goto :

Home » Administration » Configuration » Media and fix temporary
  directory.

or Goto to the path & add temp url :
config/media/file-system


Maintain angle between two 3D vectors after rotation(s)

Question: In a 3D cartesian space, I have two vectors. One vector is a static unmoving vector—let's call it S. The other vector is the vector I need to rotate—let's call it R. Both vectors have their tail as the origin (0,0,0) and their head at an arbitrary position. Let's name the current (original) angle between the two vectors A1.
I am going to perform a rotation that will result in the angle between R and S changing. I will then need to adjust R with a second transformation so that the new angle is equal to the old angle, without changing R's direction on the XY plane. What is the procedure and equations to determine/make this second transformation?
Details:

Rotate R by some arbitrary degree (call it θ) in the XY plane (i.e. rotate round the Z-Axis). The rotation may be clockwise or counter-clockwise.
However, once I rotate R in the XY plane the angle between S and R will, for almost all values of θ, change.
I need to maintain the original angle (A1) between S and R. However I also need to maintain R's newly established direction (i.e. direction post-rotation) along the XY Plane.
What transformation (I presume a series of rotations) do I need to perform, such that the resulting angle (A2) between S and R is equal to the original angle (A1), while maintaining R's direction on the XY plane?
The magnitude (length) of vector R must not change.

Note: I'm not a "math person" but instead someone who needs to write some functioning code to handle this in a program, so please don't presume too much knowledge on my part. Understanding the equations is important. Some terminology may need to be explained. Basically "showing the work" would help me understand.
Thank you!
Answer: Use dot products for angles between vectors and cross-products for oriented angles between vectors. If $\mathbf {u.v}$are column-vectors then $ \mathbf{u^tv=u \bullet v}$ If $A$ is an orthogonal matrix then $(A \mathbf u) \bullet (A\mathbf v)=\mathbf{u \bullet v}$. Rotation matrices in 2- or 3-space (about the origin) are orthogonal matrices with determinant 1. If $A$ is a rotatation matrix, then $(A \mathbf u)\times (A\mathbf v)=A(\mathbf{u \times v})$.
Comment: Thanks for replying. I'm unfamiliar with some of the terminology you're using (column-vector, orthogonal matrix, etc.) so having trouble seeing how to apply your comment. This is going into code eventually, so I'll need to use equations.


Pig - JsonMetadata - Could not find schema file

Question: There has been a major lag time when Pig evaluates LOAD statements on certain versions of pig.
Upon switching versions of Pig (during a cluster upgrade), Pig's Grunt (and via file script as well) took 30+ seconds on each LOAD statement. This was in stark contrast to the usual <1 second needed to process each LOAD statement. Pig's debug showed the LOAD statement was evaluated in about the same manner between different versions, but what differed was especially interesting.
In Version 0.9.2 (w/ Java 8), the LOAD statement was processed in <1 second. However in Version 0.11.1 and 0.12.0, the load statement was processed in 30+ seconds with the main line differing being this one:
[main] DEBUG org.apache.pig.builtin.JsonMetadata - Could not find schema file for /logs/visits/*/*visits_v15*.lzo

That debug message was not displayed until the command finished being processed which leads me to suspect the loading of the schema data is what's hanging up the entire process. The LOAD statement completes in <1 second on 0.11.1 and 0.12.0 when I specify an exact file, but still shows the warning:
[main] DEBUG org.apache.pig.builtin.JsonMetadata - Could not find schema file for /logs/visits/2014-08-01/2014-08-01-23-45-07.PDT.visits_v15.server.log.lzo

Example Pig Script:
SET debug 'on';
REGISTER s3://path/to/elephant-bird.jar;
v15_data = LOAD '/logs/visits/2014-08-01/2014-08-01-23-45-07.PDT.visits_v15.server.log.lzo';

It doesn't matter if I use Elephant Bird or not as the same debug message comes up and the performance characteristics are the same.
There are ~60 columns in each file and there are thousands of files written per day. Oddly, running the same style script above with just a "DUMP v15_data;" often gives a failed job with this style of error:
java.io.IOException: Deserialization error: invalid stream header:

Pig Versions tested:
0.11.1
0.12.0
0.13.0 - I believe I tested this one previously, but not as thoroughly as 0.11.1 or 0.12.0
Answer: After struggling with this issue for a while, I found a solution was to use the "-noschema" flag. So USING PigStorage('-noschema')


Dynamic programming efficient network

Question: Hello I have a dynamic programming  related question. How can I compute the shortest path in hops from starting vertex u to ending vertex v, with the constrain that the vertices and edges will have an equal or higher predefined value. For example the highest rate of data in a network,
i.e. the vertices A,B,C,D and E with values unlimited,6,2,5 and unlimited respectively, also the edges A->B, A->C, B->D, C->D and D->E with values 4,3,5,8 and 10 respectively. In this case the most efficient path from A to E would be A->B, B->D, D->E.
Could someone provide some pseudo-code or any thoughts, thank you in advance.
My main concern because is not like an implementation issue. So what I am thinking: Find the longest path in DAG with Dijkstra's, and some tweaks (multiply the weights of the edges with -1, finding shortest path and then multiplying again with -1 for longest), however I should fit in the values of the vertices to.
Comment: I didn't understand your problem statement. Can you make the first paragraph in your question more formal? Also Dijkstra's Algorithm wouldn't directly work for negative weights, you should use Bellman-Ford algorithm.
Comment: @ChaitanyaChavali I tried to clarify the first part of my question by providing an example.  Also I don't necessarily have negative weights in the graph, I wanted to do the conversion so I could compute the longest path. But not sure about that since I need the path with least hops (least routers), but with the most weighted ( most bandwidth)
Comment: Make your objective function and constraints clearer. From what I could grasp, you want the path with the least number of hops as your first priority(3 hops in your example) and then if there is a tie, you break it by using the condition that the sum of weights of all the vertices and edges on that path should be maximum. Is this correct?
Comment: @ChaitanyaChavali Yes, exactly, only correction first to prioritize by path weight (since the data loss must be avoided) and if there is a tie choose the one with least hopes.
Answer: You can use a modified version of Dijkstra's Algorithm with 3 modifications.
First of all you change all the weights from w to (W-w) where W is some large value. Since your case is an acyclic graph, I don't think you need Bellman-Ford algorithm.
The update step in Dijkstra's looks somewhat like this for a vertex v which is adjacent to u
if dst[v] > dst[u] + weight[(u,v)]
    dst[v] = dst[u] + weight[(u,v)]

You should modify this to include the vertex weights.
if dst[v] > dst[u] + weight[(u,v)] + weight[u]
    dst[v] = dst[u] + weight[(u,v)] + weight[u]

Also in Dijkstra, you store the predecessor in the shortest path for each vertex. In your case, you should store a set of predecessors because you are looking for multiple shortest paths.
At the end you can consider all the shortest paths(longest originally) and select the one with least hops.
Comment: Just a little clarification. Since I need to make sure that the "buffer" capacity of each node (router) and edge(link) is not less than the predefined value shouldn't the if statement be like:                                                                                `if ((dst[v] > dst[u] + weight[(u,v)] + weight[u]) && (predValue <= weight[(u,v)] && predValue <= weight[(u,v)]))
                           dst[v] = dst[u] + weight[(u,v)] + weight[u]`

Dynamic programming efficient network


TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first

Question: The following is from a project that I'm doing in Udacity on Deep Learning. The project is on Generating TV scripts. The error that i encountered is the one below.
The following function is the one after model training.
def generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100):
    """
    Generate text using the neural network
    param decoder: The PyTorch Module that holds the trained neural network
    param prime_id: The word id to start the first prediction
    param int_to_vocab: Dict of word id keys to word values
    param token_dict: Dict of puncuation tokens keys to puncuation values
    param pad_value: The value used to pad a sequence
    param predict_len: The length of text to generate
    return: The generated text
    """
    rnn.eval()

    # create a sequence (batch_size=1) with the prime_id
    current_seq = np.full((1, sequence_length), pad_value)
    current_seq[-1][-1] = prime_id
    predicted = [int_to_vocab[prime_id]]

    for _ in range(predict_len):
        if train_on_gpu:
            current_seq = torch.LongTensor(current_seq).cuda()
        else:
            current_seq = torch.LongTensor(current_seq)

        # initialize the hidden state
        hidden = rnn.init_hidden(current_seq.size(0))

        # get the output of the rnn
        output, _ = rnn(current_seq, hidden)

        # get the next word probabilities
        p = F.softmax(output, dim=1).data
        if(train_on_gpu):
            p = p.cpu() # move to cpu

        # use top_k sampling to get the index of the next word
        top_k = 5
        p, top_i = p.topk(top_k)
        top_i = top_i.numpy().squeeze()

        # select the likely next word index with some element of randomness
        p = p.numpy().squeeze()
        word_i = np.random.choice(top_i, p=p/p.sum())

        # retrieve that word from the dictionary
        word = int_to_vocab[word_i]
        predicted.append(word)

        # the generated word becomes the next "current sequence" and the cycle can continue
        current_seq = np.roll(current_seq, -1, 1)
        current_seq[-1][-1] = word_i

    gen_sentences = ' '.join(predicted)

    # Replace punctuation tokens
    for key, token in token_dict.items():
        ending = ' ' if key in ['\n', '(', '"'] else ''
        gen_sentences = gen_sentences.replace(' ' + token.lower(), key)
    gen_sentences = gen_sentences.replace('\n ', '\n')
    gen_sentences = gen_sentences.replace('( ', '(')

    # return all the sentences
    return gen_sentences

after this the following code is run:
# run the cell multiple times to get different results!
gen_length = 400 # modify the length to your preference
prime_word = 'jerry' # name for starting the script

pad_word = helper.SPECIAL_WORDS['PADDING']
generated_script = generate(trained_rnn, vocab_to_int[prime_word + ':'], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)
print(generated_script)

Upon running this code, I get the following error
TypeError                                 Traceback (most recent call last)
<ipython-input-40-68a17c4d1704> in <module>()
      7 """
      8 pad_word = helper.SPECIAL_WORDS['PADDING']
----> 9 generated_script = generate(trained_rnn, vocab_to_int[prime_word + ':'], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)
     10 print(generated_script)

3 frames
<ipython-input-39-b86c7a305356> in generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len)
     53
     54         # the generated word becomes the next "current sequence" and the cycle can continue
---> 55         current_seq = np.roll(current_seq, -1, 1)
     56         current_seq[-1][-1] = word_i
     57

<__array_function__ internals> in roll(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in roll(a, shift, axis)
   1179
   1180     """
-> 1181     a = asanyarray(a)
   1182     if axis is None:
   1183         return roll(a.ravel(), shift, 0).reshape(a.shape)

/usr/local/lib/python3.6/dist-packages/numpy/core/_asarray.py in asanyarray(a, dtype, order)
    136
    137     """
--> 138     return array(a, dtype, copy=False, order=order, subok=True)
    139
    140

/usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype)
    490     def __array__(self, dtype=None):
    491         if dtype is None:
--> 492             return self.numpy()
    493         else:
    494             return self.numpy().astype(dtype, copy=False)

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

Can anyone please help me out?
Answer: np.roll(current_seq, -1, 1) requires the input to be a NumPy array, but current_seq is a tensor, so it tries to convert it to a NumPy array, which fails, because the tensor is on the GPU. In order to convert it to a NumPy array, you need to have the tensor on the CPU.
current_seq = np.roll(current_seq.cpu(), -1, 1)