Show a UIPopoverController from a detail disclosure button in a UITableViewCell

Question: I am creating an application for the iPad, and I want to show an UIPopoverController with an arrow pointing to the detail disclosure button for the row it belongs to. I want to do this in the tableView:accessoryButtonTappedForRowWithIndexPath: method. Currently I have this, with a dummy CGRect:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    // Dismiss in the case it shows itself somewhere else
    [addFeedPopup dismissPopoverAnimated:YES];

    // Set up
    TNSubscribeToFeedController *subscribeToFeedController = [[TNSubscribeToFeedController alloc] initWithNibName:@"SubscribeToFeed" bundle:nil];
    UINavigationController *subscribeToFeedNavigationController = [[UINavigationController alloc] initWithRootViewController:subscribeToFeedController];
    subscribeToFeedController.title = @"Subscribe to feed";
    subscribeToFeedController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:nil];
    subscribeToFeedController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:nil];
    /*
     * Note that we use the UINavigationController pure for the nices UINavigationBar.
     */

    // Show in popup
    addFeedPopup = [[UIPopoverController alloc] initWithContentViewController:subscribeToFeedNavigationController];
    addFeedPopup.popoverContentSize = CGSizeMake(480, 320);
    [addFeedPopup presentPopoverFromRect:CGRectMake(0, 0, 20, 20) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];

    // Memory
    [subscribeToFeedNavigationController release];
    [subscribeToFeedController release];
}

Also, when the UITableView is in editing mode, the detail disclosure button is about 60 pixels to the left, since I use this to set up my rows:
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"SectionTwoCell"] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:@"Feed %d", indexPath.row];
cell.detailTextLabel.text = @"Description";
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.editingAccessoryType = cell.accessoryType;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
//        TWO LINES BACK DEAR SO USER        //

Can anyone help me with this problem? Thanks.

