Rails assign instance variables in controller

Question: I have the following in my controller:
if params[:option] == "1"
      id = params[:id]
      @resultsReceived = true
      begin
       @pwvav_ratings = Pwvav.find_by_id(id).recommendation.split(",")
      #or
       @pwbab_ratings = Pwbab.find_by_id(id).recommendation.split(",")
     #or
       @puvub_ratings = Puvub.find_by_id(id).recommendation.split(",")
     #or
       @tic_ratings   = Tic.find_by_id(id).recommendation.split(",")
     rescue
       redirect_to "/view_api", :flash => { :notice => "Sorry, No records returned for #{id}." }
      end

I am trying to set each of those instance variables (@pwvav_ratings,@pwbab_ratings...) to the find if the find is not nil, so that I can call it in my view. How do I check if..or and if nothing is found, rescue with the flash notice.
Answer: Add this to the end of every line. Verifying it's not nil. (Notice ! but you can also use not)
@pwvav_ratings = Pwvav.find_by_id(id).recommendation.split(",") if !Pwvav.find_by_id(id).recommendation.split(",").nil?

Or you can use unless
@pwvav_ratings = Pwvav.find_by_id(id).recommendation.split(",") unless Pwvav.find_by_id(id).recommendation.split(",").nil?

Comment: It is bad to use that: Maybe the find_by_id will not return any result + You are triggering 2 queries to the DB (one to test, one to do if result exists)
Comment: that's true. i'm assuming it's not returning `nil` in the first place. real answer is to take that down into the model, and either have a `scope` or finder there. test the response, and then do an check if there's something available. This is just a quick and dirty solution.
Answer: Try this.
if params[:option] == "1"
  id = params[:id]
  @resultsReceived = true
  @pwvav_ratings = Pwvav.find_by_id(id)
  #or
  @pwbab_ratings = Pwbab.find_by_id(id)
  #or
  @puvub_ratings = Puvub.find_by_id(id)
  #or
  @tic_ratings   = Tic.find_by_id(id)
  unless @pwvav_ratings || @pwbab_ratings || @puvub_ratings || @tic_ratings
    redirect_to "/view_api", :flash => { :notice => "Sorry, No records returned for #{id}." }
  end
end

You can call .recomendation.split(',') on each variable in your view.
Comment: When I call `.recommendation.split(",").each do ` in my view I get `undefined method recommendation for []:Array`. Any idea what might be causing this?
Comment: On which variable you are calling `.recomendation.split(',')` ?
Comment: On all of them. I  loop through ` @pwvav_ratings`, `@pwbab_ratings`, `@puvub_ratings` and `@tic_tatings` in my view.
Comment: Is `Recomendation` another model?
Comment: If so then tell me attributes of that model.
Comment: Nope, recommendation is a column I have on each of the rating models. The values in that column are comma separated, hence then split(",").
Comment: try this, `@tic_tatings.first.recommendation.split(",").each do`


Windows Server 2012 DNS returns a useless tautology

Question: For one hostname - myaccount.cargowise.com - our Windows Server 2012 DNS seemingly returns a useless and tautological answer; it resolves myaccount.cargowise.com to itself without providing an IP address. No other domain names seem to be affected.
Attempting to access the website unsurprisingly reports that the domain name could not be resolved.
We have had this issue for over a week - I have tried to search for a solution, but since there is no error message it is not very "google-able". The server seems to think it is successfully answering. So far, we have worked around it by adding an entry to the drivers/etc/hosts file on the PCs of users who need this website.
$ nslookup myaccount.cargowise.com
Server:  (internal DNS)
Address:  172.30.0.78

Non-authoritative answer:
Name:    myaccount.cargowise.com

I see no obvious issue with the domain itself:
$ nslookup myaccount.cargowise.com 22.214.171.124
Server:  dns.google
Address:  188.8.131.52

Non-authoritative answer:
Name:    syd-1.oc.wisegrid.net
Addresses:  188.8.131.52
          184.108.40.206
          22.214.171.124
          126.96.36.199
          22.214.171.124
          220.127.116.11
Aliases:  myaccount.cargowise.com

Answer: Sorry, we have figured this one out:
We have a forward lookup zone for wisegrid.net, but the entry for syd-1.oc.wisegrid.net was typoed as sys-1.oc.wisegrid.net
So we resolved this by adding a forward lookup for syd-1.oc.wisegrid.net


implement multiTouch with cocos2d

Question: I have 2 buttons ,one uses for jumping (tap) and the other for walking (hold), they works perfect. the problem is that I can't use them in the same time. when I tap on jump button my sprite stop walking until I release the button and tap + hold it again.
I have searched in google but i didn't find any good tutorial for multiTouch, can anyone help me and show me examples to implement it?
I have found that I need to use this line in the appDelegate:
[glView setMultipleTouchEnabled:YES];

but it still not working for me.
samples of my code:
self.isTouchEnabled = YES;

        -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

        for ( UITouch* touch in touches ) {

                UITouch *touch = [touches anyObject];
                CGPoint location = [touch locationInView: [touch view]];

        if(CGRectContainsPoint(jumpBtn, location)) {...}

        }
      }

Comment: someone know better / another way?
Kirit's have a nice solution, but I am sure that there are better way to implement multiTouches.
Answer: you set [glView setMultipleTouchEnabled:YES]in your Appdelegate
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSArray *touchArray=[touches allObjects];

    if ([touchArray count] == 2)
      {
        //Double Click
      }
    else if([touchArray count]==1)
     {
       //Single Click
     }

}

Comment: this looks like a right solution, but I still have a issue with the multiTouch, I try put
NSArray *touchArray=[touches allObjects];

    if ([touchArray count] > 2) {
        CCLOG(@"2 touches!!!!!!!!!!!!!!!");
    }
but it doesn't work for me. when it equal to 1 it works fine. I already put this line:
[glView setMultipleTouchEnabled:YES];
 in the appDelegate inside the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
method and enable touch in my gameScene class. any suggestions?

implement multiTouch with cocos2d


SyntaxError: invalid syntax

Question: I am using Python 2.6.6 and is a newbie. I am getting
  File "./factorizer.py", line 35
    return {n: factorize_naive(n) for n in nums}
                                    ^
SyntaxError: invalid syntax

in the for statement within the return. It is supposed to return a dict with each element having number as key and list of prime factors as value. Where am I going wrong?
Answer: Dictionary comprehensions are only available in Python 2.7 and above. You'll need to use another method, preferably using dict():
dict((i, factorize_naive(i)) for i in nums)

Comment: Specifically, I would use `dict((n, factorize_naive(n)) for n in nums)` for this example.
Comment: @PeterDeGlopper Yup, just added it :)
Comment: Hey, you beat me to answering the question, I gotta get my two cents in somewhere.

SyntaxError: invalid syntax


Solve the equation $ A\cap X=B $ where $ A,B,X $ are sets.

Question: Let $ E $ be a set and $ A,B $ two nonempty subsets of $ E $.
Find the subset $ X $ of $ E $ satisfying
$$A \cap X = B. $$
I used the fact that if such nonempty subset $ X $ exists then necessarily
$$B= A\cap X \subset X$$
and
$$B=A \cap X \subset A$$
to conclude that
$$B\subset A \text{ and } B \subset X$$
from here i think there are a lot of cases to distinguish.
any help will be so appreciated.
Comment: The equation $A\cap X=B$ is solvable only if $B\subseteq A$. In this case $X=B$ provides a solution.
Comment: If there is a solution, then $B$ will be a solution.
Comment: $B \subset X$ is not a condition because $X$ is unknown. The only condition to make equation compatible is $B \subset A$.
Comment: Notice that :
$$X = (X \cap A) \cup (X \cap \bar{A})$$
Answer: Let $C$ denote any arbitrary subset of $A^{c}$.  That is, $A$ and $C$ are disjoint.
Under the assumption that $B \subseteq A$, you can simply set $X$ to equal $B \cup C$.
If $X$ contains any element inside of $A$, other than what is in $B$, then the constructed set $A \cap X$ will not equal $B$.
Since $A$ and $C$ are disjoint, appending $C$ to $X$ does not alter the constructed set $A \cap X$.


How to get the field name in a validation handler?

Question: I have a custom class TextWidget extends WidgetBase
Inside it I have a custom validation handler that looks like this:
public function validate($element, FormStateInterface $form_state) {
  $value = $element['#value'];
  $label = 'This field'; // What method is there to get the human facing field name?
  if (strlen($value) === 0) {
    $form_state->setError($element, $this->t('@label cannot be empty.', ['@label' => $label]));
  }
}

It outputs the error "This field cannot be empty." if the field is empty.
I want to replace the static text 'This field' with the actual human facing name of the field.
Is there a public method that lets me do that?
Answer: A class that extends WidgetBase can get the label with $this->fieldDefinition->getLabel(). That is used, for example, from WidgetBase::form().
$element = [
  '#title' => $this->fieldDefinition->getLabel(),
  '#description' => $this->getFilteredDescription(),
];


How can i hide the msinfo32.exe process window?

Question: Im creating the file msinfo :
ProcessRun.Processing(contentDirectory, "msinfo32.exe" , "/nfo " + "\"" + contentDirectory + "\\msinfo.nfo" + "\"",false,"");

This is the class that create and usig the process to create the file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace Diagnostic_Tool_Blue_Screen
{
    class ProcessRun
    {

        public void ProcessesRun()
        {

        }

        public static void Processing(string WorkingDirectory, string FileName, string Arguments, bool StandardOutput, string OutputFileName)
        {
            Process proc = new Process();
            proc.EnableRaisingEvents = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = StandardOutput;
            proc.StartInfo.FileName = FileName;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WorkingDirectory = WorkingDirectory;
            proc.StartInfo.Arguments = Arguments;
            proc.Start();
            if (StandardOutput == true)
            {
                string output = proc.StandardOutput.ReadToEnd();
                DumpOutput(WorkingDirectory + "\\" + OutputFileName, output);
            }
            proc.WaitForExit();
            proc.Close();
        }

        private static void DumpOutput(string filename, string output)
        {
            StreamWriter w = new StreamWriter(filename);
            w.Write(output);
            w.Close();
        }
    }
}

Once the process start and running the msinfo32.exe there is a small window showing the process of the msinfo32.exe in the middle of the screen.
Its not the cmd window ! Its part of the msinfo32.exe
Is there any way to hide this window while its Processing ?

Edited an image showing on the left my program and next to it on the right the small window of the msinfo32.exe that i want to hide.
Comment: What is the point of the empty public constructor of your class `ProcessRun`? If your class only contains those two (or however many) `static` methods, mark the class `static` too.
Answer: You could use the native function ShowWindow. You will need to check out pinvoke to find how to use it otherwise I am happy to give you a code snippet.
Answer: Can you add:
 proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

