Find values for whom the equality is true

Question: The equality
$$
\arctan\left(a\right) + \arctan\left(b\right) =
\arctan\left(a + b \over 1 - ab\right)
$$
takes place if and only if $a$ and $b$ are ?. The answer is $ab < 1$.
I tried to form a function
$\mathrm{f}:\mathbb{R} \to \left[-\frac{\pi}{2}, \frac{\pi}{2}\right]$, where $\mathrm{f}\left(x\right) =\arctan\left(x\right) + \arctan\left(b\right) -\arctan\left(x + b \over 1 - xb\,\right)$ where $b \in \mathbb{R}$.
I have found that the derivative of $\,\mathrm{f}$ is equal to $0$ for all
$x \in \mathbb{R}$. Is that of any help ?. I know that would mean that the function is constant but i don't really know if that gives any clue to finding the values of $a$ and $b$.
Comment: See my answer here: http://math.stackexchange.com/questions/523625/showing-arctan-frac23-frac12-arctan-frac125
Comment: @labbhattacharjee I know that's the answer, i just wonder if there is a way of proving it basing on my method.
Comment: Consider that $\arctan(a)=\text{Im}\log(1+ia)$. For which couples $z_1,z_2$ of complex numbers in the line $\text{Re}=1$ we may state that $\log(z_1 z_2)=\log(z_1)+\log(z_2)$, with $\log$ being the principal branch of the logarithmic function?
Comment: @JackD'aurizio I don't really understand what you mean here
Comment: @Liviu: an arctangent is the argument of a complex number of the form $(1+ir)$. So it is enough to understand what happens when we multiply two complex numbers with such a form, in particular when we stay in the right half plane ($\text{Re}(z)>0$).
Answer: Your attempt is quite good, but you forget that the function $f$ is only defined for $x\ne b^{-1}$, assuming $b\ne0$.
If $b=0$ it is easy, because in this case the identity holds for every $a$. Thus assume $b\ne0$.
The derivative of $f$ is indeed $0$, so we can say that $f$ is constant on $(-\infty,b^{-1})$ and on $(b^{-1},\infty)$. These two constants may be different.
Indeed,
$$
\lim_{x\to-\infty}f(x)=-\frac{\pi}{2}+\arctan(b)+\arctan(b^{-1})
$$
and
$$
\lim_{x\to\infty}f(x)=\frac{\pi}{2}+\arctan(b)+\arctan(b^{-1})
$$
If $b<0$ we have
$$
\arctan(b)+\arctan(b^{-1})=-\frac{\pi}{2}
$$
and if $b>0$ we have
$$
\arctan(b)+\arctan(b^{-1})=\frac{\pi}{2}
$$
If $b<0$, the function $f$ is identically $0$ on $(b^{-1},\infty)$, that is, for $x>b^{-1}$, which is the same as $xb<1$. It is not identically zero for $xb>1$.
If $b>0$, the function $f$ is identically $0$ on $(-\infty,b^{-1})$, that is, for $x<b^{-1}$, which is the same as $xb<1$. It is not identically zero for $xb>1$.
So, independently on $b$, we have that the given identity holds for $ab<1$ (including when $b=0$) and not for $ab>1$.
Answer: If $r$ is a real number,
$$ 1+ir = \sqrt{1+r^2} \exp\left(i\arctan r\right) $$
where $r$ belongs to the range $\left(-\frac{\pi}{2},\frac{\pi}{2}\right)$. If $a$ and $b$ are two real numbers,
$$ (1+ia)(1+ib) = (1-ab)+i(a+b) = \sqrt{1+a^2}\sqrt{1+b^2}\exp\left[i\left(\arctan a+\arctan b\right)\right].$$
If $ab<1$, $(1+ia)(1+ib)$ is a point in the right half-plane, so the argument of $(1+ia)(1+ib)=(1-ab)+i(a+b)$ is the same as the argument of
$$ 1+i\frac{a+b}{1-ab} $$
and $\arctan(a)+\arctan(b)=\arctan\frac{a+b}{1-ab}$ follows. If $ab>1$, then $(1+ia)(1+ib)$ is a point in the left half-plane, and in such a case
$$ \arctan(a)+\arctan(b) = \color{red}{\pm\pi}+\arctan\frac{a+b}{1-ab}.$$
If $ab=1$, then $(1+ia)(1+ib)$ is a point on the imaginary axis, hence $\arctan(a)+\arctan(b)$ is either $\frac{\pi}{2}$ or $-\frac{\pi}{2}$: in any case, not a value of the arctangent function.


"Node Recommendation" Module alternatives

Question: I what hoping to use the Node Recommendation module for drupal 6, but after testing it for a while I have come to realize that this particular module has to many issues.
http://drupal.org/project/noderecommendation
The idea of the module is excellent! give node recommendations based on related taxonomy terms and content types.
Are there any alternatives that are under active development and are stable enough that do something similar?
Thank you.
Answer: There are two excellent modules, both compatible with Drupal versions 6 and 7:

If you want to display similar nodes calculated by the actual node content, try Similar entries
If you want to display similar nodes calculated by some sort of taxonomy setup, try Similar By Terms

There's also Relevant Content, a module which allows you to configure the recommended nodes based on many different things, with different block configurations and stuff for dealing with CCK. I haven't used it, but I've heard it's quite good.
Comment: Thank you for your detailed answer! I think we will go with Relevant Content as it seems to fit our needs better than Similar entries or Similar By Terms. It was also super easy to get up and running.
Comment: Happy to help. Cheers!
Answer: May be relatedcontent. . But I prefer Views for this as more flexible tools.


Windows form takes time to respond