Oh, and is it also possible to disable scrolling and disable selecting anything until the UIPopoverController is closed (perfectionism)?
Answer: To do what you want, you need an accessoryView and setting the accessoryType does not create one. However, it will work if you create a button and set it as the cell.accessoryView.
Create and set the accessoryView when the cell is created:
    ...
    UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [disclosureButton addTarget:self action:@selector(discloseDetails:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryView = disclosureButton;
    ...

Replace tableView:accessoryButtonTappedForRowWithIndexPath: with discloseDetails:.  This looks much like what you have before so I've only put the changes below:
- (void) discloseDetails:(UIButton *)sender {
    ...
    UITableViewCell *cell = (UITableViewCell *) sender.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];  // if needed
    [addFeedPopup presentPopoverFromRect:cell.accessoryView.bounds inView:cell.accessoryView permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
    ...
}

If you don't need the cell, it can be made even simpler:
- (void) discloseDetails:(UIButton *)sender {
    ...
    [addFeedPopup presentPopoverFromRect:sender.bounds inView:sender permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
    ...
}

Here's what it looks like


How do I interpret non-significant interaction effect?

Question: Here is the output for testing whether male earns less in a particular job market:
<code>Income=b1*education+b2*male+b3*male*education
</code>
where b1=100 (significant), b2=-50 (insignificant), b3=10 (insignificant)
How should I interpret whether this type of job is against male?
From the coefficient, I knew that

if female, income=100*educ;
if male, income=100*educ-50+10*educ=110*educ-50,

but my concern here is b2, b3 both are insignificant, so how do I interpret this whole story?
Answer: This isnt the right place for this question, but you could look at it that holding everything else constant education has a positive effect on income. Also, you would need more data to do this accurately, there could be some sample biases, or the effects of one filed could be picked up in another. For example, maybe males are more likely to have higher education for this field. Another interesting way to do this is to estimate two separate equations. One for female and one for male and then estimate what males would have made had they been female and vise versa.


hook_form_alter isn't being called when node fails validation

Question: I'm noticing that hook_form_alter isn't being called when a page has errors that display a message from form_set_error.  Changes to my form aren't taking effect, and the error page is effectively broken.
I've tried to output a dpm statement in hook_form_alter, but it isn't appearing on the error page.
Is there a way to get drupal to call the hook and alter the form?
Comment: I've found http://drupal.org/node/671574 which claims this is fixed in drupal 7, but it does not appear to be the case.
Answer: Forms are cached in Drupal so the form is loaded once (where your form_alter runs) and then it's loaded from cache to be reloaded when there are validation errors.
You should use an #after_build callback, which always gets run.
Just remember to return $element in your #after_build callback or you'll be getting WSODs.
Comment: is it possible to add elements to the form?  I'm adding a textarea when a value is set in a particular field.
Comment: Technically yes you can do anything with the form. That said, you might be better off adding the field in your form alter with #access FALSE and then setting it to TRUE in your after build if necessary.
Comment: If I add the field in the form_alter, it doesn't appear on the validation error page.  I decided to create the field in my after_build callback, but the #ajax callback is not being fired.  Autocomplete works fine.  When dealing with form_alter I found that I had to add the wrapper with `#printed => TRUE` to the root of the array, and then copy the field to the element I wanted it to display under.  I think the callback worked then because the field had already been recognized during rendering.  Do I need to call `field_default_form` or some other function to get ajax callbacks to work?
Comment: Could you please elaborate on exactly what you are trying to do with adding the extra field?  It doesn't appear in your validation error because #access was set to false, you could try checking for form_get_errors() in your after build and setting #access to true if there are any
Comment: I'm writing a module called text_field_reference that autocompletes to the value of a field in the recommendation content type I've created.  The recommendations match up to a finding select field that has integer point values (0, 1, 2, etc).  If the user changes the select field, I use an ajax call to display a textarea that autocompletes to a recommendation.  Its blur event replaces the field_text_reference field with a key representing the node that was referenced.  I'll be the first to admit it's kind of hackish.  The ajax callback to replace the reference field is intermittently working.
Comment: After adding an empty wrapper to the finding field for the textarea (it was in the alter hook before), the ajax callback started working.  At least I think this change was what fixed it.  Thanks for your help, I've accepted your answer.


displaying field from node on page in url in block

Question: I want to put a link in a block which will pull its url from a url field in the node being displayed on the page on which the block is. Meaning, the block will contain a different url for each different node-info page. How can I reference this node in the block?
Answer: I figured out how to do it. Make a template file for that specific node ie: node-job.tpl.php and set the value of that url field (which is available to you while inside of that template file) as a global variable ie: variable_set. Now you can access the url inside of your block using variable_get.


Evaluating $\lim_{(x, y) \to (0, 0)} \frac{xy^2}{x^2-y^2}$

Question: What is the value of
$$\lim_{(x, y) \to (0, 0)} \frac{xy^2}{x^2-y^2}$$
I have already tried the two paths result and I think now that the limit does exist and it is equals to 0. But i really cannot prove this.
Comment: It's a duplicate.Does this answer your question https://math.stackexchange.com/q/1219144/977780
Comment: Similar one https://math.stackexchange.com/a/4325565/977780
Comment: Restrict $|x|<1$ and let $y^2=x^2+\frac1k x^3$, where $k>1$.  Then, we have

$$\frac{xy^2}{x^2-y^2}=\frac{x(x^2+\frac1k x^3)}{-\frac1k x^3}=-x-k$$

Inasmuch as the limit depends on $k$, the limit fails to exist.
Answer: Setting $x = r\cos\theta$ and $y = r\sin\theta$, we can calculate that the expression following the limit is
$$
r \frac{\cos\theta \sin^2\theta}{\cos^2\theta - \sin^2\theta} = r \frac{\cos\theta}{\cot^2\theta - 1}
$$
We can make $r$ as small as we want as $(x,y) \to (0,0)$, but we can also make $\frac{\cos\theta}{\cot^2 \theta - 1}$ as big as we want no matter how small $r$ is (how?). Can you see how to use this to prove that the limit does not exist?
Answer: In Polar Co-ordinates , we get $x = r\cos(\theta)$ & $y = r\sin(\theta)$
Plugging that into given limit , we get $r^3$ term in $xy^2$ & $r^2$ term in $x^2-y^2$
Then the limit is $r[f(\theta)]$ where $f$ is function of $\theta$ , in terms of $\cos$ & $\sin$
Here $f(\theta) = \frac{\cos(\theta)\sin^2(\theta)}{\cos^2(\theta)-\sin^2(\theta)}$
When $\theta=0,\pi/2,\pi$ , we have $f=0$
When $\theta=\pi/4$ , we have $\cos^2(\theta) = \sin^2(\theta)$ , hence $f$ is unbounded ($1/0$)
Depending on the Path to (0,0) , we get various values of the term. Hence , the limit will not exist !
Thanks to user @CharlesHudgins & user @MathFail who Pointed out the right way.
Comment: This is not universally true. We need for $f$ to be a bounded function of $\theta$.
Comment: Oh ok , I guess I have to actually calculate $f$ here.
Comment: I have "updated" that , @MathFail
Comment: My "assumption" about $f(\theta)$ was wrong , thank you for Pointing that out , @CharlesHudgins
Answer:
$$L=\lim_{(x, y) \to (0, 0)} \frac{xy^2}{x^2-y^2}$$

$$L=\lim_{(x, y) \to (0, 0)} \frac{xy^2-x^3+x^3}{x^2-y^2}=\lim_{x \to0} (-x)+\lim_{(x, y) \to (0, 0)} \frac{x^3}{x^2-y^2}=\lim_{(x, y) \to (0, 0)} \frac{x^3}{x^2-y^2}$$
Let $y=x-ax^2$
$$L=\lim_{x \to 0} \frac{x^3}{2ax^3-a^2x^4}=\lim_{x \to 0} \frac{1}{2a-a^2x}=\frac{1}{2a}$$
So the limit depends on the value of $a$, hence the limit doesn't exist.


uniform distribution: expectation of sum squared observations

Question: I'm trying to follow ML lesson about Bayesian inference.
They have a sample of n observations from a uniform distribution: $x_i = U(0, \theta)$.
They claim that $E[(\sum x_i)^2] = n(n-1)\theta^2/4 + n \theta^2/3$ - why is that true?
I tried by myself and got a different result, where did I go wrong?:
$Var(x_i) = \theta^2/12 = E(x_i^2)-E^2(x_i);$
$E(x_i^2) = \theta^2/12 + (\theta/2)^2 = \theta^2/3$
$E[(\sum x_i)^2] = n\theta^2/3$
Where did the first term come from??
Comment: You forgot the covariance terms, i.e. $E[x_ix_j]$.
Comment: @AlexR. oops, they are independent.
Comment: It is not because they are independent that $\mathbb{E}[X_iX_j]=0$.
Comment: $E[X_i]=\theta/2$...
Answer: \begin{eqnarray*}
\left(\sum_{i=1}^{n}x_{i}\right)^{2}&=&\sum_{i=1}^{n}x_{i}^{2 }+2\sum_{i<j}^{n}x_{i}x_{j}\\
E\left(\sum_{i=1}^{n}x_{i}\right)^{2}&=&\sum_{i=1}^{n}E\left(x_{i}^{2 }\right)+2\sum_{i<j}^{n}E\left(x_{i}x_{j}\right)\\
&=&\dfrac{n\theta^{2}}{3}+2\dfrac{n(n-1)}{2}\left[Cov\left(x_{i}x_{j}\right)+E(x_i)E(x_j)\right]\\
&=&\dfrac{n\theta^{2}}{3}+2\dfrac{n(n-1)}{2}\left[0+\dfrac{\theta}{2}\dfrac{\theta}{2}\right]\\
E\left(\sum_{i=1}^{n}x_{i}\right)^{2}&=&\dfrac{n\theta^{2}}{3}+\dfrac{n(n-1)\theta^{2}}{4}
\end{eqnarray*}
Comment: thanks, but the first term should be $\frac{n\theta^2}{3}$ and not $\frac{n\theta^2}{2}$
Comment: also the second term could be simply $\sum_{i \neq j}$, why do we divide by 2 and then multiply by 2?
Comment: @ihadanny, Sorry, there was a typo.  Note that $x_{i}x_{j}=x_{j}x_{i}$, and there are $n(n-1)/2$ such pairs. $ \sum_{i\neq j} = 2\sum_{i<j}$.
Comment: got it! I was suggesting that you could write it more simply as $\sum_{i \neq j}$ and there are $n(n-1)$ such pairs - but we're saying the same thing.
Answer: This is a simple re-arrangement of the variance formula
$$var (Y)=E (Y^2)-[E (Y)]^2$$
Set $Y=\sum_ix_i $ and you have:
$$E [(\sum_ix_i)^2]=var [\sum_ix_i]+[E (\sum_ix_i)]^2$$
Comment: @ihadanny - actually, you didn't apply this formula.  The first term is $n\theta^2/12$ and the second term is $(n\theta/2)^2$.  Add them together and you have $n\theta^2 (n/4+1/12)=n\theta^2 ((n-1)/4+1/3) $.
Comment: ha :) thanks but that's exactly what I did - and it's not the correct answer... please re-read the question...
Comment: oops. you're right - I wasn't careful with the $n$s in my derivation. thanks.


Bash Script To Change Curly Brace Style

Question: I have a CSS file and a PHP file that I received from an overseas outsource partner. He prefers curly braces on a new line, while I am rather Old School and prefer the curly brace on the same line as the declaration. How can I use Bash and/or sed or other command-line tools to revert curly braces from this new style and into this older style?
EDIT: Someone wanted to see an example. Okay, here goes:
NEW SCHOOL STYLE I DO NOT LIKE
body
{
padding:4px;
margin:3px;
}

OLD SCHOOL I PREFER
body {
padding:4px;
margin:3px;
}

NEW SCHOOL STYLE I DO NOT LIKE
function foo()
{
// some code here
}

OLD SCHOOL STYLE I PREFER
function foo() {
// some code here
}

Comment: Nope not kidding, if you've ever seen [this image](http://keremkosaner.files.wordpress.com/2008/04/softwaredevelopment.gif) you'll know why
Comment: Please give sample input and sample output
Comment: You don't believe in indentation?
Answer:  sed 'N;/\n{/s// {/;P;D' file.css

Input
$ cat file.css
body
{
background-color:#d0e4fe;
}
h1
{
color:orange;
text-align:center;
}
p
{
font-family:"Times New Roman";
font-size:20px;
}

Output
$ sed 'N;/\n{/s// {/;P;D' file.css
body {
background-color:#d0e4fe;
}
h1 {
color:orange;
text-align:center;
}
p {
font-family:"Times New Roman";
font-size:20px;
}

Answer: A start might be:
sed 'N;/\n{/s/\n/ /;P;D' inputfile

If a line begins with a curly brace, it will be appended to the previous line (with an added space).

Bash Script To Change Curly Brace Style


How to use parent pom's profile properties in child pom?

Question: Current scenario:
Parent pom has a distributionManagement section, where two repositories (releases and snapshots) are defined; refer below:
Parent pom:
    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <properties>
        <buildVersion>0.7</buildVersion>
    </properties>

    <groupId>x.y.z</groupId>
    <artifactId>abc</artifactId>
    <version>${buildVersion}</version>
    <packaging>pom</packaging>

    <modules>
        <module>moduleA</module>
        <module>moduleB</module>
        <module>moduleC</module>
    </modules>

    <dependencies>

    </dependencies>

    <distributionManagement>
        <repository>
            <id>releases</id>
            <url>http://xyz/nexus/content/repositories/releases/</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <url>http://xyz/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

    <profiles>
    <profile>
        <id>snapshots-enabled</id>
        <properties>
            <repositoryUrl>http://xyz/nexus/content/repositories/snapshots/</repositoryUrl>
            <repositoryId>snapshots</repositoryId>
        </properties>
    </profile>
    <profile>
        <id>release-enabled</id>
        <properties>
            <repositoryUrl>http://xyz/nexus/content/repositories/releases/</repositoryUrl>
            <repositoryId>releases</repositoryId>
        </properties>
    </profile>
</profiles>

</project>

Based on the 'version' specified in same pom, maven automatically identifies whether to deploy artifacts in releases or snapshots repository in nexus. (I believe this is being done using whether there is any '-SNAPSHOT' suffix to version or not.)
There is a child-pom which has some deploy-file goals defined; refer below:
Child pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>x.y.z</groupId>
        <artifactId>abc</artifactId>
        <version>${buildVersion}</version>
    </parent>

    <groupId>${parent.groupId}</groupId>
    <artifactId>childArtifactId</artifactId>
    <version>${parent.version}</version>
    <packaging>war</packaging>
    <name>MyChildProject</name>

    <build>
        <sourceDirectory>src</sourceDirectory>

        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.8.2</version>
            <executions>
                <execution>
                    <id>deploy-TA</id>
                    <configuration>
                        <groupId>${project.groupId}</groupId>
                        <artifactId>TA</artifactId>
                        <version>${project.version}</version>
                        <url>http://xyz/nexus/content/repositories/releases/</url>
                        <repositoryId>releases</repositoryId>
                        <file>${basedir}/target/TA.war</file>
                    </configuration>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>deploy-OA</id>
                    <configuration>
                        <groupId>${project.groupId}</groupId>
                        <artifactId>OA</artifactId>
                        <version>${project.version}</version>
                        <url>http://xyz/nexus/content/repositories/releases/</url>
                        <repositoryId>releases</repositoryId>
                        <file>${basedir}/target/OA.war</file>
                    </configuration>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>deploy-CSA</id>
                    <configuration>
                        <groupId>${project.groupId}</groupId>
                        <artifactId>CSA</artifactId>
                        <version>${project.version}</version>
                        <url>http://xyz/nexus/content/repositories/releases/</url>
                        <repositoryId>releases</repositoryId>
                        <file>${basedir}/target/CSA.war</file>
                    </configuration>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy-file</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        </plugins>

    </build>

</project>

Problem:
As you can see in child pom above that I have to specify the url and repositoryId tags explicitly for each of the configuration tags. Without them, there is an error thrown and deploy-file goal fails.
Now, I do not want to hard-code their values in the child pom. Rather, I want to inherit these values from parent pom conditionally: If the parent uses the releases repository, then child should also use the same. If parent uses the snapshots repository, then child should also use the same. (Note again that there is no condition specified in parent pom to use respective repository, rather it is done automatically by maven as mentioned above)
So how do I make this conditional value population in child pom based on certain condition evaluation in parent/child pom?
Things I have tried:
I added the profiles section in the parent pom as follows:
<profiles>
    <profile>
        <id>snapshots-enabled</id>
        <properties>
            <repositoryUrl>http://xyz/nexus/content/repositories/snapshots/</repositoryUrl>
            <repositoryId>snapshots</repositoryId>
        </properties>
    </profile>
    <profile>
        <id>release-enabled</id>
        <properties>
            <repositoryUrl>http://xyz/nexus/content/repositories/releases/</repositoryUrl>
            <repositoryId>releases</repositoryId>
        </properties>
    </profile>
</profiles>

As seen above, there are two profiles, and each of them have same properties with different values. However, I am not able to populate the above properties in either parent or child pom using their IDs. For eg. using ${repositoryUrl} in parent pom or ${parent.repositoryUrl} in child pom does not work. IntelliJ immediately shows this in red color. Despite that, if I still try to use the command 'mvn deploy -P release-enabled', the deployment still fails as maven is not able to substitute values of above properties dynamically. (The reason I do not have activation section in profiles is because I need to build this entire project through TeamCity later, which will not have environment variable. Hence, as part of command line only I shall pass the information of which profile should be used.)
Any suggestions on how to dynamically populate values in parent/child poms? Is there any if-else kind of expression evaluation possible, may be based on some arguments that can be passed while executing 'mvn deploy' command?
Comment: is it actually configured as the parent pom?
Comment: It's just the snippet of parent pom. I shall post the whole parent pom for clarity.
Comment: whether it is a parent pom, is actually configured in the child pom, where you declare what the parent is
Comment: Added whole child pom now. It refers to the parent pom using the parent xml node. The entire project works fine with parent-child configuration, but I need to dynamically set values in both parent and child pomx, that part is not working.
Answer: you can't have a parametric version in the parent definition, how would you be able to retrieve the correct value, otherwise?
<parent>
    <groupId>x.y.z</groupId>
    <artifactId>abc</artifactId>
    <version>${buildVersion}</version>
</parent>

What you should do, is to define the correct version in the parent pom:
<groupId>x.y.z</groupId>
<artifactId>abc</artifactId>
<version>0.7</version>
<packaging>pom</packaging>

getting rid of the buildVersion variable and use the pom version plugin to change the versions of all the modules at once:
mvn versions:set -DnewVersion=0.8-SNAPSHOT

From the doc:

The set goal can be used to update the version of the current module. It will automatically climb up local directories to find the aggregation root. It will automatically update explicitly referenced dependencies. You specify the version to update to via the newVersion property
Comment: Hello @senape, the reason I have used buildVersion property is because I have many child modules, which all can refer to the buildVersion in their parent tag declaration. If I don't do that, then I have to update all child poms' parent tag with explicit version number before deploying new version of project in maven, which makes my task cumbersome. Above poms work perfectly fine, and there is no problem with them as far as versions are concerned. The problem is with populating other profile properties dynamically in both parent/child poms. You may read question again to get the context.
Comment: I'm sorry, but I honestly can't understand how `...${buildVersion}` works.
Comment: It really does work :) at least I am able to build and push artifacts to nexus with that using both IntelliJ and TeamCity. Though I am still stuck on dynamically populating profile properties part.
Answer: First of all, while you can be defining the version via the command-line, it's not really advisable. The problem is that this breaks the build portability of the code. If I check out your code, I wouldn't know which version this is, or what I should use for it in order to build it. Also, if you do it this way and then tag the code in Git, if somebody checks out the code later, they won't know what version string you used and they will be guessing (unless they're on your team).
Secondly, defining properties this way is very tricky. When you pass the version like this, the parent needs to be installed first, unless it's part of an aggregator as a sub-module.
In your example above, the parent is also an aggregator. I would recommend putting it in a separate module.


