7th Chord Question - Roots and thirds

Question: In a 7th chord, particularly minor 7th or major 7th chords, can the actual root AND the third function as the root/tonic note?
For example, a Cmin7, C and Eb can both function as root/tonic?
I ask because I notice that melodies sound resolved when starting and ending on the third (Eb). And still sound somewhat resolved, (with an urge to carry on) when ending on the root (C).
I try to make sense of it by discerning the fact the 7th chord basically has two separate root and perfect fifths (C and G , Eb and Bb) and the latter makes up a major chord. (Eb, G, Bb) Which may present the option of choosing C or Eb as a root/tonic.
Then I ask, well which "chord" in the 7th chord is the "strongest"? As you can see, my analytical probing is never ending.
Comment: A little different than what you are asking but I read a theory book that was speaking about inversions (placing different chord tones in the bass) and it was suggesting that there can be no minor 7 chord in first inversion, as this would be the same notes as a major 6 chord and would be indistinguishable.
Answer: As I see it, there are a couple different things going on in this question, which I'll deal with in turn. The first two are unrelated to seventh chords.

There's a confusion about the meaning of tonic.
There's a question about the similarities of relative major and minor scales.
There's a question about seventh chords being viewed as two chords combined.

(1)
First and foremost, you seem to be mixing the concepts of chord, and key. Specifically, the word "tonic" always relates to the key you are in, regardless of what chord you are playing. It is the tonic that describes where the melody wants to rest, or resolve to. On the other hand, terms like "root" and "third" could be used to relate to either scales, or keys, and the context should make it clear which is which. In other words, there are two possible reference points for counting intervals, and you seem to be confusing them.
This actually has nothing to do with seventh chords. For example, your Cm chord could occur in lots of different keys. Here's a few:
In the key of C minor:

The tonic is C.
The root of the Cm chord (C) is also the same as the root of the key (tonic).
The third of the Cm chord (E♭) is also the the third of the key.

In the key of E♭ major:

The tonic is E♭.
The root of the Cm chord (C) is the sixth of the key.
The third of the Cm chord (E♭) is the root of the key (tonic).

Note that this partly explains why E♭ can sound like a good tonic

In the key of A♭ major:

The tonic is A♭.
The root of the Cm chord (C) is the third of the key.
The third of the Cm chord (E♭) is the fifth of the key.

In the key of B♭ major:

The tonic is B♭.
The root of the Cm chord (C) is the second of the key.
The third of the Cm chord (E♭) is the fourth of the key.

So as for which note is the "tonic" (i.e. the note that melodies should resolve to)? It really depends on what key you're playing in.

(2)
Why do C and E♭ both sound convincing as tonics when playing this scale? You'll notice that the E♭ major and C minor (natural minor) scales share the same key signature of 3 flats. This also means they share all the same notes of the scale, but with different scale degrees (for example, the notes F-G-A♭ could be viewed as scale degrees 2, 3, 4 in E♭ major, or as scale degrees 4, 5, 6 in C minor). These keys are thus considered related to each other. You would say that C minor is the relative minor of E♭ major, or swap it around and say that E♭ major is the relative major of C minor. These same terms can be applied to chords in addition to keys. Every major scale or chord has a relative minor scale or chord that starts a minor third below it (and vice versa). Once again, this is unrelated to seventh chords.
See: Are the formulae for Minor scale and Major scales related?

(3)
Finally, you have a very interesting question that does concern seventh chords -- can seventh chords be viewed as two superimposed chords?. For example, can a chord comprised of 1-3-5-7 be viewed as a combination of the chords 1-3-5 and 3-5-7?
I would argue that the answer is yes, to a limited degree. It doesn't affect what the tonic is, since that's determined by your key. Nor does it change what the root of your chord is. But the chord's "quality" is definitely affected by the quality of the upper chord. Let's look at some examples. For each seventh chord below, try playing the two triads separately a couple times, listening to their differences, then play them together as a seventh chord, and here how they both contribute to the resulting sound.

Dominant Seventh = Major + Diminished

e.g. (G, B, D) + (B, D, F)
This chord combines the boldness of a major chord, with the instability inherent in the diminished chord, resulting a chord that demands resolution -- so much so that it practically defines the whole concept of western tonal music.

Major Seventh = Major + Minor

e.g. (C, E, G) + (E, G, B)
The outgoing happiness of the major chord is somewhat tempered by the sorrow in the minor chord, leading to a sound that could be described as bittersweet, melancholy, or even a nostalgic.

Minor Seventh = Minor + Major

e.g. (C, E♭, G) + (E♭, G, B♭)
This intense sorrow possible in a minor chord is significantly reduced and stabilized by the major chord leading to a rather laid-back, mellow or chilled-out sound. The theme from Beethoven's 5th symphony sounds dramatic over a minor chord; over a minor seventh... meh, not so much.

In each of these cases, you can think of the upper "chord" as somehow flavoring the perception of the lower chord.
Update: As @Ceart mentions, the more general term for the superposition of two different chords is a polychord. Because seventh chords are so ubiquitous, I don't think they are usually thought of as polychords, although technically they could be. When seen from that standpoint, here is a related question: Difference between Polychords and Extended chords
Comment: Thank you so much for your reply! Great information that hits home. Thank you everyone for your replies and help. It is much appreciated.
Comment: @ZachLipscomb Glad you found it useful. As the asker of the question, consider selecting one of the responses as "the answer" to let future individuals know what was helpful.
Answer: There are mainly two ambiguous seventh chords (or four, depending on your definition). Let's choose A and C as the respective root notes:
Am7     = C6
 Am7(b5) = Cm6
where = means 'has the same notes as'. There is no way to distinguish between those chords if you don't require the root to be the lowest note. Of course, the context can provide some hint as to which chord is meant, but the question which chord it is is mainly a theoretical one, because it does not affect the way you play it, neither does it affect the way you play over it (when playing a melody).
In some cases an A major 7 chord can be seen (or, actually, heard) as a C#m chord with an added b6. This is definitely rare because the b6 is normally no 'allowed' tension on a minor triad, but it can occur with line clichés, where a melody is moving chromatically over a static chord (e.g., 'James Bond theme').
However, in most practical cases there is no ambiguity in seventh chords, especially not if you take the musical context into account.
Answer: If I understand your question clearly, the Cm7, with C Eb G and Bb is actually an inversion of Eb6, with Eb G Bb and C. So to an extent, when either is played, it could become a rest point, although Eb6 is probably a more final sounding chord. If the piece is in Cmin., then the Cm7 could be a final chord. The more defining factor is usually the note played lowest. If C, the chord is likely to be Cm7, if Eb, then it'll be Eb6.
In answer, no, there can't be two roots in a chord, but there is an ambiguity between these two, which is slightly confusing you.
Answer: It sounds like you are thinking of it as a polychord. The "strongest" chord in your seventh chord will depend on the melodic context. It could be useful for modulation, i.e. changing the tonic.
For example, you could use the progression:
Dm7-G7-Cmaj7-Am7-C/G-D/F#-G
or
ii(of C Major)-V-I-vi-I/IV(of G Major)-V-I
To modulate from C Major to G Major
Answer: In a 7th chord, there is one root, one third, one fifth and one seventh. The fact that you will four notes forming intervals of 5ths in the chord doesn't matter.

can the actual root AND the third function as the root/tonic note?

Only the root can act as the root/tonic note. In Cm7 (C,Eb,G,Bb), the root is C. If you take Eb as a root, it will be a different chord - the Eb chord.
I'm not sure that this is what you are looking for, but if Eb of the Cm7 chord is on the bass, the chord will be on first inversion. The C would still be the root note, but Eb would be the lowest one.
A melody can end on any note of the chord (1,3,5,7). It is really common to start and end on the 3rd, but the 'resolved' part would be the same for the 1st as well.
Answer: Roots and Tonic notes are usually not the same thing. The roots are the notes on which chords are built. Tonics are simply the technical name for the first note of the scale.
There is off course chords build on the tonic note of the scale ( The tonic chord.) where the tonic is the root note of the chord but for all the other chords this is not the case.

For example, a Cmin7, C and Eb can both function as root/tonic

Either one can be the tonic note (Depending on the scale.) but it is clear that this chord is build on the C note. Hence the name thus it clearly does not have the Eb for the root.

7th Chord Question - Roots and thirds


Field Collection with Date for Calendar View

Question: I'm working on the content design for a new site, but I'm having a major hangup with some of the connections between the data types, especially when it comes to Dates and Calendars.  Here's the rundown:

Films share a many to many relationship with Programs.
Programs can have one or many Screenings.
Screenings each have one Date and Venue.

I've successfully accomplished this using Node Reference and Field Collection.  There is a node reference between Films and Programs.  Programs contains a field collection called Screenings.  The field collection Screenings contains the fields Date and Venue.
The functionality I love from this setup is that each Date and Venue pair is grouped, and I can just click the Add button to generate another pair within that Program.  This satisfies the one or many requirement for Screenings.
Unfortunately, when I start to build this all into a Calendar view (Date module, Calendar module), it breaks terribly.  Depending on how I set things, I end up with SQL errors or index errors within Drupal.  None of it works.  Reading through issue posts, I've gathered that this is probably some sort of complexity added by Field Collection which is not handled in Calendar.
Short of getting Field Collection to play nice with Date and Calendar, can anyone suggest another method for implementing this?  My next thought would be to move Screenings off into its own node and create another node reference between that and Programs.  However, that would mean I lose the clean and simple Add button to generate a new Screening within a program.
Perhaps a custom add/edit form is all I really need.  Unfortunately, that road seems rather perilous for me without some clear guidance.
Comment: These are threads that I came across, but haven't helped with a solution yet:  http://drupal.org/node/1211842  http://drupal.org/node/1047784
Comment: Update:  after getting all the latest dev versions (as of 2011-11-16), I'm no longer getting errors on my calendar view.  But I'm not getting Programs, either.  I've added "Field: Date" (from field collection Screening) to my contextual filters in the view, but I'm not getting anything.  Default value is current date, granularity is Month, added multiplier value, comparing by start/end range...  Hopefully someone else sees what I'm missing...
Answer: I couldn't get Calendar to play nice with Field Collections.  It seems like I needed to somehow provide for the custom calendar row plugin or calendar items within the field collection view (it's too complicated).
Ultimately, I went with the FullCalendar module, which is built on the FullCalendar jQuery plugin.
It's very clean, simple to setup, and it plays very nicely with everything I'm throwing at it.  If Calendar and Field Collections make any further progress with their development, I might revisit them, but for now this fits the bill.
Answer: I was up against this exact problem, but kept banging away at it until I figured it out.
It doesn't work by default because views is looking for nodes, and fields in field collections aren't recognized as part of a node. You need to be very explicit with views as to where to find the date field.

Install Field Collection Views module, which will create a "field
collection views" view. Clone that, don't edit it directly in case
you need to come back to it.
Change the format to Calendar
Create a relationship to the entity that contains the field
collection items
Create a contextual filter for the date field in your field
collection
create contextual filters for other fields in the content type with
the field collection
add those fields to the field section.

It was complicated and took me hours to figure out. I gave up several times. I stayed up way too late. I THINK I have outlined all the steps. Hopefully it will help someone a little bit.