Question: I'm building a pretty big Winforms application. Everything worked fine, but in the past two days I'm have problems with times. For example, if I am running a loop that opens 8 tabs and creates a webbrowser in each, it takes it some time. The UI is kind of unresponsive while the function is running, but the big problem isn't in the creating.
I have a button that responsible for removing all the things I don't need from the UI(i.e. resetting it to the normal state). It just takes a huge time when there are about 10 tabs open. I measured the time and the time it takes the code to execute is about 1-1.2 seconds, but the time it takes to the UI to get responsive and preform everything I did is a lot more, about 10 seconds.
here is a code example:
private void killGUI()
{
  DateTime a = DateTime.Now;
  TimeSpan b;
  this.SuspendLayout();
  //tabPages.RemoveAll(TabPage);
  tabPages.Clear();
  if (tabControl1.TabPages.Count > 1)
  {
      //MessageBox.Show("" + tabControl1.TabPages.Count);
      //DateTime a = DateTime.Now;
      /*while (tabControl1.TabPages.Count != 1)
      {
          //int i = 1;
          foreach (TabPage tab in tabControl1.TabPages)
          {
              if (tab.Name != "helpPanel")
              {
                  tabControl1.TabPages.Remove(tab);
                  tab.Dispose();
              }

          }
      }*/
      while (tabControl1.TabPages.Count > 1)
      {
        Application.DoEvents();
        TabPage t = tabControl1.TabPages[1];
        tabControl1.TabPages.RemoveAt(1);
        t.Dispose();
      }
      //TimeSpan v = DateTime.Now.Subtract(a);
      //MessageBox.Show(""+v.Milliseconds);
  }
  ///////
  b = DateTime.Now.Subtract(a);
  MessageBox.Show("REMOVING ALL TABS:" + a.Millisecond);
  a = DateTime.Now;
  ////////
  questions.ElementAt(0).richy.Dispose();
  questions.ElementAt(0).createNewCom.Dispose();
  //questions.ElementAt(questions.Count - 1).Name.Dispose();
  for (int i = 0; i < questions.ElementAt(questions.Count - 1).comments.Count; i++)
  {
    Application.DoEvents();
    if (questions.ElementAt(0).comments.ElementAt(i).texty != null)
        questions.ElementAt(0).comments.ElementAt(i).texty.Dispose();
    if (questions.ElementAt(0).comments.ElementAt(i).cButton != null)
        questions.ElementAt(0).comments.ElementAt(i).cButton.Dispose();
    Application.DoEvents();
  }
  /////
  b = DateTime.Now.Subtract(a);
  MessageBox.Show("REMOVING THIS QUESTION:" + a.Millisecond);
  a = DateTime.Now;
  /////
  panel1.Visible = false;
  while (panel2.Controls.Count != 0)
  {
    Application.DoEvents();
    panel2.Controls.RemoveAt(0);
  }

  panel2.Visible = false;
  backButton.Visible = false;
  forwardButton.Visible = false;
  //placePanel.Dispose();
  //urgencyPanel.Dispose();
  //categoriesPanel.Controls.Clear();
  //categoriesPanel.Dispose();
  //((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("placePanel", false)[0]).Dispose();
  ((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("categoriesPanel", false)[0]).Dispose();
  ((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("urgencyPanel", false)[0]).Dispose();
  ((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("placePanel", false)[0]).Dispose();

  //Controls[] con=tabControl1.Controls.Find("HelpPanel",false);
  newQuestionTextBox.Clear();
  browsers.Clear();
  panels.Clear();
  buttons.Clear();
  questions.RemoveAt(0);
  finalTuid = "";
  this.ResumeLayout();
  foreach (Control cl in helpPanel.Controls)
  {
    Application.DoEvents();
    if (cl.Name == "categoriesPanel" || cl.Name == "urgencyPanel" || cl.Name == "placePanel")
    {
      //WTF that shouldnt happen-i cant get this.
      //MessageBox.Show("!!!");
      cl.Dispose();
    }
  }
  foreach (Control cl in helpPanel.Controls)
  {
    Application.DoEvents();
    if (cl.Name == "categoriesPanel" || cl.Name == "urgencyPanel" || cl.Name == "placePanel")
    {
      //FFFFFFFFFFFUUUUUUUUUUUUUUUUUUU
      //MessageBox.Show("!!!!!!!!");
      cl.Dispose();
    }
  }
  /////
  b = DateTime.Now.Subtract(a);
  MessageBox.Show("ALL ELSE:" + a.Millisecond);
  ///////
  this.ResumeLayout();
}

also another probelm is if u can see:
((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("categoriesPanel", false)[0]).Dispose();
((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("urgencyPanel", false)[0]).Dispose();
((Panel)((TabPage)tabControl1.Controls.Find("helpPanel", false)[0]).Controls.Find("placePanel", false)[0]).Dispose();

This should remove three panels from the main panel, but it just doesn't work. I don't know why, but only after running the two loops below it removes the panels and just one loop isn't enough.
thanks so much in advance :)
Comment: We had a question earlier this week about a monstrous UI with 1500 questions.  Is this it?
Answer: Is there a reason why you don't have a reference to the help panel or the 3 other controls you want to dispose that exist in that panel? It seems really inefficient to have to iterate over the list of controls in your GUI (you said you had lots of tabs & controls) looking for these 3 specific controls. At bare minimum, you should cache the result of the helpPanel search as the next two lines are repeating the same search process that just occurred. The following loops can be solved with the same solution.
Wait, those two loops are iterating over helpPanel.Controls. So you already have a reference to the helpPanel and just not using it in the earlier steps?
Comment: i have a reference to all of the panels i want to dispose(i.e. categoriesPanel,urgencyPanel,placePanel) but when i use for example `code` placePanel.Dispose(); `code` it for some reason wont dispose it- realy-only after the two loops it disposes it. my main problem that after testing the time it takes the code about 1 second to run  - but until the user interface preforms what i want it takes like ten seconds and i cant get why.

Windows form takes time to respond


Does the function have derivatives at $x=0$

Question: derivatives
Hey, in this question I succeeded the first part.
Part B:
I fail to show that either have no derivative at the point $x = 0$.
I try on the definition of derivative and lodged.
Part C:
I believe I can understand with part B.
thank you!
Comment: Welcome to MathSE!
See [this guide](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for how to mark up math nicely on this site.
Answer: You were asked whether or not $f(x)$ has a derivative at $x=0$, and if so, compute.
$f(x)$ at $x=0$ is $0$ as stated by the problem, and it does in fact have a derivative. The derivative of $f(x)$ at $x=0$ is $0$, which is a constant.
The derivative of any constant is $0$.
Therefore, the derivative of $f(x)$ at $x=0$ is $0$.


hide div until all background images have loaded

Question: Is there a way to wait until all background images have loaded before some code is executed?  I know this works for one image but how can I adapt it for various images?
var firstBackgroundImage = new Image();
                firstBackgroundImage.onload = function () {
                        $('#main-slider').animate({opacity:1}),600;

            };
            firstBackgroundImage.src = "http://www.domain.com/img/iphone.png";

HTML

CSS
#main-slider{
   opacity:0;
}

Thanks!
Comment: All images on the page or a certain amount?
Comment: just a few specific background images in this case.
Answer: Try:
$(window).load(function() {
    // this code gets executed when all content of the page (including images) is loaded
});

Answer: If you want it for complete page. I mean a loading image will be displayed hiding your main div until every component is being loaded completely..
 $(document).ready(function () {
            // calculate height
            var screen_ht = jQuery(window).height();
            var preloader_ht = 5;
            var padding = (screen_ht / 5) - preloader_ht;
            jQuery("#preloader").css("padding-top", padding + "px");

            // loading animation using script

            function anim() {
                jQuery("#preloader_image").animate({ left: '1px' }, 2000,
                function () {
                    jQuery("#preloader_image"), animate({ left: '1px' }, 2000);
                }
                );
            }
            //anim();
        });
    function hide_preloader() {
    // To apply Fade Out Effect to the Preloader
    jQuery("#preloader").fadeOut(1000);
    }
    </script>

Comment: how does that work exactly? An especially for various background images? Could the code I used in the OP not be adapted?


qmail to zimbra migration

Question: I am not a mail server admin, however I've been given the task to migrate our company's current qmail server (running on Ubuntu 8.0) to a new Redhat Enterprise Linux server (RHEL 6.2).
After doing some research it seems that qmail is no longer being supported so I was thinking about installing Zimbra on the new server and then migrating the qmail users/mail boxes over to the zimbra server.
The current qmail server has 500 user accounts does not have any virtual domains nor aliases created.
We use courier-imap for user access with maildir as the mailbox format, and the mail accounts are created through an LDAP server.
My question is: What would be the best approach of getting all of the qmail server stuff over to the new zimbra server?.
Do I just need to copy everything and then change the MX record to point to the new server after everything has copied successfully?
Answer: Hire someone to do this for you.
Really, I'm serious.
Mail systems are notoriously complex and fragile beasts. You admit that you are not a "mail server admin". It would be one thing if you were migrating to a similar system, but in this case, you're migrating to a completely different environment with a lot of moving parts. You really, really, don't want to do this yourself.
I know this probably isn't the answer you're looking for, but it is the best answer for your situation.
Comment: Erika what if I was to migrate to another qmail server running in red-hat 6 would that make the task more doable on my part?
Comment: @Miguel Get rid of qmail. Run as far and as fast as you can from that disaster.
Answer: The most reasonable way to migrate mailbox data in this case would be to use periodic synchronizations of the user accounts. I've done this between dissimilar mail systems using the Imapsync utility.
Since you have a separate server, this is something you can test on a small scale and allow specific users to try.
As stated I'm the earlier comments, there's more involved to doing a mail migration, so it may make sense to bring in an outside resource to manage the details.
Comment: +1 for `imapsync`-ing between the hosts for a live migration - this can also be used in the process I outlined (for the "IMAP-copying" bit). The only downside is I'm pretty sure it needs IMAP access (and thus the mail password) to each user's mailbox.
Comment: If you have an account that can see the full IMAP tree, having each user's password is not necessary. But I can't recall how to get that ability. On the new system, a default or dummy password is fine until you let users start accessing it.
Answer: Your essential understanding of what needs to be done (copy everything over, make sure the accounts are all set up correctly, then swap the boxes) is correct, though I would advise swapping the IP address rather than the MX records (so you don't have to wait for DNS caches around the internet to figure out that the MX record has changed).
That said, it's a delicate process that requires you to do several things, and get them all right.
I've outlined one possible route to a migration below, there are others which will work equally well

Disconnect both mail servers from the internet
You can't be receiving mail during the migration, or you will lose things -- Connect both machines to a migration network for the time being.
It helps if you have a reliable secondary MX server that can catch mail until you're done.
Clone your users
Check the Zimbra documentation to see if they have any advice here, but I think you'll have to create them all manually.
Copy everyone's mail from the old server to the new server
If Zimbra uses maildir format (it probably does) and courier-imap as its IMAP server you can just tar up each maildir and extract them into the appropriate places on the new server.
You can also do this over the network (IMAP copying from the old server to the new one) but that will be substantially slower.
Make sure you can see the mail you just copied
Log in as yourself, and get a few other users to log in and test too.
This means connecting some machines with IMAP clients to your migration network.
Make sure you can receive mail
This can be as simple as telnetting in on port 25 and having a quick SMTP conversation to send yourself a test message.  You want to be sure that you can receive mail before you proceed with...
Put the NEW server on the internet and test it
Give it the IP of the old mail server, and repeat (5) from som external site like GMail.
Also make sure you can send mail through the new server.

If you're unsure about any of the steps above take ErikA's advice and hire someone for a couple of days to do the migration for you.  They will charge you an aggravation fee for dealing with email (probably more for dealing with qmail), but you'll look like an idiot if you break your company's email.
Answer: First of all, congrats on moving away from qmail, it's an ancient nightmare that belongs with dinosaurs.
As for moving to ZCS, there are multiple ways, most of them are described at http://wiki.zimbra.com/wiki/Mail_Migration
My fave is the IMAP migration tool, however, if you're buying Zimbra, definitely get the Zimbra guys to compose a solution for you, instead of experimenting.
If you're going for the free version, you can build a test ZCS server in a VM or a temp box, before you go live.
As for users, Zimbra uses openLDAP internally, so you can either migrate the users over, or get ZCS to connect to the existing openLDAP server.

qmail to zimbra migration


What is the physical significance of the height of the the bell shaped curve in normal distribution?

Question: Hello enthusiasts and explorers!!
Going through the concepts of normal distribution, one can understand that the height and the width of the bell shaped curve in a normal distribution graph tells about the spread of the data, but even going deeper into the concept, I am failing to understand the physical significance or how to verbally term the height of the given parameters in hand. In many of the articles for example the one below:
http://www.stat.yale.edu/Courses/1997-98/101/normal.htm
There is no mention of formal meaning of the height of the graph.
Can anyone provide some insights on the same ?
thanks in advance..
Answer: I agree with the OP that the interpretation of the y-axis of a PDF is quite cryptic. Here's my informal, intuitive take on it, for the real thing refer to proper sources.
It's useful to keep in mind that the y-axis is a density; density, in general, is an amount of something per unit of something else. In the case of a PDF, density could be taken as the expected number of events occurring in a unit of the x-axis (whatever that x happens to be). Since the unit of measurement matters, the y-axis can have values above 1 which is often cause of puzzlement.
The example below could represent the PDF of human height in one sex. It doesn't matter if you measure height in centimetres or metres but the density changes because relatively few people fall in 1-cm interval whereas almost everybody is in a 1-m interval.

(Similarly, I guess, you could measure population density as people per km^2 and find, typically, values greater than 0 or people per m^2 and find values less than 0)
We could then ask the percentage of people falling in the interval 170-171 cm, the answer doesn't change by changing the unit of measurement (R code):
integrate(dnorm, 170, 171, mean= 178, sd= 7)
0.0321063 with absolute error < 3.6e-16

integrate(dnorm, 1.70, 1.71, mean= 1.78, sd= 0.07)
0.0321063 with absolute error < 3.6e-16

~0.03 is the value of the y-axis at ~170 cm on the plot on the left.
Asking for the percentage of people falling in a given 1-metre interval would return ~100% for most sensible intervals.
This is a simulated example from measuring 1 million people and asking the same question, the answer is practically the same as above:
set.seed(1234)
cm <- rnorm(n= 1000000, mean= 178, sd= 7)

# Number of people with height between 170 and 171 cm divided by sample size
length(cm[cm >= 170 & cm < 171])/length(cm)
0.032245

# Using metres
m <- rnorm(n= 1000000, mean= 1.78, sd= 0.07)
length(m[m >= 1.70 & m < 1.71])/length(m)
0.03228

Code for plot:
par(mfrow= c(1,2))
plot(150:210, dnorm(x= 150:210, mean= 178, sd= 7), type= 'l', xlab= 'Height (cm)', ylab= 'Density')
plot(150:210/100, dnorm(x= 150:210/100, mean= 178/100, sd= 7/100), type= 'l', xlab= 'Height (m)', ylab= 'Density')


Mostrar dados agrupados na view

Question: tenho os models departamento e instituição, como se vê a seguir.
public class Institution
{
   public long? InstitutionId { get; set; }
   public string Name { get; set; }
   public string Address { get; set; }
   public virtual ICollection<Department> Departments { get; set; }
}

public class Department
{
   public long? DepartmentId { get; set; }
   public string Name { get; set; }
   public long? InstitutionId { get; set; }
   public Institution Institution { get; set; }
}

Estou tentando mostrar numa view os departamentos agrupados por instituição. Eis o meu controller e o meu service:
//controller
public async Task<IActionResult> DepartmentGroupedByInstitution()
{
   return View(await _departmentService.GetDepartmentGroupedByInstitution());
}

//service
public async Task<List<IGrouping<Institution, Department>>> GetDepartmentGroupedByInstitution()
{
   var result = await _context.Departments.Include(d => d.Institution).OrderBy(d => d.InstitutionId).GroupBy(d => d.Institution).ToListAsync();
   return result;
}

Porém, o seguinte erro acontece:
InvalidOperationException: The LINQ expression 'DbSet<Department>()
.OrderBy(d => d.InstitutionId)
.Join(
inner: DbSet<Institution>(),
outerKeySelector: d => EF.Property<Nullable<long>>(d, "InstitutionId"),
innerKeySelector: i => EF.Property<Nullable<long>>(i, "InstitutionId"),
resultSelector: (o, i) => new TransparentIdentifier<Department, Institution>(
Outer = o,
Inner = i
))
.GroupBy(
keySelector: d => d.Inner,
elementSelector: d => d.Outer)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Alguém, por gentileza, poderia ajudar? Desde já agradeço.
Comment: Você leu a mensagem do erro?
Comment: Boa noite, Leandro. Li sim e até pesquisei algo a respeito. Mas comecei a estudar asp net tem pouco tempo, então ainda estou dando os primeiros passos. Realmente não consegui compreender qual foi o problema.
Answer: Este erro acontece provavelmente por causa da sequência da chamada dos elementos na query.
Tenta trocar isso:
var result = await _context.Departments.Include(d => d.Institution).OrderBy(d => d.InstitutionId).**GroupBy**(d => d.Institution).ToListAsync();

Por isso:
var result = await _context.Departments.Include(d => d.Institution).GroupBy(d => d.Institution).OrderBy(d => d.InstitutionId).ToListAsync();

Mostrar dados agrupados na view


TWIG if/else to filter through templates

Question: I am trying to write a TWIG else/if statement that loops through four different templates based on the number of customers are chosen from a list. So if a designer chooses 1 customer a certain template is used to create that view, and if they choose 3 customers a different template is used.
{% if content.field_featured_customers|length == 1 %}
{% include "node--customer--featured-full.hmtl.twig" with content.field_featured_customers %}
{% elseif content.field_featured_customers|length == 2 %}
{% include "node--customer--featured-split.html.twig" with content.field_featured_customers %}
{% elseif content.field_featured_customers|length == 3 %}
{% include "node--customer--featured-3block.html.twig" with content.field_featured_customers %}
{% else %}
{% include "node--customer--featured-carousel.html.twig" with content.field_featured_customers %}
{% endif %}

This is what I have tried so far, but nothing is rendered. I have created templates for all of the different views I am trying to display. Here is an example for the featured-full.html.twig

{{ content.field_logo }}

{{ content.field_comapny_name }}

{{ content.field_description }}

Learn More

Am I doing something wrong in the if/else statement, do I need to create different views, or is there something in the theme that I need to include?
Comment: You don't need of 'with' keyword. `include` itself pass the active context to new template, 'with' keyword is just if you want to add some template defined var to new template or declare which var will be passed to template with 'only' keyword. http://twig.sensiolabs.org/doc/tags/include.html
Answer: If not rendered at all, for sure, Twig not found your template file.
There is a var that store the base dir of your theme, just use it to define where is your template file.
Twig file:
{% include "#{directory}/templates/node/node--customer--featured-full.hmtl.twig" %}

Comment: while this didn't completely solve my problem, it did get me a lot closer - the file path allowed my template to render, but I had to include a preprocess function to render the field content
Comment: hmm, strange, I have similar situation in one of my templates (used in views instead node), and preprocess function wasn't needed at all. Again if you set any var in one template, you must use 'with' keyword in your include statement, if context itself is enough 'with' keyword is not required.


splitting the text, make the view of text false in textview

Question: i have a text file, that i want to display it's text in the number of text views,that i set their texts in run time.
here is my code, that i use for my program:
while(text.length() > 0)
    {
        text = text.trim();
        int index = text.indexOf("L1");
        int index2 = 0;
        temp = "";
        if(index > -1 && index == 0)
        {
            index2 = text.indexOf("/L1");
            temp = text.substring(index + 2, index2);
            temp.trim();
            t = temp.toCharArray();
            text = text.substring(index2 + 3, text.length());
            index = text.indexOf("\r\n");
            while(index > -1 && index == 0)
            {
                temp += "\r\n";
                text = text.substring(index + 2, text.length());
                index = text.indexOf("\r\n");
            }
            temp = String.valueOf(t);
        }
        else
        {
            index = text.indexOf("L2");
            if(index > -1 && index == 0)
            {
                index2 = text.indexOf("/L2");
                temp = text.substring(index + 2, index2);
                text = text.substring(index2 + 3, text.length());
                index = text.indexOf("\r\n");
                while(index > -1 && index == 0)
                {
                    temp += "\r\n";
                    text = text.substring(index + 2, text.length());
                    index = text.indexOf("\r\n");
                }
            }
            else
            {
                index = text.indexOf("List");
                if(index > -1 && index == 0)
                {
                    index2 = text.indexOf("/List");
                    temp = text.substring(index + 4, index2);
                    text = text.substring(index2 + 5, text.length());
                    index = text.indexOf("\r\n");
                    while(index > -1 && index == 0)
                    {
                        temp += "\r\n";
                        text = text.substring(index + 2, text.length());
                        index = text.indexOf("\r\n");
                    }
                }
                else
                {
                    text = text.trim();
                    index = text.indexOf("Plain");
                    if(index > -1 && index == 0)
                    {
                        index2 = text.indexOf("/Plain");
                        temp = text.substring(index + 5, index2);
                        text = text.substring(index2 + 6, text.length());
                        index = text.indexOf("\r\n");
                        while(index > -1 && index == 0)
                        {
                            temp += "\r\n";
                            text = text.substring(index + 2, text.length());
                            index = text.indexOf("\r\n");
                        }
                    }
                }
            }
        }

    }
    for(int i = 0; i < texts.length; i++)
    {
        TextView tv = new TextView(this);
        tv.setText(Farsi.Convert(texts[i]));
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/naz.ttf");
        tv.setTypeface(font);
        tv.setTextColor(Color.BLACK);
        tv.setGravity(Gravity.RIGHT);
        tv.setPadding(10, 10, 10, 10);
        tv.setLayoutParams(params);
        linearLayout.addView(tv);
    }
    layout.addView(linearLayout);
    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    this.addContentView(layout, p);
}

i use some auxiliary words(such as "L1" and "/L1") for some reasons in text file, that delete them in run time. but, when i run the program, in the output the text that shown in text views, is not in right style, i want to align it to right, but in the output there are some additional text, that aren't in the input text file.
in the 2 images in below, i attach the output with and without the auxiliary words in the input text file.
output with auxiliary words:

output without auxiliary words, in this state, i set the content of layout using, "setContentView" function, and read the whole file instead of split text using auxiliary words index. in this state, the input does not contain the auxiliary words.

what is the problem friends?
thanks
Answer: First of all:use String.split() to split your string.It works like this, if you have a string A,B,C and you use myString.split(,) output will be an array of substrings i.e [A,B,C].But this is useful in your case if you can have the same delimiter ie L1 and L2 will be same.
Second: You can use android:gravity="right" in the textview of your layout.xml. This will resolve the issue of strings being aligned to left.
Comment: thanks for your answer, but i set gravity with the this line : "tv.setGravity(Gravity.RIGHT);", but it does not worked for me! the problem is that, when i use the substring function, and make new text views with these texts, the output will been such the output image in the post


Isomorphism of Groups given by Generators and Defining Equations

Question: I need help proving that $G$ and $G'$ are isomorphic given $G= Z_2 \times Z_2 \times Z_2 $ and $G'=\{e,a,b,c,ab,ac,bc,abc\}$ where $a^2=b^2=c^2=e$ and $(ab)^2=(bc)^2=(ac)^2=e$
Do I need to show that the elements of $Z_2$ apply to the defining equations of G'? For example $(0,1)^2=(1,0)^2=(1,1)^2=(0,0)=e$ and $((0,1)(1,0))^2=((1,0)(1,1))^2=((0,1)(1,1))^2)=(0,0)=e$
Comment: Wouldn't an element of $G$ be $(0,1)^3$, not $(0,1)^2$?
Comment: @JeremyUpsal I think the correct correction is that he means $(0,1,0)^2$ or something (ordered triples instead of ordered pairs).
Comment: @blf Thanks, this is what I meant as well.
Answer: If you can find elements of $G$ that "play the role" of $a$, $b$, $c$, in that they satisfy the defining equations, then that gives you a homomorphism from $G'$ to $G$. Then you just need to show surjectivity.
Comment: I don't see a $d$ in the posted question.
Comment: @coffeemath Thanks! edited.
Comment: I know in the OP problem that $G'$ happens to be commutative (follows from relations). But say $G'$ was just the (nonabelian) group generated by $a,b,c$ with $a^2=b^2=c^2=1$. Then one could find elements in $G$ to map these generators onto, and the map would be also onto if the chosen elements were $(1,0,0),(0,1,0),(0,0,1)$. Then the elements of $G$ would satisfy the defining relations, yet $G$ would not be isomorphic to $G'$.
Comment: @coffeemath but you would need some other relation to specify your group, right?
Comment: I think as soon as generators and relations are specified one automatically has a group. In the nonabelian group $G''$ [using the double prime to distinguish from the $G'$ of the OP] of my comment the element $ab$ has infinite order, and gets mapped to an element of $G$ having of course finite order. I agree one would need more relations if one wanted $G''$ to wind up being isomorphic to the $G$ of OP, but my point was about there being more needed than to map $G''$ to $G$.
Comment: @coffeemath oh of course, I only claimed that this gives you a homomorphism, not an isomorphism.
Answer: Prove that the defining equations of $G'$ uniquely determine a single group up to isomorphism. Then all you have to do is show that those defining equations apply to $G$, and you're done.
You can prove that the defining equations uniquely determine one group by writing out the multiplication table for $G'$. You'll notice that the defining equations allow you to deduce the entire table. Hint: start by proving that $a$, $b$ and $c$ are pairwise commutative. From then on it's smooth sailing.


Fixed point property for projective space

Question: Let K be an algebraically closed field. Is it true that any endomorphism $\mathbb{P}_K^n\to \mathbb{P}_K^n$ has a fixed closed point?
For $K=\mathbb{C}$ the (oriented) topological version is a classical result and the proof uses Lefschetz fixed point theorem.
If it's true for any algebraically closed field, can it also be generalized to arbitrary field or perhaps to any ring?
Comment: I added a proof but deleted it because it assumed $n=1$. It's true for all $n$ though (the point is that the diagonal and the graph of your map have to intersect in $\mathbb{P}^n \times \mathbb{P}^n$) and false for non-algebraically closed fields (e.g. when $n = 1$ and over $\mathbb{F}_2$ just shuffle the only three rational points).
Comment: @hunter that still has a fixed closed point, it's just not a $\Bbb F_2$-rational fixed point.
Comment: @KReiser if he's not asking about rational points the result is the same since you can compute after base change to the algebraic closure
Comment: @hunter I meant any closed point. So how do you prove that those two graphs in $\mathbb{P}^n \times \mathbb{P}^n$ intersect?
Comment: @Kamil there is a sketch of the computation of the Chow ring of that product in Example 1 here. From there you can compute that any two graphs meet. I'll bet there is an easier proof that I don't know, though! http://www.math.columbia.edu/~chaoli/docs/IntersectionTheory.html#sec2
Answer: The Chow ring of $\mathbb{P}^n \times\mathbb{P}^n$ can be written as
$$
\mathrm{CH}^\bullet(\mathbb{P}^n) \cong
\mathbb{Z}[h_1]/h_1^{n+1} \otimes \mathbb{Z}[h_2]/h_2^{n+1}.
$$
The class of the diagonal in it is
$$
[\Delta] = 1 \otimes h_2^n +
h_1 \otimes h_2^{n-1} + \dots + h_1^n \otimes 1.
$$
Similarly, the graph $\Gamma$ of an endomorphism of degree $d$ has the class
$$
[\Gamma] = 1 \otimes h_2^n +
d h_1 \otimes h_2^{n-1} + \dots + d^n h_1^n \otimes 1.
$$
Their intersection product is equal to
$$
[\Delta] \cdot [\Gamma] = d^n + \dots + d + 1.
$$
As it is non-zero, the intersection is nonempty, hence the endomorphism has a fixed point.
Comment: Awesome, thanks a lot!


Circle Geometry Assistance

Question: Two circles $C_1$ and $C_2$ meet at the points $P$ and $Q$.
A circle $C_3$, with centre at point $P$, meets $C_1$ and $C_2$ at points $A$, $B$, $C$ and $D$ respectively.
Prove that $\angle AQD= \angle BQC$.
Answer: Using the inscribed angle theorem,
$$\begin{align}\angle{AQD}&=\angle{AQP}+\angle{DQP}\\&=\angle{ABP}+\angle{DCP}\\&=\angle{BAP}+\angle{CDP}\qquad(\leftarrow \text{$\triangle{PAB},\triangle{PCD}$ are isosceles triangles})\\&=\left(180^\circ-\angle{BQP}\right)+\left(180^\circ-\angle{CQP}\right)\\&=360^\circ-\angle{BQP}-\angle{CQP}\\&=\angle{BQC}\end{align}$$

Circle Geometry Assistance


paypal no shipping address on file

Question: Problem statement: When users pay for an order at paypal, in almost 50% cases(for both verified and unverified paypal users) the transaction slip(for business account) does show shipping address(confirmed address), but for other 50% users it is saying "We have no shipping address on file" even if users enter shipping details on paypal review page.
Using Paypal Express Checkout payment Method.
Currently we are passing NOSHIPPING=1
What should be the parameter for NOSHIPPING ? What could be the problem ?
Please help.
Answer: try not passing that parameter at all
Here is an excerpt from the PayPal's Express Checkout Integration guide  about Shipping address:

Suppressing the Buyer's Shipping Address
You can suppress the display of the buyer's shipping address on the
PayPal pages. You might want to do this in these cases:

You are selling a product or service that does not require shipping.
You prefer to handle addresses completely on your own and do not want
to let buyers choose from their PayPal address book.

To suppress the display of the buyer's shipping address, set the NOSHIPPING parameter to 1
in the call to SetExpressCheckout. No shipping address displays
on Express Checkout pages.

Hope this helps.
Comment: Tested this as of today and it works: I removed both `NOSHIPPING` and the `REQCONFIRMSHIPPING` fields from the `SetExpressCheckout` call.

paypal no shipping address on file


Convert Html or RTF to Markdown or Wiki Compatible syntax?

Question: Is there a .net api that can do this?  I saw Pandoc has a standalone exe that I could wrap but I'd rather not if there is something already out there.  Any suggestions?
Answer: Here's the code I used to wrap pandoc.  I haven't seen any other decent methods so far unfortunately.
public string Convert(string source)
{
    string processName = @"C:\Program Files\Pandoc\bin\pandoc.exe";
    string args = String.Format(@"-r html -t mediawiki");

    ProcessStartInfo psi = new ProcessStartInfo(processName, args);

    psi.RedirectStandardOutput = true;
    psi.RedirectStandardInput = true;

    Process p = new Process();
    p.StartInfo = psi;
    psi.UseShellExecute = false;
    p.Start();

    string outputString = "";
    byte[] inputBuffer = Encoding.UTF8.GetBytes(source);
    p.StandardInput.BaseStream.Write(inputBuffer, 0, inputBuffer.Length);
    p.StandardInput.Close();

    p.WaitForExit(2000);
    using (System.IO.StreamReader sr = new System.IO.StreamReader(
                                           p.StandardOutput.BaseStream))
    {

        outputString = sr.ReadToEnd();
    }

    return outputString;
}

Comment: Two small changes: "ASCIIEncoding.UTF8" should be "Encoding.UTF8", and you can replace "Thread.Sleep(2000)" with "p.WaitForExit(2000)", which will return sooner if the process exits sooner.
Comment: Why `string args = String.Format(@"-r html -t mediawiki");` and not just `string args = "-r html -t mediawiki";`? Is there any intended side effect of String.Format that I'm missing?
Answer: I have created a library Html2Markdown. Usage is very simple.
var markdown = new Converter().Convert(html);

Where html is the string representation of the HTML you wish to convert. I actively support it and happily accept contributions.


Triangulation induces regular CW complex structure

Question: If a topological set is triangulable, dose the triangulation map gives it the regular CW complex structure? From definitions, I see it seems to be, but I am not that sure, for may exist some strange examples.
Really, thanks for any help
Answer: Yes, you are right. You can see it as a consequence of Proposition 5.33 in Lee's book:

Introduction to Topological Manifolds, 2nd ed. Grad. Texts in Math.,
  Springer, 2011.

I quote the proposition:

If $\mathcal{K}$ is a Euclidean simplicial complex, then the
  collection consisting of the interiors of the simplices of
  $\mathcal{K}$ is a regular CW decomposition of $|\mathcal{K}|$ (the
  polyhedron associated to $\mathcal{K}$).


Most efficient way to find indices of common tuples in two very large lists of tuples in python 3?

Question: I have two large lists of tuples: "neg" (length ~40K) and "All" (length ~2M) whose proxies can be downloaded from the following link
ftp://ftp.lrz.de/transfer/List_Intersect/
I would like to search "neg" inside "All" and return the matched indices in "All". I tried the following solution which takes 788.1487 seconds on a fairly powerful pc (see specs below). Moreover, it doesn't retain the correct order.
https://stackoverflow.com/a/39500933/6524326
In fact, the following code does the required job in 202.6451 seconds. Can It be made even faster?
def findTupleIndices(smallList, bigList):
 comList = sorted(set(smallList) & set(bigList), key=smallList.index)
 idx = [bigList.index(x) for x in comList]
 return(idx)

pc specs
Intel(R) Core(TM) i7-5930K CPU @ 3.50GHz, 32GB RAM DDR4-2133 MHz
Answer: Smashingly with temporary hash-table (dict) where tuples of "big list" are keys and their indices - values.
Initial approach stats:
from timeit import timeit

def findTupleIndices(sub_lst, search_lst):
    comList = sorted(set(sub_lst) & set(search_lst), key=sub_lst.index)
    idx = [search_lst.index(x) for x in comList]
    return idx

# sub_lst, search_lst are lists of tuples extracted from `ftp://ftp.lrz.de/transfer/List_Intersect/`

print(timeit('findTupleIndices(sub_lst, search_lst)', 'from __main__ import findTupleIndices, sub_lst, search_lst', number=1000))

The output:
191.43023270001868

New approach stats:
from timeit import timeit

def find_tuple_indices(sub_lst, search_lst):
    pos_dict = dict((t,i) for i, t in enumerate(search_lst))
    return [pos_dict[t] for i, t in enumerate(sub_lst) if t in pos_dict]

# sub_lst, search_lst are lists of tuples extracted from `ftp://ftp.lrz.de/transfer/List_Intersect/`

print(timeit('find_tuple_indices(sub_lst, search_lst)', 'from __main__ import find_tuple_indices, sub_lst, search_lst', number=1000))

The output:
1.4070011030125897

Comment: WOW! I am switching to python


Visual studio 2012: 0 of 1 error: No error message shown

Question: When I try to build my code in VS 2012 I keep on getting build error; and in the error list it says 0 of 1 error; and no error message is shown there. So basically, I am stuck because I can't find where the error is (if there is actually any). I have tried restarting VS; but no help. The code has been working fine; I only modified the code deleting one of the forms.
Has anybody come across such issue?
Comment: Ok, found the problem. It's the error in the Designer.cs files where the events are hooked up with the event handlers. Since I deleted one of the forms I needed to delete one of the click events and event handler hookups. But I would expect the error to be shown in the errorlist as it normally does.
Answer: Most likely your errors are being filtered so you only see warnings or messages.  Here is a link which talks about viewing errors and sorting / filtering them.  Make sure you have Errors selected or just view all 3 categories.


Filtrar um campo conforme o formato do texto

Question: É possível eu filtrar em um determinado campo do mysql a seguinte formatação: (21)2222-2222. Peço a compreensão dos colegas se não fui claro na minha dúvida, pois tive um problema no cadastro do qual a máscara:
$("#telefone").mask("(99)9999-9999"); estava  $("#telefone").mask("(99) 9999-9999"); e isso deu problema aqui.
Comment: Da sim vc quer pegar somente os números que não tem o `9` no inicio?
Answer: Pode filtrar os números com like usando o coringa para um caractere _.
SELECT * FROM tabela WHERE telefone like '(__)____-____'

Relacionado:
Pra que serve o undescore "_" no LIKE do MYSQL?
Comment: @Fox.11 o `%` ser para especificar qualquer quantia de caracteres e o `_` somente um, mais em: [Pra que serve o undescore "_" no LIKE do MYSQL?](http://pt.stackoverflow.com/q/87504/91)
Comment: show... perfeito.. nao conhecia esse tipo de filtro... obrigado ray, funcionou
Comment: não está permitindo dar como resposta correta, só depois de 9 minutos, mas vou voltar pra confirmar ;)


Peer Upgrade command not running

Question: I am trying to build a supply chain blockchain, using a reference from github. I have modified the contents of the chaincode and trying to update the chaincode using the command:
peer upgrade -name of the file

However after I am getting a an error:
Command 'peer' not found, did you mean:

command 'pee' from deb moreutils
command 'peet' from deb pipexec
command 'pear' from deb php-pear
command 'seer' from deb seer
command 'beer' from deb gerstensaft

Try: sudo apt install <deb name>

Please someone help
Answer: There is no such "peer upgrade" command. I suggest you review the official docs that includes step by step on how to perform several tasks. A chincode upgrade it's almost identical to a chaincode deployment as detailed here:
https://hyperledger-fabric.readthedocs.io/fa/latest/deploy_chaincode.html

Peer Upgrade command not running


Successful approaches to the modelization of ''randomness''

Question: If you pick a number $x$ randomly from $[0,100]$, we would naturally say that the probability of $x>50$ is $1/2$, right?
This is because we assumed that randomly meant that the experiment was to pick a point from $[0,100]$ (with numbers equally distributed). But, since $f(r)=r^2$ is a bijection  $[0,10] \rightarrow [0,100]$, we could also pick a number $r$ from $[0,10]$ and then do $x=r^2 \in [0,100]$ and let that be our random experiment. This time $x>5$ only for $r> \sqrt{50} \sim 7.07$.
In this case we would agree that the first way of choosing $x$ looks a lot more natural. So we would equally agree that is a successful way of modeling the experiment ''pick a random number from [0,100]''.
There are sometimes when we can't even agree on that! For example, on Bertrand's Paradox we are asked to pick a random chord from a circumference and calculate the probability that it is longer than the side of the inscribed equilateral triangle. The point is there are several (a priori) natural ways of choosing the chords (three of them are nicely described here) which, of course, produce different probabilities.
How and when can we consider something is truly random? Does it even make any sense saying something is truly random or is it more a matter of agreement?
Is there any convention in the mathematical community about this issues?
Could we say the common notion of randomness relates to the notion of uniform distribution?
Are there any successful approaches on models about randomness? (That let us decide if a certain distribution represents randomness in the sense of being an uniform distribution)
For example, on the comments it is said: "One can show [using Kolmogorov Complexity] that a number in [0,1] is random with probability 1 under the uniform distribution, so it coheres well with other notions.''
Comment: "Have we achieved a mathematical model for randomness?"

Yes. It's called probability theory.
Comment: Google "Kolmogorov complexity".
Comment: @ZangoLotino There are certainly lot of applications. One can also  show that a number in $[0,1]$ is random with probability $1$ under the uniform distribution, so it coheres well with other notions.
Comment: @ZangoLotino It is the only succesful one I'm aware of (I think probabilist Reichenbach tried to do something related without success).
Comment: @ChristianBlatter, I think Bayes, Laplace, Cox, Polya and many others would take exception to your statement. A recent issue of the journal Stat. Sci. for example analyzed various ways in which frequentist and Bayesian statistical methdos (which deal with uncertainty if not "randomness) diverge in results, despite given the same data.
Comment: @alancalvitti And continuous conditional distributions use **very much** measure theory. Yawn... Well, since each had a chance to express their view, I think I will take my leave.
Comment: Wikipedia:''Kolmogorov randomness – also called algorithmic randomness – defines a string (usually of bits) as being random if and only if it is shorter than any computer program that can produce that string.'' That seems a nice definition, is it useful?
Comment: Your observation is in a way turned around to say a pseudo-random number generator is a procedure that is equally likely to produce a ``random'' number in equal length intervals.
Comment: Ok, thank you. Is kolmogorov randomness the best mathematical object we have for modeling the human notion of random string?
Comment: I would look up [**Kolmogorov complexity and Shannon entropy**](http://www.mdpi.com/1099-4300/13/3/595/pdf) and [**Shannon Entropy**](http://www.lptl.jussieu.fr/user/lesne/MSCS-entropy.pdf). You might also want to look into DIEHARD and TESTU01 for testing, especially as it relates to the great need for randomness in cryptographic applications. Regards
Comment: If @MichaelGreinecker or Amzoti would write an answer with a little bit explanation of that... that was the kind of answers I was expecting instead of ''you need to give a distribution along with it'' which I thought I made clear I already knew (by my first example).
Comment: highly related:  http://math.stackexchange.com/questions/15055/in-a-family-with-two-children-what-are-the-chances-if-one-of-the-children-is-a/15085#15085
Comment: I don't understand how Kolmogorov complexity is supposed to help you pick numbers in $[0,100]$ or chords in a circle in a uniform way. In other words, I don't understand the connection between your motivating examples and your comment that Kolmogorov complexity is the kind of answer you were looking for.
Comment: @RahulNarain Ok, maybe I have to re-write everything a bit. My examples are just for showing that _random_ is a concept that, by itself, doesnt have a mathematical meaning. I am looking for approaches to the modelling of the notion of _random_ (or some variants). As Michael Greinecker pointed out: ''There are certainly lot of applications [of Kolmogorov complexity]. One can also show that a number in [0,1] is random with probability 1 under the uniform distribution, so it coheres well with other notions'' That is a good reason why it is a nice approach/model.
Comment: I don't know if the edit is any better. Is the entire field of probability theory unsuccessful? Of course any nontrivial distribution represents randomness if it is the distribution of a random variable. I really think you mean "uniform distribution" when you say "random". The sum of two dice rolls has a higher probability of coming up 7 than of coming up 2. Is it not random?
Comment: Ok, agree with you observation. Restated the question...
Comment: @alancalvitti I doubt the Great Ones you cite would have taken exception to *that*. Would you be confusing the true fact that some given real-life situations are liable to several modelizations with the equally true fact that all of these modelizations pertain to probability theory as delineated by Uncle K in 1933, for example?
Comment: @ChristianBlatter, no I'm not confusing it: although Bayes theorem itself is a direct consequence of the product rule, the Bayesian logical framework is not based on measure theory in contrast to K's development. Rather it's an extension of laws of logic such as weak syllogism in place of classical Modus Ponens, see eg Jaynes' "Probability Theory" 2003. Jaynes was a physicist and in his book says the bulk of measure theory (eg, absolute continuity) is basically irrelevant to statistics.
Comment: @alancalvitti (You misattributed my last comment.) Bayesians never use continuous parameters?
Comment: @did, my bad: (can a moderator please change ChristianBlatter --> did in my previous comment?)... Bayesians use continuous and discrete parameters: the distribution of the fairness of a coin would be a continuum, eg [0,1]. They also use discrete distributions. Jaynes in his book writes that there's no difference between model selection and parameter estimation, since in any indexable set of models the index can be considered a parameter
Comment: @ChristianBlatter, pace - I accidentally misattributed you in a previous comment.
Comment: @alancalvitti How to use continuous parameters without measure theory?
Comment: @did, I'm not sure what you mean by continuous: topological spaces deal with continuity, measure spaces deal with measures. There are measure-theoretical concepts like absolute continuity that are central in functional analysis - but as I was saying, Jaynes says in applied statistics they make no difference (I would agree as all data is finite).
Comment: @alancalvitti Well, continuous [like this](http://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution), of course. Ergo, measure theory. For some perspective on Jaynes' always interesting and sometimes extreme views, you might try [this](http://www.siam.org/news/news.php?id=81).
Comment: @did, great quote by Diaconis in that review: "I had to fight to keep the measure theory requirement in Stanford's statistics graduate program. The fight was lost at Berkeley." and I agree that the book is not "modern" - statistical methods are accelerating. However re your Q: Baysesian use continuous distributions, but stay away from measure spaces (K's). See, eg Sivia's *Data Analysis: a Bayesian Tutorial* 2006
Comment: @alancalvitti From the Preface by Sivia: *What we were not told in our undergraduate lectures is that there is an alternative approach to the whole subject of data analysis which uses only* **probability theory** (my emphasis). *In one sense, it makes the topic of statistics entirely superfluous. In another, it provides the logical justification for many of the prevalent statistical tests and procedures, making explicit the conditions and approximations implicitly assumed in their use. This book is intended to be a tutorial guide to this alternative Bayesian approach.*
Comment: @did, I have that book. When you look through it, you will find distributions of course, including continuous ones. But the methods diverge from K's methods. The central concepts are priors, conditional and posterior distributions, not algebra of events and measure spaces.
Comment: @did, ok I give up too. In any case, why did you mention continuous distributions? Measure theory applies as well to discrete distributions.
Answer: One way to interpret your motivating examples is not that the word random is ill-defined (all of probability theory would disagree with that), but that you want a mathematically natural characterization and generalization of the notion of a uniform distribution. In that case, the answer could be the Haar measure on Lie groups (among other things). This is a measure that is invariant under the action of the group, and if you restrict it to a compact set you can normalize it to form a probability distribution.
For example, the real numbers form a Lie group under addition, and the corresponding Haar measure is nothing but the usual uniform measure on $\mathbb R$, which restricted to $[0,100]$ leads to the uniform distribution on the same. We can tell that the distribution produced by uniformly picking a number in $[0,10]$ and squaring it is not uniform, because it is not invariant under addition (the probability of $[20,30]$ is not equal to the probability of $[20,30]+40 = [60,70]$).
Similarly, when dealing with lines in the plane, the relevant Lie group is the Euclidean group of rigid motions of the plane, which comes equipped with a Haar measure. This induces a measure on the space of lines which is invariant to translation and rotation. When restricted to the lines that intersect a given circle, it gives you something you could objectively call "the" uniform distribution over chords of the circle. This corresponds to picking the angle and the distance from the center uniformly, and matches Jaynes' solution using the principle of maximum ignorance.
The field of integral geometry deals with exactly this sort of thing: the properties of geometrical objects under measures that are invariant to the symmetry group of the geometrical space. It has many interesting results such as the Crofton formula, stating that the length of any curve is proportional to the expected number of times a "random" line intersects it. Of course, this could not be a theorem without precisely formalizing what it means for a line to be random.
Comment: Thank you for your answer, I was looking for such things.
Comment: +1 for a nice summary answer. Be aware however that in practice, the symmetry group (or more generally, inverse semigroup or partial symmetries) of the system under study is not at all easy to characterize. By the way, even the notion of *averaging* has been studied from an invariance point of view - this is the Chisini mean approach.
Comment: @ZangoLotino, related to Rahul's answer, check: http://en.wikipedia.org/wiki/Jeffreys_prior
Comment: Thank you all, I wasnt expecting such a feedback. It this goes on, I will do some kind of summary in a few days ;)
Answer: When someone says 'random' there should be a distribution that goes along with it.  In your example, to pick a random $x$ from $[0,100]$, it is implied that you pick $x$ over a uniform distribution.  Of course, like you pointed out, using a different distribution will give you a different result.
The point is, 'random' needs a distribution to define it.
Comment: No the point is that when someone says something is random, from context it is usually implicitly understood what the distribution is.  In your random chord example, the paradox isn't really a paradox, it's just that the question doesn't properly define a distribution of chords, so depending on how you choose it, you will get different answers.  Using the word 'random' is fine, as long as everybody knows its underlying distribution.
Comment: Would you say "number" is a mathematical term?  It's part of several specifically defined mathematical terms — real numbers, natural numbers, complex, *p*-adic, etc. — but on its own, it doesn't have a uniquely defined meaning.  "Random" is similar: it's part of several formally defined notions (e.g. random variables, Kolmogorov randomness, …), and randomness is certainly something that's studied mathematically, but the informal idea of randomness corresponds to several different mathematical concepts, and so there's no single formal definition of "random".
Comment: Rather, we often forget to mention the words *uniformly distributed* when introducing a random variable. Similarly, the word *independant* is often forgotten when talking about two random variables. But that is a matter of imprecision in linguitic expression. The concept of random variable has a very precise *mathematical* definition, but connot easily be transferred fully to everyday experiments (coin flips, dice rolls, weather forecasts, ...).
Comment: So the answer is that there is no such thing as randomness?. Since we need a distribution for every time we use that word, we wouldn't need to use it. So we have failed in modeling the notion of random, or we are confused about it.
Comment: Maybe the title of my question is not well posed. Is _random_ a mathematical term? In the sense that, have we achieved to give a mathematical object which models it (the human feeling about it)?
Comment: I agree with @PeterLeFanuLumsdaine.  In mathematics, randomness is well-defined.  In everyday language, randomness may not have such a formal definition.
Comment: I would say ''number'' is a mathematical term and a _good_ one since any person who understands the underlying definitions would agree that the detailed mathematical definition I'm giving them coincides with their own _feelingg_ about (real, natural, complex) number. But the thing is that doesn't seem to happen with random. Of course there are adjectives to _random_ which are studied and are mathematical objects but if I model a potato with a sphere it becomes an unsuccessful model, even though the sphere is still a mathematical object.
Comment: @ZangoLotino, just to augment timidpueo's answer, there is no uniform distribution on infinite sets obviously, since probability measure is finite and additive.
Answer: A common abuse of language is to say "let $x$ be a random foo" when one really means "let $x$ be a random variable uniformly distributed over all foo".
It is also common to abuse language to use "random" to mean "something that appears too hard to predict".
The fundamental rationale behind applying probability distributions to real world observations is really a matter of metaphysics, not mathematics.
Comment: Ok, completely agree on the first 2 paragraphs. My concern is that the last one is also true... so the fact that we trust in such applications is a matter of faith in some way?
Comment: Anyway, if I said the chords are _equally distributed_, this time it is not even defined _equally distributed_, otherwise there would be agreement on the solution.
Answer: If we look at dice or a pseudo-random number generating algorithm, we need to know laws (physics or algorithm) and initial conditions to predict the result.
Based on that, here goes my attempt to define randomness:

If function's $f\left( x_1, x_2, \ldots \right)$ value can't be predicted while knowing the values of all variables $x_1, x_2, \ldots$, then the value of the function is a random number.

Any comments on this are welcome.
Truly random numbers in real life
I disagree that a truly random number is impossible.
It would be hard to believe that a deterministic algorithm could produce random results. But an algorithm is not the only way to produce a number. You just need to assign numbers to possible outcomes of some random process to get random numbers. In quantum physics the result of an experiment is random.
Example 1
State of a particle is described by wave function $\psi \left( q \right)$. Probability to find particle somewhere in $\delta$ is $\int\limits_\delta \left| \psi \left( q \right) \right| ^2 dq$. If you perform many experiments, you'll get results distributed according to $\left| \psi \left( q \right) \right| ^2$. But outcome of a single experiment is a random number from that distribution.
Example 2
Let's look at another experimental situation: light travels along $z$ axis and it is polarized along $x$ axis. It falls on a polarizer whose axis of polarization is not the same $x$ axis. For simplicity let's put our polarizer so that the angle between it's axis and $x$ axis is $\pi/4$. In that case half of the light goes through and half is absorbed. for individual photons it means that a photon will randomly either be absorbed or let through with equal probability.
The second experiment is almost the same coin toss, but, when throwing coin, one could think

if i could very precisely know initial speed and position and everything else, I could predict it's final position without any randomness

but in case of photons the are no underlying variables, the result of a single experiment is fundamentally unpredictable (random), however the result of many (infinitely many) experiments approach the 50/50 distribution.
Furthermore, the processes in atmosphere are very unstable so some tiny quantum randomness might actually be enough to make a macroscopic result random.
Comment: This answer does not actually reflect the status of quantum mechanics.  There are entirely deterministic models of quantum theories (by Bohm, t'Hooft, and many others) that have isomorphic predictions to the probabilistic models (and thus are models of the same theory).  So you can't accurately say "the result of an experiment is random" according to your definition.  Instead, you need to actually point out that in deterministic models, measurement of variables is contextual and modifying, so measurement is the problem, not the lack of variables (among other things).
Answer: I would recommend looking into:

Kolmogorov complexity $K(x)$ measures the amount of information contained in an individual object $x$, by the size of the smallest program that generates it.
Shannon entropy $H(X)$ of a random variable $X$ is a measure of its average uncertainty. It is the smallest number of bits required, on average, to describe $x$, the output of the random variable $X$.

Here are two references for your review Kolmogorov complexity and Shannon entropy and Shannon Entropy.
Today, most people marry this into Information Theory.
Random numbers are very important in many fields and particularly for cryptographic applications (since getting this wrong could make a secure system insecure). I would recommend looking into the papers and code for DIEHARDER and TESTU01 and there are interesting papers and results for psuedo-RNGs and crypto-strength RNGs.
Random numbers, as you are finding, are a very complex area and it is a great idea to question them.
Here is a List of random number generators for your perusal. You might also have a look at the Handbook of Applied Cryptography - HAC for some crypto related ones.
Regards
Comment: Interesting question, and great references!


ggplot: geom_area - erro com aes(fill)

Question: Tenho os seguintes dados e gostaria de criar um gráfico com o ggplot2::geom_area() com cores diferentes para os valores positivos e negativos. No entanto, estou obtendo um erro e não estou conseguindo resolve-lo. Alguém poderia ajudar?
dados <- structure(list(year = c(2020, 2020, 2020, 2020, 2020, 2020, 2020,
2020, 2020, 2020, 2020, 2020), month = structure(1:12, .Label = c("January",
"February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"), class = "factor"),
    diff = c(167916.47, 58945.82, 432269.2, 532863.2, -434494,
    -493142.3, -50919.75, -207215.3, -278524.84, -77664.68, 161101.79,
    144261.69), signal = c("pos", "pos", "pos", "pos", "neg",
    "neg", "neg", "neg", "neg", "neg", "pos", "pos")), row.names = c(NA,
-12L), class = c("tbl_df", "tbl", "data.frame"))

Quando 'ploto' os dados sem o geom_area(aes(fill = signal)), o gráfico sai correto:

No entato, quando uso o argumento fill para tentar preencher positivos e negativos com cores diferentes
dados %>%
  ggplot(aes(x = month, y = diff,
             group = 1))+
  geom_area(aes(fill = signal))

obtenho o seguinte erro: Erro: Aesthetics can not vary with a ribbon.
Alguém sabia dizer onde está o erro? Tentei com dados diferentes desses (com variável contínua no eixo X) e consegui, mas com esses não. Obrigado.
Comment: Isto responde à sua pergunta? [Geom\_area com cores diferentes de preechimento](https://pt.stackoverflow.com/questions/467729/geom-area-com-cores-diferentes-de-preechimento)
Comment: é exatamente isso que quero, cheguei a ver essa pergunta/resposta, mas não consegui transpassar a lógica para os meus dados. vou tentar/estudar mais um pouco. valeu!
Answer: Você precisa do parâmetro group quando usar fatores no gráfico para que o geom_area não interprete cada fator como um grupo diferente.
A doc neste link tem um exemplo com geom_line.
Para obter o efeito que vc deseja, é necessário dividir os dados em grupos, conforme explicado aqui.
No seu caso, você tem apenas 1 grupo, o que facilita a situação. Mas este gráfico pode ficar complicado se você tivesse vários grupos com valores positivos e negativos alternados. Há uma boa discussão a respeito nesta thread.
Comment: obrigado pela resposta, tentei reproduzir aqui, a partir dos meus dados, e de primeira não saiu. vou tentar descobrir onde está o erro.

ggplot: geom_area - erro com aes(fill)


Convert FP32 to Bfloat16 in C++

Question: How can I convert from float (1bit sign, 8bit exp, 23bit mantissa) to Bfloat16 (1bit sign, 8bit exp, 7bit mantissa) in C++?
Comment: [`frexp`](https://en.cppreference.com/w/cpp/numeric/math/frexp) can be used to break a `float` down into components. Assembling it back into whatever structure you call `Bfloat16` is left as an exercise for the reader.
Comment: @IgorTandetnik but that would be expensive. Bfloat16 is designed as the top half of float so that you can truncate it easily
Comment: I imagine you want to do this efficiently, since the only reason for such a small floating point format is when you have a very large number of them. I also imagine it needs to do proper rounding.
Answer: As demonstrated in the answer by Botje it is sufficient to copy the upper half of the float value since the bit patterns are the same. The way it is done in that answer violates the rules about strict aliasing in C++. The way around that is to use memcpy to copy the bits.
static inline tensorflow::bfloat16 FloatToBFloat16(float float_val)
{
    tensorflow::bfloat16 retval;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    memcpy(&retval, &float_val, sizeof retval);
#else
    memcpy(&retval, reinterpret_cast<char *>(&float_val) + sizeof float_val - sizeof retval, sizeof retval);
#endif
    return retval;
}

If it's necessary to round the result rather than truncating it, you can multiply by a magic value to push some of those lower bits into the upper bits.
float_val *= 1.001957f;

Answer: memcpy wouldn't compile for me in the little endian case for some reason. This is my solution.
I have it as a struct here so that I can easily access the data and run through different ranges of values to confirm that it works properly.
struct bfloat16{
   unsigned short int data;
   public:
   bfloat16(){
      data = 0;
   }
   //cast to float
   operator float(){
      unsigned int proc = data<<16;
      return *reinterpret_cast<float*>(&proc);
   }
   //cast to bfloat16
   bfloat16& operator =(float float_val){
      data = (*reinterpret_cast<unsigned int *>(&float_val))>>16;
      return *this;
   }
};

//an example that enumerates all the possible values between 1.0f and 300.0f
using namespace std;

int main(){
   bfloat16 x;
   for(x = 1.0f; x < 300.0f; x.data++){
      cout<<x.data<<" "<<x<<endl;
   }

   return 0;
}

Comment: Works great :). Do check this answer, which also include `operator >>` overload for cin: https://stackoverflow.com/a/56017304/1413259
Answer: From the Tensorflow implementation:
static inline tensorflow::bfloat16 FloatToBFloat16(float float_val) {
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    return *reinterpret_cast<tensorflow::bfloat16*>(
        reinterpret_cast<uint16_t*>(&float_val));
#else
    return *reinterpret_cast<tensorflow::bfloat16*>(
        &(reinterpret_cast<uint16_t*>(&float_val)[1]));
#endif
}

Comment: I think that implementation is flawed because it violates aliasing. If you copy the two bytes as individual bytes (e.g. `unsigned char`'s), it'll be right.
Comment: @AlexeyFrunze : why is de-referencing violating aliasing ? It seems like it should be fine since we never update/modify or write to `float_val` , if we are just reading and never writing to the different pointer type , is it still a violation or UB ?
Comment: @user179156 Doesn't matter. You can legally peek/poke an object through a pointer to a compatible type, a pointer to the (un)signed variant of the same type, or a pointer to a char. float and uint16_t is not an allowed pair here (unless uint16_t is a type name that stands for unsigned char).
Comment: @AlexeyFrunze : got it . thanks . Could you please give an example why such a rule was decided. Understand that this is what standard says but do not understand the rationale and what can possibly go wrong , any code snippet or example would help
Comment: @user179156 For one, different types may have different alignments and using a badly aligned pointer may not work how one may expect it to (it may not work at all, just crash your program). For another, this rule gives the compiler the ability to know that certain pointers in the code never point to the same object and the compiler can safely make optimizations (like caching the object in a register, knowing it won't mysteriously change through some other pointer).
Comment: @AlexeyFrunze agreed about alignment part. But the second part , how does that get violated if we are doing such reinterpret_cast to a read only memory location , If my program never writes or updates that memory location , and this is purely a read only storage , is it ok to apply reinterpret cast (assuming i make sure the memory are aligned).
Comment: @user179156 The language standard does not always state the rationale. Try asking its authors or looking for their discussions and things like the language defect reports. I know, it's not always clear and logical but that's what it is.

Convert FP32 to Bfloat16 in C++


How do I generate two correlated Poisson random variables?

Question: How would I simulate observations from a bivariate Poisson distribution such that they have a nonzero covariance? The hint I was given is that I need to use the fact that the sum of two Poisson random variables is also Poisson.
Comment: Please see the `self-study` [tag wiki](http://stats.stackexchange.com/tags/self-study/info). The hint you already have is a complete giveaway; I'm not sure there's much of anything between the hint you already have and telling you exactly which Poissons to add ... i.e. a complete solution. Oh, wait, there's one -- start with more than two independent Poissons.
Comment: See http://stats.stackexchange.com/questions/108705.  Both answers there show how values can be simulated by means of three independent Poisson variates (although they do not explicitly point that out).
Answer: Since you do not impose any constraint on the joint distribution, any copula structure gives you a solution. For instance,

take a bivariate normal
$$(x_1,x_2)\sim\mathcal{N}_2\left((0,0),\left[\matrix{1 &\rho\\\rho &1}\right]\right)$$generation;
turn $(x_1,x_2)$ in correlated uniforms as $$(u_1,u_2)=(\Phi(x_1),\Phi(x_2))$$where $\Phi(\cdot)$ is the normal CDF;
derive two Poisson variates $(n_1,n_2)$ with parameters $\lambda_1$ and $\lambda_2$ from $(u_1,u_2)$ by inverting the Poisson CDF.
Comment: +1 but could you maybe also add an introductory reference to the copula link? It's a wikipedia stub at present.
Comment: @conjugateprior: thank you, the link was damaged and I just corrected it to the entire Wikipedia page.


How to prove that the values of Eisenstein Series $E_2$ are algebraic integers?

Question: I'm looking for a proof (see my older question here) that the following term is an algebraic integer whenever $\tau_N=\frac{N+\sqrt{-N}}{2}$ is a quadratic irrationality with class number $1$:
$$A_N:=\sqrt{-N}\cdot\frac{E_2(\tau_N)-\frac{3}{\pi\Im(\tau_N)}}{\eta^4(\tau_N)}$$
Here $\eta$ denotes the Dedekind $\eta$-Function and $E_2$ is the Eisenstein series of weight $2$.
I calculated the numerical value of $A_N$ for all discriminants with class number 1. The results are:

$A_3 = 0$
$A_4 = 0$
$A_{7}=3\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{7})^6=729$
$A_{8}=4\cdot e^{i\pi/2}\qquad\Longrightarrow\qquad(A_{8})^6=-4096$
$A_{11}=8\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{11})^6=262144$
$A_{12}=6\cdot4^{1/3}\cdot e^{i\pi/2}\qquad\Longrightarrow\qquad(A_{12})^6=-746496$
$A_{16}=12\cdot2^{1/2}\cdot e^{i\pi/2}\qquad\Longrightarrow\qquad(A_{16})^6=-23887872$
$A_{19}=24\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{19})^6=191102976$
$A_{27}=24\cdot9^{1/3}\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{27})^6=15479341056$
$A_{28}=54\cdot e^{i\pi/2}\qquad\Longrightarrow\qquad(A_{28})^6=-24794911296$
$A_{43}=144\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{43})^6=8916100448256$
$A_{67}=456\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{67})^6=8990607867641856$
$A_{163}=8688\cdot e^{i\pi/3}\qquad\Longrightarrow\qquad(A_{163})^6=430049922234001951555584$

Thus we get numerically, that these $A_N$ are algebraic integers, but I don't see how I can prove it. Does anyone know how to do that?
Comment: The expression $\left(E_2(\tau)-\frac{3}{\pi \operatorname{Im} (\tau)}\right) /\eta^{4}(\tau)$ was first studied by Ramanujan in his paper *Modular Equations and Approximations to $\pi$*. He proved that it is an algebraic number if $\tau$ has positive imaginary part and is algebraic of degree $2$.
Answer: Using a theorem of Masser it is possible to show that the quantities $(A_N)^6$ listed are rational numbers.  It seems reasonable to show using his arguments that they must be integral, but this would involve digging deeper into coefficients of modular polynomials.
The reference to look up is the monograph by Masser:
D. Masser, Elliptic Functions and Transcendence, Springer Lecture Notes in Math., vol. 477, 1975.
In Appendix I, he considers the function,
$$\Psi(\tau) := \frac{3E_4(\tau)}{2E_6(\tau)} \biggl(E_2(\tau) - \frac{3}{\pi\, \mathrm{Im}(\tau)} \biggr),$$
for $\tau \in \mathbb{H} = \{ \tau \in \mathbb{C} \mid \mathrm{Im}(\tau) > 0 \}$.  Now $\Psi$ is invariant under the action of $\mathrm{SL}_2(\mathbb{Z})$, but it is not holomorphic on $\mathbb{H}$.  Here $E_4(\tau)$ and $E_6(\tau)$ are normalized Eisenstein series: for $q = e^{2\pi i \tau}$,
$$E_4(\tau) = 1 + 240 \sum_{n=1}^{\infty} \sigma_3(n)q^n,$$
$$E_6(\tau) = 1 - 504 \sum_{n=1}^{\infty} \sigma_5(n)q^n.$$
We also have the discriminant function,
$$\Delta(\tau) = \frac{E_4(\tau)^3-E_6(\tau)^2}{1728} = \eta(\tau)^{24} = q \prod_{m=1}^{\infty} (1 - q^m)^{24},$$
and the $j$-invariant,
$$j(\tau) = \frac{E_4(\tau)^3}{\Delta(\tau)},$$
which is a modular function.  If $\tau \in \mathbb{H}$ is a quadratic irrationality, then $j(\tau)$ is an algebraic integer.
Theorem (Masser, 1975): Let $\tau \in \mathbb{H}$.  If $\tau$ is a quadratic irrationailty not equivalent to $i=\sqrt{-1}$, then $\Psi(\tau) \in \mathbb{Q}(j(\tau))$.
Now for $\tau \in \mathbb{H}$, set
$$\Phi(\tau) := \left( \frac{E_2(\tau) - \dfrac{3}{\pi\,\mathrm{Im}(\tau)}}{\eta(\tau)^4} \right)^6 = \frac{ \biggl( E_2(\tau) - \dfrac{3}{\pi\,\mathrm{Im}(\tau)} \biggr)^6}{\Delta(\tau)}.$$
Claim: Suppose that $\tau \in \mathbb{H}$ is a quadratic irrationality not equivalent to $i$ or $e^{2\pi i/3}$.  Then $\Phi(\tau) \in \mathbb{Q}(j(\tau))$ and so then is algebraic.
To prove this multiply top and bottom by $E_4(\tau)^6 E_6(\tau)^6$ (why we avoid $i$ and $e^{2\pi i /3}$), we have
$$\Phi(\tau) = \Psi(\tau)^6 \cdot \frac{2^6 E_6(\tau)^6}{3^6 \Delta(\tau) E_4(\tau)^6}.$$
Now $E_6^6/(\Delta E_4^6)$ is a modular function and so is an element of $\mathbb{Q}(j)$.  In fact it is simply
$$\frac{E_6(\tau)^6}{\Delta(\tau) E_4(\tau)^6} = \frac{(j(\tau)-1728)^3}{j(\tau)^2}.$$
In any event this, together with Masser's theorem, implies that $\Phi(\tau) \in \mathbb{Q}(j(\tau))$, which proves the claim.
On a final note, Masser shows more explicitly (see equation (106) in his App. I) that when $\tau$ is a quadratic irrationality not equivalent to $i$,
$$\Psi(\tau) = 9\gamma_{\tau}\cdot j(\tau) + \frac{3}{2} \cdot \frac{7j(\tau)-6912}{j(\tau) - 1728},$$
where $\gamma_\tau \in \mathbb{Q}$ is an expression in terms of the coefficients of modular polynomials.  Since $j(\tau)$ is an algebraic integer, determining more information about $\gamma_{\tau}$ may lead to showing that $D^3 \Phi(\tau)$ is an algebraic integer in general ($D$ the fundamental discriminant for $\tau$).
In the case of class number 1, Masser includes a table of the values of $\Psi(\tau_N)$, so showing that $(A_N)^6$ is an integer in these cases can likely be deduced from his table (I did not have time to verify it).
Comment: wow, thank you @Matt!!! But my goal is to calculate the values of $\Psi$ from Massers table, so I can't use them for the proof... (sorry I didn't tell earlier)


How does System.Net.Sockets.Socket() use its parameters?

Question: When creating a new instance of this class, you specify a SocketType and ProtocolType. I want a SocketType of Stream. In the description of the Stream member, it says, "stream uses the TCP ProtocolType." However, I can still specify a different ProtocolType manually of UDP, ICMP, IGMP, ...
I'm not sure how this works at lower layers though - If I were to do something like...
new NetworkStream(new Socket(SocketType.Stream, ProtocolType.Icmp))
Would I be wrapping my stream in ICMP traffic (meaning stream data within ICMP headers)? Please provide as much information as possible so I might understand how this is actually working under the hood.
Comment: Note the allowed exceptions for the [constructor](http://msdn.microsoft.com/en-us/library/hh264899.aspx): "[`SocketException`](http://msdn.microsoft.com/en-us/library/system.net.sockets.socketexception.aspx): The combination of *socketType* and *protocolType* results in an invalid socket." - you can't arbitrarily mix and match the types.
Comment: actually you are creating a new instance of your Stream, so there shouldn't be wrapped anything.
Comment: So you're suggesting in the example given, the "ProtocolType.Icmp" is basically thrown out/ignored?
Answer: The Socket constructor provides an explanation saying that "The combination of socketType and protocolType results in an invalid socket."
This means that nothing is done under the hood per se. It throws an exception and never makes it to the underlying winsock functions.


SQL Server 2008 Chaining Merge Replication

Question: Is there a way to have multiple "tiers" for a merge replication in SQL Server 2008.  For example I have SiteA with SQL Server 2008 that has a publication setup on TestDB.  SiteB, also with SQL Server 2008 is subscribed to the SiteA publication for TestDB. SiteB then has a publication on its TestDB and multiple instances of SQL Server Express 2008 subscribe to the publication for TestDB on SiteB.
The goal here being the local SQL Express instances are merge replicating with site B and then site B is merge replicating with Site A.
I tried setting this up, but when I got to SiteB to setup the publication I got the following message
"You cannot create a merge publication in this database because it contains one or more anonymous or local merge subscriptions. To create a merge publication, drop the existing anonymous or local merge subscriptions, create the publication, and then recreate the subscriptions."
Answer: It appear this works, but the first tier of replication (the republisher) needs to be a server side push subscription instead of a pull subscriptions.


The goalkeeper mistakenly kicks the ball into the goal during kicks from the penalty mark

Question: There is a video of a kick taken during kicks from the penalty mark.
The goalkeeper dived and blocked the ball from going into the goal. However as the goalkeeper was standing up immediately from the dive, his foot kicked the ball back into the goal and the referee disallowed it.
Is it a goal or not?
Comment: @OlaStrom please do not remove correct terminology. The change to link formatting was also unnecessary.
Answer: It's pretty close, but no goal is the correct decision. The referee was right when he disallowed the goal.
During kicks from the penalty mark, the kick is completed when the ball

is out of play
stops moving

In your video the ball just lays on the ground after the save, so the kick was already completed when the goalie kicked it into the goal.


$M/im(f)$ is Torsion

Question: Let $R$ be a Principal ideal domain and $f:R^{n}\rightarrow M$, be an injective homomorphism where $M$ is a finitely generated $R$-module. I need to show that $M/im(f)$ is Torsion.
I know that since $f$ is injective then $ker(f)$ is trivial. Also that $im(f)$ is a submodule of $M$, therefore $M/im(f)$ is well defined since it is a quotient module. Do I have to use the existence of decomposition factors for $M$, and if so how?
Thanks
Comment: Doesn't $f$ want to be rather *surjective*?
Comment: @Berci In that case, $M/im(f)=\{0\}$ would certainly be torsion :)
Comment: Ah, ok :) you're right. I was thinking about a less trivial proof for that case
Comment: @leonhardLeibniz have you checked the statement of the problem to make sure you copied it correctly?
Answer: Let $M$ be $R\times R$ and let $f:R\to M$ be given by $f(r)=(r,0)$.
Then $M/Im(f)\cong R$ is not torsion.

$M/im(f)$ is Torsion


Angular2 : HTTP error handling

Question: I am trying to reproduce the following behaviour that I successfully implemented using Angular 1.x interceptors and promises, in a Angular2 based Ionic2 app :

Intercept HTTP request errors
If the status code is 401, then
a. make another request to register the client. This will provide some token that I can subsequently attach to each request.
b. Retry the orignal request and provide the result to the caller through the promise / observable
If the error status is anything other than 401 just let the flow normally to the caller

NB: The register process does not need any intervention from the user (no login) so I want it to be completely transparent for the user. I register once when the app is first loaded, but the session will eventually expire and I need to automatically re-register.
This is the original Angular 1 implementation (I include only the responseErrorpart of the interceptor):
responseError : function(rejection){
    if(rejection.status == 401){
        $log.info('Intercepting unauthorized 401 response. Will try to re-register the session and retry the request.');

        var security = $injector.get('SecurityService');
        var $http = $injector.get('$http');

        return security.registerSession().then(function(){
            return $http(rejection.config);
        });

    }else{
        return rejection;
    }
}

Now, I have wrapped Angular2's HTTP service and I can do simple things like adding a header to each request. However I am struggling to reproduce the same behaviour using Angular2 and Observables.
My attempt so far, this is the request method of my HTTP wrapper that my services will call :
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {

    let req: Request = this.buildRequest(url, options);

    this.beforeCall(req);

    var observable = this.http
        .request(req)
        .retry(3)
        .catch(res => {
            debugger;
            console.log("ERROR! " + res.status);
            if(res.status == 401){
                this.logger.log('Unauthorized request. Trying to register the session and then retry the request.');
                return this.securityService.registerSession().subscribe(() => {
                    // What to do here so the client gets the result of the original request ??
                });
            }
        })
        .do((res:Response) => { this.afterCall(req, res) });

    return observable;
}

Comment: @Günter : Related but not a dupe IMO. I want to handle the error inside the wrapper and do something with it, then retry. He wants to return error feedback to the caller.
Comment: Looks like a dup of http://stackoverflow.com/questions/33941836/angular2-handling-http-response
Comment: Has this solution been implemented? I have been trying to do the  same but without any success. It would be really helpful if you can post the complete solution.
Answer: You could execute again the request after initialize the session using the flatMap operator of observables:
    var observable = this.http
        .request(req)
        .retry(3)
        .catch(res => {
            debugger;
            console.log("ERROR! " + res.status);
            if(res.status == 401){
                this.logger.log('Unauthorized request. Trying to register the session and then retry the request.');
                return this.securityService.registerSession().flatMap(() => {
                  return this.http.request(req); // <--------
                });
            }
        })
        .do((res:Response) => { this.afterCall(req, res) });

    return observable;
}

Comment: what does this mean `retry(3)` ? request executed 3 times if failed once ?

Angular2 : HTTP error handling


Real Analysis Cauchy Sequence Question

Question: So I've been been working on the question below, and I have some questions in regards to the validity of my answer.

Let $(a_n)$ be a sequence such that
  $$\lim_{N \to \infty} \sum_{n=1}^{N} |a_n - a_{n+1}| < \infty .$$
  Show that $(a_n)$ is Cauchy.

I make the claim that the distance between the terms of $(a_n)$ must approach zero. As such for every $\epsilon > 0$, there must be be an integer $N$ such that
$$|a_m - a_n| < \epsilon$$
for all $m,n \geq N$. That is, the sequence is Cauchy. To show this, assume that the distances between the terms of $(a_n)$ do not approach zero. Let
$$a=\min \left \{ |a_1 - a_2|,|a_2 - a_3|,...,|a_N - a_{N+1}|,... \right \}.$$
Then we have $a \neq 0$. Observe that
$$\lim_{N \to \infty} Na \leq \lim_{N \to \infty} \sum_{n=1}^{N} |a_{N}-a_{N+1}| < \infty,$$
which, is a contraction, as
$$\lim_{N \to \infty} Na= \infty$$
for any $a \neq 0$. Thus, we must have $a=0$, and the distance between the terms of $(a_n)$ must approach zero and as such the sequence is Cauchy.
I am unsure about setting $a= \min \{...\}$. Any input or comments about my answer would be appreciated.
Comment: What if you change $a_2$ to be the same as $a_1$ keeping all other terms the same. The convergence properties will not change, but $a$ will be 0.
Answer: Your $a$ could be $0$, so this does not work, even if the idea is great.
Take $\epsilon>0$.
Since the series converges, there exists $N$ such that
$$
\sum_{n=N}^{+\infty} |a_{n+1}-a_n|\leq \epsilon.
$$
Now for all for $N\leq k<l$, we have
$$
|a_k-a_l|=|\sum_{n=k}^{l}a_{n+1}-a_n|\leq \sum_{n=k}^{l}|a_{n+1}-a_n|\leq \sum_{n=N}^{+\infty}|a_{n+1}-a_n|\leq \epsilon.
$$
So the sequence $a_n$ is indeed Cauchy.

Real Analysis Cauchy Sequence Question


What makes a Turkish March a Turkish March?

Question: I can only find 2 pieces called Turkish March. There is the 5th movement of The Ruins of Athens by Beethoven. Then there is the infamous Rondo Alla Turka by Mozart.
And when I search Turkish March Beethoven, I usually get a piano transcription.
Anyway, these are the parallels I can draw between the 2 pieces:

Major key
Upbeat
Rondo form
Minor key used for harmony, drama or both
Basic 8th note pulse at quarter note = 110 BPM
Left hand sort of sounds like footsteps

All I can get from the internet on what a Turkish March is, is that it is a march in the Turkish style. Since I only have that and the parallels drawn between Beethoven's Turkish March and Mozart's Rondo Alla Turka, it is hard for me to know how to compose a Turkish March and it feels like I am relying on Mozart to help me with this. In fact, mine is sort of based off of Rondo Alla Turka as far as form and the ending in octaves.
Is there anything besides the parallels I have already drawn between the 2 Turkish March pieces that will help me compose my Turkish March?
Comment: Wait, why do you think it is a duplicate? I mean first off I mention Beethoven's Turkish March which isn't mentioned at all in the other question and I compare it to Mozart's Rondo Alla Turka to see what they have in common. And I also mention that I am composing a Turkish March myself.
Comment: I don't think this question is a dupe, @Carl.
Comment: Possible duplicate of [Why is Mozart's Turkish March considered a rondo?](https://music.stackexchange.com/questions/31899/why-is-mozarts-turkish-march-considered-a-rondo)
Comment: Karl King wrote at least one march, "Burma Patrol," which he subtitled, "Turkish March." I performed this with my high school band (pre internet) and always wondered just what made it "Turkish." The "A" & "B" sections are in minor key, and the trio, as I recall, went to the parallel major.
Answer: The 'Turkish style' was a form of exoticism occasionally used by composers of the Classical era.  It was loosely based on Turkish military bands.  The basic feature was a lively march, often including exotic percussion instruments - triangle, cymbals and bass drum.
https://en.wikipedia.org/wiki/Turkish_music_(style)
We could compare the craze for all things Oriental in the later Victorian era, that infulenced all areas of art and decor.
Answer: One thing I have noticed in "Turkish Marches" (and listening to other marches which may be based on Turkish music) is the sequence (in cut time): half-half; quarter-quarter-half.
Answer: There is nothing authentically Turkish about those pieces.
The musical characteristics...

March, 2/4 meter
Somewhat exotic scale, harmonic minor
Somewhat rapid contrasting of parallel major and minor

...just help create a dramatic march.
It may seem trite, but simply erase "Turkish" from the titles and no one would have any way to identify them as Turkish.
At a minimum make sure your music identifies as a march, then use some exotic scales and maybe an unusual modulation.
The Turkish national anthem is a march, maybe look to it or some Turkish folk tunes for melodic inspiration.
Comment: The Turkish national anthem was written in 1921 or perhaps slightly earlier, so it does not help anyone who wants to identify authentic Turkish influences in Western European music of the 18th and 19th centuries.  Folk tunes are perhaps also of limited use since the model for so-called "Turkish" music was Turkish military music.  After listening to a few janissary marches on YouTube, I turned my attention to the national anthem, and it sounds almost Italian by comparison.


Yii2: Is there a Yii-way to force the browser reloading a CSS file?

Question: Normally I would just do something like this:
<link href="main.css?<?= filemtime($file) ?>">

Is there a better way in Yii? – If not, is there a way I can add this to $this->head() for a specific CSS file?
Comment: You are trying to use a different layout for each view, is that what you want to do?
Answer: If you are properly using asset bundles to load your styles you can set yii\web\AssetManager::$appendTimestamp property of asset manager component to append timestamp automatically.
You can do that in your app config file (for example frontend/config/main.php):
return [
    'components' => [
        'assetManager' => [
            'appendTimestamp' => true,
        ],
    ],
    // ... other configurations ...
]

See the guide article for more info about asset bundles.


Multiple regex capture groups using quantifiers

Question: Is there a way to get multiple capture groups out of a regex that is using quantifiers?  For example, say I have this data (simplified from what I have to deal with):
Data 1
data 2
data 3
data 4

Right now, if I write a regex like this:
(?:(.+?)<\/td>\s*){4}

I end up with only one capture group, the last one "data 4".  Is there a way to use the quantifier and end up with 4 capture groups, or am I forced to write the regex like this to get what I want:
(.+?)<\/td>\s*(.+?)<\/td>\s*(.+?)<\/td>\s*(.+?)<\/td>

Yes, I am well aware that I can hack this simple example up much easier programmatically and then apply and necessary regexes or simpler pattern matches.  The data I am working with is far more complex and I would really like to use a regex to handle all of the parsing.
Comment: I guess you missed the last paragraph.  This is a question of "is something possible with a regex", not "whats the best way to parse html".
Comment: Again, this isn't about parsing HTML, its about whether or not a regex can capture multiple groups using quantifiers.  This is a simple example to illustrate the point.
Comment: Too bad. [Perl 6 and .NET have the capability](http://stackoverflow.com/questions/2652554/which-regex-flavors-support-captures-as-opposed-to-capturing-groups) to access individual matches in a repeated group, PHP doesn't.
Comment: I've removed my first comment, but I disagree that the concept here is worth pursuing. Regex is only good for parsing HTML in  *very* simple cases. This isn't such.
Answer: With php you can use preg_match_all :
$str = 'Data 1
data 2
data 3
data 4
';
preg_match_all('/(?:(.+?)<\/td>\s*)/', $str, $m);
print_r($m);

output:
Array
(
    [0] => Array
        (
            [0] => Data 1

            [1] => data 2

            [2] => data 3

            [3] => data 4

        )

    [1] => Array
        (
            [0] => Data 1
            [1] => data 2
            [2] => data 3
            [3] => data 4
        )

)

Comment: I upvoted this because a more complex version of this is what I am doing already.  It doesn't answer my question about the regex capture groups with quantifiers though.  As I stated in the original content of the question, I would like to avoid programmatic answers to this question and would like to know if its possible from a pure regex perspective.
Comment: @Tony Lukasavage: Thanks. Unfortunatly, as Tim Pietzcker said in a comment, it's not possible in php.


Gamma function and limit of integral

Question: For $n \to \infty$, prove
$\int_{2n}^{\infty} t^n e^{-t}\ dt = o(\Gamma(n+1))$.
I have no clue to resolve this.
I started like this :
$\Gamma(n+1) =\int_{0}^{\infty} t^n e^{-t} dt$ and $\Gamma(n+1)= n\Gamma(n)$
but now I am stuck.
I am not allowed to use Stirling's Approximation.
Could anyone help me?
Answer: In the interval $[2n, +\infty)$ we have (by splitting $e^{-t} = e^{-t/2} e^{-t/2}$) that $e^{-t} \leq e^{-n} e^{-t/2}$. Thus, by a change of variables $u = t/2$,
$$ \int_{2n}^{+\infty} t^n e^{-t} dt \leq e^{-n} \int_{2n}^{+\infty} t^n e^{-t/2} dt = 2 \cdot 2^n e^{-n} \int_{n}^{+\infty} u^n e^{-u} du \leq 2\cdot 2^n e^{-n} \Gamma(n+1). $$
Hence,
$$ \lim_{n \to \infty} \frac{\int_{2n}^{+\infty} t^n e^{-t} dt}{\Gamma(n+1)} = 0 $$
because $e > 2$.
Comment: Wonderful! Thank you!

Gamma function and limit of integral