logic equivalence question?

Question: I am trying to prove how these 2 formulas are equivalent using logical equivalence laws.
(p ↔ q) → r     =    (¬p∧q)∨(¬q∧p)∨r
For  (p ↔ q) → r, What I tried to do was
(p → q) ∧ (q → p) V r  (Bi conditional law)
(p v ¬q) ∧ (q V ¬p) v r  (conditional law)
(¬q v p) ∧ (¬p v q) v r (commutative law)
From there I got stuck as I wasn't sure for the next equivalence law.
What would be next?
Thanks.
Comment: Welcome to MSE. You can format maths with [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: You made a small mistake as after the Conditional Law (and DeMorgan) you should get:
$$(p \land ¬q) \lor (q \land ¬p) \lor r $$
That is, you get:
$$((p \rightarrow q) \land (q \rightarrow p)) \rightarrow r \Leftrightarrow \text{ (Conditional Law)}$$
$$\neg ((\neg p \lor q) \land (\neg q \lor p)) \lor r \Leftrightarrow \text{ (DeMorgan)}$$
$$\neg (\neg p \lor q) \lor \neg (\neg q \lor p)) \lor r \Leftrightarrow \text{ (DeMorgan x 2)}$$
$$(p \land \neg q) \lor (q \land \neg p) \lor r \Leftrightarrow \text{ (Commutation)}$$
$$(q \land \neg p) \lor(p \land \neg q) \lor  r \Leftrightarrow \text{ (Commutation x 2)}$$
$$(\neg p \land q) \lor(\neg q \land p) \lor  r$$
Comment: Thanks for the help. I was thinking about adding Demorgan before, again I wasn't sure. Thanks again!
Comment: @Blueberry23 You're welcome!  Please do use MathJax for future posts ... it's not hard to use.

logic equivalence question?


Using the digits 0, 1, 2, 3 and 4, find the number of 8-digit sequences

Question: Using the digits 0, 1, 2, 3 and 4, find the number of 8-digit sequences (it may begin with 0) that can be written so that the difference between any two consecutive digits is 1.
Examples of such 8-digit sequences are 01234343, 12321010, 23232323.
Comment: What have you tried?  Do you know the multiplication principle?  How about counting the two digit sequences by hand?  That might help your intuition.
Answer: Here is a somewhat general way to deal with this type of problem. Let $G$ be a simple graph with vertices $\{0,1,2,3,4\}$ and edges $\{(0,1),(1,2),(2,3),(3,4)\}$. The adjacency matrix of $G$ is
$$A=\left(\begin{array}{ccccc}
0&1&0&0&0\\
1&0&1&0&0\\
0&1&0&1&0\\
0&0&1&0&1\\
0&0&0&1&0
\end{array}\right)
$$
Now how many directed paths of length 1 in this graph? Well there are 8, and as every such path would be recorded in the matrix $A$, it is also the sum of all numbers in $A$.
Here comes the interesting part: the number in the $(i,j)$-slot of $A^n$ is exactly the number of different directed paths of length $n$ from vertex $i-1$ to vertex $j-1$(try to convince yourself of it). As such, the number of  8-digit sequences that satisfy your condition is exactly the sum of all numbers in $$A^7=\left(\begin{array}{ccccc}
 0 &14&0&13& 0\\
14 &0&27& 0&13\\
 0 &27&0&27& 0\\
13&  0 &27&0& 14\\
 0& 13&  0& 14&  0
\end{array}\right)$$
which is 216. There are also some tricks to help you calculate the matrix power, so you can actually obtain a general formula for this or maybe some generalized question.


Publish Spring MVC Metrics To Multiple Monitoring System Simultaneously Using Micrometer

Question: I have a use case wherein I want to publish my spring boot API metrics to Datadog & CloudWatch simultaneously.
I have added the below dependencies to my pom.
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-statsd</artifactId>
  <version>${micrometer.version}</version>
</dependency>

<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-cloudwatch</artifactId>
  <version>${micrometer.version}</version>
</dependency>

Main Application class
@SpringBootApplication
public class MyApplication {
    @Bean
    MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
      return registry -> registry.config().commonTags("my-tag", "my-common-tag");
    }
}

I have added all required properties in the application. properties as well.
I can see metrics are being published to both Datadog & CloudWatch with default metrics name http.server.request
But I want the metrics name for Datadog to be different & for this, I have added the below property.
management.metrics.web.server.requests-metric-name = i.want.to.be.different
But this is changing the name for both CloudWatch & Datadog.
My question is, how can I change the default metrics name for Datadog only or keep words different for both.
Answer: Micrometer uses MeterFilters registered with a MeterRegistry to modified the meters that are registered. The modifications include the ability to map a meter's ID to something different.
In Spring Boot, you can use a MeterRegistryCustomizer bean to add a MeterFilter to a registry. You can use generics to work with a registry of a specific type, for example MeterRegistryCustomizer<DatadogMeterRegistry> for a customizer that is only interested in customizing the Datadog registry.
Putting this together, you can map the ID of the http.server.request meter to i.want.to.be.different using the following bean:
@Bean
MeterRegistryCustomizer<DatadogMeterRegistry> datadogMeterIdCustomizer() {
    return (registry) -> registry.config().meterFilter(new MeterFilter() {

        @Override
        public Id map(Id id) {
            if ("http.server.request".equals(id.getName())) {
                return id.withName("i.want.to.be.different");
            }
            return id;
        }

    });
}


Problema em código de snake game

Question: Depois de aprender JavaScript, criei um desafio para mim mesmo: refazer o "jogo da cobrinha". Porém, estou com um problema: quero que, quando a cobra passe pela comida, a comida mude de lugar, porém ela continua no mesmo lugar.

//canvas
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = "lightgreen";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //variaveis
    let grid = 20;
    let size = 5;
    let directions = [];
    //cobra
    let head = {
        x: 10,
        y: 10,
    };
    let tail = {
        x: 10,
        y: 10,
    };
    //comida
    let food = {
        x: Math.floor(Math.random() * grid) * grid,
        y: Math.floor(Math.random() * grid) * grid,
    };
    //função principal
    function main(e) {
        switch (e.keyCode) {
            case 37:
                head.x--;
                directions.push('left');
                break;
            case 38:
                head.y--;
                directions.push('up');
                break;
            case 39:
                head.x++;
                directions.push('right');
                break;
            case 40:
                head.y++;
                directions.push('down');
                break;
        };
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x, food.y, grid, grid);
        ctx.fillStyle = 'black';
        ctx.fillRect(head.x * grid, head.y * grid, grid, grid);
        if (directions.length >= size) {
            ctx.fillStyle = 'lightgreen';
            ctx.fillRect(tail.x * grid, tail.y * grid, grid, grid);
            switch (directions.shift()) {
                case 'left':
                    tail.x--;
                    break;
                case 'up':
                    tail.y--;
                    break;
                case 'right':
                    tail.x++
                    break;
                case 'down':
                    tail.y++;
                    break;
            };
        };
        if (head.x == food.x && head.y == food.y) {
            food.x = Math.floor(Math.random() * grid) * grid;
            food.y = Math.floor(Math.random() * grid) * grid;
        };
    };
    document.addEventListener('keydown', main);