What is the difference between manifold learning and non-linear dimensionality reduction?

Question: What is the difference between manifold learning and non-linear dimensionality reduction?

I have seen these two terms being used interchangeably. For example:
http://www.cs.cornell.edu/~kilian/research/manifold/manifold.html :

Manifold Learning (often also referred to as non-linear dimensionality reduction) pursuits the goal to embed data that originally lies in a high dimensional space in a lower dimensional space, while preserving characteristic properties.

http://www.stat.washington.edu/courses/stat539/spring14/Resources/tutorial_nonlin-dim-red.pdf :

In this tutorial 'manifold learning' and 'dimensionality reduction' are used interchangeably.

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3337666/ :

Dimensionality reduction methods are a class of algorithms that use mathematically defined manifolds for statistical sampling of multidimensional classes to generate a discrimination rule of guaranteed statistical accuracy.

However, http://scikit-learn.org/stable/modules/manifold.html is more nuanced:

Manifold learning is an approach to non-linear dimensionality reduction.

One first difference I can see is that a manifold can be linear, therefore one should compare non-linear manifold learning and non-linear dimensionality reduction.
Answer: Non-linear dimensionality reduction occurs when method used for reduction assumes that manifold on which latent variables are lying is, well... non-linear.
So for linear methods manifold is a n-dimensional plane, i.e. affine surface, for non-linear methods it's not.
"Manifold learning" term usually means geometrical/topological methods that learn non-linear manifold.
So we can think about manifold learning as a subset of non-linear dimensionality reduction methods.


Is Apache DBCP2 JCA compliant?

Question: I'm working on re-configuring a JEE application to work standalone, and we're making a list of components to use. Two of those are Narayana (JTA/transaction manager), and Apache DBCP2 (JDBC connection pool). It looks like these pieces should work together, but we want to be standards compliant where we can.
So, a question has come up: is DBCP2 a JCA (JEE Connector Architecture) implementation?
JCA compliance might not matter much if we can easily configure DBCP to work with Narayana, so any hints on that front would be appreciated too.
Answer: maybe too late for original purpose but good for future reference: if by JCA compliant you mean JTA managed, then it depends on what DataSource you are gonna use. According to here the BasicManagedDataSource is indeed JTA compliant.
Comment: DBCP is not JCA compliant at all, because it doesn't implement any interfaces (`javax.resource` and sub-packages) from JCA.
Comment: JCA not but JTA yes. And I believe thats actually the question, if DBCP is JTA compatible, its formulated wrong.

Is Apache DBCP2 JCA compliant?


Executing a python script through php button

Question: I am having an issue with executing my python script through using a button on PHP. I looked through any or all relevant questions regarding my issue, and tried any answers i could find and modifying the file name to my own.
This is the PHP code on my website:
    <FORM>
    <button type="button" onclick="parent.location='action.php'">open</button>
    </FORM>

The PHP code will be executing the python script, which i wrote:
    <?
       exec("python /var/www/open.py")
    ?>

The website works, the python script works when i manually execute it on terminal. However, when i try to click on the button on my website, nothing happens. I also went and changed the configs on the sudoers file so that www-data functions without the use of a password, and also did chmod gu+x on /var/www/open.py.
Is there anything else that I might be missing? Can someone help me please?
Thank you.
Comment: What do your logs say?
Comment: Which logs would you be talking about?
Comment: try echo exec("python /var/www/open.py");
Comment: alternatively you could use `system` instead of `exec` to avoid need for `echo` as seen in comment above
Comment: I gave your suggestion a shot. The line system("python /var/www/open.py"); doesn't seem to function. Could there be an issue with how I have written
`open`

please let me know
Comment: You have two separate problems.  1. Do you actually perform the exec statement? 2. Does exec work?  Add php trace message for (1).  Change exec to do `date` to ensure exec is working.  Then, try "exec /usr/bin/python /var/www/hello_world.py".  As others said, try selinux in permissive mode.  I bet it does _not_ like /usr/bin/python from web server.  You may need to create a custom exception rule.  Check /var/log/audit/audit.log and /var/log/secure and system log messages, and web server logs
Comment: I'm voting to close this question as off-topic because it is about programming.
Answer: It could just be a PATH problem since the user www-data doesn't have a path set. Try using:
<?
   exec("/usr/bin/python /var/www/open.py")
?>

and see if that makes a difference (check that /usr/bin/python is the correct path for your distribution first with which python).
Answer: Could 2 paths to resolution:

fetch http://my.site.com/action.php directly and confirm that code execures that way. In case of some PHP issues.
SELinux: if your SELinux is set to "enforcing", try temporary disabling it just to confirm that it's not in the way: "setenforcing Permissive". If that cures the issue - you know you need to adjust things. First and foremost I doubt any default policy would allow executable scripts in /var/www dir, check your distro's default policy and locate appropriate folder. /var/www/cgi-bin may be one of them, or possibly system-wide directory like /usr/local/bin etc.
Answer: there are builtin php methods for this job : shell_exec() or system()


Proving a side of a triangle is a cube.

Question: I was given the question by one of my former students and I tried different approaches. I tried to do it geometrically and but it seems to get rather confusing pretty quickly. I tried an algebraic approach and it seems to give better results but I have problems connecting the common factor of 1 with the rest of the solution.
Proving that cos and sin are rational is relatively straightforward (I used cosine rule and since all the sides are integers then the cos needs to be a rational number) but then I get stuck.
The question is as follows:
How do I prove that at least of the sides p, q, r is a cube given the following: the side lengths p, q, r of a triangle PQR are positive integers such that the highest common factor of p, q, and r is 1 and that angle P = 3Q?
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Answer: Using sine law, ${p\over q} = {\sin(3Q)\over \sin(Q)} = {3\sin(Q)-4\sin^3(Q)\over \sin(Q)} = 3-4\sin^2(Q) = 2\cos(2Q)+1$. Now ${r\over q}={\sin(4Q) \over \sin(Q)}={4\sin(Q)\cos(Q)\cos(2Q)\over \sin(Q)}=4\cos(Q)\cos(2Q)=2\cos(Q)({p\over q}-1)$, so $2\cos(Q) = {r\over q({p\over q} - 1)} = {r\over p-q}$
Using cosine law, $p^2+r^2-2pr\cos(Q)=q^2$ so $p^2+r^2-{pr^2\over p-q}=q^2$.
Simplify, $(p^2-q^2)(p-q) = r^2q$ and $(p-q)^2(p+q)=r^2q$.
Suppose $\gcd(p,q)=k$ and $p=p'k$ and $q=q'k$. Then we have $(p'-q')^2(p'+q')k^2=r^2q'$. Notice that $q'$ is coprime with $p'-q'$ and $p'+q'$, and furthermore $r$ is coprime with $k$ as $\gcd(p,q,r)=1$ is given, we can conclude $q'=k^2$. Therefore $q=k^3$.

Proving a side of a triangle is a cube.


Give permission to jenkins to access unix:///var/run/docker.sock

Question: I have installed the docker plugin into jenkins and I am trying to configure a docker cloud.
My jenkins installation is running inside a docker container and I have bound to the docker socket on the host like so:
version: '3.3'
services:
    jenkins:
        container_name: jenkins
        ports:
            - '7345:8080'
            - '50000:50000'
        volumes:
            - /docker/jenkins/data/jenkins_home:/var/jenkins_home
            - /var/run/docker.sock:/var/run/docker.sock
        image: 'jenkins/jenkins:lts'

This method works fine using docker-ce-cli.  If I install the cli and bind to the socket of host then it works.
However setting up jenkins I am getting an error:

Inside the jenkins container everything is run under user "jenkins" with a UID of 1000.  On my host, UID 1000 is a user called "ubuntu".
I have added this user to the docker group
usermod -aG docker ubuntu

And checked the socket permissions:
# ls -lisa /var/run/docker.sock
833 0 srw-rw---- 1 root docker 0 Jul 22 22:02 /var/run/docker.sock

But jenkins still complains it doesn't have permissions.
What is right way to give jenkins permissions to access this socket?
Comment: Have you tried this? https://stackoverflow.com/a/51921594/530160
Comment: Thanks, I haven't seen that.  I tried to add the docker group with same ID inside the jenkins container but I need to be root to do it and it asks for a password when I try to elevate myself
Comment: You should be able to override that with `docker exec -it -u 0  bash`
Comment: Nice, I didn't know about that switch, thanks.  I think though that would cause an issue everytime I restarted the container.  I think only permanent way is to make a custom dockerfile?
Comment: I think so. I looked at the docs for bind mounts, and I couldn't find a way to mount a file in as a different user.
Comment: Cool, thanks for your help.  I will give custom Dockerfile a try
Comment: Adding group with same gid ` addgroup --gid 998 docker` then `usermod -aG docker jenkins` didn't fix issue.  Still getting permission denied :(
Answer: None of the customizations in the other thread worked but I tweaked it a bit and got it working with the below file:
FROM jenkins/jenkins

USER 0

ARG DOCKERGID=998

# Docker
RUN apt-get update \
    && apt-get install software-properties-common apt-transport-https ca-certificates gnupg-agent dialog apt-utils -y \
    && curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add - \
    && add-apt-repository \
        "deb [arch=amd64] https://download.docker.com/linux/debian \
        $(lsb_release -cs) \
        stable" \
    && apt-get update \
    && apt-get install docker-ce-cli -y

# Setup users and groups
RUN addgroup --gid ${DOCKERGID} docker
RUN usermod -aG docker jenkins

USER 1000

Answer: To be able to use docker from jenkins - just add jenkins user to docker group, not ubuntu one.
usermod -aG docker jenkins

Comment: This is incorrect.  If UID 1000 is set in docker then it has to be UID 1000 from the host. which is ubuntu user as stated in question.  I have resolved issue please see my previously posted answer.


How can I use a variable name to refer to an import in React?

Question: I have a series of objects that look like this:
{
  color: '#7018A7',
  icon: 'User',
  label: 'todd',
  text: "Lorem ipsum..."
},

I need to use my icon property inside a Font Awesome Component <FontAwesomeIcon icon={icon}. However, I'm importing the icons I need import {faUser} from ''. Of course, if I interpolate the icon's name (icon={`fa${icon}`}), I get an error because it is not equal to the actual imported icon.
Is there any way to refer to the imported icon by using the variable/property name?
Answer: The problem: FontAwesomeIcon does not accept a string as an argument.
The solution: have the icon property's value set to the imported icon
icon: faUser


Edit links in GridModel (MVCContrib)

Question: MvcContrib GridModel : Is it possible to do ActionSyntax in a GridModel
I've read this article and it's quite useful but I can't apply this. I don't know if in the newest MVCContrib, they removed the ".Action()" because somehow I cannot access this.
Is there someway i can put the ActionLink of the edit link into a grid model?
Thank you
Answer: It seems that the old method has been removed.
Here's how to do it now:
VB.NET
First, you pass the Html object into the gridmodel class through the constructor, then you can use it from within the gridmodel class.
Imports MvcContrib.UI.Grid

Public Class PersonGridModel
    Inherits GridModel(Of Person)

    Public Sub New(ByVal html as HtmlHelper)
        Column.For(Function(u) html.ActionLink("Edit", "Edit", "Person", New With {.id = u.PersonId}, Nothing)).DoNotEncode()
    End Sub