Answer: You can hide the window by referencing user32.dll.
Although the window will appear for a short time, it is possible to prevent the user from accidentally touching the cancel button.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace Diagnostic_Tool_Blue_Screen
{
    public class GetSystemInfo
    {
        [DllImport("user32.dll")]
        private static extern int FindWindow(string className, string windowText);

        [DllImport("user32.dll")]
        private static extern int ShowWindow(int hwnd, int command);

        public void GetInfo(string path)
        {
            using (Process exeObj = new Process())
            {
                exeObj.StartInfo.FileName = "msinfo32.exe";
                exeObj.StartInfo.Arguments = string.Format("{0}{1}{2}", "/nfo ", path, @"\mysysinfo.nfo");

                exeObj.StartInfo.UseShellExecute = false;
                exeObj.StartInfo.RedirectStandardInput = true;
                exeObj.StartInfo.RedirectStandardOutput = true;
                exeObj.EnableRaisingEvents = true;
                exeObj.Start();
                exeObj.BeginOutputReadLine();
                exeObj.Close();
            }

            Thread.Sleep(1000);
            const int SW_HIDE = 0;

            int hwnd = FindWindow(null, "System Information");

            if (hwnd != 0)
            {
                var num = ShowWindow(hwnd, SW_HIDE);
            }
        }
    }
}


Mann-Whitney null hypothesis under unequal variance

Question: I'm just curious about the null hypothesis of a Mann-Whitney U test. I often see it stated that the null hypothesis is that two populations have equal distributions. But I'm thinking - if I had two normal populations with the same mean but extremely unequal variance, the Mann-Whitney test would probably not detect this difference.
I have also seen it stated that the null hypothesis of the Mann-Whitney test is $\Pr(X>Y)=0.5$ or  the probability of an observation from one population ($X$) exceeding an observation from the second population ($Y$) (after exclusion of ties) is equal to 0.5. This seems to make a bit more sense but does not seem equivalent to the first null hypothesis I stated.
I'm hoping to get a bit of help untangling this. Thanks!
Answer: The Mann-Whitney test is a special case of a permutation test (the distribution under the null is derived by looking at all the possible permutations of the data) and permutation tests have the null as identical distributions, so that is technically correct.
One way of thinking of the Mann-Whitney test statistic is a measure of the number of times a randomly chosen value from one group exceeds a randomly chosen value from the other group.  So the P(X>Y)=0.5 also makes sense and this is technically a property of the equal distributions null (assuming continuous distributions where the probability of a tie is 0).  If the 2 distributions are the same then the probability of X being Greater than Y is 0.5 since they are both drawn from the same distribution.
The stated case of 2 distributions having the same mean but widely different variances matches with the 2nd null hypothesis, but not the 1st of identical distributions.  We can do some simulation to see what happens with the p-values in this case (in theory they should be uniformly distributed):
<code>> out <- replicate( 100000, wilcox.test( rnorm(25, 0, 2), rnorm(25,0,10) )$p.value )
> hist(out)
> mean(out < 0.05)
[1] 0.07991
> prop.test( sum(out<0.05), length(out), p=0.05 )

        1-sample proportions test with continuity correction

data:  sum(out < 0.05) out of length(out), null probability 0.05
X-squared = 1882.756, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.05
95 percent confidence interval:
 0.07824054 0.08161183
sample estimates:
      p