<!DOCTYPE html>

    <title>Jogo da cobrinha</title>
    <meta charset="utf-8" />
    <meta name="author" content="Tomás Ricardo" />

    <canvas id="canvas" width="400" height="400"></canvas>

Comment: Olá Tomás, se colocar um `console.log(head.x, food.x, head.y, food.y);` antes da IF vai notar que os valores de X e Y de ambos são totalmente diferentes. E o problema dessa diferença de localizações é devido a como vc adicionou os objetos: `ctx.fillRect(food.x, food.y, grid, grid);` `ctx.fillRect(head.x * grid, head.y * grid, grid, grid);`
Comment: Boa tarde, Tomás. Não adicione "[Resolvido]" no título da pergunta. Caso alguma resposta tenha solucionado seu problema, apenas marque a resposta como aceita.
Answer: Voce fez uma multiplicacao desnecessaria para o valor de food com o grid em:
let food = {
        x: Math.floor(Math.random() * grid) * grid,
        y: Math.floor(Math.random() * grid) * grid,
    };

isso faz com que os valores de head.x head.y sejam sempre diferentes de food.x e food.y. Remova a segunda multiplicaco, deixe assim:
let food = {
        x: Math.floor(Math.random() * grid),
        y: Math.floor(Math.random() * grid),
      };

Voce esqueceu de multiplicar por grid na funcao ctx.fillRect em :
ctx.fillRect(food.x, food.y, grid, grid);

coloque assim:
ctx.fillRect(food.x * grid, food.y * grid, grid, grid);

e la no seu if, remova a multiplicacao extra do grid:
if (head.x == food.x && head.y == food.y) {
          food.x = Math.floor(Math.random() * grid) * grid;
          food.y = Math.floor(Math.random() * grid) * grid;
        }

Fica assim:
if (head.x == food.x && head.y == food.y) {
          food.x = Math.floor(Math.random() * grid);
          food.y = Math.floor(Math.random() * grid);
        }

Agora os valores de head e food irao se igualar em algum momento e entao a posicao do food ira mudar(veja o console.log()). Segue o codigo completo(execute e veja o resultado esperado é este):

//canvas
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = 'lightgreen';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //variaveis
      let grid = 20;
      let size = 5;
      let directions = [];
      //cobra
      let head = {
        x: 10,
        y: 10,
      };
      let tail = {
        x: 10,
        y: 10,
      };
      //comida
      let food = {
        x: Math.floor(Math.random() * grid),
        y: Math.floor(Math.random() * grid),
      };
      //função principal
      function main(e) {
        switch (e.keyCode) {
          case 37:
            head.x--;
            directions.push('left');
            break;
          case 38:
            head.y--;
            directions.push('up');
            break;
          case 39:
            head.x++;
            directions.push('right');
            break;
          case 40:
            head.y++;
            directions.push('down');
            break;
        }
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x * grid, food.y * grid, grid, grid);
        ctx.fillStyle = 'black';
        ctx.fillRect(head.x * grid, head.y * grid, grid, grid);
        if (directions.length >= size) {
          ctx.fillStyle = 'lightgreen';
          ctx.fillRect(tail.x * grid, tail.y * grid, grid, grid);
          switch (directions.shift()) {
            case 'left':
              tail.x--;
              break;
            case 'up':
              tail.y--;
              break;
            case 'right':
              tail.x++;
              break;
            case 'down':
              tail.y++;
              break;
          }
        }
        // console.log(food, head);
        if (head.x == food.x && head.y == food.y) {
          food.x = Math.floor(Math.random() * grid);
          food.y = Math.floor(Math.random() * grid);
        }
      }
      document.addEventListener('keydown', main);
<!DOCTYPE html>

    <title>Jogo da cobrinha</title>
    <meta charset="utf-8" />
    <meta name="author" content="Tomás Ricardo" />

    <canvas id="canvas" width="400" height="400"></canvas>

Problema em código de snake game


Exponentiating the Lie Derivative: Which direction does it rotate?

Question: I've been working through the book Functional Differential Geometry by Sussman and Wisdom and am having trouble with an example they give.
We can exponentiate a Lie derivative
$$
e^{\mathsf{t\mathcal{L}_v}}\mathsf{y} = \mathsf{y + t \mathcal{L}_v y + \frac{t^2}{2!} \mathcal{L}^2_v y + \dots }
$$
which evolves $\mathsf{y}$ along the integral curves of $\mathsf{v}$.  As a concrete example they evolve the coordinate basis vector $\frac{\partial}{\partial \mathsf{y}}$ along $\mathsf{J}_z = x\frac{\partial}{\partial \mathsf{y}} - y\frac{\partial}{\partial \mathsf{x}}$  (a counter clockwise circular field or z-angular momentum generator) and give as an answer
$$\exp(a \mathcal{L}_{\mathsf{J}_z})\tfrac{\partial}{\partial \mathsf{y}} = -\sin(a)\tfrac{\partial}{\partial \mathsf{x}} + \cos(a)\tfrac{\partial}{\partial \mathsf{y}}.$$
This agrees at $a=0$ and indicates that the evolution maintains the orientation of $\mathsf{v}$ and $\mathsf{y}$ along the flow.  $\tfrac{\partial}{\partial\mathsf{y}}$ just rotates along $\mathsf{J}_z$.
If I try to calculate the expansion, for the first term I get
$$
a\mathcal{L}_{x\frac{\partial}{\partial \mathsf{y}} - y\frac{\partial}{\partial \mathsf{x}}}\tfrac{\partial}{\partial \mathsf{y}} =
a\mathcal{L}_{- y\tfrac{\partial}{\partial \mathsf{x}}}\tfrac{\partial}{\partial \mathsf{y}} = -a[y\tfrac{\partial}{\partial \mathsf{x}}, \tfrac{\partial}{\partial \mathsf{y}}] = a\tfrac{\partial}{\partial \mathsf{x}}
$$
which disagrees with the expansion of the answer by a sign, giving rotation in the opposite direction.
The intuitive notions of the Lie Derivative I have also say it should be $a\tfrac{\partial}{\partial \mathsf{x}}$.  For example, beginning at $x=1, y=0$ we can travel along $\epsilon\mathsf{J}_z$ and then  $\epsilon \tfrac{\partial}{\partial \mathsf{y}} $, or begin along $\epsilon \tfrac{\partial}{\partial \mathsf{y}} $ and then along $\epsilon\mathsf{J}_z$ (points slightly to the left).  The difference between these paths will be $\epsilon^2 \tfrac{\partial}{\partial \mathsf{x}} $.  The same goes for beginning at $x=0,y=1$ or if I do it using a pushforward.  I'm tempted to say the book is mistaken, and that to get a rotation operator which coincides with the direction of $\mathsf{J}_z$ we should use $e^{-t\mathcal{L}_{\mathsf{J}_z}}$ but would appreciate some confirmation.
Comment: The action of flow on functions is opposite to the action on points, for the same reason that translating the graph of $f(x)$ in the positive direction by $a$ requires subtracting $a$ to get $f(x-a)$. This is a common source of sign errors although I am not sure if it's what you're doing. Some people also just use the opposite Lie bracket on vector fields from others.
Comment: Hmm, do you have any intuition for whether the evolution operator would cause the basis vector d/dy to turn counter-clockwise (as they say) or clockwise (as the calculation would indicate)?
Comment: You are right. Thinking of things geometrically, I think it is a typo in the book. It should be $+sin(a)$ not $-sin(a)$.
Answer: You are right. I believe it is a small typo in the book. Indeed, here is a geometric interpretation of $exp(a \mathcal{L}_{J_z})\frac{\partial}{\partial y}$. You flow by $J_z$ for some time $a$, evaluate the vector field $\frac{\partial}{\partial y}$ at that new point, then take $d\varPhi_{-a}$ of that vector. As you can see, we are making use of $d\varPhi_{-a}$ (note the minus sign). Thus your calculation was right, and I believe it was a small typo in the book. I think it should be:
$\exp(a \mathcal{L}_{\mathsf{J}_z})\tfrac{\partial}{\partial \mathsf{y}} = \sin(a)\tfrac{\partial}{\partial \mathsf{x}} + \cos(a)\tfrac{\partial}{\partial \mathsf{y}}$.
One way to check would be to do the calculation explicitly (though I did not do that).
Comment: Thanks for the confirmation!  I was getting a bit nervous that I was misunderstanding everything.
Comment: oh books often have typos. I sometimes send typos to authors hoping to get thanked in the next edition!
Answer: To add to @Malkoun: I would definitely say a typo. It seems the book is based upon a technical report by Sussman and Wisdom which can be found here. In that report (on page 48) they have the same calculation but the result this time is $+\sin(a)\frac{\partial}{\partial x}$, as you have calculated.
It does makes me chuckle that they preface the result of the calculation with "apparently the result is" - maybe they were unsure of the answer too!
Comment: Ah, I should have thought to check the monograph!


Conditional field display in node template

Question: I have a specific content type that I am overwriting the template node--contenttype.html.twig.
This conent type has 4 fields.