End Class

Then, in your view you pass it through the constructor:
<%=Html.Grid(Model).WithModel(New MemberRetentionTrackingSystem.InboundCallGridViewModel(Html))%>

C#
GridModel:
public class PersonGridModel : GridModel {
    public PersonGridModel(HtmlHelper html) {
        Column.For(u => html.ActionLink("Edit", "Edit", "Person")).DoNotEncode();
    }
}

View:
< %= Html.Grid(ViewData.Model).WithModel(new PersonGridModel(Html)) %>

REFERENCE: http://www.jeremyskinner.co.uk/2009/02/22/rewriting-the-mvccontrib-grid-part-2-new-syntax/ (see comment from Amitabh)
Answer: As a side note, more recent change, .DoNotEncode() is deprecated now, so use .Encode(false)
Answer: First, big thank you to @Andrew for his answer: Amitabh's question and Skinner's answer really solved my doubt. Anyway with ASP.NET MVC 4 I had a hard time trying to figure out why this in a Grid Model wasn't working:
Column.For(hospital => html.ActionLink("View Details", "Show", "Foo")).Encode(false);

Why? Because I wasn't adding the necessary using directive:
using System.Web.Mvc.Html;

I had only this using suggested by Visual Studio Intellisense:
using System.Web.Mvc;

Hope it helps anyone facing the same problem!

Edit links in GridModel (MVCContrib)


Mysql - empty value in date field

Question: I want to add a joindate field in company table:
alter table company add joindate date;

And I want to set empty value in the joindate field:
$joindate = '';

Update query:
$query = "UPDATE company
          SET joindate = '" .$joindate. "'
          WHERE ID = '" .$ID. "'";

When I update the record, it show the following warnings:
Data truncated for column 'joindate' ...

Why? How should I set the empty value in the joindate field?
Comment: What is your query for PHP?
Comment: Make sure your column's length is correct. Most likely an issue with the column misalignment.
Answer: Column type is date, not varchar (or some string type). So you must write correct date by format or NULL. Empty string '' is not correct value so your value is truncated and inserted 0000-00-00.
Answer: You could allow the value to be null in the columns rules. Unless for some reason, you need an 'empty value'.
Answer: You are trying to enter a string in a date column. That is not allowed and the data is truncated/removed; lowest date of 0000-00-00 is entered instead.
My recommendation is to just keep the value as NULL, which is what joindate will have across all rows when you add joindate column. There is nothing wrong with that column containing no value (represented by NULL).
If you were to do alter table tablename add field1 int and then update tablename set field = '' where id = 1, you will receive similar warning Incorrect integer value: '' for column 'field1' at row 1 and that column will receive a value of 0.

Mysql - empty value in date field


Base change and ordinals

Question:
Problem. Define the operation base change from $k$ to $m$: to make the operation for natural number $n$ we should write $n$ in the base-$k$ numeral system and read this in the base-$m$ numeral system.
Let $n$ be a natural number. Make for $n$ base change from $2$ to $3$, then subtract $1$, then change base from $3$ to $4$, then subtract $1$ and so on.
Prove that we'll get zero after finitely many steps.

For example, for $n=4$ the sequence is
$$9,8,10,9,11,10,12,11,12,11,12,11,12,11,12,11,12,11,\\
12,11,11,10,10,9,9,8,8,7,7,6,6,5,5,4,4,3,3,2,2,1,1,0.$$
For $n=6$ the sequence contain 762 terms.
The problem has elementary proofs, but it's from a book on Set Theory and authors says that it has a solution using ordinals: change all bases to $\omega$ and get decreasing sequence of ordinals.
I can't understand this hint.
Comment: The "standard proof" I know constructs a strictly decreasing parallel series of ordinals by substituting every $n$ in your presentation with $\omega$. At each step your parallel series is greater or equal to your original series, but as it is strictly increasing and the ordinals are well ordered it has to go to zero eventually, so that your original series has to go to zero. By the way: This is known as [Goodstein's theorem](http://en.wikipedia.org/wiki/Goodstein%27s_theorem).
Comment: I think you meant strictly **decreasing**.
Comment: @BrianM.Scott: The theorem is perfectly true for ordinary base-$k$ notation. It is just that in Goodstein's theorem the exponents are also recursively expressed in base-$k$ so as to obtain an even wilder statement (one that cannot be proved in PA, I think).
Comment: My sequence is not a Goodstein's sequence, because I change *only* base, but in a Goodstein's sequence we work with so called *hereditary* base-$k$ notation and change *all* $k$ to $k+1$. My sequence follow to zero much faster.
Comment: Yes, there is a hierarchy of stronger and stronger "Goodstein theorems". In your case, we replace $2^a+2^b+\dots$ with $3^a+3^b+\dots$, etc. The next case applies the change of base to $a,b,\dots$ as well. For the next case, you write $a=2^\alpha+2^\beta+\dots$, same for $b$, etc, and apply the change of base also to $\alpha,\beta,\dots$. Etc. The usual "Goodstein theorem" is in a sense the limit of this process. Each new level we go up, the corresponding theorem requires an extra instance of induction to be provable (over the base theory that is Peano arithmetic without the induction schema).
Answer: Suppose at the base $n$ stage you have the representation $a_ka_{k-1}\dots a_1a_0$, representing
$$g_n=a_kn^k+a_{k-1}n^{k-1}+\ldots+a_1n+a_0\;,$$
where $a_0,\dots,a_k\in\{0,\dots,n-1\}$, and $a_k\ne 0$. Let
$$\hat g_n=\omega^k\cdot a_k+\omega^{k-1}\cdot a_{k-1}+\ldots+\omega\cdot a_1+a_0\;,$$
where the arithmetic is all ordinal arithmetic. The change of base from $n$ to $n+1$ changes the interpretation of $a_ka_{k-1}\dots a_1a_0$ to
$$a_k(n+1)^k+a_{k-1}n^{k-1}+\ldots+a_1(n+1)+a_0\;.\tag{1}$$
If $a_0\ne 0$, subtracting $1$ yields
$$g_{n+1}=a_k(n+1)^k+a_{k-1}n^{k-1}+\ldots+a_1(n+1)+(a_0-1)\;,$$
and
$$\hat g_{n+1}=\omega^k\cdot a_k+\omega^{k-1}\cdot a_{k-1}+\ldots+\omega\cdot a_1+(a_0-1)<\hat g_n\;.$$
In general suppose that $a_i$ is the rightmost non-zero coefficient/digit. Then subtracting $1$ from $(1)$ yields
$$g_{n+1}=a_k(n+1)^k+\ldots+(a_i-1)(n+1)^i+\underbrace{n(n+1)^{i-1}+\ldots+n(n+1)+n}_{\text{all coefficients }=n}\;,$$
and
$$\hat g_{n+1}=\omega^k\cdot a_k+\omega^{k-1}\cdot a_{k-1}+\ldots+\omega^i\cdot(a_i-1)+\underbrace{\omega^{i-1}\cdot n+\ldots\omega\cdot n+n}_{\text{all coefficients }=n}\;.$$
This is again less than $\hat g_n$, since
$$\omega^i\cdot a_i>\omega^i\cdot(a_i-1)+\underbrace{\omega^{i-1}\cdot n+\ldots\omega\cdot n+n}_{\text{all coefficients }=n}\;:$$
this follows from the (possibly more evident) fact that
$$\omega^i>\underbrace{\omega^{i-1}\cdot n+\ldots\omega\cdot n+n}_{\text{all coefficients }=n}\;,$$
since $\omega^i\cdot a_i=\omega^i\cdot(a_i-1)+\omega^i$.
Thus, the sequence of ordinals $\hat g_n$ is strictly decreasing and must terminate at $0$ in finitely many steps. But $\hat g_n=0$ if and only if $g_n=0$, so the same is true of the sequence of numbers $g_n$.

Base change and ordinals


How make an app without menu? Android

Question: I use this for change the menu:
<code>public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_log_in, menu);
    return true;
}
</code>
but...
If i want that my activity haven't menu, how make it?
I want make activities without menu because i don't have navigation in this scenes. How make it?
Comment: Just remove the the snippet from your code, Extend the activity to Activity (android.app.activity).
Comment: Thx. Fixed the problem.
Answer: Remove these two methods in your Activity:
<code>    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_del, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
</code>
Comment: If you are ok with the answer then you can up vote it.

How make an app without menu? Android


Timeseries with multiplicative noise in Stan

Question: Say we have a monthly time series $y_t \geq 0$ dominated by seasonality, where the absolute differences from year to year are much smaller during low season. To avoid negative values and capture the higher uncertainty during high seasons I want to fit the time series based on last year's value with multiplicative noise, i.e. as
$$ y_t = y_{t-12} \cdot \varepsilon_t. $$
What is the correct Stan code for this?
Comment: Fair enough, the proper assumption would be Lognormal I guess? I will adapt the question, thanks :-)
Comment: Could you explain what the data are supposed to be?  You seem be generating them as a perturbation of a sine wave, but that would have a standard deviation different from that of the perturbing lognormal noise.  Moreover, although $\sigma$ might equal $0.1,$ that is not the same as the standard deviation of that lognormal variable--it would be the *geometric* sd.
Comment: The data is supposed to simulate freight train traffic volumes. They show some trends, but are mainly periodic. Some vary quite a bit during high seasons, e.g. crops are not always harvested the same week -- but for the rest there is none of this crop and therefore no traffic with high certainty.
Comment: I made a mistake simulating the data in the current version of the question ... I will edit the question heavily and adapt the current version as a reply, to make it useful for future reference.
Comment: What is your argument that $y_t$ must have a Normal distribution?  After all, if that is correct, then it applies just as well to $y_{t-12},$ implying $y_t$ is the *product* of two independent Normally distributed variables, which definitely is not Normal.  Something's not quite right here... .
Answer: I would try exponential noise, in which case your Stan program would be
data {
  int<lower = 0> N;
  vector<lower = 0>[N] y;
}
transformed data {
  vector[N - 12] y_lead = y[13:N];
  vector[N - 12] y_lag_inv = inv(y[1:(N - 12)]);
}
parameters {
  real<lower = 0> alpha;
}
model {
  y_lead ~ exponential(inv(alpha) * y_lag_inv);
  // prior on alpha
}

Comment: Thanks for your input. Would you mind explaining the rational behind exponential noise? I believe exponentially distributed numbers are positive and mainly around zero, so I would have to add them when generating predictions? I clarified the question. Also, what does `inv()` do? I can't find it in the manual ...
Comment: `inv()` is the inverse, i.e. reciprocal. The expectation of this exponential distribution is `alpha * y_lag` so it is a reasonable starting point. It is skewed toward zero, which may be unrealistic. If so, you could then move to a gamma distribution and estimate an additional parameter.
Answer: One might argue, that multiplicative errors should follow the log-normal distribution, because a log-normally distributed value times another one is again log-normally distributed. As the median of $\textrm{Lognormal}(\mu, \sigma)$ is $e^\mu$, the model
$$ y_t \sim \textrm{Lognormal}(\log(y_{t-12}), \,\sigma) $$
might be reasonable. This can be modeled in Pystan as:
import numpy as np
import pystan