0.07991
</code>
So clearly this is rejecting more often than it should and the null hypothesis is false (this matches equality of distributions, but not prob=0.5).
Thinking in terms of probability of X > Y also runs into some interesting problems if you ever compare populations that are based on Efron's Dice.
Comment: Hi Greg, thank you for the answer. It sounds like what you are saying is I found somewhat of a special case where the test does not work properly under the equal distributions null. And furthermore, the null hypotheses I stated are not equal. Is that correct?
Answer: Mann-Whitney isn't sensitive to changes in variance with equal mean, but it can - as you see with the $P(X>Y)=0.5$ form, detect differences that lead $P(X>Y)$ to deviate from $0.5$ (e.g. where both mean and variance increase together). Quite clearly if you had two normals with equal mean, their differences are symmetric about zero. Therefore $P(X>Y) = P(X-Y>0) = \frac{1}{2}$, which is the null situation.
For example, if you have the distribution of $Y$ being exponential with mean $1$ while $X$ has an exponential distribution with mean $k$ (a scale change), the Mann-Whitney is sensitive to that (indeed, taking logs of both sides, its just a location-shift, and the Mann-Whitney is unaffected by monotonic transformation).
--
If you're interested in tests which are conceptually very similar to the Mann-Whitney that are sensitive to differences in spread under equality of medians, there are several such tests.
There's the Siegel-Tukey test and the Ansari-Bradley test, for example, both closely related to the Mann-Whitney-Wilcoxon two sample test.
They are both based on the basic idea of ranking in from the ends.
If you use R, the Ansari-Bradley test is built in ... <code>?ansari.test</code>
The Siegel-Tukey in effect just does a Mann-Whitney-Wilcoxon test on ranks computed from the sample differently; if you rank the data yourself, you don't really need a separate function for the p-values. Nevertheless, you can find some, as here:
http://www.r-statistics.com/2010/02/siegel-tukey-a-non-parametric-test-for-equality-in-variability-r-code/
--
(in relation to ttnphns' comment under my original answer)
You would be over-interpreting my response to read it as disagreeing with @GregSnow in any particularly substantive sense. There's certainly a difference in emphasis and to some extent in what we're talking about, but I'd be very surprised if there was much real disagreement behind it.
Let's quote Mann and Whitney: "A statistic $U$ depending on the relative ranks of the $x$'s and $y$'s is proposed for testing the hypothesis $f=g$." That's unequivocal; it utterly supports @GregSnow's position.
Now, let's see how the statistic is constructed: "Let $U$ count the number of times a $y$ precedes an $x$." Now if their null is true, the probability of that event is $\frac{1}{2}$ ... but there are other ways to get a probability of 0.5, and in that sense one might construe that the test can work in other circumstances. To the extent that they're estimating a (re-scaled) probability that $Y$>$X$, it supports what I said.
However, for the significance levels to be guaranteed to be exactly correct, you'd need the distribution of $U$ to match the null distribution. That's derived on the assumption that all the permutations of the $X$ and $Y$ group-labels labels to the combined observations under the null were equally likely. This is certainly the case under $f=g$. Exactly as @GregSnow said.
The question is the extent to which this is the case (i.e. that the distribution of the test statistic matches the one derived under the assumption that $f=g$, or approximately so), for the more generally expressed null.
I believe that in many situations that it does; in particular for situations including but more general than the one you describe (two normal populations with the same mean but extremely unequal variance can be generalized quite a bit without altering the resulting distribution based on ranks), I believe that the distribution of the test statistic turns out to have the same distribution under which it was derived and so should be valid there. I did some simulations that seem to support this. However, it won't always be a very useful test (it may have poor power).
I offer no proof that this is the case. I've applied some intuition/hand-wavy argument and also done some basic simulations that suggest it's true -- that the Mann-Whitney works (in that it has the 'right' distribution under the null) much more broadly than when $f=g$.
Make of it what you will, but I don't construe this as substantive disagreement with @GregSnow
Reference - Mann&Whitney's original paper
Comment: Did I get you right that you concur with this words from Wikipedia's Mann-Whitney talk page: `the null hypothesis of Mann-Whitney U-test is not about the equality of distributions. Is is about the symmetry between two populations with respect to the probability of obtaining a larger observation`. And so you don't agree with @Greg's answer, right?
Comment: I have added some discussion in edit.
Comment: Very nice addition. I'll be studying it (I always felt as if there are nuances in MW test that continue to elude me). Meanwhile, will you agree if I'd say: "Because MW test statistic reflects just the (in)equality of _mean ranks_, there can be situations when f~=g [I understand f,g as original distributions, prior ranking] but the test is nevetherless fully relevant as it continues to deal with the same H0 as under f=g. An example of such situation is symmetric distributions fully identical _except_ for spread parameter (variance)".
Comment: In the notation (Mann and Whitney's by the way), $f$ and $g$ are the densities of $X$ and $Y$. I'd agree that to the extent that I have verified/understood the circumstances, your statement appears to be the case. I suspect there's still plenty about the Mann-Whitney that eludes me also.


AppSettings.*.json files not copied on Publish in ASP.NET CORE 1.1

Question: I am publishing an ASP.NET Core 1.1 project with .csproj file ...
When I publish it the project is compiled and all the files, including the ones in wwwroot are copied, but all appsettings.*.json files are missing.
I am not sure why because I have the following:
<Content Include="**\*.json" />

What am I missing? Here is the complete .csproj file.
<Project>

  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" />

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="**\*.cs" />
    <Content Include="**\*.json" />
    <EmbeddedResource Include="**\*.resx" />
  </ItemGroup>

 <ItemGroup>
    <PackageReference Include="System.Runtime" Version="4.3.0" />
    <PackageReference Include="Microsoft.NETCore.App" Version="1.1.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Web" Version="1.0.0-alpha-20161104-2-112">
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Tools" Version="1.1.0-preview4-final" />
    <PackageReference Include="Microsoft.AspNetCore.ResponseCaching" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="1.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Rewrite" Version="1.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Routing" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0-msbuild1-final" />
  </ItemGroup>

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

  <Target Name="Prepublish" BeforeTargets="PrepareForPublish" Condition=" '$(IsCrossTargetingBuild)' != 'true' ">
    <Exec Command="npm install" />
    <Exec Command="bower install" />
    <Exec Command="gulp build" />
  </Target>

</Project>

Comment: I faced with the same problem. Just change **Copy to Output Directory** to **Copy Always**.
Comment: Any news? I am facing the same problem.
Comment: I'm also interested in the solution to this
Answer: I had a similar issue with four json files I was using as translation files for angular-translate. What I did to include them was explicitly mark them as content.
<Content Include="Language\locale-en.json" />
<Content Include="Language\locale-fr.json" />
<Content Include="Language\locale-es.json" />
<Content Include="Language\locale-pt.json" />


Conformal map from upper half plane to the slit unit disk

Question: I am trying to find a conformal map from $\mathbb{H}=\{z:Im(z)>0\}$ onto $\mathbb{D}$ take away $(-1,0]$, where $\mathbb{D}=\{z:|z|<1\}$ (the slit unit disk).
I have found that $f(z)=\frac{z-i}{z+i}$ takes $\mathbb{H}$ onto $\mathbb{D}$. Since it is a linear fractional transform, it is conformal.
However, I have no idea how to approach the slit.
Edit: One can map $\mathbb{H}$ onto $\mathbb{C}$ take away the positive imaginary axis by composing the conformal mappings $f(z)=e^{\pi i}z$ (maps to the bottom half plane) and $g(z)=z^{2}$ (doubling all angles), and then $h(z)=e^{\pi/2i}z$.
After this we can apply the fractional linear (Moebius) transformation $F(z)=\frac{z-i}{z+i}$. Since $F(0)=-1$ and $F(i)=0$, we can see that the slit of the positive imaginary axis maps to the negative real axis, exactly as we desire. However, $F$ maps the real axis to the boundary of the unit circle. This unfortunately means that $\phi(z)=\frac{e^{\pi/2i}(e^{\pi i}z)^2-i}{e^{\pi/2i}(e^{\pi i}z)^2+i}$ maps $\mathbb{H}$ onto $\{w:|w|\leq1\}-(-1,0]$, which is not quite $\mathbb{D}-(-1,0]=\{w:|w|<1\}-(-1,0]$. Please help.
Comment: Such a slit points to the possible use of the (principal branch of the complex) logarithm function.
Comment: Good methodology is given here for similar issues : https://math.stackexchange.com/questions/604877/conformal-map-from-disk-with-a-slit-to-the-upper-half-plane and https://math.stackexchange.com/q/264865
Comment: But for the logarithm to be conformal, the domain must be restricted to have a slit, defeating the purpose, am I wrong?
Answer: It is easier if we transform the slit circle into $\Bbb H$. The principal branch of $\sqrt z$ transforms the slit circle into the right semicircle. Multiplication by $i$ takes it to the upper semicircle. Now, the LTF $(1+z)/(1-z)$ takes the semicircle to the first quadrant. ¿Can you finish from here?
Comment: Surely you mean the right semicircle. Then the linear fractional transformation should be taken as $(\pm i + z)/(\pm i - z)$.
Comment: @Maxim Yes, that is what I meant. Thankyou for commenting.


meaning of $GF(2)[x]/(x^3-1)$

Question: What does $GF(2)[x]/(x^3-1)$ mean? I know $GF(2)$ is the Galois field with 2 elements, but what does the forward slash mean? Also, what's the meaning of the entire expression?
Thanks!
Comment: Numerator means the polynomials in indeterminate x with coefficients in GF(2).  The /(x^3-1) means "mod x^3-1" i.e. two polynomials are considered the same if they give the same remainder on division by x^3-1.
Answer: $\mbox{GF}(2)$ is the finite field with 2 elements (one of the rare instances in mathematics where the common name for an object is kind of larger than the object itself).
$\mbox{GF}(2)[x]$ is the ring of polynomials in the variable $x$ with coefficients in that field. If you're not sure what this means, you should probably learn about this first before you tackle the expression at hand. Let's call this ring $R$.
$x^3-1$ is a specific polynomial in that ring. Since the field is $\mbox{GF}(2)$, it's actually the same polynomial as $x^3+1$.
$(x^3-1)$ is the ideal generated by that polynomial: it's all the polynomials of the form $(x^3-1)f(x)$ where $f(x)$ is an arbitrary polynomial over $\mbox{GF}(2)$. Let's call this ideal $I$.
The forward slash means "quotient" - the quotient of ring $R$ by the ideal $I$, denoted $R/I$. One good way to think about it is as the the set of polynomials of degree 2 (or less), endowed with the operations of ordinary polynomial addition and ordinary multiplication except that after multiplying you take the remainder of the result upon division by $x^3-1$.
Comment: 1. For any ring $R$, the ring of polynomials in the variable $x$ with coefficients in $R$ is denoted $R[x]$. That's where the brackets come from and it has nothing to do with any modulo.
Comment: 2. In $R/(f)$ where $f$ is a polynomial, we're allowed to replace any polynomial by its residue modulo $f$. That's what "quotienting $f$ out" means. Since in your case $f$ has degree 3, any polynomial can be replaced by an equivalent one of degree 2 or less. For example, in the quotient ring, $x^3$ is the same as $-1$, and $x^4$ is the same as $x$. We might as well choose representatives of degree 2 or less.
Comment: 3. No, of course not! $(x^3-1)$ is the ideal generated by $x^3-1$.
Comment: thanks for the detailed answer! I'd appreciate it if you can clarify 3 more questions: 1. In $GF(2)[x]$, why is the x bracketed? Is it related to modulo? 2. why is $R/I$ the set of polynomials of degree 2 or less? I mean, why can't the degree be greater than 2? 3. You said $(x^3-1)$ is the ideal generated by "that" polynomial. Does "that" refer to any polynomial over $GF(2)$? thanks again!

meaning of $GF(2)[x]/(x^3-1)$


Checking if a string starts with another string

Question: Simple enough issue but I cannot seem to solve it. I need the below to be True.
var1="was shot by skeleton"
var2="was shot by"

if [ "$var1" == "$var2" ]; then
    echo "true"; else
    echo "false"
fi

I have Tried putting "*" beside var2 but no luck.
Thanks,
Simon
Answer: Try double brackets :
if [[ "$var1" == *"$var2"* ]]; then
.....

Comment: great... here is some info... http://serverfault.com/questions/52034/what-is-the-difference-between-double-and-single-square-brackets-in-bash ...
Comment: Yep that worked! Could you explain why? Thanks!


Linear maps: map construction

Question: From "Linear algebra done right" chapter 3:

Linear maps can be constructed that take on arbitrary values on a basis. Specifically, given a basis $\{v_1, \dots, v_n\}$ of $V$ and any choice of vectors $w_1, \dots, w_n \in W$, we can construct a linear map $T: V \to W$ such that $T(v_j) = w_j$ for $j = 1, \dots, n$. There is no choice of how to do this — we must define $T$ by $T(a_1v_1 + \dots + a_nv_n) = a_1w_1 + \dots + a_nw_n$, where $a_1, \dots, a_n$ are arbitrary elements of $\mathbb{F}$. Because $\{v_1, \dots, v_n\}$ is a basis of $V$, the equation above does indeed define a function $T$ from $V$ to $W$. You should verify that the function $T$ defined above is linear and that $T(v_j) = w_j$ for $j = 1, \dots, n$.

It seems obvious, and we can prove $\{w_1, \dots, w_j\}$ is a basis for $W$, but how to prove $T(v_j) = w_j$ exactly? Thank you.
Comment: $v_j=0v_1+0v_2+\cdot+1v_j+0v_{j+1}+\cdots+0v_n$.
Comment: Got it. Thanks.
Comment: Good. You can write it up as an answer, help clear up the Unanswered Questions list.
Answer: First of all, you can't prove that $\{w_1, \dots, w_n\}$ is a basis for $W$. This is false as $\{w_1, \dots, w_n\}$ is any choice of $n$ vectors in $W$, they may not even be distinct. For example, the construction outlined above works perfectly well for $w_1 = \dots = w_n = 0$.
Regarding your question, as Gerry Myerson pointed out in his comment, given $T : V \to W$ defined by
$$T(a_1v_1 + \dots + a_nv_n) = a_1w_1 + \dots + a_nw_n$$
we can see that $T(v_j) = w_j$ by noting that
\begin{align*}T(v_j) &= T(0v_1 + \dots + 0v_{j-1} + 1v_j + 0v_{j+1} + \dots + 0v_n)\\
&= 0w_1 + \dots + 0w_{j-1} + 1w_j + 0w_{j+1} + \dots + 0w_n\\
&= w_j.\end{align*}

Linear maps: map construction


Dominant 7th and Mixolydian

Question: Is the mixolydian mode the same as the dominant 7th? I don't know how else to ask it - My grammar is very good!
Answer: They are not the same, because the Mixolydian mode is a mode and the dominant 7th is a chord.
However, they are related. The G Mixolydian mode is G A B C D E F, and the G dominant 7th chord is G B D F, a subset of that Mixolydian mode.
This similarity is because the dominant 7th chord is built on the fifth scale degree of a major key. Similarly, the Mixolydian mode begins on the fifth scale degree of a major key (note that G Mixolydian has the same members as a C-major scale, and G is scale-degree 5 of C).
Part of the confusion is that jazz musicians can use a Mixolydian scale to improvise over a dominant 7th chord, and some musicians thus take that to mean the two are synonymous. They are similar, but not the same.
Comment: So I have got it nearly correct, except for the scales bit
Comment: Looks like it, yep. If you can clarify exactly why they are different but also why they're similar, then I'd say you've got it.
Comment: Yeah, I've actually learnt something today: Mixolydian Scales!
Comment: @Goodra - yes, except 'scales' that use the notes from a normal scale (Cmajor, Eb harmonic minor, F# melodic minor, etc. but have another note , not that root, as their base or home, are generally called *modes*.
Comment: @Tim , so is it appropriate to call it a scale or not?
Comment: I would say mode is more accurate. Wonder what Richard thinks.
Comment: You'll also hear people say things like "Mixolydian scale" (as I do in my final paragraph), but mode technically *is* more accurate.
Comment: Another case where nomenclature is confusing.  I would say that "modes" (which usually means the medieval European modes) are a subset of "scales" (which means any set of tones that are the basis of a particular piece of music).  Mixolydian is thus both a scale and a mode.  And definitely not a chord.
Answer: First, lets check you know what a Mixolydian scale is. It is a scale whose root note is the 5th note. For example, a Mixolydian C Scale consists of G A Bb C D E F G. A Mixolydian G Scale is D E F G A B C D
A Dominant 7th scale is just essentially the same thing. They have the same definitions!
However, the Dominant 7th chord is incorrect. Mixolydian is a type of scale. Dominant 7th is a chord.
Comment: Umm, the first scale is G Dorian, not C Mixolydian. Same pitches, different starting point. Ditto, for the second scale: it's D Dorian, not G Mixolydian.
Comment: Although I would personally call those two scales the G and D Mixolydian scales, respectively, just because we tend to name scales based off of their initial pitch.

Dominant 7th and Mixolydian


Django reduce queries

Question: I have two models, Post and Vote. Users can upvote and downvote posts.
models.py:
class Post(models.Model):
    poster = models.ForeignKey('auth.User')
    question = models.ForeignKey('self', null=True, blank=True)
    post_title = models.CharField(max_length=300)
    post_content = models.TextField(null=True, blank=True)

    is_published = models.BooleanField(default=True)
    is_locked = models.BooleanField(default=False)
    is_question = models.BooleanField(default=True)
    is_deleted = models.BooleanField(default=False)

    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)
    date_modified = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.post_title

class Vote(models.Model):
    user = models.ForeignKey('auth.User')
    post = models.ForeignKey('Post')
    vote_type = models.SmallIntegerField()#-1, 0, 1
    date_voted = models.DateTimeField(
            default=timezone.now)
    def __str__(self):
        return self.user

I use the following code in my view to return the posts to templates:
views.py:
def index(request):
    posts = Post.objects.filter(created_date__lte=timezone.now(
    ), is_question=1, is_published=1).order_by('-created_date')
    #removed the paging stuff here for simplification
    return render(request, 'homepage/index.html', {'posts': posts})

This just returns the posts, but I also want to check if the current user has voted or not (and possibly the sum of the vote_type column for each post which is the total number of votes for the post).
Currently I use template tags for each post to check if the current user has voted or not. This creates a lot of queries. (Currently 50 queries with 40 duplicates).
My index.html sample code:
{% for post in posts %}
       {% if post|userVotedThisPost:request.user.id == 1 %}

       {% else %}

       {% endif %}
{% endfor %}

Is there any way to query everything in the views.py and then in the template I could check like this: (if post.user_voted), so that the database is not hit each time in the for loop?
Answer: You can use prefetch_related to fetch the related votes for that user.
from django.db.models import Prefetch

Post.objects.filter(
    created_date__lte=timezone.now(),
    is_question=1,
    is_published=1
).order_by(
    '-created_date',
).prefetch_related(
    Prefetch('vote_set', queryset=Vote.objects.filter(user=request.user), to_attr='user_votes')
)

Then in your template, change the check to:
{% if post.user_votes %}

Comment: Is it possible to check for vote_type too? Did this user downvote, upvoted or did nothing (vote_type = 1, -1 or 0)? I mean could I change the prefetch query to return the vote_type?
Comment: The prefetch query returns a list of votes. If you only allow one vote per user per post, then the list will have one item (or it will be an empty list if the user didn't vote). You could show the vote type in the template with `{{ post.user_votes.0.vote_type }}`.
Comment: @ Alasdair is there some way to get the sum of the vote_type column for each post which is the total number of votes for the post
Comment: That would be better to ask as a separate question.
Comment: @ Alasdair here is the link to the new question: http://stackoverflow.com/questions/42303070/django-get-the-sum-of-votes-per-post

Django reduce queries


Are there infinitely many pairs of primes, $p$ and $q$, such that $q = 4p + 1$?

Question: How close can one come to proving that there are infinitely many primes, $p$ and $q$, such that $q = 4p + 1$?
The idea for this question came from reading the question and answers posed by
user39898, Quadratic reciprocity and proving a number is a primitive root, URL (version: 2012-12-12): Quadratic reciprocity and proving a number is a primitive root
Based on that result if there are infinitely many pairs of such primes then $2$ is a primitive root modulo infinity many primes.
This would relate to Artin's conjecture on primitive roots: https://en.wikipedia.org/wiki/Artin%27s_conjecture_on_primitive_roots
Because that conjecture has not been proven, all I am looking for is how close we are to proving that such a set of primes is infinite or suggestions on how to proceed.  I don't know how to begin answering it.
Comment: https://oeis.org/A023212
Comment: No-one knows. Probably, this will never be known.
Comment: I am aware of that.  What do we know?  What is the largest pair found so far?
Comment: @Dietrich Burde Yes, that is true, but that doesn't mean nothing is known about the question.  For example, a Sophie Germain prime cannot be one of the $p$ in this pair for $p > 3$ as mentioned in the the OEIS list A023212 that Will Jagy linked to.
Answer: The tuple $(x, 4x+1)$ is an admissible $2$-tuple in the language of the $k$-tuples conjecture of the conjectures of Hardy and Littlewood. It is believed that there are infinitely many $x$ such that $x$ and $4x+1$ are simultaneously prime. More generally, given an admissible $k$-tuple, it is beleived that there are infinitely many $x$ such that all $k$ elements of the $k$-tuple are simultaneously prime.
We do not know how to prove this. And before a few years ago, there was essentially no major progress towards the $k$-tuple conjecture.
The recent works of Zhang-Maynard-Tao-Polymath8 have made major progress towards a weakened version of the $k$-tuple conjecture. Namely, for any $k$, it has been shown that there exists some $n = n(k)$ (meaning that it depends on $k$) such that for any admissible $n$-tuple, there are infinitely many $x$ making $k$ elements of the $n$-tuple simultaneously prime.
For $2$-tuples, the number is on the order of $250$. What this means is that if one considers a $250$-tuple (like $(x, 4x+1, \ldots, \text{lots of other pieces})$) then there are infinitely many $x$ such that one of the pairs are simultaneously prime. Under the most ideal circumstances, one might hope to reduce the number $250$ to something smaller, but the current methods of proof are not capable of reducing this number all the way down to $2$.
Similarly, one might hope to isolate a particular pair, but there is no known way towards this either.
So this is the current state of the art, and there is no current widely-known method or idea of significantly improving this. It should take a genuine new idea (or more likely several new ideas) for progress to be made. I would not be surprised if it took many decades for further significant progress.


How to display the blocks to display in certain page in Drupal?

Question: Consider a module deserts:

page1:- deserts/*
page2:- deserts/*/*
page3:- deserts/*/*/*

A dynamic content ...
I have three blocks, namely a,b and c:

Block a should be displayed only in page1
Block b should be displayed only in page2
Block a should be displayed only in page3

How should do that restriction?
Comment: @Ajmal It would be useful if you could comment on the given answers and explain why they haven't helped. People will (naturally) assume that the high-voted answer is the correct one, and not go on to provide an alternative, if you haven't explained why that answer doesn't work for you.
Comment: Maybe it's just me, but this seems confusing.  `*` means wildcard.  So asking for a solution where the block appears for `desert/*/*` implies that it __should__ show up for `desert/*/edit` or, for that matter, `desert/*/whatever`.
Comment: Drupal 6 or 7? 6 makes it easier to define PHP code for block visibility.
Comment: It's drupal7 molot
Comment: I have the page
  `desert/*/*/`
  `desert/*/edit`
my block should display
   for all the
  `desert/*/*` not for
  `desert/*/edit`

 In such case it doesn't works for me..
Comment: hmm yes there comes an issue. I just want to explain more clear desert/*/* it should appear for all the wild card except the option edit.
Comment: Are those wildcards possibly numeric? or they can also be strings?
Answer: Use the context module. Though I'm not generally a fan of this module, this is one of the cases where it comes in handy.
Add a condition for a path. So if I want a block on page 1, but not page 2 or 3, I would write the paths like so, one for each block:
Case 1 - Block A

deserts/*
~deserts/*/*
~deserts/*/*/*

Case 2 - Block B

~deserts/*
deserts/*/*
~deserts/*/*/*

Case 3- Block C

~deserts/*
~deserts/*/*
deserts/*/*/*

The ~ means to exclude in this case. After that, add the block to the region you would like for it to show up. You can also add back in specific paths that might otherwise be excluded, and vice versa.
Comment: It holds good for this case. But we want to fix this for all the possible scenarios, that is the original solution, there is an case where it doesn't holds good. i have explained that case above. so please kindly refer that
Comment: I updated my answer, so hopefully this will explain it better. You would make one rule for each block.
Answer: You can use the "Pages on which this PHP code returns TRUE (expert only)" visibility option. But putting PHP code in the database is, IMHO, a bad practice. Instead, consider using something like the Extended block visibility module or implementation of hook_block_list_alter() such as
function MODULE_block_list_alter(&$blocks) {
  global $theme_key;
  foreach ($blocks as $key => $block) {
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
      // This block was added by a contrib module, leave it in the list.
      continue;
    }
    switch ("{$block->module}_{$block->delta}") {
      case "moduleA_deltaA":
        if (arg(0) != 'deserts' || !arg(1) || arg(2)) {
          unset($blocks[$key]);
        }
        break;
      case "moduleB_deltaB":
        if (arg(0) != 'deserts' || !arg(1) || !arg(2) || arg(3)) {
          unset($blocks[$key]);
        }
        break;
      case "moduleC_deltaC":
        if (arg(0) != 'deserts' || !arg(1) || !arg(2) || !arg(3)) {
          unset($blocks[$key]);
        }
        break;
    }
  }
}

Note: There is probably a smarter way to implement your visibility rule.
Answer: You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?

Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the various URLs corresponding your page1, page2 and page3.


Definite integral $\int_1^2 \sqrt{1+\left(-x^{-2}+x^2/4\right)^2}\,dx$

Question: I'm having trouble solving this integral. It relates to an arc length question. I tried Wolfram|Alpha, but when it solves it doesn't give me the option to view step-by-step.
Integral:
$$
\int_{1}^{2} \sqrt{1+\left(-x^{-2}+\frac{x^2}{4}\right)^2}\,dx
$$
Original question:
$$
y=\frac{1}{x} + \frac{x^3}{12}
$$
Find the arc length of the function on [1,2].
I used the equation:
$$
L = \int_a^b \sqrt{1+(f'(x))^2}
 dx$$
Comment: using Wolfram for the indefinte integral give a long solution: http://www.wolframalpha.com/input/?i=integrate+sqrt%281%2B%28x%5E%28-2%29%2Bx%5E2%2F6%29%5E2%29+dx
Comment: @String Unless you're Cleo. Then you can find closed-form solutions of integrals with no problem at all (but never ever the step-by-step ;)).
Comment: Yes it is! Thanks. I'm reading your code to learn for future reference.
Comment: @Stacksofoverflow You can simply hover over anything that is mathematically typeset and right-click: `Show Math As > TeX Commands`. That will show you how the equation or whatever it is you are looking at is typeset. Alternatively, you can simply look at the [edit history](http://math.stackexchange.com/posts/1177227/revisions) for questions to see how someone wrote something up.
Comment: It does seem like something you would only like to compute numerically. Unless you are a CAS, Newton or something similarly close to infinitely powerful ;)
Comment: Ok, thanks @therapist
Comment: @String ok I'll post the original arc length question, I'm probably approaching it incorrectly.
Comment: The derivative of $x^{-1}$ is $-x^{-2}$
Comment: Yeah I realized this as I edited, thanks @Dr.MV sloppy mistake.
Comment: There are very few of these problems for arc length that work out nicely.  Miss a sign, and you have one that doesn't work out in closed form.
Comment: @GEdgar Ok, I'll re-attempt it now that I have cleared the calculation errors.
Answer: Simplifying the integrand proceed as follows.$$1+\left( -x^{-2}+\frac14x^2\right)^2=1+\left(\frac{x^4-4}{4x^2}\right)^2=\frac{(x^4+4)^2}{16x^4}$$Then after taking a square root, the integrand simplifies to $$\frac{x^4+4}{4x^2}=x^{-2}+\frac14x^2$$which is trivial to integrate.
Comment: But the square root?
Comment: He included the square root, just didn't show it in the calculations.
Comment: Yes.  The integrand includes a square root.
Answer: If you expand the square, you can incorporate the $+1$ term into the expansion and then neatly factor everything into a quantity that has a simple square root. $$1+\left(-x^{-2}+\frac{x^2}{4}\right)^2 = 1+\left(x^{-4}-\frac{1}{2}+\frac{x^4}{16}\right) \\ = x^{-4}+\frac{1}{2}+\frac{x^4}{16}  \\ = \left(x^{-2}+\frac{x^2}{4}\right)^2$$ and hence $$
\int_{1}^{2} \sqrt{1+\left(-x^{-2}+\frac{x^2}{4}\right)^2}\,dx
 =
\int_{1}^{2} \sqrt{\left(x^{-2}+\frac{x^2}{4}\right)^2}\,dx
$$
Can you take it from here?
Comment: Dr.MV provided me with the solution, thanks for your help though


What does $\Bbb{Z}_{18}$ mean in this question?

Question: I am trying to solve this question

Let $G=\Bbb{Z}_{18}$ and $H$ a subgroup of G generated by $3$, Talk about normal subgroups and coset multiplication then find the cosets $(G/H,\bigotimes)$

Does $\Bbb{Z}_{18}$ mean $$\{0,1,2,3,...,16,17\}$$
or
$$\{1,a,a^2,...,a^{16},a^{17}\}$$
where $a$ is the generator of $G$.
If it is the second the definition then what does $a$ equal to here?
I am just confused if I am supposed to use the multiplication or addition here.
Comment: I think $\mathbb Z_{18}$ means integers modulo $18$
Comment: Yes, normally the first option.
Comment: @Théophile, so when calculating the cosets do I use the addition or multiplication i.e $g +H$ or $g.H$ where $g\in G$?
Comment: What is the book you are using?
Comment: When it says "generated by $3$" I deduce that the second option is no good.
Answer: As I am looking Your first option sounds good to me. if your $Z_{18}$ is $\Bbb{Z}_{18}$.
and the cosets in  $\Bbb{Z}_{18}/H$ are
$0+H=\{0,3,6,9,12,15\}$,
$1+H=\{1,4,7,10,13,16\}$  and so on. Can you complete it?
Comment: Yes, $Z_{18}$ is $\Bbb{Z}_{18}$. So when calculating the cosets do I use the addition too or do I use multiplication i.e $g +H$ or $g.H$ where $g\in G$?
Comment: addition i.e., $g+H$.
Comment: But why does $\bigotimes$ appear in $(G/H,\bigotimes)$. Doesn't this mean multiplication?
Comment: This is the modulo addition.
Comment: I think $H=\{0,3,6,9,12,15\}$.
Comment: @gbd yup, I forgot.
Comment: @Aman Pandey check that you are saying , costs in Z₁₈/H, but it is not ok, you have to say cosets of H in Z₁₈.
Comment: @AmanPandey, Is $0+H=H$ a coset too. Since $0\in G$
Comment: @gnd I wrote so.
Comment: @Subhajit Sorry! I can't get you. Well!Thanks  for your suggestion.
Comment: @gbd which book are you using?
Answer: Both are same. In the second group if you replace a by $1$ and use the operation of addition modulo $18$, then you get $\mathbb{Z}_{18}$. The notation $a^n$ means you apply the group operation on $a$, $n$ times. Both the sets you mentioned will be isomorphic if you use the map $1$ goes to $a$. So both are isomorphic. We generally use the first set you mentioned under addition modulo $18$ as it is easier to handle.
If you are talking about the normal subgroups of $G/H$:
As far as the quotient is concerned, $G/H$ has three elements and hence is a cyclic group (thus abelian) of order $3$. It is of the form $\{ H, 1+H, 2+H \}$. Since it is abelian, all the subgroups are normal. But since the order of group is $3$ it has only two subgroups $\{e\}$ (where $e$ is the identity) and the group $G/H$ itself.
Comment: "\left\{" and "\right\}".
Comment: Simpler yet, just `\{` and `\}`. Use `\left` and `\right` when size is an issue, e.g., if there are fractions or nested parentheses.
Comment: Yes. Will edit soon.
Answer: $\mathbb{Z}_{18}$ is the set of integers mod $18$. It is a group of order $18$ defined under modulo addition.
$$\mathbb{Z}_{18} = \{0, 1, 2, 3,..., 17\}$$
Notice that we stop at $17$. This is because $0$ is the identity element. If you're not familiar with modulo arithmetic, you may also be confused about how this group is closed under addition. After all, isn't $1+17=18$? Well, in this group, $17$ is the inverse of $1$. So $1+17=0$. Furthermore, $$2+16=0$$ $$3+15=0$$
and so on.
To answer your second question, factor (quotient) groups are defined under coset multiplication, which is defined as follows:
$$(aH)(bH) = (a\cdot b)H$$
where $\cdot$ is the binary operation of the original group.
Comment: Do you mean I should use  $g+H$ or $g.H$, g∈G when calculating the cosets?
Comment: Well, when you're calculating the cosets, you're going to use the "original" group's binary operation. Take an element in $G$ and add it to each element in $H$. Repeat this process for each element in $G$. Some of your cosets will be identical, so you don't have to rewrite these cosets. Now, the group $G/H$ is defined under coset multiplication. This is what I've defined in my answer.


I am a bit confused on how to prove that $\mathbb{R}^2 \rightarrow \mathbb{R}$ sending $(x,y)$ to $x+y$ and $xy$ are continuous.

Question: I am currently reading Hatcher's point set topology notes. My proof so far is,
Let $(\mathbb{R},d)$ be a metric space where $d$ is euclidean metric. This metric space induces a topological space labeled $(\mathbb{R},\mathcal{O})$. We can define a topology on $\mathbb{R}^2$ by defining the basis $\mathcal{B} = \{U \times V: U,V \in \mathcal{O} \}$. This is a basis since it satisfies (1) and (2) in Hatcher(Proposition 2). Since $\mathbb{R} \in \mathcal{O}$, then $\mathbb{R}^2 \in \mathcal{B}$ which satisfies (1). To show that it satisfies (2), suppose $U_1 \times V_1 \in \mathcal{B}$ and $U_2 \times V_2 \in \mathcal{B}$. Let, $x \in (U_1 \times V_1) \cap (U_2 \times V_2)$. Since $(U_1 \times V_1) \cap (U_2 \times V_2) = (U_1 \cap U_2) \times (V_1 \cap V_2)$ and $\mathcal{O}$ is closed under finite intersections, then there exists $B_3 = (U_1 \cap U_2) \times (V_1 \cap V_2) \in \mathcal{B}$ such that $x \in B_3 \subset (U_1 \cap U_2) \times (V_1 \cap V_2)$. Thus, $\mathcal{B}$ is a basis for a topology on $\mathbb{R}^2$ denoted as $\mathcal{O}_2$.
I want to show that both functions($f(x,y) = x+y$ and $g(x,y) = xy$) are continuous(note, $(\mathbb{R},\mathcal{O})$ and $(\mathbb{R}^2,\mathcal{O}_2)$. I suppose that $O \in \mathcal{O}$. I am trying to show that $f^{-1}(O) \in O_2$. I am struggling with what $f^{-1}(O)$ set looks like.
Comment: Might be easier to show limits of sequences are preserved.
Comment: it really depends first on your definition of what a real number is and how addition is defined
Comment: also, it would be worth noting that both topologies are equivalent, so you can just use the standard epsilon delta definition of continuity
Comment: There are at least 2 ways to approach this problem.
Answer: In Hatcher's notes, this is exercise 13 p. 15, which requires "using
only definitions and results from this class, not results from calculus for example". On p. 14, Hatcher advised you to "check that [your map $f:(x,y)\mapsto x+y$] is continuous by seeing directly that the inverse image of an open interval is open". On p. 12 he said that the product topology on $\mathbb R^2$ coincides with the "usual topology", which he defined on p. 3.
Let $U=f^{-1}((a,b))$ and $(x_0,y_0)\in U$, i.e. $a<x_0+y_0<b$. Let $\epsilon=\frac12\min(b-x_0-y_0,x_0+y_0-a)$. Then, the open square $(x_0-\epsilon,x_0+\epsilon)\times(y_0-\epsilon,y_0+\epsilon)$ is contained in $U$. This proves that $U$ is open, q.e.d.
Answer: The continuity of $\phi : X \to Y$ can be characterized by various equivalent properties. The standard definition is probably that $\phi^{-1}(V)$ is open in $X$ whenever $V \subset Y$ is open. But sometimes it is easier to work with this property:

$\phi$ is continuous iff it is continuous at each $x \in X$.  Continuity at $x \in X$ means that for each open neigbborhood $V$ of $\phi(x)$ in $Y$ there exists an open neigborhood $U$ of $x$ in $X$ such that $\phi(U) \subset V$.

Let $(x,y) \in \mathbb R^2$ and $V$ be an open neigborhood of $s = f(x,y) = x+y$ in $\mathbb R$. Choose $r >0$ such that $(s-r,s+r) \subset V$. Then $U = (x-r/2,x+r/2) \times (y-r/2,y+r/2)$ is an open neighborhood of $(x,y)$ in $\mathbb  R^2$ such that $f(U) \subset (s-r,s+r) \subset V$.
Let $(x,y) \in \mathbb R^2$ and $V$ be an open neigborhood of $p = g(x,y) = x \cdot y$ in $\mathbb R$. Choose $r >0$ such that $(p-r,p+r) \subset V$. Choose $u> 0$ such that $u^2 < r/2$ and $u(\lvert x \rvert + \lvert y \rvert) < r/2$. Then $U = (x-u,x+u) \times (y-u,y+u)$ is an open neighborhood of $(x,y)$ in $\mathbb  R^2$ such that $g(U) \subset (p-r,p+r) \subset V$.
Answer: Another method of proving maps are continuous is to show they preserve limits of sequences. That is if:
$$f(\lim\limits_{n\in\mathbb{N}}s_n) = \lim\limits_{n\in\mathbb{N}}f(s_n),$$
for an arbitrary sequence $\{s_n\}_{n\in\mathbb{N}}\in dom(f)$.

If we argue that any sequence of points in $\mathbb{R}^2$ is given by a collection of coordinates indexed as follows:
$$\{(x_n,y_n)\}_{n\in\mathbb{N}}$$
Then with the addition and multiplication maps, we have respectively:
$$\color{blue}{+\big(\lim\limits_{n\to\infty}(x_n,y_n)\big)} = +\big((\lim\limits_{n\in\mathbb{N}}x_n,\lim\limits_{n\in\mathbb{N}}y_n)\big):= \lim\limits_{n\in\mathbb{N}} x_n + \lim\limits_{n\in\mathbb{N}}y_n = \lim\limits_{n\in\mathbb{N}}(x_n+y_n) =: \color{blue}{\lim\limits_{n\in\mathbb{N}}+\big((x_n,y_n)\big)}$$
and
$$\color{blue}{*\big(\lim\limits_{n\to\infty}(x_n,y_n)\big)} = *\big((\lim\limits_{n\in\mathbb{N}}x_n,\lim\limits_{n\in\mathbb{N}}y_n)\big):= \lim\limits_{n\in\mathbb{N}} x_n * \lim\limits_{n\in\mathbb{N}}y_n = \lim\limits_{n\in\mathbb{N}}(x_n*y_n) =: \color{blue}{\lim\limits_{n\in\mathbb{N}}*\big((x_n,y_n)\big)}.$$
The limit applying component wise in the first equality is more or less intuitive. The compatibility with limits in the 3rd equalities is assumed known.


What is the difference between 1-year partial prevalence and annual incidence?

Question: In cancer research, like in this article, partial prevalence is sometimes used to assess the epidemiological state of a disease in a population.
The document I'm trying to understand (link, in french) gives total prevalence and partial prevalences at 1, 3, 5 and 10 years. It defines partial prevalence at 1 year as:

Partial prevalence at 1 year:

The number of people 15 years of age and older diagnosed with cancer during the year and still alive in 2008 is estimated at nearly
280,500: 155,675 men and 124,860 women.
This indicator makes it possible to quantify people with cancer in initial treatment

To me, this definition is very close to the one of annual incidence.
I've found very few documents explaining what was partial prevalence (example, example) but no one ever compare it to incidence.
What is the difference between these two notions?
Answer: This page from one of your links puts it pretty clearly:

Partial prevalence is the number of all cancer patients, being alive at specific date  (usually the last day of calendar year) and being diagnosed with cancer within a defined period of time before the date of calculation. One year partial prevalence includes patients, diagnosed with cancer one year before the date of calculation, patients included in 1-4 years prevalence were diagnosed within one and five years before calculation, ... they reflect the number of cancer cases in different course of disease, e.g. the one-year prevalence includes patients during their primary treatment, 1-4 years prevalence those requiring regular clinical follow-up, while 5-9 and especially 10 and more years prevalence includes predominantly those considered cured from cancer.

Start with the difference between the 1-year partial prevalence and the 1-year incidence. The latter is easy and independent of cancer type, simply how many patients were diagnosed with the disease in question over the previous year. The former is the product of that incidence times an estimate of survival over the year.* The partial prevalence thus depends on survival, not just incidence.
So for a disease like estrogen-receptor-positive stage 0 or 1 breast cancer, with 100% 5-year survival, you are correct that incidence and partial prevalence will be essentially identical in any partial prevalence calculated for time periods that do not extend beyond 5 years.
For anaplastic thyroid cancer, where "Most patients ... do not live 1 year from the day they are diagnosed," even the 1-year partial prevalence will be much lower than the incidence: many of those diagnosed over the year will have died by the end of the year. The 1-4 year partial prevalence for anaplastic thyroid would be almost 0.
Summary data like those in your second link can combine data across different types of cancer. Many people diagnosed with cancers have high 1-year survival, so 1-year partial prevalence combined across cancer types will be close to 1-year incidence. Incidence and partial prevalence will become more distinct at later time intervals after initial diagnosis.

*With epidemiologic whole-year data, this survival estimate might be taken at 1/2 year to account for accrual of patients over a period of 0 to 12 months.
Comment: Since I am working on rather non aggressive cancers, I totally missed out the point of survival. Thanks a lot once again, this was very helping!


How to select a random element from a part of a list?

Question: I have a list called game
game = ['X','O',' ',' ',' ',' ',' ',' ',' ']

I need to select a random element from all the ' ' elements only. It will then change it to X or O and do again.
Using simple random.choice() has a chance of never ending. random.choices() returns the element instead of its index so I cannot think of a way to update the weights.
Comment: Get the indexes of the elements that are blank or ' ' in a list and then do random.choice() on it. and then change corresponding data in your game list.
Comment: Rejection sampling with repeated calls of `random.choice` may be a reasonable thing to do here, the probability of it never ending rapidly approaches 0.
Comment: @miradulo rejection sampling is new to me and from what I read, I can't see a way to use it here. Can you explain it or give a link that explains it?
Comment: @KushagraGupta Just continue calling `random.choice` until you happen upon a `' '`.
Answer: Determine which indices have spaces and use random.choice to choose one
from random import choice

game = ['X','O',' ',' ',' ',' ',' ',' ',' ']
index = choice([i for i, x in enumerate(game) if x == ' '])

Comment: Thanks. This is exactly what I needed. I can't believe I didn't even think of this.


Como separar em pares os digitos de uma variável em C#?

Question: Como eu pego uma variável que possui um valor de 4 dígitos, dividir esses dígitos em pares e salva-los em outras variáveis?
exemplo: 3025 = 30 25
Answer: Se quiser dividir qualquer número inteiro, sem converter para string, e com suporte para tamanho de agrupamento arbitrário:
using System.Collection.Generic;

long[] DividirNumero(long valor, int tamanhoGrupo)
{
    if(tamanhoGrupo <= 0)
        return new [] {valor};

    int localTamanhoGrupo = (int) Math.Pow(10, tamanhoGrupo);
    Stack<long> resultado = new Stack<long>();
    valor = Math.Abs(valor);

    do
    {
        resultado.Push(valor % localTamanhoGrupo);
        valor /= localTamanhoGrupo;

    } while (valor > 0);

    return resultado.ToArray();
}

// 1234 (tamanho agrupamento 0) => 1234
// 1234 (tamanho agrupamento 2) => 12 34
// 1234 (tamanho agrupamento 3) => 1 234
// 123456789 (tamanho agrupamento 2) => 1 23 45 67 89
// 123456789 (tamanho agrupamento 6) => 123 456789
// 123456789 (tamanho agrupamento 1) => 1 2 3 4 5 6 7 8 9
// 9223372036854775807 (tamanho agrupamento 3) => 9 223 372 36 854 775 807
// 2147483647 (tamanho agrupamento 2) => 21 47 48 36 47
// -2147483648 (tamanho agrupamento 2) => 21 47 48 36 48

(Pode ver um exemplo aqui).
Answer: A pergunta está bem vaga, não dá pra saber o tipo da variável e qual seria o propósito disso, mas considerando que seja uma string, pode-se fazer assim:
Exemplo utilizando 5 valores para exemplificar:
using System;

public class Program
{
    public static void Main()
    {
        string[] valores = new string[]{"3025","302","","1","12345"};

        for (int i =0; i < valores.Length; i++)
        {
            Console.WriteLine("Valor " + (i + 1)+":");
            string p1 = valores[i].Substring(0,valores[i].Length/2);
            string p2 = valores[i].Substring(valores[i].Length/2);

            Console.WriteLine("Parte 1: "+ p1);
            Console.WriteLine("Parte 2: "+ p2);
            Console.WriteLine("------------");

        }

    }
}

Resultado:

Valor 1:
Parte 1: 30
Parte 2: 25
------------
Valor 2:
Parte 1: 3
Parte 2: 02
------------
Valor 3:
Parte 1:
Parte 2:
------------
Valor 4:
Parte 1:
Parte 2: 1
------------
Valor 5:
Parte 1: 12
Parte 2: 345

Answer: Este método suporta qualquer tipo de elemento, desde que seja enumerável. De princípio, declare o seguinte método:
    ///
    /// Splits an array into several smaller arrays.
    ///
    /// <typeparam name="T">The type of the array.</typeparam>
    /// <param name="array">The array to split.</param>
    /// <param name="size">The size of the smaller arrays.</param>
    /// <returns>An array containing smaller arrays.</returns>
    internal static IEnumerable<IEnumerable<T>> Split<T>(T[] array, int size)
    {
        for (var i = 0; i < (float)array.Length / size; i++)
        {
            yield return array.Skip(i * size).Take(size);
        }
    }

Para usar em uma String, você fará o seguinte:
string palavra = "30250892";
IEnumerable<IEnumerable<char>> conjuntos = Split(palavra.ToCharArray(), 2); // não se esqueça do ToCharArray()

foreach (IEnumerable<char> par in conjuntos) {
     string parFormatado = string.Join("", par);
     Console.WriteLine(parFormatado);
}

// 30
// 25
// 08
// 92

Você pode usar este método em qualquer tipo, desde que esteja enumerado (em listas).

Créditos do método Split.


Does correlation assume stationarity of data?

Question: Inter-market analysis is a method of modeling market behavior by means of finding relationships between different markets. Often times, a correlation is computed between two markets, say S&P 500 and 30-Year US treasuries. These computations are more often than not based on price data, which is obvious to everyone that it does not fit the definition of stationary time series.
Possible solutions aside (using returns instead), is the computation of correlation whose data is non-stationary even a valid statistical calculation?
Would you say that such a correlation calculation is somewhat unreliable, or just plain nonsense?
Comment: there is a new site which might be more suitable for your question: http://quant.stackexchange.com. Now you are clearly confusing calculation with interpretation.
Comment: what do you mean by "valid statistical calculation" you should say valid statistical (estimation) calculation of something. Here the something is very important. Correlation is a valid calculation of the linear relation between two set of data. I don't see why you need stationarity, did you mean auto-correlation ?
Comment: @mpiktas, the quant community is settled on using returns vs prices because of the stationarity of returns and the non-stationarity of prices. I'm asking here for something more than an intuitive explanation of why this should be so.
Comment: @robin, there are several things that may have you question a statistical analysis. Sample size comes to mind, as does more obvious things such as manipulated data. Does non-stationarity of data call into question a correlation calculation?
Comment: not the calculation, maybe the interpretation if the correlation is not high. If it is high it means high correlation (i.e. high linear relation), two non stationnary time series say $(X_t)$ and $(Y_t)$ can be  potentially highly correlated (for example when $X_t=Y_t$.
Answer: The correlation measures linear relationship. In informal context relationship means something stable.  When we calculate the sample correlation for stationary variables and increase the number of available data points this sample correlation tends to true correlation.
It can be shown that for prices, which usually are random walks, the sample correlation tends to random variable. This means that no matter how much data we have, the result will always be different.
Note I tried expressing mathematical intuition without the mathematics. From mathematical point of view the explanation is very clear: Sample moments of stationary processes converge in probability to constants. Sample moments of random walks converge to integrals of brownian motion which are random variables. Since relationship is usually expressed as a number and not a random variable, the reason for not calculating the correlation for non-stationary variables becomes evident.
Update Since we are interested in correlation between two variables assume first that they come from stationary process $Z_t=(X_t,Y_t)$. Stationarity implies that $EZ_t$ and $cov(Z_t,Z_{t-h})$ do not  depend on $t$. So correlation
$$corr(X_t,Y_t)=\frac{cov(X_t,Y_t)}{\sqrt{DX_tDY_t}}$$
also does not depend on $t$, since all the quantities in the formula come from matrix $cov(Z_t)$, which does not depend on $t$. So the calculation of sample correlation
$$\hat{\rho}=\frac{\frac{1}{T}\sum_{t=1}^T(X_t-\bar{X})(Y_t-\bar{Y})}{\sqrt{\frac{1}{T^2}\sum_{t=1}^T(X_t-\bar{X})^2\sum_{t=1}^T(Y_t-\bar{Y})^2}}$$
makes sense, since we may have reasonable hope that sample correlation will estimate $\rho=corr(X_t,Y_t)$. It turns out that this hope is not unfounded, since for stationary processes satisfying certain conditions we have that $\hat{\rho}\to\rho$, as $T\to\infty$ in probability. Furthermore $\sqrt{T}(\hat{\rho}-\rho)\to N(0,\sigma_{\rho}^2)$ in distribution, so we can test the hypotheses about $\rho$.
Now suppose that $Z_t$ is not stationary. Then $corr(X_t,Y_t)$ may depend on $t$. So when we observe a sample of size $T$ we potentialy need to estimate $T$ different correlations $\rho_t$. This is of course infeasible, so in best case scenario we only can estimate some functional of $\rho_t$ such as mean or variance. But the result may not have sensible interpretation.
Now let us examine what happens with correlation of probably most studied non-stationary process random walk. We call process $Z_t=(X_t,Y_t)$ a random walk if $Z_t=\sum_{s=1}^t(U_t,V_t)$, where $C_t=(U_t,V_t)$ is a stationary process. For simplicity assume that $EC_t=0$. Then
\begin{align}
corr(X_tY_t)=\frac{EX_tY_t}{\sqrt{DX_tDY_t}}=\frac{E\sum_{s=1}^tU_t\sum_{s=1}^tV_t}{\sqrt{D\sum_{s=1}^tU_tD\sum_{s=1}^tV_t}}
\end{align}
To simplify matters further, assume that $C_t=(U_t,V_t)$ is a white noise. This means that all correlations $E(C_tC_{t+h})$ are zero for $h>0$. Note that this does not restrict $corr(U_t,V_t)$ to zero.
Then
\begin{align}
corr(X_t,Y_t)=\frac{tEU_tV_t}{\sqrt{t^2DU_tDV_t}}=corr(U_0,V_0).
\end{align}
So far so good, though the process is not stationary, correlation makes sense, although we had to make same restrictive assumptions.
Now to see what happens to sample correlation we will need to use the following fact about random walks, called functional central limit theorem:
\begin{align}
\frac{1}{\sqrt{T}}Z_{[Ts]}=\frac{1}{\sqrt{T}}\sum_{t=1}^{[Ts]}C_t\to (cov(C_0))^{-1/2}W_s,
\end{align}
in distribution, where $s\in[0,1]$ and $W_s=(W_{1s},W_{2s})$ is bivariate Brownian motion (two-dimensional Wiener process). For convenience introduce definition $M_s=(M_{1s},M_{2s})=(cov(C_0))^{-1/2}W_s$.
Again for simplicity let us define sample correlation as
\begin{align}
\hat{\rho}=\frac{\frac{1}{T}\sum_{t=1}^TX_{t}Y_t}{\sqrt{\frac{1}{T}\sum_{t=1}^TX_t^2\frac{1}{T}\sum_{t=1}^TY_t^2}}
\end{align}
Let us start with the variances. We have
\begin{align}
E\frac{1}{T}\sum_{t=1}^TX_t^2=\frac{1}{T}E\sum_{t=1}^T\left(\sum_{s=1}^tU_t\right)^2=\frac{1}{T}\sum_{t=1}^Tt\sigma_U^2=\sigma_U\frac{T+1}{2}.
\end{align}
This goes to infinity as $T$ increases, so we hit the first problem, sample variance does not converge. On the other hand  continuous mapping theorem in conjunction with functional central limit theorem gives us
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TX_t^2=\sum_{t=1}^T\frac{1}{T}\left(\frac{1}{\sqrt{T}}\sum_{s=1}^tU_t\right)^2\to \int_0^1M_{1s}^2ds
\end{align}
where convergence is convergence in distribution, as $T\to \infty$.
Similarly we get
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TY_t^2\to \int_0^1M_{2s}^2ds
\end{align}
and
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TX_tY_t\to \int_0^1M_{1s}M_{2s}ds
\end{align}
So finally  for sample correlation of our random walk we get
\begin{align}
\hat{\rho}\to \frac{\int_0^1M_{1s}M_{2s}ds}{\sqrt{\int_0^1M_{1s}^2ds\int_0^1M_{2s}^2ds}}
\end{align}
in distribution as $T\to \infty$.
So although correlation is well defined, sample correlation does not converge towards it, as in stationary process case. Instead it converges to a certain random variable.
Comment: @whuber my take away from the answer is that a correlation based on non-stationary data yields a random variable, which may or may not be useful. Correlation based on stationary data converges to a constant. This may explain why traders are attracted to "x-day rolling correlation" because the correlated behavior is fleeting and spurious. Whether "x-day rolling correlation" is valid or useful is for another question.
Comment: The mathematical point of view explanation is what I was looking for. It gives me something to contemplate and explore further. Thanks.
Comment: This response seems to sidestep the original question: Aren't you just saying that yes, calculating correlation makes sense for stationary processes?
Comment: @whuber, I was answering the question having in mind the comment, but I reread the question again and as far as I understand the OP asks about calculation of correlation for non-stationary data. Calculation of correlation for stationary processes makes sense, all the macroeconometric analysis (VAR, VECM) relies on that.
Comment: I'll try to clarify my question with a response.
Comment: But can you take the first differenced correlation to be an estimate of the correlation coefficient between the two data generating processes? In other words, are you stuck with a correlation where the interpretation is in first differences?
Answer:
...is the computation of correlation whose data is non-stationary even a valid statistical calculation?

Let $W$ be a discrete random walk.  Pick a positive number $h$.  Define the processes $P$ and $V$ by $P(0) = 1$, $P(t+1) = -P(t)$ if $V(t) >  h$, and otherwise $P(t+1) = P(t)$; and $V(t) = P(t)W(t)$.  In other words, $V$ starts out identical to $W$ but every time $V$ rises above $h$, it switches signs (otherwise emulating $W$ in all respects).

(In this figure (for $h=5$) $W$ is blue and $V$ is red.  There are four switches in sign.)
In effect, over short periods of time $V$ tends to be either perfectly correlated with $W$ or perfectly anticorrelated with it; however, using a correlation function to describe the relationship between $V$ and $W$ wouldn't be useful (a word that perhaps more aptly captures the problem than "unreliable" or "nonsense").
Mathematica code to produce the figure:
<code>With[{h=5},
pv[{p_, v_}, w_] := With[{q=If[v > h, -p, p]}, {q, q w}];
w = Accumulate[RandomInteger[{-1,1}, 25 h^2]];
{p,v} = FoldList[pv, {1,0}, w] // Transpose;
ListPlot[{w,v}, Joined->True]]
</code>
Comment: @robin girard, I think the key here is that for non-stationary processes the theoretical correlation varies with time, when for the stationary processes theoretical correlation stays the same. So with sample correlation which basically is one number, it is impossible to capture the variation of true correlations in case of non-stationary processes.
Comment: @robin That's a good point, but I constructed this example specifically so that for potentially long periods of time these two processes are *perfectly* correlated.  The issue is not one of dependence versus correlation but inherently is related to a subtler phenomenon: that the relationship between the processes changes at random periods.  That, in a nutshell, is exactly what can happen in real markets (or at least we ought to worry that it can happen!).
Comment: it is good that your answer points that out but I wouldn't say the process are correlated, I would say they are dependent. This is the point. Calculation of correlation is valide and here it will say "no correlation" and we all know this does not mean "no dependence".
Comment: @whubert yes, and this is a very good example showing that there are processes that have very high correlation for potentially long periods of time and still are not correlated at all (but highly dependent)  when regarding the larger temporal scale.


Multi month selector

Question: Does anybody know whats the name of the multi-month selector control used in Mint.com?
I have a video of it been used here. I've come across a lot of date picker and calendar controls but all of them are pretty much the same.
Preferably in jQuery
Comment: You mean the month slide-selector thingy at the top?  I would guess that is custom code.
Comment: There is no plugin that provides that functionality like in this video ! You will have to do in on your own.
Comment: Thanks. I guess I'll just build that myself.
Answer: How about jQuery UI Datepicker? Its widely used and well tested.
Answer: It seems to me that this is a control from Qlik softwares (either Qlik Sense or QlikView) that allows users to do such selections. It can be embedded into Mint's solution.
Here's an example:
My Life in Data - Tab Running: https://eu-b.demo.qlik.com/QvAJAXZfc/opendoc.htm?document=qvdocs%2FMy%20Life%20in%20Data.qvw&host=demo11

Note that it is really hard to make sure as the video is not 'browsable'.

Multi month selector


How to bind D and C

Question: Can someone point me to a good tutorial of how to call C code from D ( and possibly to call a FORTRAN library from D)?
I've researched the topic online and keep finding incomplete examples. I would like someone to spell it out for me one time. For example, show some example bindings and explain the steps to compiling and linking them to work together.
I have both the DMD and GDC compilers on windows.
Some background: Programming isn't my main job, but I do it A LOT at work. I work with Python and Java a lot, my first language was C, and I've done some web programming too. For my next project I'd like to use D, as it seems the learning curve is much lower than C++. Also I want a compiled language, and I've never mixed two languages before.
Comment: It is unbelievable how antisocial people on SO are... Why voting to close this thread?? It is a perfectly good and polite question...
Answer: have a look to Derelict.org, it contains dozen of C bindings using ffi and dynamic-linking (run-time loading and delegate assignation.)
Comment: You'll probably want to use the D compiler for the final step, so it links in the D runtime. You could still use the C++ compiler or linker directly, but you'll need to specify the C and D runtime libraries to link manually.
Comment: How do I link the source files from different languages into 1 executable?
Comment: Just pass the object or library files to the compiler on its command line. The compiler will pass them to the linker.
Comment: @CyberShadow, I think I'm figuring this out, so compile with the -c option for each language with it's respective compiler, then compile again with any compiler passing the *.obj files. Sound correct?
Answer: Deimos is a huge repository of bindings and wrappers of C libraries to D. I suggest you take a look at some small binding, and see how people did it.

How to bind D and C


In standard tuning, does guitar string 6 produce E3 or E2?

Question: I am finding confusing information concerning guitar string 6's frequency.  Many articles claim it to be E2. How can it be E2 when string 6 is E below middle C which is E3?
Comment: See also: [Why is guitar music written one octave higher?](https://music.stackexchange.com/q/101432/70803).
Comment: @ejbpesca No, that's the small c, or C3, an octave lower. If you want to play a middle C, go to the B string, fret 1.
Comment: Given, that there are several octave numbering schemes, this is hard to answer. But the interval between strings is constant, so which octave has your fifth string?
Comment: @guidot I think it's clear from context that the asker considers middle C to be C4.
Comment: I am going by the common expression that middle C is C4 261.6 Hz.
Comment: To be more clear, is string 5 fret 3 not the frequency of middle C?
Answer: The guitar is a quasi-transposing instrument because it sounds an octave lower than written. When we read E3 on a score and then play the lowest string on the guitar, the sound that comes out is E2. When we read middle C on the score and play the third fret of the A string the sound that comes out is C3.
For transposing instruments, each fingering has two pitches related to it. There's the "written" pitch, which means when we see that note in sheet music, we play that fingering. The other pitch related to a specific fingering is the "concert" pitch, which is the pitch (similar to frequency) that we hear coming from the instrument as the actual sound.
On the guitar, every fingering has a concert pitch that is an octave lower than the written pitch. So when we see middle C written on the page, we play the fifth string, third fret. And when we play that, what we hear is an octave below middle C.
Since every string and fret combination on guitar has two pitches associated with it, we have to give two answers to the question "is string five, fret 3 middle C?" It is and it isn't. It is middle C written, but it's an octave below middle C concert.
Comment: @JohnBelzaguy There's no way to talk about guitar transposition without getting criticism for the terminology used, so I made up my own term - not to avoid criticism, but to own the criticism.
Comment: Why the phrase  "quasi-transposing"? "Octave transposing" is a standard phrase and description for instruments like guitar, flute and piccolo to name a few.
Comment: In a sane world, guitar would be notated with an explicit octave-shifted treble clef — with a small subscript '8' to indicate that the notes sound an octave lower than written — and there would be no ambiguity (nor any need to pretend that it's a transposing instrument)…
Comment: To be more concrete the guitar is what we consider a tenor instrument, which are notated in treble clef but sound an octave lower.
Comment: It's a 'transposing instrument'.  More specifically, an 'octave transposing instrument'.   Nothing quasi about it.
Comment: @ejbpesca When you see middle C written on the page, you play string 5, fret 3. When you play string 5, fret 3, what comes out of the guitar is the C an octave below middle C. That is normal and it is how the guitar works. Technically, E2, E3, and middle C are not frequencies, they are *pitches*. Pitches are related to frequencies but they are different.
Comment: @ejbpesca "Is string 5 fret 3 not middle C/C4?" Yes and no. It both **is** middle C and it **isn't** middle C at the sand time. We call it "middle C" and we write down middle C on staff paper when we want a guitarist to play fret 3 string 5. But when the guitarist plays that note, we don't hear middle C. What we hear is the C one octave below middle C, C3. That's what "transposing" means.
Comment: There are no transposing instruments. There is only transposing notation. And yes, it should be a treble clef with an 8 subscript.
Comment: @ToddWilcox No criticism intended, just a query. Whenever I hear something unfamiliar related to music I like to find out if I've missed something.
Comment: Oh, in my previous comment I meant to type "bass", not "flute". I missed the 5 minute edit window for comments…by 2.5 hours
Comment: I am referring to E2 and E3 as frequencies.  They both are not the same.  Is string 5 fret 3 not middle C = 261.6 Hz?
Comment: I found a chart giving a frequency value to the alphanumeric designation of C4 of 261.6 Hz and C4 as piano key in the middle of the keyboard calling that middle C.   Is string 5 fret 3 not middle C/C4?  If not, what key on the piano is its equivalent?
Comment: @gidds If the clef with the 8 at the bottom is used, then the guitar doesn't sound an octave lower than written, because that clef indicates to play an octave lower than treble clef. That would be a way for guitarists to read the same way they read now and no longer be playing a transposing instrument.
Answer: Guitar is written in treble clef, but sounds an octave lower than written.   Sometimes we use the 'treble (down 8)' clef which makes this transposition explicit.
There are (at least) two numbering conventions for pitch.  One of them calls Middle C 'C4'.  Another calls it 'C3'.  But whatever you call it, guitar sounds one octave lower.
Comment: @ejbpesca Yes, you want them in the staff where they can be easily read, not a messy bunch of ledger lines below.
Comment: @Divizna That makes sense as to why you wouldn't write them as-heard on a treble clef. But for me, it just shifts the question - why not place the notes in the correct position on a bass clef? No extra ledger lines required.
Comment: @NuclearHoagie I guess because way fewer people are literate in the bass clef than treble. (And when a guitarist makes the effort to learn a second system, they're likely to go with tabs.)
Comment: @NuclearHoagie treble clef is actually optimal in terms of the number of ledger lines needed to notate lots of guitar music, see https://music.stackexchange.com/q/101432/63781 and https://music.stackexchange.com/q/118892/63781
Comment: Is there a functional purpose to not placing  guitar notes to the staff at the correct position of their sound?
Comment: @NuclearHoagie Putting guitar on bass clef would require a ridiculous number of ledger lines above the bass clef for the higher octaves of the guitar. Treble clef means three ledger lines down to the lowest E on the guitar and three ledger lines above for the highest E. It's kinda perfect for the guitar's range.
Answer: Empty guitar strings are:

great E, aka E2, ~82.4 Hz
great A, aka A2, 110 Hz
small d, aka D3, ~147 Hz
small g, aka G3, ~196 Hz
small b, aka B3, ~247 Hz
one-lined e', aka E4, ~330 Hz

Neither the high E nor the low E string is the small e (E3).
The high E (string 1) is the one-lined e' (E4), a major third above middle C and a fourth below chamber A.
The low E (string 6) is the great E (E2).
Comment: Great E? Small D? One-lined E? This is a notation I've never heard of before; I'd be interested in learning more about it. Is it a guitar-specific thing, or a regional thing, or what?
Comment: This answer addresses the question without any extraneous information. Thank you.
Comment: @Hearth Regional, it seems. I'm afraid the numbered notation feels rather foreign to me in turn - that is something I've seen at the English-speaking internet and nowhere else. Wikipedia has [an article](https://en.wikipedia.org/wiki/Helmholtz_pitch_notation), and a handy table in the [Octave](https://en.wikipedia.org/wiki/Octave#Octave_of_a_pitch) article.
Comment: @Divizna I had no idea Helmholtz did research into acoustic physics; I know of him for a few contributions to my field, electrical engineering. You say english-speaking; what language does your notation usually get used in? I'd guess German, as Helmholtz was German?
Comment: @Hearth I don't know. It's definitely the unambiguous standard in my country, and unsurprisingly, it [seems to be](https://de.wikipedia.org/wiki/Oktave#Untergliederung_des_Tonraumes_in_Oktavr%C3%A4ume) the standard for German-speaking places, too. Other than that, beats me. If I were to guess, I'd place my bet on "the entire northern half of Europe from British Isles to Russia", but it's really just a largely uninformed guess and I may be completely wrong.
Comment: @Divizna - I haven't seen it used like that in Britain, so maybe not :-)
Answer: In standard tuning guitar string 6 produces E2.


How can I programmatically get the theme name?

Question: In Drupal 8, is there a way to figure out what theme you are currently using in a module?  I need to get the name programmatically within the code of a module.
Answer: Using the theme manager is the proper Drupal 8 way of getting information about your theme.
\Drupal::service('theme.manager')->getActiveTheme()

A general rule in drupal 8 is look for the manager (/handler) service.
** Note: as Neograph734 pointed out, \Drupal::service('theme.manager')->getActiveTheme() will return the active theme object. If you want to get the theme machine-name then use \Drupal::service('theme.manager')->getActiveTheme()->getName()
Comment: Note that the actual theme name can be derived from the ActiveTheme with `getName()`. So to get the theme name one would use `\Drupal::service('theme.manager')->getActiveTheme()->getName();`
Answer: This will do it:
$config = \Drupal::config('system.theme');
print $config->get('default');

You can always use drush to explore your available configs:
drush config-list

and
drush config-list system

gave me a list:
...
system.rss
system.site
system.theme.global
system.theme
...

and then I could check with the following:
drush cget system.theme.global

and
drush cget system.theme

to finally find out that it holds a default property that was what you asked for.
Comment: This answers returns the default theme.  The OP asked for the current theme, and the accepted answer returns current theme.  Normally it won't matter, but if there is a module that dynamically selects a theme depending on page/domain/user etc then the difference is important.
Comment: True, if there is a custom theme negotiator in play, the results will differ. If not, then the `getActiveTheme()` function will end up returning exactly the same:  `$this->configFactory->get('system.theme')->get('default')`
Answer:
if you want to get actual active theme name administration theme included Use :

 $activeThemeName = \Drupal::service('theme.manager')->getActiveTheme();

if you want your default selected theme theme used in front not
admistartion theme Use :

 $defaultThemeName = \Drupal::config('system.theme')->get('default');


Use xarray with custom function and resample

Question: I'm trying to take an array and resample it with a custom function. From this post: Apply function along time dimension of XArray
def special_mean(x, drop_min=False):
    s = np.sum(x)
    n = len(x)
    if drop_min:
        s = s - x.min()
    n -= 1
    return s/n

is an example sample_mean.
I have a dataset that is:
<xarray.Dataset>
Dimensions:  (lat: 100, lon: 130, time: 7305)
Coordinates:
  * lon      (lon) float32 -99.375 -99.291664 -99.208336 ... -88.708336 -88.625
  * lat      (lat) float32 49.78038 49.696426 49.61247 ... 41.552795 41.46884
    lev      float32 1.0
  * time     (time) datetime64[ns] 2040-01-01 2040-01-02 ... 2059-12-31
Data variables:
    tmin     (time, lat, lon) float32 dask.array<chunksize=(366, 100, 130), meta=np.ndarray>
    tmax     (time, lat, lon) float32 dask.array<chunksize=(366, 100, 130), meta=np.ndarray>
    prec     (time, lat, lon) float32 dask.array<chunksize=(366, 100, 130), meta=np.ndarray>
    relh     (time, lat, lon) float32 dask.array<chunksize=(366, 100, 130), meta=np.ndarray>
    wspd     (time, lat, lon) float32 dask.array<chunksize=(366, 100, 130), meta=np.ndarray>
    rads     (time, lat, lon) float32 dask.array<chunksize=(366, 100, 130), meta=np.ndarray>
Attributes:
    history:  Fri Jun 14 10:32:22 2019: ncatted -a _FillValue,,o,d,9e+20 IBIS...

And then I apply a resample that is:
data.resample(time='1MS').map(special_mean)

<xarray.Dataset>
Dimensions:  (time: 240)
Coordinates:
  * time     (time) datetime64[ns] 2040-01-01 2040-02-01 ... 2059-12-01
    lev      float32 1.0
Data variables:
    tmin     (time) float32 dask.array<chunksize=(1,), meta=np.ndarray>
    tmax     (time) float32 dask.array<chunksize=(1,), meta=np.ndarray>
    prec     (time) float32 dask.array<chunksize=(1,), meta=np.ndarray>
    relh     (time) float32 dask.array<chunksize=(1,), meta=np.ndarray>
    wspd     (time) float32 dask.array<chunksize=(1,), meta=np.ndarray>
    rads     (time) float32 dask.array<chunksize=(1,), meta=np.ndarray>

How do I do this function such that I can retain the 'lon' and 'lat' coordinates like when doing
data.resample(time='1MS').mean()

Answer: Here's one example of how you can use xr.apply_ufunc().
import xarray as xr
data = xr.tutorial.open_dataset('air_temperature')

def special_mean(x, drop_min=False):
    s = np.sum(x)
    n = len(x)
    if drop_min:
        s = s - x.min()
    n -= 1
    return s/n

def special_func(data):
    return xr.apply_ufunc(special_mean, data, input_core_dims=[["time"]],
            kwargs={'drop_min': True}, dask = 'allowed', vectorize = True)

data.resample(time='1MS').apply(special_func)

<xarray.Dataset>
Dimensions:  (lat: 25, lon: 53, time: 24)
Coordinates:
  * time     (time) datetime64[ns] 2013-01-01 2013-02-01 ... 2014-12-01
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
Data variables:
    air      (time, lat, lon) float64 244.6 244.7 244.7 ... 297.7 297.7 297.7

Comment: As shown in the documentation, vectorize=True is very slow for my size dataset. Do you have any idea how I can make it a little bit quicker?
Comment: Also, is there a way to pass in variables to special_func that are out of scope. The use case would be drop_min only 1 versus drop_min twice or something like that.
Comment: @blueduckyy try converting your data into a dask array using `.chunk()` and then switch the argument to `dask='parallelized'` :) It'll allow the ufunc to operate lazily on your data using dask, you can then load the data into memory later on using `da.compute()`.

Have a look at my other answer, see if it helps. :) https://stackoverflow.com/questions/38960903/applying-numpy-polyfit-to-xarray-dataset/60517358#60517358
Answer: I suspect that you can do what you want with the apply_ufunc method.
(although as a disclaimer I do not know the Xarray API well.)
Comment: How? I've tried using ufunc and i'm not sure if I just don't know how it works? Where does it go?