Title
Body
Image
Video

I am trying to hide the image field from displaying if VIDEO field has value. Which I am doing by using this code in custom twig template.
{% if node.field_video is not empty %}
{{ content.field_video }}
{% else %}
  {{ content.field_image }}
{% endif %}

The only problem is that I get one of the fields printed as needed plus I get both fields shown.
Video filed is displayed, plus I get an image and video shown again. Wherever those fields are positioned in MANAGE DISPLAY.
If I disable the two fields in MANAGE DISPLAY then, nothing shows up at all.
How can this be fixed?
Comment: You can't disable the fields from display - they will not be added to the content render array.
Answer: You wrote that you are using Twig conditions to selectively print fields, but they show up twice now. This most likely is, because your template still renders the entire content variable somewhere like {{ content }}.
You can easily avoid the fields being rendered twice by using the without Twig filter. Locate the {{ content }} part in your template and alter it to
{{ content|without('field_video', 'field_image') }}

Comment: Mario, do you have any tips on how to implement this on a display suite template? I have created a custom layout and placed it under the templates directory in my subtheme. But on the ds-custom-lyout.html.twig I only see regisons, no contect variable. {% set left = left|render %}
{% set middle = middle|render %}
{% set right = right|render %}

{% if (left and not right) or (right and not left) %}
  {% set layout_class = 'group-one-sidebar' %}
{% elseif (left and right) %}
  {% set layout_class = 'group-two-sidebars' %}
{% elseif (left) %}


Installing app through GPO

Question: I will need your help... The last day i set up an app to be installed using GPO under computer configuration.
The most of our computers are using WIFI to log in to our domain. Some of them, they received the .msi file and installed it without any issue.
But some of the, could not install it... From GPO i tried to increase the "Startup Policy Processing wait time" (Computer Configuration > Policies > Admin Templates > System > Group Policy) to 30sec, 60sec, 120sec, but nothing...
Also, in our Default Domain Policy i have enabled the "Always wait for the network at computer startup and logon".
After testing i found out the following:
In the computer that the app was installed successfully, i ping it from another pc during rebooting. When this pc was in CTL+ALT+DEL, i can ping it.
I did the same in a laptop which the app was not installed and when this pc was in CTL+ALT+DEL, i can not ping it... I can ping it only when a user logs in!!
I believe that this is the issue. Do you know why this happens? How can i solve it?
Thank you
PS: All computers have Windows 7 and our DC Servers have Windows 2016 R2
Comment: What do the event logs of the affected computers show abput this?
Answer: This can happen if there is a third-party wireless utility managing the adapter but not running as a service.
Typically these utilities have an option to "Let Windows manage the wireless" or "Run as a service". Either one may resolve the problem.
Generally, you're better off installing the wireless driver only and using Windows to manage the adapters if you can.
Comment: Thank you for your reply. Both laptop are using the save drivers and same WIFI utility. I will try to find how to run the utility Run as a service.

Installing app through GPO


Load multiple images in Air not working properly?

Question: So I made a drag and drop app where I can drop in an image, it get's resized and saved automatically on the desktop.
But now I want to do the same when there are multiple images dragged in.
This is where I'm stuck...
private function onDrop(e:NativeDragEvent):void
{
    trace("Dropped!");
    var dropfiles:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
    for each (var file:File in dropfiles){

        var ldr:Loader = new Loader();
        ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);

        switch (file.extension.toLowerCase()){
            case "png" :
                ldr.load(new URLRequest(file.url));
                trace('png');
                break;
            case "jpg" :
                ldr.load(new URLRequest(file.url));
                trace('jpg');
                break;
            case "jpeg" :
                ldr.load(new URLRequest(file.url));
                trace('jpeg');
                break;
            case "gif" :
                ldr.load(new URLRequest(file.url));
                break;
            default:
                Alert.show("Kies een geldige afbeelding!");
        }
    }
}

private function completeHandler(event:Event):void {
    var ldr:Loader = Loader(event.target.loader);
    var b:Bitmap = Bitmap(ldr.content);
    var encoder:PNGEncoder = new PNGEncoder();
    var bytes:ByteArray = encoder.encode(resizeimage(b.bitmapData, 600, 600));

    //new FileReference().save(bytes, "abc.png");
}

The problem is that I want the completeHandler() to run after every ldr.load() but in my code it only runs once right after the for each loop.
Does anyone know what I'm doing wrong here?
Answer: It looks like you the Loaders are only referenced as local variables. After the function onDrop ends, they're probably getting garbage collected. Once that happens, they won't be around to call your event handler. You need to save them somewhere to keep them memory.
I'd save them in an Array. Make a private variable on your class, like this:
private var _loaders:Array = [];

Then, when you create a Loader, save it:
var ldr:Loader = new Loader()
_loaders.push(ldr);

In your completeHandler, or whereever you're done with the Loader, be sure to remove it from the Array:
var index:int = _loaders.indexOf(ldr);
_loaders.splice(index, 1);

Comment: By the way, it's a common misconception that adding an event listener to a dispatcher creates a reference to the dispatcher. It's the other way around, though. The dispatcher holds a reference to the listener, and there is no extra reference to the dispatcher.


Is there an extension point in the Intershop back office for payment methods?

Question: I'm looking to add a new tab to specific payment methods, after the "Preferences" tab for example, to provide additional functionality to interact with the payment method. The methods are implemented using the Payment services framework.
Unfortunately the Payment cookbook in the Knowledge Base doesn't go into detail about the possible templates here.
Answer: Looking at payment/PaymentMethodTabs_52.isml.
There seems to be no extension point. You would have to override this template and add the new tab yourself. Preferably you should override this template, add an extension point and then write some extension that adds new tabs to the screen. This way your code can easily be migrated to the next version of intershop if they added an extension point later.


Coordinates of Basis For Hermite Polynomials

Question: Let n = 2. Show that the following Hermite polynomials
$H_0(t) = 1$,
$H_1(t) = 2t$,
$H_2(t) = 4t^2 − 2$,
form a basis of $P_2$.
2) What are the coordinates of $H_0, H_1, H_2$ in the basis {$H_0, H_1, H_2$}? And in the basis {$1, t, t^2$}?
For part two, is this thinking terribly incorrect: if we have the basis {$ 1, 2t, 4t^2-2$} and we want to express the coordinates of $H_0, H_1, H_2$, would it be: ($1, 1, 1$)?
And to express $H_0, H_1, H_2$ in {$1, t, t^2$} , (1, 2, 4)? I would appreciate any assistance in helping me figure out how to think about this. I do think I am off-base (..ha). Thank you.
Answer: Let $a_1=1, a_2=t$ and $a_3=t^2$. $\{a_1,a_2,a_3\}$ form a basis of $P_2$. Let us assign vectors $v_1=[1,0,0]^T,v_2=[0,1,0]^T$ and $v_3=[0,0,1]^T$ to $a_1$,$a_2$ and $a_3$. Note that any polynomial $a+bt+ct^2$ in $P_2$ can then be expressed in vector notation as $av_1+bv_2+cv_3 = [a,b,c]^T$.
To show that $\{H_1,H_2,H_3\}$ also form a basis of $P_2$ one must show that the corresponding vectors are linearly independent. The vectors corresponding to $H_1,H_2$ and $H_3$ are $v_1,2v_2$ and $4v_3-2v_1$, respectively. It is easy to show that they are indeed independent using the definition.
If the chosen basis is $\{H_0,H_1,H_3\}$ then the coordinates of $H_1,H_2$ and $H_3$ are $e_1,e_2$ and $e_3$, respectively. If the chosen basis is $\{a_1,a_2,a_3\}$ then the coordinates become (can you see what they will be from above ?).


we have Android Application Size more than max Size?

Question: What should we do if the size of our Android application is more than max size? Currently the acceptable size for Android applications (i.e. <App>.apk) on the Android market is 50 MB.
If our <Application>.apk size is more than 50 MB then what's the alternative to follow on?
Comment: I think it's obvious that you won't be able to upload the app if the size is above the max limit... Have you tried optimizing your images and sounds using optimizers?
Comment: I want to know the Uploading case of our Android Application if there Size is greater than the max acceptable size of Android Market.
Answer: Try removing the resources from the project and changing the app so that the resources will be downloaded upon first app opening to the SD card...
It will take some time to develop the changes, but I don't think you really have a choice...
Note that Samsung devices have an even smaller size limit...
Comment: Just for the record (<3 search engine users): Samsungs limit is 30 MB.
Answer: The first reason for .apk size growth is resources. The more specialized application gets on each configuration (screen sizes, orientations, densitites etc) the more .apk size grows. Usually .apk still has size much less then 50 mb limits, but even with 20mb users may perceive your application as heavy.
Android Market added support for multiple .apk per application. This feature was designed to specifically address the issue of .apk size growth due to many different configuration. You can read more about it  in Multiple APK Support in Android Market post from official Android blog. Though this is considered as last resort.