n_years = 4
y = (np.sin(np.linspace(0, n_years*np.pi, n_years*12+1))**2  + 0.05) * np.random.lognormal(0, 0.1, n_years*12+1)

model = pystan.StanModel(model_code="""
data {
    int<lower=0> N;
    vector[N] y;
}
parameters {
    real<lower=0, upper=0.5> sigma;
}
model {
    y[13:N] ~ lognormal(log(y[1:N-12]), sigma);
}
""")

fit = model.sampling(data={'N': len(y), 'y': y}, iter=1000, chains=4)

Which recovers $\sigma$ fairly well:
        mean se_mean     sd   2.5%    25%    50%    75%  97.5%  n_eff   Rhat
sigma   0.15  7.1e-4   0.02   0.12   0.14   0.15   0.16   0.19    704    1.0
lp__   49.62    0.03   0.76  47.41  49.46   49.9   50.1  50.17    860   1.01

The fit can be further improved by using the (geometric) mean of the last two year's values.


How To Break a while loop inside a sensing if condition

Question: The essence of my psuedo-code is as follows (I have simplified it to arrange for simpler answers):
if (vibrate == 1){ //this is the input sensing to the arduino.
  //It is either 1 or 0
  //constantly run a while loop IF vibrate ==1
  i=51;
  while(vibrate ==1){
     analogWrite(Motor,i); //constantly outputing a pulse of increasing magnitude
     delay(10); //delay it for a certain period of time
     i=i+50; //increment i
     if (i>=255){
       i=51;
     }
  }
}
else{ //do something else. Has it's own functions}

Now vibrate is coming in from a sensor. If vibrate is 1, I would automatically want to output a ramped pulse (i.e. the while loop). However, if vibrate changes it's value (i.e. goes to zero), I would like the while loop not to be triggered, and if it is triggered, I would like to exit the while loop. The issue that I face is that vibrate updates itself outside of the while loop, and hence i'll get an infinite loop. Is there a better way to incorporate this? I can't update the value of vibrate in the while loop either, since I need to check the greater 'if' too.
Comment: why can you not read vibrate from within the while loop, can you not add if (!vibrate = analogRead(pin)) break; after delay(10); ?
Comment: While you have acted in good faith, pseudocode is the least helpful thing you can do, generally. Please see https://stackoverflow.com/help/mcve. Also you should format your code better because currently it's divided into multiple different sections. Also `if (i > /255)` is probably very wrong.
Comment: @138 interesting, I will try putting that in
Comment: Is this some manner of bit-banging GPIO? Use PWM hardware and your problems will go away.
Answer: Inside a loop you could call break; to continue execution outside the loop you called it in.
Comment: I think you mean "break; " instead of "break();".
Comment: Yep, that was my first idea to use a break statement, the only thing is the value of the variable 'vibrate' doesn't update in arduino. I'm unsure why, but as soon as it enters the while loop, it won't update till the while loop is done.
Comment: Maybe there's a call you could make to update the value. I don't know arduino.
Answer: update the vibrate variable within the while loop. You don't need to use break
void updateVibrate(){
       //UPDATE THE VIBRATE VARIABLE
    }

    if (vibrate == 1){ //this is the input sensing to the arduino.
      //It is either 1 or 0
      //constantly run a while loop IF vibrate ==1
      i=51;
      while(vibrate ==1){
         analogWrite(Motor,i); //constantly outputing a pulse of increasing magnitude
         delay(10); //delay it for a certain period of time
         i=i+50; //increment i
         if (i>=255){
           i=51;
         }
       updateVibrate();//Call function which will update the vibrate (Global) Variable
      }
    }
    else{ //do something else. Has it's own functions}

Alternatively, when you have fixed number of iterations, you can use for loop with break statement


Help me to simplify $\sum\limits_{i=0}^{\lfloor\frac{r}{2}\rfloor}\binom{r}{i}\binom{r-i}{r-2i}$

Question: I tried to simplify $\sum\limits_{i=0}^{\lfloor\frac{r}{2}\rfloor}\binom{r}{i}\binom{r-i}{r-2i}$ by using generating function in the similar way of markus-scheuer's answer to the question How to prove $\sum\limits_{i=0}^{\lfloor\frac{r}{2}\rfloor}\binom{r}{i}\binom{r-i}{r-2i}2^{r-2i}=\binom{2r}{r}$. What I got is $[u^r](1+u+u^2)^r$. I don't know how to compute the coefficient of $u^r$ in $(1+u+u^2)^r$. I tried using by trinomial expasion but I didn't suceed.
Comment: You might try $1+u+u^2 = (1-u^3)(1-u)^{-1}$
Comment: If you carefully compute the sum for the first few values of $r$ and then search the OEIS, you should find https://oeis.org/A002426 -- there are lots of formulas there, but none of them seem to be the simple kind of expression you're looking for, which suggests there might not be one. Unless I overlooked something; there's a lot in the entry!
Comment: You could try using a binomial expansion?  $$(1+u+u^2)^r=\sum_{n=0}^r{\binom{r}{n}u^n(1+u)^n}$$
Comment: @Eleven-Eleven On RHS $(1+u)^nu^{2r-2n}$. After simplifying also I got expression like in the question.
Comment: @BarryCipra I taught the link you suggested is very helpful because I want to represent the numbers 1,3,7,19,51,141,393,...Thank you very much
Answer: There   is  no closed form available for the  central trinomial coefficients
\begin{align*}
[u^r](1+u+u^2)^r&=\sum_{i=0}^{\lfloor r/2\rfloor}\binom{r}{i}\binom{r-i}{r-2i}
=\sum_{i=0}^{\lfloor r/2\rfloor}\binom{r}{2i}\binom{2i}{i}
\end{align*}

Plausibility check:
We consider the more general expression
  $$\sum_{i=0}^{\lfloor r/2\rfloor}\binom{r}{i}\binom{r-i}{r-2i}t^{r-2i}$$
   and obtain
  \begin{align*}
\color{blue}{\sum_{i=0}^{\lfloor r/2\rfloor}}&\color{blue}{\binom{r}{i}\binom{r-i}{r-2i}t^{r-2i}}\\
&=\sum_{i=0}^\infty[z^{i}](1+z)^{r}[u^{r-2i}](1+tu)^{r-i}\tag{1}\\
&=[u^r](1+tu)^r\sum_{i=0}^\infty\left(\frac{u^2}{1+tu}\right)^i[z^i](1+z)^r\tag{2}\\
&=[u^r](1+tu)^r\left(1+\frac{u^2}{1+tu}\right)^r\tag{3}\\
&\color{blue}{=[u^r](1+tu+u^2)^{r}}\tag{4}\\
\end{align*}
We observe in case of $t=2$ the nice simplification
  \begin{align*}
[u^r](1+2u+u^2)^{r}=[u^r](1+u)^{2r}=\binom{2r}{u}
\end{align*}
  Regrettably there is no obvious similar simplification for other values of $t$.
Comment:

In (1) we apply the coefficient of operator twice and set the upper limit of the sum to $\infty$ without changing anything, since we are adding zeros only.
In (2) we use the linearity of the coefficient of operator, do some rearrangements and use the rule
\begin{align*}
[u^{p-q}]A(u)=[u^p]u^qA(u)
\end{align*}
In (3) we apply the substitution rule of the coefficient of operator with $z:=\frac{u^2}{1+tu}$
\begin{align*}
A(u)=\sum_{i=0}^\infty a_i u^i=\sum_{i=0}^\infty u^i [z^i]A(z)
\end{align*}
In (4) we do some simplifications.

Notes from the experts:
D.E. Knuth gives in Concrete Mathematics, Appendix A 7.56 the following representation of a more general expression
\begin{align*}
[u^r](a+bu+cu^2)^r=[u^r]\frac{1}{\sqrt{1-2bu+(b^2-4ac)u^2}}
\end{align*}
He states that according to the paper Hypergeometric Solutions of Linear Recurrences with Polynomial Coeffcients by Marko Petkovšek there exists a closed form (more precisely: a closed form solution as a finite sum of hypergeometric terms) if and only if
  $$\color{blue}{abc(b^2-4ac)=0}$$
In case of central trinomial coefficients we have $a=b=c=1$. Since then the expression $abc(b^2-4ac)=-3\ne 0$
  there is no such closed form in particular for the central trinomial coefficients.
Comment: Thanks a lot sir. I learned solving by generating function method by you only. Your efforts are amazing for helping research scholars. Thanks again...
Comment: @Dhanalakshmi: You're welcome! Many thanks for your nice comment! ... and good to see the answer(s) are useful. :-)
Comment: +1. Very nice your 'Notes from the experts'. I have the book but never read that Appendix. I'll check it.
Comment: Really nice answer. (+1)
Answer: The central trinomial coefficient (A002426): the coefficient of $x^n$ in $(1+x+x^2)^n$, is given by:
$$\sum_{i=0}^{\lfloor\frac{n}{2}\rfloor} \binom{n}{i;2n-2i-2\lfloor\frac{n}{2}\rfloor;i}$$
because $i$ represents the number of $2$'s, $2n-2i-2\lfloor\frac{n}{2}\rfloor(=n-2i+n-2\lfloor\frac{n}{2}\rfloor)$ represents the number of $1$'s and $i$ represents the number of $0$'s in a partition of $n$ into $\{0,1,2\}$.
For example, $n=6$, we have $222000,221100,211110,111111$, represented in multinomial format as $303,222,141,6$.
So the sum is:
$$\frac{720}{3!0!3!}+\frac{720}{2!2!2!}+\frac{720}{1!4!1!}+\frac{720}{6!}$$
$$=20+90+30+1$$
$$=141$$
Comment: Thank you I tried using trinomial expantion but I didn't get. But I need in more simple form. I don't know whether it is possible or not. I taught I want to look the link you suggested. thanks a lot


Inequality $\lvert(1+\lvert u\rvert^2) v-(1+\lvert v\rvert^2)u\rvert > \lvert u\bar{v}-\bar{u}v\rvert$ for complex $u,v$

Question: This is exercise 4.(b) from Theory of Complex Functions, GTM 122, page 17. I was able to solve exercise 4.(a), but I don't see how this could help solving 4.(b):

a) Show that from $(1+\lvert v\rvert^2) u=(1+\lvert u\rvert^2)v,\,u,v\in\mathbb{C}$, it follows that either $u=v$ or $\bar{u}v=1$.
b) Show that for $u,v\in\mathbb{C}$ with $\lvert u\rvert<1, \lvert v\rvert<1$ and $\bar{u}v\ne u\bar{v}$, we always have $$\lvert(1+\lvert u\rvert^2) v-(1+\lvert v\rvert^2)u\rvert > \lvert u\bar{v}-\bar{u}v\rvert$$

For a), I took modulus of both sides and get either $\lvert u\rvert=\lvert v\rvert$ or $\lvert u\rvert \lvert v\rvert=1$, where the conclusion follows easily. For b), I tried substituting $u=x+iy$ and $v=p+iq$ but the resulting inequality is too complicated and it's difficult to see where the condition $\lvert u\bar{v}-\bar{u}v\rvert=2\lvert xq-yp\rvert\ne 0$ is used. Any advice?
Answer: Notice that both sides remain the same if we substitute $u \to cu, v \to cv$ for $|c| = 1$. Thus without loss of generality, we can assume $u$ is real. Then
$$\begin{align*}Left&= |(1+|u|^2)v - (1+|v|^2)u| \\
&= |\left((1+|u|^2) \mathrm{Re} (v) - (1+|v|^2)u\right) + \left((1+|u|^2) \mathrm{Im}(v)\right) i|\\
&\text{Since norm of a complex number is at least absolute value of its imaginary part,} \\
&\ge |(1+|u|^2) \mathrm{Im} (v)| \\
&= (1+|u|^2) |\mathrm{Im}(v)| \\
&\ge 2|u| |\mathrm{Im}(v)| \\
&= |u| |\overline{v} - v| \\
&= |u\overline{v} - \overline{u}v| \text{ (since $u$ is real)} \\
&= Right
\end{align*}
$$
Answer: For Part (a), we note that $\big(1+|v|^2\big)\,u=\big(1+|u|^2\big)\,v$ implies  $\big(1+|v|^2\big)\,|u|=\big(1+|u|^2\big)\,|v|$.  That is,
$$\big(|u|-|v|\big)\,\big(1-|u|\,|v|\big)=0\,.$$
If $|u|=|v|$, then we obtain $u=v$.  If $u\neq v$, then $|u|\,|v|=1$, whence $u\neq 0$ and $v=\dfrac{1}{|u|^2}\,u$.  Ergo,
$$\bar{u}\,v=\bar{u}\,\left(\frac{1}{|u|^2}\,u\right)=\frac{|u|^2}{|u|^2}=1\,.$$
For Part (b), we shall prove that
$$\Big|\big(1+|v|^2\big)\,u-\big(1+|u|^2\big)\,v\Big|\geq \big|u\,\bar{v}-\bar{u}\,v\big|\tag{*}$$
for all $u,v\in\mathbb{C}$, and the equality occurs if and only if $u=v$.  If $u=0$ or $v=0$, then (*) trivially holds.  From now on, we assume that $u\neq 0$ and $v\neq 0$.
Observe that
$$\begin{align}\Big|\big(1+|v|^2\big)\,u-\big(1+|u|^2\big)\,v\Big|^2&=\Big(\big(1+|v|^2\big)\,u-\big(1+|u|^2\big)\,v\Big)\,\Big(\big(1+|v|^2\big)\,\bar{u}-\big(1+|u|^2\big)\,\bar{v}\Big)
\\
&=\big(1+|v|^2\big)^2\,|u|^2+\big(1+|u|^2\big)^2\,|v|^2-2\,\big(1+|u|^2\big)\,\big(1+|v|^2\big)\,\text{Re}\big(u\,\bar{v}\big)\,.
\end{align}$$
Using the AM-GM Inequality on $\big(1+|v|^2\big)^2\,|u|^2+\big(1+|u|^2\big)^2\,|v|^2$, we obtain
\begin{align}\Big|\big(1+|v|^2\big)\,u-\big(1+|u|^2\big)\,v\Big|^2&\geq2\,\big(1+|u|^2\big)\,\big(1+|v|^2\big)\,|u|\,|v|-2\,\big(1+|u|^2\big)\,\big(1+|v|^2\big)\,\text{Re}\big(u\,\bar{v}\big)\\
&= 2\,\big(1+|u|^2\big)\,\big(1+|v|^2\big)\,\Big(|u|\,|v|-\text{Re}\big(u\,\bar{v}\big)\Big)\,.
\end{align}
Because $\big(\text{Im}(z)\big)^2=z^2-\big(\text{Re}(z)\big)^2$ for every $z\in\mathbb{C}$, we get
\begin{align}\Big|\big(1+|v|^2\big)\,u-\big(1+|u|^2\big)\,v\Big|^2&\geq2\,\left(\frac{\big(1+|u|^2\big)\,\big(1+|v|^2\big)}{|u|\,|v|+\text{Re}\big(u\,\bar{v}\big)}\right)\,\Big(\text{Im}\big(u\,\bar{v}\big)\Big)^2
\\
&\geq 2\,\left(\frac{\big(1+|u|^2\big)\,\big(1+|v|^2\big)}{2\,|u|\,|v|}\right)\,\Big(\text{Im}\big(u\,\bar{v}\big)\Big)^2\,,
\end{align}
where we have applied the trivial inequality $\text{Re}(z)\leq |z|$ for each $z\in\mathbb{C}$.  Finally, using the AM-GM Inequality $t+\dfrac1t\geq 2$ for all $t>0$, we get
\begin{align}
\Big|\big(1+|v|^2\big)\,u-\big(1+|u|^2\big)\,v\Big|^2&\geq\left(|u|+\frac{1}{|u|}\right)\,\left(|v|+\frac{1}{|v|}\right)\,\Big(\text{Im}\big(u\,\bar{v}\big)\Big)^2
\\
&\geq 4\,\Big(\text{Im}\big(u\,\bar{v}\big)\Big)^2=\big|u\,\bar{v}-\bar{u}\,v\big|^2\,,\end{align}
and the claim is proven.  (The equality case is easy to verify.)


Testing for Convexity

Question:
Could somebody please explain the method for answering a question like this?
Answer: It is easy to see, that the curve in definition of $A$ is an ellipse. Hence the set of extreme points of $A$ is this ellipse. Convexity is obvious: we use the same arguments as in the case of a closed ball.
Comment: @CalebJamesCoppersmith I am not sure, which tools you can use. But again for a unit ball i ${\bf R}^2$ it is easy to see that no point of its sphere is a linear combination of points from the ball (in this case we will have an interval on the sphere. An ellipse is obtained by a linear transformation of a sphere, hence all the arguments are valid. (I assume that arguments, showing, that you understand the problem, are enough. If not, one can take two points and compute, where lies a point from the interior of an inteerval with these ends).

Testing for Convexity


What is the safest way to set down a cello?

Question: In my orchestra group, all of the cellists set their cellos on their side on the floor next to their chair during break. However, one cello coach told us that since it's easy for the cello to fall over in that position, you should never leave your cello like that. Instead, he suggested putting the end pin all the way in and setting the scroll on the front edge of the chair with the front side up, so that the bottom edge of the back of the cello is resting on the floor.
His point was that in this position the cello would less likely to fall if it was bumped.  But if it were  bumped, it would have farther to fall.
Which of these two methods is safer for the cello?
Answer: The safest place to put your cello is back in its case.  It really doesn't matter how you put a cello down on the floor or on a chair: there's still a reasonably good (bad) chance that someone will trip over it, or tip a stand over onto it, etc.
Yeah, I'm paranoid, but that's what happens when you realize your instrument is worth as much as a small car :-) .
Comment: My late violin teacher used to charge 50 dollars to anyone who dropped, or fumbled, their violin. He was fond of saying, "Chairs are for sitting, floors are for walking, tables are for food, violin cases are for violins." I tend to be paranoid after all that!
Comment: my cello isn't expensive relative to the normal price of a cello, but of course this still means several thousand dollars. Sometimes this fact strikes me when i'm playing and yeah, definitely doesn't hurt to be paranoid!
Answer: You can't fall off the floor. I recommend the usual way, putting the cello in its side, and putting the endpin in if it gets in the way or is likely to snag someone passing. Naturally, keep the safety of your instrument in mind and tuck it agains a wall or like that (but don't face the bridge towards the wall, as it could get crunched if someone does nudge the instrument).
Comment: I would recommend this for shorter amounts of time, when it's simply more efficient to lay the cello down than put it back in the case.
Answer: We were taught a third method: have the side of the cello towards the floor, and lay the instrument against the edge of your chair, in a diagonal position. The top of the waist of the cello gets 'seated' on the chair pad, and the end pin is out, in its hole (just when it is played). The rib edges and the pin together will stabilise the cello, if it is laid properly. The bow gets to be laid on the seat.
This way the cello is occupying less than half of floor-space (as opposed to be layed on the floor), and it is both stable and very orderly. Also this is very swift, and takes less movement / manouevering by the player.
This is a very orchestral approach, as it is most important in that setting that the players are swift, and are not only orderly, but also orderly looking.  They are learning and practicing to move in unison in a very orderly way not only when playing, but also when they need to leave their instruments behind (eg when the show starts, or is over, or goes for an interval). The players and orchestra practice this all the time (to move together, be orderly, be neat looking, etc), so these rules go on in practice times as well, and layers are taught to do the same at home.
It is part of the cello practice and cello culture to move around the instruments with care and take caution, so it becomes second nature.
Cellos do not belong in their casings all the time, it is just simply not practical. Dragging the cello back / forth and in / out of its casing unnecessarily is poor practice, and actually increases the chances of accidents. Putting in the end stick and pulling it out each time the group goes on a break is also poor practice. It requires double / triple handling, it is simply not economical, not a good use of energy, and otherwise unpractical.
If your orchestra group laid down each cello with its side against the chair, you would have more room. If the chairs and cellos were lined up as well (in an orderly way) and adequate space between them, then the group would eventually find it easy to not bogged in with feet, loose clothing, etc, not to trip / knock the instruments over - it will become a house rule, as it should.
It is the responsibility of the conductor, or team leader / coach, to set these rules, and to keep them going. These rules are also necessary for occupational safety of the players (not only for the cellos), as someone tripping over a cello could end up breaking a leg, or hand, or neck (compared to that, the falling of the bridge would not be a big deal!).
If you do not have a regular coach, you need to agree amongst yourselves about how to set, and how to keep these rules. Good Luck.
Answer: Putting the end pin all the way in and putting it on it's side is usually safe. However, as mentioned above, putting it back in it's case is safe. Unless you are planning to play relatively soon.
Answer: Not really usable in orchestra context, but at home I use a guitar stand like this one with the end pin all the way inside. This is very stable, takes up little horizontal space and it is fast to put/retrieve the instrument.


Subset of a closed set cannot be open relative to a superset

Question: Take $E \subset Y \subset X$, where $X$ is a metric space. Assume that $Y$ is closed relative to $X$. Then $E$ is not open relative to $X$.
Is this proposition true? It seems so to me (but I am still moving my first steps in real analysis/basic topology).
Thanks!
Comment: X = R, Y = [0,1], E = (0,1) is counter example.
Comment: What does "standard metric" mean in this context?
Comment: How about $Y=X$ and $E=\emptyset$?
Comment: Ok, I meant proper subsets.
Comment: I also edited, eliminating "standard metric"
Answer: As it stands, this is not true. Consider $X:= \mathbb{R}$ and $Y := [0,1]$ and $E:= (0,1)$. Then we have $Y$ is closed in $X$ since it is the complement of the open set $(- \infty, 0) \cup (1, \infty)$, but $E$ is open in $X$.
I'm not sure if there are reasonable assumptions under which your claim could be true.
Comment: Thanks. No, it was only this simple intuition around which I wanted to get clarity. It's clear that my intuition was wrong.


Can i Run two ant tasks at the same time?

Question: i want to reduce the build time taken for a build by excecuting  as many independent tasks at the same time as possible. is it possible to do it?
I have tried using parallel tasks in the targets but parallel task will only parallelise within a target.i didnt get any significant build time reduction with parallel tasking.so now i am want to run entire targets in parallel.
Answer: Ant supports parallel tasks. See this documentation: http://ant.apache.org/manual/Tasks/parallel.html
Comment: Just be sure to not miss the warning:

> Warning: While the Apache Ant core is believed to be thread safe, no such guarantees are made about tasks, which are not tested for thread safety during Ant's test process. Third party tasks may or may not be thread safe, and some of Ant's core tasks, such as  are definitely not re-entrant. This is because they use libraries that were never designed to be used in a multithreaded environment.


How can I confirm a path is internal?

Question: In my theme's theme file I'm using preprocess_node to create variables for a node based on the section of my site its in, and that's figured out by checking the path's alias.
So for example a path like:
/events/this_is_my_node
It'll see that this node is in the events section of the site and the variables provided to the twig template facilitate theming the node page based on the section it's in.
Everything works great if the node and the node that's the section's landing page have their aliases generated, but if they don't, I get an error like:
UnexpectedValueException: External URLs do not have internal route parameters. in Drupal\Core\Url->getRouteParameters() (line 583 of core/lib/Drupal/Core/Url.php).

So basically I'm trying to figure out a conditional I can use so that I'm only getting Route parameters from a path it recognizes as being internal and should something go wrong and a path alias isn't set I don't get a WSOD.
I've tried using UrlHelper::isExternal but that doesn't seem to help as it just seems to look at the path structure to determine if its external or not vs actually check the page.
This is my code:
function THEME_preprocess_node(&$variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  $variables['#cache']['contexts'][] = 'route.name.is_layout_builder_ui';
  $internal_path = \Drupal::service('path.current')->getPath();
  $current_path = \Drupal::service('path_alias.manager')->getAliasByPath($internal_path);
  $variables['current_path'] = $current_path;
  $variables['internal_path'] = $internal_path;
  $int_exp = explode("/", $current_path);
  $alias = \Drupal::service('path_alias.manager')->getPathByAlias($int_exp[1]);
  $is_layout = false;
  if ($route_name ) {
    $node = $variables['node'];
    // check if layout builder is active
    if (isset($int_exp[3])) {
      if ($int_exp[3] == 'layout' or $int_exp[1] == 'layout_builder')
      {
        $is_layout = true;
      }
    }

    if (isset($internal_path) && !$is_layout) {
      $params = Url::fromUri("internal:/" . $alias)->getRouteParameters();
      $entity_type = key($params);
      if (isset($entity_type)) {
        $node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
        $variables['section_nid'] = $node->nid->value;
        $variables['is_site_section'] = false;
        if ($node->type->target_id == 'sections') {
          $variables['is_site_section'] = true;
          $variables['current_section'] = $node->field_section_machine_name->value;
          $variables['current_section_title'] = $node->title->value;
        }
      }
    }

  }
}

Comment: The code should be based on the route match, which you use only to determine whether a route name was matched, but you don't use the route name or the route parameters from there. You don't need to write code trying to match the current path again, it is already matched.
Comment: Truly, what returned by `\Drupal::service('path_alias.manager')->getAliasByPath($internal_path)` is a path alias, and what returned by `\Drupal::service('path_alias.manager')->getPathByAlias($int_exp[1])` is the path matching the path alias. The code assigns the value returned by `\Drupal::service('path_alias.manager')->getAliasByPath($internal_path)` to `$current_path`, and the value returned from `\Drupal::service('path_alias.manager')->getPathByAlias($int_exp[1])` to `$alias`.
Answer: You should not check for internal. An url like internal:/robots.txt is internal, but it is no route and has no route parameters.
So before you do Url::getRouteParameters() you should check for Url::isRouted()

How can I confirm a path is internal?


Setar Adapter dentro de uma Thread

Question: Estou tentando listar em um RecyclerView no fragment, mas o retorno da lista está em uma thread, não sei se estou fazendo algo errado mas não mostra nenhum registro.
No logcat não retorna nenhum erro, e a lista vem preenchida quando uso o Debug.
Segue método com o Adapter sendo setado dentro e passando a lista:
public void ListarArquivosdoFTP() {

        new Thread() {
            @Override
            public void run() {
                try {
                    Recibo recibo = null;
                    classe_FTP ClienteFTP = new classe_FTP();
                    ClienteFTP.Conectar("ftp.meuhost.com.br", "usuario", "senha", 21);
                    FTPFile[] arquivos = ClienteFTP.Dir("/caminho");
                    if (arquivos != null) {
                        int length = arquivos.length;
                        for (int i = 0; i < length; ++i) {
                            FTPFile f = arquivos[i];
                            if (f.isFile()) {
                                recibo = new Recibo();
                                recibo.setRecibo(f.getName());
                                ArquivosFTP.add(recibo);
                            }
                        }
                        // Adapter
                        ReciboAdapter adapter = new ReciboAdapter(ArquivosFTP);
                        recyclerRecibo.setAdapter(adapter);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

Meu ReciboAdapter:
public class ReciboAdapter extends RecyclerView.Adapter<ReciboAdapter.ReciboHolder> {

    List<Recibo> listaRecibo;

    public ReciboAdapter(List<Recibo> listaRecibo) {
        this.listaRecibo = listaRecibo;
    }

    @NonNull
    @Override
    public ReciboHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View vista = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.lista_recibo, viewGroup, false);
        RecyclerView.LayoutParams layoutParams =
                new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        vista.setLayoutParams(layoutParams);
        return new ReciboHolder(vista);
    }

    @Override
    public void onBindViewHolder(@NonNull ReciboHolder reciboHolder, int i) {

        reciboHolder.txtRecibo.setText(listaRecibo.get(i).getRecibo().toString());
    }

    @Override
    public int getItemCount() {
        return listaRecibo.size();
    }

    public class ReciboHolder extends RecyclerView.ViewHolder {

        TextView txtRecibo;

        public ReciboHolder(@NonNull View itemView) {
            super(itemView);

            txtRecibo = (TextView) itemView.findViewById(R.id.txtRecibo);
        }
    }

}

Comment: Talvez vc precise do runOnUIThread()
Comment: Vou pesquisar e tentar implementar @Rocigno Medeiros.
Answer: Tente dessa forma:
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        recyclerRecibo.setAdapter(adapter);
    }
});

Comment: Não funcionou, ficou a mesma coisa, o recyclerView sem registro e no logcat mostrou essa linha: E/RecyclerView: `No adapter attached; skipping layout`
Comment: Consegui, estava colocando em uma parte errada do código. vlw...

Setar Adapter dentro de uma Thread


Javascript bug in i.e function returning NAN (works in other browsers)

Question: Hello i have created a javascript function that recaculates the grand total of an order when the delivery method is changed. The code works fine in firefox, chrome and i.e 9 but returns NAN in i.e 8 and 7, which i understand means Not a number.
I have tried using parseInt, pareseFloat and Number but can't understand why it does not work in i.e 6, 7 or 8
my code is as follows

and the markup

         <input name="shipping_method" value="tablerate_bestway" id="s_method_tablerate_bestway" checked="checked" class="radio validation-passed" onclick="ChangePrice('0')" type="radio">

UK Delivery (3 - 7 Working Days)
Free delivery

            <input name="shipping_method" value="flatrate_flatrate" id="s_method_flatrate_flatrate" class="radio validation-passed" onclick="ChangePrice('10')" type="radio">
             Next Day - Orders Before 2pm
             £10.00

Answer: You can never rely on reading back the same HTML that the page was created with.
If you read back  in IE you will actually get  (sans ") so your replace fails and the parse to a numeric returns NaN.
You can either choose to rely on .replace('','i') or better give the span an id: £xxx and get the numeric value from its innerHTML, or even better retain all the numeric values in memory in the first place.
Comment: for anyone looking for a solution in the future i modified my function to use a stripTags function which returnns the prices in chrome, i.e 7,8,9 and firefox.


Need help compiling external github modules (Ti.Facebook)

Question: I am trying to download and compile the github version of Ti.Facebook found here: https://github.com/appcelerator-modules/ti.facebook. Specifically I am working on the Android module.
I have currently cloned the repo to my local machine, then used Terminal to enter the project 'android' folder. I then ran 'appc run' (also tried 'appc ti build') but after starting well i get a build error.
Error and version data etc. here: http://pastie.org/10842167
I assume that the error is something to do with my setup, rather than an issue with the repo?
It's quite possible that I have missed a setup step but i can find any information to point me in the right direction.
Answer: You can't run modules directly. Modules have to be build.
You can either import this module in Appcelerator studio and "package" from there or build it from command line with "ant".
How to Build ti.facebook from command line:

Download or clone repo
rename android/build.properties.example to android/build.properties and set the paths in there
terminal to the module root and run "ant"
Comment: Thanks Nils, I am trying to build not run, sorry bad choice of words! I can't open in Appcelerator studio because it contains no project files. I guess i could create a new project and copy in all of the relevant files etc but surely thats not what everyone has to do? In regard to ant I think that i read that ant is no longer used and 'appc run' is the command to use... just wondering if i missed anything else
Comment: I just build the module with the steps I edited in above. Can you build the module that way? I believe you have to use ant because "appc run" will actually run something, and this should not be possible with modules... Please also make sure that you have all prerequisites for building an android module: http://docs.appcelerator.com/platform/latest/#!/guide/Android_Module_Quick_Start-section-43289022_AndroidModuleQuickStart-AndroidModulePrerequisites
Comment: Thanks again Nils, I have run through the steps. It took me a while to get the correct paths in the build.properties but when I did so I still receive the same errors as before. I now believe that this is a specific module issue, rather than a generic one! I will accept your answer as correct as my question was a generic one, but if you happen to test on the ti.facebook module it would be good to hear of your progress :-)
Answer: Running app and building module is two different thing in Appcelerator Studio. For building module you need to install some additional component in your environment.Like: Ant,Eclipse java developemnt tool, Android development too, gpref, Python. You can find full documentation in the following link.
Documentation Link


MongoDb aggregate not grouping correctly

Question: So what I want to do is get the total number of sport activities offered per province per type. For Berlin and Cologne the activities are Running and swimming
The output should look something like this:
{
    "_id" : {
        "province" : "Berlin",
        "type" : "Running"
    },
    "number" : 2.0
}
{
    "_id" : {
        "province" : "Berlin",
        "type" : "Swimming"
    },
    " number" : 2.0
}
{
    "_id" : {
        "province" : "Cologne",
        "type" : "Running"
    },
    "number" : 2.0
}
{
    "_id" : {
        "province" : "Cologne",
        "type" : "Swimming"
    },
    "number" : 1.0
}

my query looks like this, im not getting the result that i want. It shows me the provinces where Running and Swimming are activities which are not Berlin or Cologne. I tried putting the $or insinde a $and and it still didnt produce the outcome i wanted. What am I missing?
db.getCollection("Sport").aggregate([
    {$match: {$or: [{province: "Cologne"}, {province: "Berlin"}], $or: [{type: "Running"}, {type: "Swimming"}]}},
    {$group: {_id: {province: "$province", type: "$type"}, count: {$sum: 1}}},
    {$sort: {count: -1}}
])

Comment: Does using `{"$match": {"province": {"$in": ["Cologne", "Berlin"]}, "type": {"$in": ["Running", "Swimming"]}}}` make it work?
Answer: So the issue is within the match query, specifically the query object has the same key more than once (the "$or" key), in this case the query parser of your driver takes the last appearance of the key, Here is a simplified example:
const query = { score: 1, score: 2 }
results = db.find(query)