If you .apk size is large due to other reasons, then you're most likely doing something wrong. If its some embedded video/audio file (or even files!), consider moving them to web and download when user needs them for the first time. This will save internal memory space which is might be critical to users (especially on older devices).
Comment: I think you're going the wrong way here.  If you have large media files that are required by the app, it's better to have them in the market.  What's the point of a tiny, useless initial download followed by a few hundred megs of video on the first run?  Just do it all up front.  Google announced support for 4G apks is coming (in June...).
Answer: I can't image why an application would be more than 50 mb from just the source code alone.  If alot of the size is in design elements(images, etc) or data(database files), you could always have the user download this info when the application is first run.
Comment: Paying the cost up front in the initial download is a better user experience.
Comment: yea... I understand this, but I don't see how that relates to my post. Obviously you try to put as much as you can in the .apk and if you can't fit everything then you could always have the user download the rest the first time the app is run.
Comment: Sure, but that's just a workaround for a problem that Google says will be fixed soon (assuming the apk is going to fit in 4G...).  It's something to get rid of ASAP.
Answer: if you are using Android 2.3.3 version then minimum size of the application must be minimum 9MB and maximum size is depend upon the device,the capacity of memory of the device. but if you take it 50 MB then no problem, its disadvantage is only that the AVD takes time to start.i don't know the Android Market place current application size.
Comment: Sounds very weird to me that the minimum size is 9MB... Anyway, it would be a bad idea to upload an app (even if it is possible) that would be supported only from 2.3.3


Proof n-cube graph is connected

Question: I am studying graph theory and my text book gives a proof for an n-cube graph being connected that I find really weird/confusing. Is there a simpler proof to show that the n-cube is connected.
The n-cube graph is the graph where the vertices {0,1} strings of length n. Two strings are adjacent if they differ is exactly one position.
For example the 2-cube graph has vertices V:{00, 01, 10, 11} and edges:
(00 <-> 01),
(00 <-> 10),
(01 <-> 11),
(10 <-> 11)
This is simply a square. What kind of proof can I use show that it is connected? I am currently thinking induction.
My rough try at a Proof
Proof By Induction
Base Case ( n=1 )
Then graph has two vertices, 0 & 1 which are connected (since they differ by one). Assume than P(n) is true. Prove P(n+1). Lets remove the last digit. From the inductive hypothesis we know that P(n) is connected. Add the last digit back in. We can partition P(n+1) into $A_0$ which contains all the vertices with a 0 as the last digit; $A_1$ which contains all the vertices with 1 as the last digit. Since $A_0$ and $A_1$ are essentially P(n), we know they are connected from the inductive hypothesis. Since $A_0$ and $A_1$ are connected we can conclude that P(n+1) is connected!
Is this correct?
Comment: It would help if you could describe your textbook's proof. The way I'd do it is show that we can define the $n$-cube graph inductively from two $(n-1)$-cube graphs, then inductively show that an $n$-cube graph is connected (because there's an edge connecting the two $(n-1)$-cube graphs.)
Comment: I was writing out an inductive proof as you wrote this comment. Thanks for the insight. Is the 'rough idea of a proof' that I have provided correct?
Comment: Almost; you need to show that there's an edge connecting $A_0$ and $A_1$, too. Once you've done that, you've shown they're connected, yes.
Comment: If I show that since there exists a vertex in $A_0$ that is connected by an edge to $A_1$ because they differ by one digit(last digit) then is that enough?
Comment: Yeah.${}{}{}{}$
Comment: Awesome! Thanks :)
Answer: Your proof may be correct but it is weird/confusing. There is a simpler proof that the $n$-cube is connected. A graph is connected if there is a path from any vertex to any other vertex. In terms of the $n$-cube, that just means that you can get from one $\{0,1\}$-string of length $n$ to another one by changing one bit at a time. Which is so obvious that there is no point in writing a detailed proof.
Comment: @MikeMiller A more interesting approach would be to prove (by induction on $n$) that the $n$-cube has a [Hamiltonian](http://en.wikipedia.org/wiki/Hamiltonian_path) path (a Hamiltonian *cycle* for $n\gt1$), which is of course a much stronger property than just being connected.
Comment: Amusingly this much more clear way of doing things is precisely the inductive proof given in my answer, which somewhat obfuscates what's going on.
Comment: Yeah, that's when I thought when I read the answer, it seemed incredibly obvious. I wonder what it is that makes things so obvious after a while.
Comment: @Zee Out of curiosity, how does your book prove it? By the way what book is that?
Comment: @bof The book is a compiled version of course notes for a course I'm taking. It uses some convoluted logical process that keeps passing over my head. It proves that from $v_0$ (a vertex with all 0's) there exists a path to every other vertex, by x (another string with k 1's in positions 1 - j). It then iterates through each of the 1's positioned and somehow concludes that they are connected.
Answer: Here's a full proof as outlined above.
The $1$-cube graph is connected by inspection. (You could even do the $0$-cube graph, which is automatically connected, as it only has one vertex.) Now assume that the $n$-cube graph is connected. In the $(n+1)$-cube graph, consider the subgraphs consisting of those vertices with final digit $0$ and $1$ respectively (and all edges between them); call these $A_0$ and $A_1$. Then $A_0$ and $A_1$ are isomorphic to the $n$-cube graph, thus connected by hypothesis. Now note that there is an edge between $(0,\dots,0)$ and $(0,\dots,1)$ as they differ by a single digit.
So the $(n+1)$-cube graph is connected; for pick any vertices $p$ and $q$ in the graph. If they are both in $A_0$ or $A_1$ they are connected by inductive hypothesis; so suppose WLOG $p$ is in $A_0$ and $q$ is in $A_1$. There is a path connecting $p$ to $(0,\dots,0)$ and a path connecting $(0,\dots,1)$ to $q$ by inductive hypothesis. Connect these paths by including the edge between $(0,\dots,0)$ and $(0,\dots,1)$ and we've constructed a path connecting $p$ and $q$, as desired.
Answer: proof by construction.
any two nodes, pairwise different, noted by -, if same, noted by .
then any two nodes, the difference are noted as --.--.--.--
then one is --0--1--0--1--, the other is --1--0--1--0--
then there is edges between
between --0--1--0--1-- and --1--1--0--1--
between --1--1--0--1-- and --1--0--0--1--
between --1--0--0--1-- and --1--0--1--1--
between --1--0--1--1-- and --1--0--1--0--
then there is a path betwen --0--1--0--1-- and --1--0--1--0--
so, there is path between any two node, so graph is connected.

Proof n-cube graph is connected


Python Instance Variable as Default Parameter

Question: I have am writing a Python function that takes a timeout value as a parameter.  Normally, the user will always use the same timeout value, but on occasion he may want to wait slightly longer.  The timeout value is stored as a class instance variable.  I want to use the class' timeout instance variable as the default parameter.  Currently, I am implementing this as follows:
def _writeAndWait (self, string, timeout = -1):
    if (timeout == -1):
        timeout = self._timeout

I was just wondering, is the proper way to use an instance variable as a default parameter?  Or is there a better way that would avoid the "if" check?
Answer: A common way is to use None as the default value
def _writeAndWait (self, string, timeout=None):
    if timeout is None:
        timeout = self._timeout

Answer: The short answer to your question is no, you cannot eliminate the if statement, because Python examines the signature only once, and so the default is shared across all calls. Consider, for example:
def addit(x, L=[]):
    L.append(x)
    return L

Versus:
def addit(x,L=None):
     if L is None:
         L=[]
     L.append(x)
     return L

These two functions, though they look identical, actually have completely different behavior; in the first one, the default value of L is shared between invocations so that addit(1) followed by addit(2) will return, in the first case, two objects that are actually point to the same underlying object and that have a value of [1,2], while it the second case it will return two separate objects, [1] and [2].
The only recommendation I have for you, then, is to use a default of None simply because that is the standard convention for parameters that have not been specified, but to continue using an if check, because using as a default value some existing object will have subtly different (usually wrong) behavior.
Answer: In python >2.5 you can safe one line by using the ternary condition operator:
def _writeAndWait (self, string, timeout=None):
    timeout = self._timeout if timeout is None else timeout


Calculating $\lim_{x\rightarrow +\infty} x \sin(x) + \cos(x) - x^2 $

Question: I want to calculate the following limit:
$\displaystyle\lim_{x\rightarrow +\infty} x \sin(x) + \cos(x) - x^2 $
I tried the following:
$\displaystyle\lim_{x\rightarrow +\infty} x \sin(x) + \cos(x) - x^2 = $
$\displaystyle\lim_{x\rightarrow +\infty} x^2 \left( \frac{\sin(x)}{x} + \frac{\cos(x)}{x^2} - 1 \right) = +\infty$
because
$\displaystyle\lim_{x\rightarrow +\infty} x^2 = +\infty$,
$\displaystyle\lim_{x\rightarrow +\infty} \frac{\sin(x)}{x} = 0$, and
$\displaystyle\lim_{x\rightarrow +\infty} \frac{\cos(x)}{x^2} = 0$,
but I know from the plot of the function that this limit goes to $- \infty$, so I'm clearly doing something wrong. Sorry in advance for the simple question and perhaps for some silly mistake.
Comment: You are SUBTRACTING $x^2$. This term is the highest order so it will dwarf everything else in your limit.
Comment: You were so close! Check the sign of your $x^2$ term :)
Comment: $\lim_{x\rightarrow +\infty} x^2 \left( \frac{\sin(x)}{x} + \frac{\cos(x)}{x^2} - 1 \right)$ is equivalent to $\lim_{x\rightarrow +\infty} -x^2 \left( -\frac{\sin(x)}{x} - \frac{\cos(x)}{x^2} + 1 \right)$
Answer: Using your work: $$\lim_{x\rightarrow +\infty} x^2 \left( \underbrace{\frac{\sin(x)}{x}}_{\to 0} + \underbrace{\frac{\cos(x)}{x^2}}_{\to 0} \color{blue}{\bf - 1 }\right) = \lim_{x\rightarrow +\infty} x^2(-1) = -\infty$$
Answer: Denote $f(x)$ the given expression then since $\sin$ and $\cos$ functions are bounded then we have easily
$$\lim_{x\to\infty}\frac{f(x)}{x^2}=-1\implies f(x)\sim_\infty-x^2$$
which means that $f(x)$ is asymptotically equivalent to $-x^2$ at $\infty$
Answer: Hint: $-\frac{1}{2}x^2\geq x+1-x^2\geq (x\sin x+\cos x-x^2)$ for $x\,$ large enough. Now let $x$ go to infinity.