With query the "results" will all have score: 2, because the score: 1 condition was overwritten when parsed by the query parser.
Now replace score with $or and you get the point.
You can simplfy your query by using $in:
{
    "$match": {
        "province": {"$in": ["Cologne", "Berlin"]},
        "type": {"$in": ["Running", "Swimming"]}
    }
}

Or your instinct to use $and could also work, i'm assuming there was just some syntax issue there:
{
    $match: {
        $and: [
            {$or: [{province: "Cologne"}, {province: "Berlin"}]},
            {$or: [{type: "Running"}, {type: "Swimming"}]},
        ]
    },
}

Answer: Tom Slabbaert had already great input but having no idea how your data structure actually looks it's hard to pin point the mistake. But incase the field 'type' or 'province' is an array, you would need to unwind the field first.
  {
    $unwind: "$type"
  },
  {
    $match: {
      $and: [
        {
          $or: [
            {
              province: "Berlin"
            },
            {
              province: "Cologne"
            }
          ]
        },
        {
          $or: [
            {
              type: "Running"
            },
            {
              type: "Swimming"
            }
          ]
        }
      ]
    }
  }

Comment: Your answer with the combination of Toms made it work! It was indeed the $unwind that I was missing. Next time ill make sure to post the data structure as well! Thanks a lot.


Persist AWS Cognito User with Amplify

Question: I've been following the Serverless Stack tutorial and can get a positive response with calling Auth.signIn(username, passsword)
The current workflow we have is that the user will need to reset their password as accounts will be handed out.
The .changePassword function takes 3 arguments; user, oldPassword, newPassword
I can't for the life of me figure out what it's looking for for the user. When I set the object returned from .signIn() I get the following error:

Local storage is missing an ID Token, Please authenticate

Obviously I wouldn't use this flow for production, but I'm trying to figure out what Auth is looking for.
Auth.signIn(this.state.emailAddress, this.state.password)
  .then(user => {
    this.setState({ isLoading: false, user });
  }).then(async () => {
    Auth.changePassword(this.state.user, 'P@ssw0rd!', 'NewP@ssw0rd!');
  }).catch(err => {
    this.setState({ isLoading: false, errorMessage: err.message })
});

I do see an ID token in the Storage property from the object returned from .signIn. For clarification: I probably shouldn't have placed it in the chaining. I'm not really doing above in practice. When I save the response from Signin and pass it to the changePassword I get the localstorage error. I'm wondering if there is a config issue setting up Amplify that normally would place this info in localStorage.
Answer: Auth.changePassword takes in a CognitoUser as it's first argument, something which should be returned from Auth.signIn.
The issue here, is your promise chaining, and using this.setState() and reading it back before it's actually been set:
Auth.signIn(this.state.emailAddress, this.state.password)
  .then(user => {
    // Triggers a setstate here:
    this.setState({ isLoading: false, user });
  }).then(async () => {
    // this.state.user is not defined at this point
    Auth.changePassword(this.state.user, 'P@ssw0rd!', 'NewP@ssw0rd!');
  }).catch(err => {
    this.setState({ isLoading: false, errorMessage: err.message })
});

From the React docs:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

The easiest way to fix this, is to return the user in the first .then callback, to pass it to the second:
Auth.signIn(this.state.emailAddress, this.state.password)
  .then(user => {
    // Triggers a setstate here:
    this.setState({ isLoading: false, user });
    return user;
  }).then((user) => {
    // this.state.user is not defined at this point
    Auth.changePassword(user, 'P@ssw0rd!', 'NewP@ssw0rd!');
  }).catch(err => {
    this.setState({ isLoading: false, errorMessage: err.message })
});

Personally, I think it would look a lot nicer entirely in async/await:
try {
    const user = await Auth.signIn(this.state.emailAddress, this.state.password);

    this.setState({ isLoading: false, user });

    await Auth.changePassword(user, 'P@ssw0rd!', 'NewP@ssw0rd!');
} catch (err) {
    this.setState({ isLoading: false, errorMessage: err.message })
}

Comment: I probably shouldn't have placed it in the chaining. I'm not really doing that in practice. When I save the response from Signin and pass it to the changePassword I get the localstorage error. I completely agree it should be what is returned from Signin, that's why I'm confused. I'm wondering if there is a config issue setting up Amplify that normally would place this info in localStorage
Comment: Looking at [this issue](https://github.com/aws-amplify/amplify-js/issues/1853) @JonHarding, could it be "You guys need to use the `completeNewPassword` method instead of `changePassword`. This will actually complete the auth challenge presented by the API."?
Comment: I haven't been able to revisit this for a while. Did you get the bounty points?
Comment: Nope, expired this morning with no winning bounty @JonHarding

Persist AWS Cognito User with Amplify


Pytorch: using CUDA prevents optimization from working

Question: I have a very simple optimization: a straight line. Here is the code:
use_gpu = torch.cuda.is_available()
learning_rate = 0.05
loss_function = nn.MSELoss()

train_inputs = torch.FloatTensor([1,2,3,4,5,6]).T.unsqueeze(0)
y_truth = torch.FloatTensor([10, 15, 20, 25, 30, 35]).unsqueeze(0)

W = torch.nn.Parameter(torch.rand(1), requires_grad=True)
b = torch.nn.Parameter(torch.rand(1), requires_grad=True)
optimizer = optim.Adam([b, W], lr=learning_rate)

# if use_gpu:
#     y_truth = y_truth.cuda()
#     W = W.cuda()
#     b = b.cuda()
#     train_inputs = train_inputs.cuda()

for epoch in range(1000):
    optimizer.zero_grad()
    y_preds = b + W * train_inputs
    loss = loss_function(y_truth, y_preds)
    loss.backward()
    optimizer.step()

    if epoch % 100 == 0:
        print(loss.data, W.data, b.data)

That code works fine if I do not put the data on the GPU. If I uncomment the if use_gpu bloc, the code runs, but does not minimize anything and the variables do not update.
I would expect the code to work similarly on the GPU or not. Any idea what is happening?
Thanks!
Answer:
Any idea what is happening?

Yes, the parameters you are training, W and b stayed on the host (CPU).
When you did
W = W.cuda()
b = b.cuda()

you just chose to ignore the actual parameters being optimized.

If you wish to use the GPU for this, you could try:
W = torch.nn.Parameter(torch.rand(1).cuda())
b = torch.nn.Parameter(torch.rand(1).cuda())

instead.
Comment: Ok, but when I move the optimizer definition passed the `is_gpu` block, I have this error:
`ValueError: can't optimize a non-leaf Tensor`
Comment: @Damien see the edit
Comment: Ah! The cuda declaration had to be inside `torch.nn.Parameter`. Ok, got it. Thanks for the help!


High load on Xen guests

Question: We're facing a weird issue with a freshly installed Xen (4.2) system.
The server is an Intel SR1690WB equipped with 4x1Tb HDD and with a RS2BL040 RAID card which configured to use RAID10.
The problem is that any newly spawned paravirtualized guest OS (Debian Squeeze) is working with very high load (70-80% use of CPU, mostly caused by events/0 or events/1) no matter what they're doing (serving a dynamic page, or just simply downloading an iso file).
Each guest configured to use 2 CPU cores and 4gb RAM.
Just hoping there's some misconfiguration on the Dom0, but what can cause these terrible loads?
Please let me know if i can clarify my question.
Comment: How much of that "CPU load" is actually iowait?
Comment: @ErikA iostat gives me 0.09 %iowait.
Answer: Fortunately the problem was found in our configuration.
After pinning a CPU core to Dom0 (instead of starting with the nosmp parameter) in grub options with
GRUB_CMDLINE_XEN_DEFAULT="dom0_mem=1024M dom0_max_vcpus=1 dom0_vcpus_pin"
All of the guest OS's are running healthy and fast. :)

High load on Xen guests


Nome dinâmico de componente Delphi

Question: Em jQuery conseguimos fazer referencia a um elemento da forma abaixo:
var tipo = "B";
$("#campoTipo"+tipo).val("Teste");

que seria o mesmo que:
$("#campoTipoB").val("Teste");

Preciso em Delphi, desabilitar alguns botões que dependem de uma Query
procedure TFormCupom.BitBtn3Click(Sender: TObject);
var
ponteiro: Integer;
painel: TPanel;
begin
 DM.FDConexao.Connected := true;
 ponteiro := 0;
 with DM.FDQ_Recentes do
 begin
  close;
  sql.clear;
  sql.add('SELECT * FROM rotativo');
  open;
  First; // primeiro
  while not eof do
   begin
   inc(ponteiro);
   painel := FindComponent('Pn' + IntToStr(ponteiro)) as TPanel;
    if painel <> nil then
      painel.Visible := false;
      Next; // proximo
    end;
   end;
end;

Comment: Não consegui entender o porque da consulta ao banco de dados. O código não utiliza nenhum dado da query. Para saber porque o código não está funcionando é preciso saber como os TPanel foram criados e nomeados. O FindComponent retornará a referência ao Panel apenas se for o Owner do mesmo, e se Panel.Name estiver corretamente especificado.
Comment: Ricardo, os Panel são criados em tempo de design e ficam invisíveis. De acordo com a query eles ficarão visíveis ou não.
Comment: O nome de cada TPanel foi atribuído no Object Inspector (Pn1, Pn2, ...)? Quantos Panels há no form?
Comment: Sim. No Object Inspetor. Há vários mas os que preciso manipular são 7. Pn1... Pn7
Comment: Ok. E o que vc lê da query para determinar qual panel será ativado?
Comment: Na verdade a cada laço ativará o Panel correspondente. Ex. var ponteiro = 1 Pn1 fica visível. Eu usarei os dados dos campos para popular Label's que tem dentro dos Panel.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/66362/discussion-between-ricardo-alves-carvalho-and-ezequiel-tavares).
Comment: Tentei usar o chat, mas não consegui. Eu fiz um teste assim e funcionou:procedure TForm2.Button1Click(Sender: TObject);
var
  panel: TPanel;
  ponteiro: integer;
begin
  for ponteiro := 1 to 5 do
  begin
    panel := FindComponent('Pn' + IntToStr(ponteiro)) as TPanel;
    if Assigned(panel) then
      panel.Visible := True;
  end;
end;
Comment: Assim que chegar em casa testo e volto aqui
Answer: Assim você consegue pegar o elemento utilizando uma string, como no jquery:
var
painel: TPanel;
painel := FindComponent('Pn' + IntToStr(ponteiro)) as TPanel;
if painel <> nil then
    painel.Visible := not painel.Visible;

Comment: Deu um Exception
Comment: Você esta testando? É para conferir o código? Se o elemento que você quer pegar for um TPanel acredito que vá funcionar, para você fazer os teste de forma mais efetiva, coloque uma string de forma manual para pegar apenas 1 elemento, assim você já descarta qualquer outro problema que possa acontecer no while.
Comment: Exatamente é TPanel, estou testando para desabilitar e mesmo colocando manualmente da o erro.
Comment: Qual é a Exception?
Comment: Exception class $C0000005 with message 'c0000005 ACCESS_VIOLATION'.
Comment: Fiz uma alteração na resposta utilizando painel, olhe se vai funcionar desta forma.
Comment: Agora não dá a exceção mas nao deixa invisivel o Panel
Comment: Se você trocar not painel.Visible; por False, volta a exceção?
Comment: troquei e nao voltou a exceção.
Comment: Mas depois da alteração, funcionou?
Comment: Não desabilitou os Panel e não deu a exceção
Comment: Ele não esta entrando no 'if painel <> nil then', consequentemente ele não esta encontrando o elemento, e a variável painel esta nula, verifique se o nome é realmente 'Fn' alguma coisa do painel.
Comment: Os nomes são Pn1, Pn2, ... Pn7 . Estava olhando aqui, eles estão dentro de outro Panel, sera que tem algo a ver?
Comment: Eu acredito que não vá fazer diferença estando em outro painel, até porque o FindComponent simplesmente pega o elemento usando uma string, já vi esta forma de usar também TPanel(FindComponent('Pn' + IntToStr(ponteiro)), mas quando vi a pessoa esta criando o elemento, eu não estou entendo porque ele não esta conseguindo pegar, o FindComponent faz parte do TComponent que provavelmente já foi importado, já que você utiliza outros elementos.
Comment: Atualizei a pergunta com o codigo que tenho até o momento.
Comment: Tenta só mais uma coisinha, estava lendo aqui tenta desta forma: painelExterno.FindComponent(...
Comment: painel := Panel2.FindComponent('Pn' + IntToStr(ponteiro)) as TPanel;             nada feito
Comment: Como esse panel é criado? Ex: panel := TPanel.Create(Self) / TPanel.Create(nil) / TPanel.Create(Application) ???
Comment: Ele é inserido em tempo de design. E ficará visível dinamicamente
Answer: Fiz um teste com esse código e funcionou:

procedure TForm2.Button1Click(Sender: TObject);
var
  panel: TPanel;
  ponteiro: integer;
begin
  for ponteiro := 1 to 5 do
  begin
    panel := FindComponent('Pn' + IntToStr(ponteiro)) as TPanel;
    if Assigned(panel) then
      panel.Visible := True;
  end;
end;

Um possível problema seria se os panels não tivessem a propriedade name setadas como esperado (diferente da propriedade caption).

Nome dinâmico de componente Delphi


How to change HTML output of main menu

Question: When I output the main menu this is the html that gets generated:

Home

Page

page

However I'd like to completely restructure the menu like this:

                    SIGN UP
                    LOGIN
                    <a class="main-nav__button animate grid__item xl--1-5 l--1-5 sp s--tbp t--tbp" href="<?php echo $front_page; ?>">HOME
                    LINK 1
                    LINK 2
                    LINK 3
                    LINK 4

How can I change the html output of the menu as well as the links inside?
Ideally I'd like to output any menus as a  element and be able to pass classes and an id to each one, the same also goes for the links inside.
Also the first two links in the menu are login and signup buttons which only display at certain screen sizes and have completely different classes to the rest of the menu links. Is this also possible to do?
I have tried altering the theme_menu_tree and theme_menu_link functions but am having no luck as I am somewhat of a beginner in PHP and Drupal.
Answer: Most likely that your theme renders them menu either in theme_preprocess_page() in its template.php and passing it page.tpl.php. That's how Garland does it:
https://api.drupal.org/api/drupal/themes%21garland%21template.php/function/garland_preprocess_page/7
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_links/7
Given your question, you're most likely going to end up with a custom theme, which is normal for most sites. The best way to tackle this is to change the logic in preprocess_page to set it up how you like.
That's more sustainable and specific than altering or overriding theme_links() globally in module-space.
Answer: Instead of trying to alter the html of the main menu the theme prints out for you, it could be easier to disable the main menu from the theme settings and use the Menu block module for rendering the menu, and Menu attributes module to add some additional attributes such as ids, classes, styles etc. to menu items. Those extra links, sign up and login, you can create at menu configuration itself at admin/structure/menu/manage/main-menu/add.
This way ýou can have high quality html with all the necessary ids and classes you'll ever need for making the main menu look what you want. You can also assign the menu block to any region you want.
https://drupal.org/project/menu_block
https://drupal.org/project/menu_attributes
Comment: I think this is the better method. Messing about with `template.php` and hacking the way menus render is just horrible, and something I've done countless times on Drupal sites. It's just more effort than it's worth, and using contrib modules that render the menu in their own way is much more flexible and easy to use. +1
Answer: Although I'm sure the  answers posted are both great solutions I couldn't manage to get to grips with either. My solution was to create a custom links__system_main_menu function for my theme like this:
function mytheme_links__system_main_menu($variables) {
$site_frontpage = variable_get('site_frontpage', 'node');
  $html = "\n";
  foreach ($variables['links'] as $link) {
      if($link['href'] == '<front>') {
        $html .= "" .$link['title'] ."";
      }
      else {
        $html .= "" .$link['title'] ."";
      }
  }
  $html .= "\n";

  return $html;
}

The separate rule for the front page link was due to receiving <front> in the href of the a tag normally.
One thing I couldn't do however was pass classes through to the function. from here in my page template:
print theme('links__system_main_menu', array('links' => $main_menu, 'heading' => t('Main menu')));

How to change HTML output of main menu


Create list from comma separated string

Question: I want to create a list from a list of items, where some of the items include values separated by commas. In other words, from
['a, b', 'c', 'd, e']
achieve
[['a', 'c', 'd'], ['a', 'c', 'e'], ['b', 'c', 'd'], ['b', 'c', 'e']]
I tried iterating over each item in nested loops, but the comma separation seems to be an issue.
Thanks in advance!
Comment: Try the split (',') method
Comment: It's seems like you have to divide your problem to 2 steps (which both have answers here): 1) convert your list of strings to a nested list of letters ([how do you split a string to create nested list?](https://stackoverflow.com/questions/7680729/how-do-you-split-a-string-to-create-nested-list)) 2) Then get the combinations from this nested list ([All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists))
Comment: Please update the question to show the code you've tried, it's output and *exactly* where you are stuck.
Answer: To tackle the problem of the comma separation we can split each string in the list.
data = ['a, b', 'c', 'd, e']
print([value.split(',') for value in data])

This gives us ['a', ' b'], ['c'], ['d', ' e']]
To get rid of those extra whitespaces we can modify the function by using map to apply str.strip to each resulting element of the inner list.
data = ['a, b', 'c', 'd, e']
print([list(map(str.strip, value.split(','))) for value in data])

The result is [['a', 'b'], ['c'], ['d', 'e']]
Now we can use itertools.product for the final combinations.
import itertools
data = ['a, b', 'c', 'd, e']
data_normalized = [list(map(str.strip, value.split(','))) for value in data]
print(list(itertools.product(*data_normalized)))

The result is [('a', 'c', 'd'), ('a', 'c', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e')].
Comment: Was trying to work this one out myself - thanks for introducing `product`. Learned something new today!

Create list from comma separated string


Evaluate the$\int_0^1\int_{\sin^{-1} y}^{\pi/2} \cos x\sqrt{1+\cos^2 x}\,dxdy$ and $\int_0^2\int_0^1\int_y^1 \sinh(z^2)\,dzdydx$

Question:

Evaluate the following integrals:
  \begin{gather}
\int_0^1\int_{\sin^{-1} y}^{\pi/2} \cos x\sqrt{1+\cos^2 x}\,dxdy;\\
\int_0^2\int_0^1\int_y^1 \sinh(z^2)\,dzdydx
\end{gather}

I tried doing integration by parts, got nowhere as nothing seems to reduce. I tried converting $\cos(x)^2$ into $1-\sin(x)^2$ and u-sub, but ended up with $\sqrt{2-u^2}$. Again stuck.
Know the hyperbolic equivalents $\sinh x = \frac{e^x-e^{-x}}{2}$, and evaluate the integral with $x=z^2$.

Help with number 1? Also maybe links to how to deal with these types of integrals?
Comment: Please don't post images, especially low quality ones. Please use [MathJax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) instead and type images out.
Comment: Got it. Wondered what everyone was using.
Answer: Help with number 1?
Hint. You are on the right track. To evaluate
$$
\int \sqrt{2-u^2}du
$$ one may use the change of variable $u=\sqrt{2}\cdot \sin t$ obtaining
$$
\begin{align}
\int \sqrt{2-u^2}du&=2\int \cos^2 t \:dt
\\&=2\int \left(\frac12+\frac{\cos (2t)}2 \right)dt
\\&=\int \left(1+\cos (2t) \right)dt
\\&=t+\frac{\sin (2t)}2
\\&=t+\sin t \cdot \cos t
\\&=\arcsin\left(\frac{u}{\sqrt{2}}\right)+\frac{1}{2}u \sqrt{2-u^2}.
\end{align}
$$ Thus
$$
\begin{align}
\int_{\arcsin y}^{\pi/2}\cos x \cdot \sqrt{1+\cos^2 x}\:dx&=\int_{\arcsin y}^{\pi/2}\cos x \cdot \sqrt{2-\sin^2 x}\:dx
\\\\&=\int_{y}^{1}\sqrt{2-u^2 }\:du
\\\\&=\frac12+\frac{\pi}4-\frac12\cdot y \sqrt{2-y^2}-\arcsin\left(\frac{y}{\sqrt{2}}\right)
\end{align}
$$ Can you finish it?
Comment: Perfect! Thanks! Easier than I thought!
Answer: The trick for integral number 2 is to switch the order of integration as integrating with respect to y is much easier than with respect to z.
$$\int_{0}^{1} \int_{y}^{1} sinh(z^2) dz dy = \int_{0}^{1} \int_{0}^{z} sinh(z^2) dy dz$$
Now evaluating the inner integral is no problem and the result is
$$\int_{0}^{1} z sinh(z^2) dz$$
Now substitute $u = z^2$ to finish off the problem.
Answer: Regarding the first integral there is also another quicker solution strategy applying differently the Fubini's theorem. Indeed, the domain of integration can also be expressed as the region of the plane given by
$$
\Omega=\{(x,y)\in\mathbb{R}^2\;:\; y\in[0,\sin x]\;\forall x\in[0,2\pi]\}.
$$
Then, we have
\begin{align}
     \int^{1}_{0}\int^{\pi/2}_{\arcsin y} \cos x \sqrt{1 + \cos^2 x}\, dx\, dy
     & =\int^{\pi/2}_{0}\int^{\sin x}_{0} \cos x \sqrt{1 + \cos^2 x}\, dx\,dy
     \\
&
=\int^{\pi/2}_{0}\bigg(\int^{\sin x}_{0}\,dy \bigg)\cos x \sqrt{1 + \cos^2 x}\, dx
\\
&
=\int^{\pi/2}_{0}\underbrace{\sin x\cos x \sqrt{1 + \cos^2 x}}_{=\,\frac{d}{dx}\big(-\frac{1}{3}(1+\cos^2x)^{3/2}\big)}\; dx
\\
&
 =\Big[-\frac{1}{3}(1+\cos^2x)^{3/2}\Big]^{\frac{\pi}{2}}_0
\\
&=\frac{1}{3}\Big(2^{\frac{3}{2}}-1\Big).
&
\end{align}