Question about ring homomorphism.

Question: I have a ring homomorphism $f : \mathbb{Z}[x] \to \mathbb{Z}$ such that $f$ sends $x$ to $3$. I want to find $f(x^3+2)$.
My attempt is, since $f$ is a homomorphism
$$f(x^3+2)=f^3(x)+f(2)=27+f(2)$$ but what is $f(2)$?
Comment: A ring homomorphism sends the identity to the identity, hence $f(1)=1$, so $f(2)=f(1+1)=\,...$
Comment: @quasi A ring-with-identity homomorphism sends the identity to the identity; that can't  be literally true for a  ring homomorphism, since a ring need not have an  identity. (And in fact if $R$ is a ring with identity and $f:R\to R$ iis defined by $f(x)=0$ then $f$ _is_ a ring homomorphism.) In this example it's not hard to _prove_ that $f(1)=1$, in spite of that (and without assuming that we really havve a ring-with-identity homomorphism): $3=f(x)=f(1x)=3f(1)$.
Comment: @David C. Ullrich: Many authors require, as part of the definition of ring, the existence of a multiplicative identity $1$, and for such rings, they require, as part of the definition of homomorphism, that a ring homomorphism sends $1$ to $1$. But I agree, if rings are not required to have a multiplicative identity, then your argument nicely avoids the issue.
Answer: As mentioned in the comments, $f(2) = f(1 + 1) = f(1) + f(1) = 1 + 1 = 2$, so $f(x^3 + 2) = 29$.

Question about ring homomorphism.


What is the maven base directory?

Question: I'm struggling to find documentation on the maven site that explicitly tells me what the "base directory" is. The term is bandied around on several pages as if I'm meant to already know what it means.
I imagine it's the directory that contains the pom.xml (which pom, if one pom references another?), but it might be more subtle than that?
Answer: Found it in the Introduction to the POM:

project.basedir: The directory that the current project resides in.
Answer: It's a directory where the pom.xml is stored (in the root of the project).

What is the maven base directory?


UTF16 stored string doesn't match once retrieved back from CoreData

Question: So I am using CoreStore to save a string identifier in CoreData.
The string may have some Swedish UTF16 characters. Inspecting from the debugger console:
> po identifier
"/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder åäö/Test with Swedish characters - åäö.xlsx"

Immediately after being saved back to CoreData:
>po record
<File: 0x281e140a0> (entity: File; id: 0xdcac6620f1e9eb63 <x-coredata://BA0168AF-92CE-4AC2-A934-1020E41C5C20/File/p615>; data: {
    // ...
    identifier = "firstname.lastname@example.com@files.runcloud.se/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder \U00e5\U00e4\U00f6/Test with Swedish characters - \U00e5\U00e4\U00f6.xlsx";
    // ...
})

Which looks like the UTF16 string has been stored as an UTF8 one. But still a valid one as:
> po record.identifier == identifier
true

The problem comes later when trying to retrieve the record with again a UTF16 Swedish identifier string as the original above as it doesn't match anymore.
CoreStore.fetchOne(From<Record>().where(\.identifier == identifier)) // Fails

How could I convert identifier to a representation that would match the stored CoreData value?
Update
Even more strange, a hardcoded identifier does succeed:
CoreStore.fetchOne(From<Record>().where(\.identifier == "email@example.com@files.runcloud.se/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder åäö/Test with Swedish characters - åäö.xlsx")) // Works

And identifer and this hardcoded string do match:
po identifier == "email@example.com@files.runcloud.se/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder åäö/Test with Swedish characters - åäö.xlsx"
true

But using identifier instead of the hardcoded one doesn't.
Update 2
Comparing .unicodeScalars of identifier and the hardcoded string does show that they are indeed different:
Answer: CoreData does save and return strings exactly the same.
The issue at trying to retrieve values using complex characters is that CoreData (and most probably SQLite behind it) do not consider my sentences equal as they have different grapheme clusters. Both sentences are valid and compare equal in Swift but not in CoreData as values to retrieve objects.
There doesn't seem to be a proper way to convert grapheme clusters in Swift, so my workaround was to recreate the process that lead to have the original grapheme clusters in the first place. This involved first creating a URL out of the string and then letting the FileProvider framework create the same grapheme clusters by calling persistentIdentifierForItem(at: url)!.rawValue. Then use this value to retrieve my saved object.


Image upload in content type, no previous image is present

Question: Oddly worded title, I know. I'm not sure how to phrase it or what to ask exactly.
In previous versions of Drupal if I added an image field to a content type, once an image was uploaded it was saved in a library of images and it was available without being uploaded again.
Currently in Drupal 8.5.4 that's no longer the case.

I'm given the option to either upload or embed but not to select from an already existing list of uploaded images.
This is more of a nuisance since I have to reupload images even if I want to use them on a separate content type.
I'm not sure if this is a bug or it has completely changed in this version.
Drupal 8 bug tracker doesn't offer anything relevant.
Any help is appreciated.
Comment: That looks like Media? Is it the media browser / upload? If it is, then it should be available, but it looks like you're missing a tab that lets you select from existing.
Comment: Yes, I think it's the media browser / upload. I don't know what the module it's called. And yes, I am missing a tab. Not sure what's going on there.
Answer: A little more configuration is necessary to add the feature of browsing existing media, you can do it with Entity browser and Core Media module in Drupal 8.5 and upwards.
Here's a great tutorial on how to do that, you need the Part 4: How to Browse Media Assets: Managing Media Assets using Core Media in Drupal 8


Difference in sample means showing its estimated standard error

Question: I've been using the Welch t-test for finding p-values for whether two means are the same, from populations with unequal variances (but samples look normally distributed).
However, sometimes I have a case like 79.4±0.5 vs 73.5±0.4 where the p-value would just be astronomically small. A more useful way of characterizing this would be a difference in means accompanied with a standard deviation (how confident I am of that difference in means).
What are the best statistical ways to go about this?
TLDR:

Unequal variances
Normally distributed
Diff. in means is there; I want to characterise how big it is based on sample data
Answer: As an example for the first population, I will take $77.4\pm 0.5$ to mean
a sample from $\mathsf{Norm}(\mu=77.4,\sigma=0.5),$ and similarly for the second population. [If you intended to write confidence intervals, then
my standard deviations will not be what you intended, but the methods
shown in my example below still apply.]
Accordingly, suppose you have $n = 20$ observations from each population and
perform a Welch two-sample t test for differences in population means.
In R, it looks like this:
set.seed(2020)
x1 = rnorm(20, 77.4, 0.5)
x2 = rnorm(20, 73.5, 0.4)
mean(x1);  sd(x1)
[1] 77.34882
[1] 0.7131236
mean(x2);  sd(x2)
[1] 73.68158
[1] 0.3486032

t.test(x1, x2)

        Welch Two Sample t-test

data:  x1 and x2
t = 20.661, df = 27.59, p-value < 2.2e-16
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
 3.303421 4.031060
sample estimates:
mean of x mean of y
 77.34882  73.68158

Notice that the output gives a 95% confidence interval
$(3.303, 4.031)$ for the difference $\mu_1 - \mu_2$ in population
means.
The difference $\bar X_1 - \bar X_2$ between the two sample means
estimates the difference $\mu_1 - \mu_2$ between the two population means.
For independent samples, the variance of the difference in sample means is
$$Var(\bar X_1 - \bar X_2) = Var(\bar X_1) + Var(\bar X_2)
=\frac{\sigma_1^2}{n_1} + \frac{\sigma_2^2}{n_2},$$
estimated by
$$\widehat{Var}(\bar X_1 - \bar X_2) = \frac{S_1^2}{n_1} + \frac{S_2^2}{n_2},$$
where $S_1^2$ and $S_2^2$ are the respective sample variances.
The 95% confidence interval in the R output for the Welch two-sample t test
is of the form
$$\bar X_1 - \bar X_2 \pm t^*\sqrt{\frac{S_1^2}{n_1} + \frac{S_2^2}{n_2}},$$
where $t^*$ cuts probability $0.025 = 2.5\%$ from the upper tail of
Student's t distribution with $\nu^\prime = 27.59$ degrees of freedom.
To get $\nu^\prime$ you need to use the formula for the degrees of
freedom of a Welch test. (It involves sample sizes and sample variances
and satisfies the inequality $\min(n_1-1,n_2-1) \le \nu^\prime \le n_1 + n_1 - 2.$ The computer output above uses $t^* = 2.050.)$
qt(.975, 27.59)
[1] 2.049779

If you just want to show the estimated difference in population means
along with its standard deviation, you might write
$$\bar X_1 - \bar X_2 \pm \sqrt{\frac{S_1^2}{n_1} + \frac{S_2^2}{n_2}},$$
being careful to mention that you are showing a 'standard error' on the right and
not a 'margin of error' as in a confidence interval.
Answer: An alternative to the p-value for the hypothesis test is to report a confidence interval for the mean difference.  In cases where there is an obvious difference this ought to show up in the confidence interval.  If you are using the t.test function in R then the confidence interval is reported along with the test results.


If $X_1$ and $X_2$ are individually independent to $\{Z_k\}$ does it follow that their sum is too.

Question: If $X_1$ and $X_2$ and $\{Z_k\}_{k}$ denote Random variables on a probability space and it holds that

$\{X_1\}\cup\{Z_k\}$ is a collection of independent r.v.s
$\{X_2\}\cup\{Z_k\}$ is a collection of independent r.v.s

does it then hold that $\{X_1+X_2\}\cup\{Z_k\}_k$ is a collection of independent random variables? We do not assume that $X_1$ and $X_2$ are independent.
We know that $\sigma(X_1+X_2) = \sigma(\sigma(X_1)\cup \sigma(X_2))$, however this doesn't say much?
Answer: No. Let $A,B,C$ be pair-wise independent events with $P(A\cap B\cap C) \neq P(A)P(B)P(C)$. Let $X=I_A, Y=I_B$ and $Z=I_C$. Then the hypothesis is satisfied. If $X+Y$ is indepdent of $Z$ then we would have $E((X+Y)^{2}Z)=E(X+Y)^{2}EZ$. A little simplification of this equation gives $P(A\cap B\cap C) =P(A)P(B)P(C)$ which is not true.
For an eample of such events see https://en.wikipedia.org/wiki/Pairwise_independence
Comment: Right we get $P(A)P(C)+2P(A\cap B \cap C)+P(B)P(C) =E(XZ)+2E(XYZ)+E(YZ) = E((X+Y)^2Z) = (E(X)+E(X)E(Y)+E(Y))E(Z) = (P(A)+P(A)P(B)+P(B))P(C) = P(A)P(C)+P(A)P(B)P(C)+P(B)P(C)$ implying that $P(A\cap B\cap C) = P(A)P(B)P(C)$. Thanks!


Freeman and Tukey interval

Question: If $Y$ is Poisson$(\lambda)$ distributed, how do we obtain this confidence interval for $\lambda$:
$$
\left (\frac{(\sqrt Y+\sqrt{Y + 1}-z_{(α⁄2)} )^2 - 1}{4},\  \frac{(\sqrt Y+\sqrt{Y  +1}+z_{(α⁄2)} )^2 - 1}{4} \right )
$$
Comment: Not an answer, but some additional information in regards to the OP's comments: 1. A definition of the FT CI appears here, along with a discussion of/comparison with other Poisson CIs: [Byrne and Kabaila](http://www.tandfonline.com/doi/pdf/10.1081/STA-200052109) 2. The original paper by Freeman and Tukey can be found here: [Freeman and Tukey](https://projecteuclid.org/download/pdf_1/euclid.aoms/1177729756). The term $\sqrt{Y} + \sqrt{Y+1}$ derives from the variance stabilising transformation.
Comment: The Byrne and Kabaila reference in Maurits' comment gives the above interval, and also refers to Freeman and Tukey (1950) for it, so presumably it does follow directly from what is there. However, as mentioned above I didn't see the direct connection at first glance. I might get time to have a closer look later.
Comment: I think I may have it: there's an approximation $E(\sqrt{Y}+\sqrt{Y+1})\approx \sqrt{4\lambda+1}$. This is not explicitly given in Freeman and Tukey, 1950, but is mentioned in other works where Tukey is an author or co-author, for example in connection with the (closely related) double root residual. However, perhaps it can be derived from the binomial case in F&T 1950. That's sufficient to derive the interval. If nobody beats me to it I'll try to write it up as an answer.
Comment: The only reference I can find with this formula (Patil&Kulkarni, 2012,  *Comparison of confidence intervals for the Poisson mean*, REVSTAT) simply mentions the original paper by Freeman and Tukey, which itself doesn't contain this formula, nor, at first sight, anything that would obviously give it. It may be that it's possible to derive it as a limiting case of the binomial interval there, but Molenaar (1973, Biometrics, "*A simple approximation to the Poisson, Binomial, ...*") offers a different interval  based on the limit of the binomial case in Freeman and Tukey ...ctd
Comment: ctd... so I am unconvinced that it comes directly from there (but maybe can be had via a similar argument).
Answer: Taking these as given:
$E(\sqrt{Y}+\sqrt{Y+1})\approx \sqrt{4\lambda+1}$
$\text{Var}(\sqrt{Y}+\sqrt{Y+1})\approx 1$
and assuming $\lambda$ is large enough that $(\sqrt{Y}+\sqrt{Y+1})$ is approximately normal, then
$P(-z_{1-\alpha/2}<\sqrt{4\lambda+1}-(\sqrt{Y}+\sqrt{Y+1})<z_{1-\alpha/2})\approx 1-\alpha$
$P((\sqrt{Y}+\sqrt{Y+1})-z_{1-\alpha/2}<\sqrt{4\lambda+1}<(\sqrt{Y}+\sqrt{Y+1})+z_{1-\alpha/2})\approx 1-\alpha$
Further assume that $\lambda$ and $\alpha$ are large enough that the lower limit ($(\sqrt{Y}+\sqrt{Y+1})-z_{1-\alpha/2}$) is non-negative. For $\alpha=0.05$ this means $Y$ should be at least $1$ (though for a reasonably good approximation you'll want it larger than that anyway) -- and the case $Y=0$ would require a different approximation, as it does for the double root residual. If your observed $Y$ is $0$ you simply shouldn't be using this sort of approximation there (and down that far any hope of a two-tailed $1-\alpha$ interval with $\alpha$ at typical values is gone as well).
Then we can square all the terms without complication (we won't be flipping any inequalities, having to consider separate cases for $\pm$, or introducing any extraneous solutions):
$P((\sqrt{Y}+\sqrt{Y+1}-z_{1-\alpha/2})^2<{4\lambda+1}<(\sqrt{Y}+\sqrt{Y+1}+z_{1-\alpha/2})^2)\approx 1-\alpha$
$P(\frac14 [(\sqrt{Y}+\sqrt{Y+1}-z_{1-\alpha/2})^2-1]<{\lambda}<\frac14[(\sqrt{Y}+\sqrt{Y+1}+z_{1-\alpha/2})^2-1]\approx 1-\alpha$
which is the required interval.
Note that since $\lambda$ must be positive, we now require $Y$ to be at least 2 to get even a feasible answer for the lower limit at the 5% level (though it won't give a very good approximation for the coverage down that far) --  don't try to use this at all when $Y\leq 1$.
Indeed I'd suggest using it when $Y\leq 4$ or so isn't a great idea; once you get much above $4$ it tends to work at least reasonably well at typical levels and nearby $\lambda$ values. (Your own utility function or circumstances may vary, don't take that value as in any way prescriptive or even worth quoting).
Comment: Thaaaaaaaaaaaaaaaaaaank you!!!!! I don't know how to thank you!!! Really really really thank you!!! @Glen_b

Freeman and Tukey interval


foreign key as initial value not passed to the ModelForm in django

Question: I need to pass the value (based on category_id) for a ForeignKey to the ModelForm but it's not working. My field remains "--------" and proper value is not set from the drop-down field.
Value for the Category must BE SELECTED and other values must be not hided from user to choice.
As the result category value successfuly passed to template but drop-down field Category not set!
As I can see other guys solved it via constructor for ModelForm, but I feel there must be native django solution.
Would be thankful for any solutions!
my models.py:
class Category(models.Model):
    name = models.CharField('Name', max_length=20)
    icon = models.CharField('Icon', blank=True, max_length=20)

class Transaction(models.Model):
    type = models.CharField('Type', default='exp', max_length=20)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    note = models.CharField('Note', blank=True, max_length=20)

my urls.py:
urlpatterns = [
url(r'^add/(?P<category_id>[0-9]+)', "core.views.add_trans_view", name='add_trans_url'),
]

my views.py:
def add_trans_view(request, category_id):
    category = Category.objects.get(id=category_id)
    form = TransactionForm(request.POST or None, initial={'category':category.name,})
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return render(request,
            'core/transaction_form.html', {'form': form, 'for_debug':category})

my forms.py:
class TransactionForm(forms.ModelForm):
class Meta:
    model = Transaction
    fields = ['type', 'category', 'note']

my template:

Initial 'category' value transfered from view:

{{for_debug}}

<form method='POST' action=''> {% csrf_token %}
  {{form.as_p}}
  <input type='submit' value='Done'/>
</form>

Comment: Why do you pass the name of the category at `form = TransactionForm(request.POST or None, initial={'category':category.name,})`? Have you tried `{'category':category}`?
Comment: But does your `Category` model have any data in there?
Comment: @Shang Wang, Sure, there are records. for_debug variable passed successfully to the template
Comment: I mean when you initialize the form at `initial={'category':category.name,}`. Try there with `category` (the instance) instead of `category.name`.
Comment: @LostMyGlasses, you are damn great! Thanks for dabbin with finger! Please reply - I'll give a vote
Comment: Great! I'll post it as an answer
Answer: Try replacing
form = TransactionForm(request.POST or None, initial={'category':category.name,})

with
form = TransactionForm(request.POST or None, initial={'category':category,})

initial needs the instance (category), instead of only the string that contains its name (category.name).
Comment: Just a warning, be careful of your browser's cache. In my case, It showed the previous selected item and wouldn't update. Wasted a lot of my time.


Is there a way to set the interstial AdUnitID in AdMob after loading the ad?

Question: We use a different ad ID for each piece of content in our game so that we can track which piece of content an ad was shown for (long story). I'd like to start pre-loading the ad before I know which piece of content the user has selected. The problem is that I get an exception if I don't set the AdUnitID before loading the ad. I haven't found a way to do this, and I wonder if you have?
Answer: There is no way. The AdUnitId is what determines what ads to supply. If you don't specify it

Admob can't determine what ads to send you
Admob can't determine who to pay for any click on an ad (if it did somehow send you one).
Comment: That confirms what my coworker said. I guess we need to write a little system to track what content was watched on our own.