INSERT statement works only once

Question: I asked something like this earlier, but now I ran better tests, and tried to analyze what the problem was.
This is the ajax request:
  //start ajax request here//
   $.post('purchaseitem.php',{itemAmount:itemAmount, itemId:itemId}, function(data){
    $('.savestatus_'+itemId).text(data);
   });
  //end it here

I echo out all the items in the items table, along with an ahref link and an input field to allow the user to type in the quantity and click buy.
<?php
    $shop_query = mysql_query("SELECT * FROM sector0_item WHERE item_location = '$chapter'");
    while(($shop_row = mysql_fetch_array($shop_query))){
        $itemid = $shop_row['item_id'];
        $item_name = $shop_row['item_name'];
        $item_price = $shop_row['item_price'];
        ?>

<?php echo $item_name; ?>

<?php echo $item_price; ?>

        <input type = 'text' class = "purchaseAmount_<?php echo $itemid;?>" name = "purchaseAmount" />
        <a id = "purchaseButton_<?php echo $itemid; ?>" href = "prevent default();" class = "purchase_button" onclick = "buy(); return false;">Buy
        <div class = 'savestatus_<?php echo $itemid; ?>'>

        <?php
    }
?>

This is a test version of my code, so I know that it is messed up...
The php part:
$user_inventory_query = mysql_query("SELECT * FROM sector0_inventory WHERE id = '$dbid' AND item_id = '$item_id'");
                        $checking_item_inventory = mysql_num_rows($user_inventory_query);
                        if($checking_item_inventory === 0){
                            /*^*/  $insertion_into_inventory = mysql_query("INSERT INTO `sector0_inventory`(`id`, `item_id`, `username`, `item_name`, `quantity`) VALUES ('$dbid','$item_id','$dbuser','$item_name','$purchase_amount')");
                                if($insertion_into_inventory === true){
                                mysql_query("UPDATE sector0_players SET cash = cash-'$total_cost' WHERE id = '$dbid'");
                                echo "Purchase complete";
                                }
                        }else if ($checking_item_inventory === 1){
                            $update_inventory_quantities = mysql_query("UPDATE sector0_inventory SET quantity = quantity+'$purchase_amount' WHERE id = '$dbid' AND item_id = '$item_id'");
                            if($update_inventory_quantities===true) {
                                mysql_query("UPDATE sector0_players SET cash = cash-'$total_cost' WHERE id = '$dbid'");
                                echo "Purchase complete, quantity updated.";
                                }
                        }

The above is the query. the /^/ part is the part that fails.
When I Truncate the table, and click buy, the insertion is completely successful. But for any other item, insertion fails. It's a php, I guess, I am really confused.
relative table to the insert and update queries
CREATE TABLE `sector0_inventory` (
 `id` bigint(20) NOT NULL COMMENT 'The input in this field will be php code exclusive. No increment allowed.',
 `item_id` bigint(20) NOT NULL COMMENT 'The input is also code exclusive',
 `username` varchar(250) NOT NULL COMMENT 'This value will be used to search for the user inventory information. Admin privileges only',
 `item_name` varchar(250) NOT NULL COMMENT 'This value will be used to identify (user side) the item. It will be used by admins to query out when a removal of a specific item is needed',
 `quantity` bigint(20) NOT NULL COMMENT 'This value will be 0 by default BIG int is to allow calculations',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Comment: I hope you sanitized those variables...
Comment: I have a very hard-coded custom function to sanitize every sort of user-input variable :)
Answer: Show the output of CREATE TABLE sector0_item to get more help, but my guess is that your primary key on that table is id and you're trying to specify that manually in your INSERT statement:
INSERT INTO `sector0_inventory`(`id`, `item_id`, `username`, `item_name`, `quantity`) VALUES ('$dbid','$item_id','$dbuser','$item_name','$purchase_amount')

Your primary key must be unique for each row. Try:
INSERT INTO `sector0_inventory`(`item_id`, `username`, `item_name`, `quantity`) VALUES ('$item_id','$dbuser','$item_name','$purchase_amount')

That will work if your id column is set to AUTO INCREMENT.
EDIT: After you posted the table structure, your problem is the database table design. Right now the primary key is id which means you can only have one row per PHP session ID. I don't know your application, but that seems wrong.
If you can delete the table and start from scratch, then DROP the table and re-create it using:
CREATE TABLE `sector0_inventory` (
 `transaction_key` INT NOT NULL AUTO INCREMENT COMMENT 'The unique ID for each row',
 `id` bigint(20) NOT NULL COMMENT 'The input in this field will be php code exclusive.     No increment allowed.',
 `item_id` bigint(20) NOT NULL COMMENT 'The input is also code exclusive',
 `username` varchar(250) NOT NULL COMMENT 'This value will be used to search for the     user inventory information. Admin privileges only',
 `item_name` varchar(250) NOT NULL COMMENT 'This value will be used to identify (user     side) the item. It will be used by admins to query out when a removal of a         specific item is needed',
 `quantity` bigint(20) NOT NULL COMMENT 'This value will be 0 by default BIG int is to     allow calculations',
 PRIMARY KEY (`transaction_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

then restore your PHP back to the way you had it.
Note that this will forfeit all of your data in that table...
Comment: The first id column is inserted/valued as the user's session/cookie ID
It is a bigint(20), item_id is the same, username is a varchar, item_name is varchar, quantity is bigint(20).
I will try to add an auto increment index field, and retry the the insertion.
Comment: Edit the question to include the output of `SHOW CREATE sector0_inventory` and that will help.
Comment: Updated to include another solution.
Comment: This really did work! Thanks for, not only the answer, but also the explanation, much appreciated!

INSERT statement works only once


How do I use commas to "add" strings together in a return statement?

Question: Let's say I want to add these strings together: "I" "use" "Python"
Firstly, I could concatenate them using the + sign like this:
print("I " + "use " + "Python")

But that is bulky and wastes a lot of time, especially when you need to combine a lot of strings. Also, note that I embedded the spaces into the string, whereas I usually have to use variables, meaning that I have to add spaces separately, which is an even bigger pain.
Secondly, there is a way to add with commas:
print("I", "use", "Python")

This is what I want, however this has a caveat. It doesn't seem to work in return functions.
def function():
  return "I", "use", "Python"
print(function())

This returns a tuple, instead of the string I want, which means that sigh, I have to use the boring plus sign concatenation. This sucks up tons of time because I need to continuously add spaces.
So back to the main question, how do I use this method in a return statement?
Comment: Mind explaining how `"I" + "use" + "Python"` is worse than `"I", "use", "Python"`? Seems about the same number of characters to me
Comment: What makes you think concatenating strings with `+` wastes time? And why do you think `,` doesn't waste time? (`,` doesn't concatenate strings at all, by the way.)
Comment: Note that `,` does not "concatenate" strings. `print` is a function, guess what `,` does in a function - that's right, it separates arguments. That's all it does there. It just so happens that the `print` function concatenates all its arguments with a space. Same way the answer in the linked question does.
Comment: @Chase In a print statement you need to add spaces manually if you use `+` signs.
Comment: As others already said string concatenation doesn't take any longer time in python. However in pypy3 it does take almost O(n) time, so better watch it there pypy users!
Comment: Did you mean: `print(*function())`?
Comment: Hi guys, what I meant was that it didn't work when I tried to do it in a return statement, as you can see in the last one. Also, in return statements, you need to add a space like every other word, which takes forever when you have a lot of words, and it seems like everyone is glossing over the "in a function part", which I will reword. Sorry if the question was poorly worded.
Comment: Also, i didn't mean how long it takes to run, I meant how long it takes to type.
Answer: You can use f-strings if you are on Python3.6+ or format your strings with .format.
def foo(name, age):
    return f'{name} is {age} years old.'

def bar(name, age):
    return '{} is {} years old'.format(name, age)

>>> foo('Ben', 25)
'Ben is 25 years old.'
>>> bar('Tom', 20)
'Tom is 20 years old'

If you have list of strings that you need to join with some character, use .join
>>> my_list = ['I', 'love', 'Python']
>>> ' '.join(my_list)
'I love Python'

Answer: s1 = 'I'
s2 = 'use'
s3 = 'python'

def function(*strings):
    x = ''
    for s in strings:
        x += s + ' '

    return x

print(function(s1,s2,s3))

Comment: This sticks an extra space on the end of the string, and aside from that bug, is a slow and unnecessary reimplementation of `''.join`.
Comment: While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code,
a reason for why this code works, and some references to documentation for further reading.
From [answer]: _"Brevity is acceptable, but fuller explanations are better."_


Convex set with empty interior is nowhere dense?

Question: Suppose $C\subseteq\mathbb R^n$ is a convex set and $C^o=\varnothing$. Is it necessarily true that $(\overline C)^o=\varnothing$? In general, is this true if $\mathbb R^n$ is replaced by a topological vector space $X$? Or can a counterexample be found?
I know that if $C^o\neq\varnothing$, then $C^o=(\overline C)^o$, so my question is whether this result can be generalized to the case when $C^o=\varnothing$.

Update: It's not true in general topological vector spaces. Indeed, if $X$ is a topological vector space and $Y$ is a proper dense subspace (such examples can be constructed), then $Y$ is convex and has empty interior, but $(\overline Y)^o=X^o=X$ is clearly not empty. Yet, I'm still not sure if the result holds for finite-dimensional vector spaces (in which every proper subspace is closed and thus no proper subspace is dense, so the preceding counterexample doesn't work).
Comment: Seems obvious that a convex subset of $\mathbb R^n$ with empty interior is contained in a hyperplane, which is a nowhere dense closed set. What am I missing?
Answer: This is true in $\mathbb{R}^n$. Say $n = 3$. If $\overline{C}$ has non empty interior that $C$ is dense in some ball hence it contains the vertices of a tetrahedron (just take a tetrahedron inside the ball and move its vertices slightly to land on a point in $C$). But now by convexity, $C$ must contain the whole solid tetrahedron which contradicts the fact that $C$ has empty interior. In higher dimensions, you can start with a generalized cube and move its vertices slightly to enter $C$.
Comment: I see that the intuitive argument works, but I still have trouble operationalizing it rigorously. I will keep trying. Thank you for the answer!
Comment: Maybe I'm missing something, but it seems to me that you don't need to resort to "move its vertices slightly". If $C$ is dense in some ball, then $C$ must contain $4$ non-coplanar points (because no subset of a plane can be dense in a ball). Use these points as the vertices of a tetrahedron.
Comment: That works too.
Answer: Here is a rigorous—and, accordingly, a bit lengthy—operationalization of the intuition offered by the answer by @OohAah.
$\textbf{Proposition}\phantom{---}$ Let $C\subseteq \mathbb R^n$ ($n\in\mathbb N$) be a convex set. If $C$ has no interior, then nor does $\overline C$.
$\textit{Proof}\phantom{---}$ Suppose that $(\overline C)^o\neq\varnothing$. I will show that $C^o$ is not empty, either. Let $\mathbf x_0\in (\overline C)^o$. Then, there exists some $\varepsilon>0$ such that $\mathbf x_0\in B(2\varepsilon,\mathbf x_0)\subseteq\overline C$, where $B(2\varepsilon,\mathbf x_0)$ denotes the open ball of radius $2\varepsilon$ around $\mathbf x_0$ with respect to the Euclidean norm. Let $\{\mathbf e_i\}_{i=1}^n$ denote the standard basis of $\mathbb R^n$ and define $\mathbf x_i\equiv \mathbf x_0+\varepsilon \mathbf e_i$ for each $i\in\{1,\ldots,n\}$. Clearly, $$\{\mathbf x_i\}_{i=0}^n\subseteq B(2\varepsilon,\mathbf x_0)\subseteq \overline C.$$
That is, $\{\mathbf x_i\}_{i=0}^n$ is included in the closure of $C$, so that, for each $i\in\{0,1,\ldots,n\}$, there exists some $\mathbf y_i$ such that

$\mathbf y_i\in C$; and
$\mathbf y_i\in B((2\sqrt n)^{-1}\varepsilon,\mathbf x_i)$.

For each $i\in\{1,\ldots,n\}$ define $\mathbf b_i\equiv \mathbf y_i-\mathbf y_0$. I claim that the vectors $\{\mathbf b_i\}_{i=1}^n$ are linearly independent. Indeed, suppose that $\lambda_1,\ldots,\lambda_n\in\mathbb R$ satisfy
$$\sum_{i=1}^n\lambda_i\mathbf b_i=0.$$
Suppose, for the sake of contradiction, that not all of $\{\lambda_i\}_{i=1}^n$ are zero. Then, $$\sum_{i=1}^n|\lambda_i|>0\tag{1}.$$
In addition,
\begin{align*}
0=&\,\sum_{i=1}^n\lambda_i\mathbf b_i=\sum_{i=1}^n\lambda_i(\mathbf y_i-\mathbf y_0)=\sum_{i=1}^n\lambda_i(\mathbf y_i-\mathbf x_i+\mathbf x_i-\mathbf x_0+\mathbf x_0-\mathbf y_0)\\=&\,\sum_{i=1}^n\lambda_i(\mathbf y_i-\mathbf x_i+\varepsilon\mathbf e_i+\mathbf x_0-\mathbf y_0),
\end{align*}
or
\begin{align*}
-\varepsilon\sum_{i=1}^n\lambda_i\mathbf e_i=\sum_{i=1}^n\lambda_i(\mathbf y_i-\mathbf x_i+\mathbf x_0-\mathbf y_0).
\end{align*}
Clearly, the Euclidean norm of the left-hand side is $\varepsilon\sqrt{\sum_{i=1}^n\lambda_i^2}$, so the following chain of inequalities holds true:
\begin{align*}
&\varepsilon\sqrt{\sum_{i=1}^n\lambda_i^2}=\left\|\sum_{i=1}^n\lambda_i(\mathbf y_i-\mathbf x_i+\mathbf x_0-\mathbf y_0)\right\|\leq\sum_{i=1}^n|\lambda_i|\left(\|\mathbf y_i-\mathbf x_i\|+\|\mathbf x_0-\mathbf y_0\|\right)\\
\underset{\text{see (1)}}{<}&\,\sum_{i=1}^n|\lambda_i|\left(\frac{\varepsilon}{2\sqrt{n}}+\frac{\varepsilon}{2\sqrt{n}}\right)=\sum_{i=1}^n|\lambda_i|\frac{\varepsilon}{\sqrt{n}}\leq\sqrt{\sum_{i=1}^n|\lambda_i|^2}\sqrt{\sum_{i=1}^n\frac{\varepsilon^2}{n}}=\varepsilon\sqrt{\sum_{i=1}^n\lambda_i^2},
\end{align*}
where I used the Cauchy–Schwarz inequality. This is a contradiction, which implies that $\lambda_1=\ldots=\lambda_n=0$. Hence, the vectors $\{\mathbf b_i\}_{i=1}^n$ are linearly independent, and since $\dim\mathbb R^n=n$, it follows also that they constitute a basis.

If $\mathbf z\in\mathbb R^n$, there exists a unique $(\mu_i)_{i=1}^n\in\mathbb R^n$ such that $\mathbf z=\sum_{i=1}^n\mu_i\mathbf b_i$. Define $\|\mathbf z\|_b\equiv\sum_{i=1}^n|\mu_i|$. Then, $\|\cdot\|_b$ is a norm and since $\mathbb R^n$ is finite-dimensional, it must be equivalent to the Euclidean norm. Therefore, there exists some $\xi_b>0$ such that $\|\cdot\|_b\leq \xi_b\|\cdot\|$.

Let $$D\equiv\left\{\sum_{i=0}^n\alpha_i\mathbf y_i\,\Bigg|\,\alpha_i\geq0\text{ for all $i\in\{0,1,\ldots,n\}$ and }\sum_{i=0}^n\alpha_i=1\right\}.$$
Since $\{\mathbf y_i\}_{i=0}^n\subseteq C$ and $C$ is convex, it follows that $D\subseteq C$. Define $$\mathbf w\equiv\sum_{i=0}^n\frac{1}{n+1}\mathbf y_i.$$ Clearly, $\mathbf w\in D$ and $$\mathbf w-\mathbf y_0=\sum_{i=1}^{n}\frac{1}{n+1}(\mathbf y_i-\mathbf y_0)=\sum_{i=1}^{n}\frac{1}{n+1}\mathbf b_i.$$

Let $$\delta\equiv\frac{1}{n(n+1)\xi_b}>0.$$
I will show that $B(\delta,\mathbf w)\subseteq D$. To this end, pick any $\mathbf z\in B(\delta,\mathbf w)$, so that $\|\mathbf z-\mathbf w\|<\delta.$ Since $\{\mathbf b_i\}_{i=1}^n$ is a basis, there exists a unique $(\mu_i)_{i=1}^n\in\mathbb R^n$ such that $\mathbf z-\mathbf y_0=\sum_{i=1}^n\mu_i\mathbf b_i$. Then, $$\mathbf z-\mathbf w=(\mathbf z-\mathbf y_0)-(\mathbf w-\mathbf y_0)=\sum_{i=1}^n\left(\mu_i-\frac{1}{n+1}\right)\mathbf b_i.$$ Consequently, for any $i\in\{1,\ldots,n\}$, it follows that
\begin{align*}
\left|\mu_i-\frac{1}{n+1}\right|\leq\sum_{j=1}^n\left|\mu_j-\frac{1}{n+1}\right|=\|\mathbf z-\mathbf w\|_b\leq \xi_b\|\mathbf z-\mathbf w\|<\xi_b\delta=\frac{1}{n(n+1)}.
\end{align*}
Hence,
$$0\leq\frac{(n-1)}{n(n+1)}=\frac{1}{n+1}-\frac{1}{n(n+1)}<\mu_i<\frac{1}{n+1}+\frac{1}{n(n+1)}=\frac{1}{n},$$
for each $i\in\{1,\ldots,n\}$ so that $\sum_{i=1}^n\mu_i<1$. It follows that
\begin{align*}
\mathbf z=\mathbf y_0+\sum_{i=1}^n\mu_i\mathbf b_i=\mathbf y_0+\sum_{i=1}^n\mu_i(\mathbf y_i-\mathbf y_0)=\left(1-\sum_{i=1}^n\mu_i\right)\mathbf y_0+\sum_{i=1}^n\mu_i\mathbf y_i,
\end{align*}
so $\mathbf z\in D$.

Conclusion:

$\mathbf w\in B(\delta,\mathbf w)\subseteq D\subseteq C$; and
$B(\delta,\mathbf w)$ is a non-empty open set; so that
$\mathbf w\in C^o$.

In particular, $C^o$ is not empty. $\blacksquare$

Intuitively, the points $\{\mathbf x_i\}_{i=0}^n$ in $\overline C$ span an $n$-dimensional simplex, whose vertices are perturbed slightly so that the new vertices do not lie in the same hyperplane and are all in $C$. The convex hull of these new vertices gives rise to a "distorted simplex" fully contained in $C$. Then, the centroid of this distorted simplex can be surrounded by a small ball still included in the distorted simplex, and hence in $C$.


Apache on Lion Server with two IP addresses

Question: I'm trying to run Apache and nginx on the same machine, on different IP addresses.
It's a Mac Mini with one ethernet card. I configured two eth network devices. I tried to change the apache configuration in /etc/apache2 to listen only on one IP, and most of it works. However, there is still an apache redirect from http:80 to https:443 on the second IP and I don't know where else to look. I changed all virtual hosts, virtual host global files and the httpd.conf including all default and __shadow files.
So I suppose it's not a problem of the SSL configuration, as I don't even want to get to the SSL part. It's the redirect from 80 to 443 which is not supposed to happen.
What else do I need to change to make apache listen on only one IP address and not change the protocol?
httpd.conf is too large. Important part:
#Listen 184.108.40.206:80
<IfDefine !MACOSXSERVER>
Listen 22.214.171.124:80
</IfDefine>

000_any_80__shadow.conf
<VirtualHost 126.96.36.199:80>
ServerName *
RewriteEngine On

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
CustomLog "/var/log/apache2/access_log" combinedvhost
SSLProxyEngine On
SSLCipherSuite "ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM"
SSLProxyProtocol -ALL +SSLv3 +TLSv1
DocumentRoot /var/empty

</VirtualHost>

0000_any_80_.conf.default
## Default Virtual Host Configuration

<VirtualHost 22.214.171.124:80 >
ServerAdmin email@example.com
DocumentRoot "/var/empty"
DirectoryIndex index.html index.php /wiki/ default.html
CustomLog "/var/log/apache2/access_log" combinedvhost
ErrorLog "/var/log/apache2/error_log"

<IfModule mod_ssl.c>
    SSLEngine Off
    SSLCipherSuite "ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM"
    SSLProtocol -ALL +SSLv3 +TLSv1
    SSLProxyEngine On
    SSLProxyProtocol -ALL +SSLv3 +TLSv1
</IfModule>

<Directory "/var/empty">
    Options All +MultiViews -ExecCGI -Indexes
    AllowOverride None
    <IfModule mod_dav.c>
        DAV Off
    </IfModule>
</Directory>

</VirtualHost>

sites/virtual_host_global.conf
Listen  126.96.36.199:443
NameVirtualHost 184.108.40.206:443
Listen  188.8.131.52:80
NameVirtualHost 22.214.171.124:80

apachectl -S
VirtualHost configuration:
Syntax OK

Thanks!
Comment: Patrick, I think your going to need to post/link to all your configuration files for us to help you. Have you checked the ssl.conf file? All your vhosts?
Comment: The output of `apache2ctl -S` or `apachectl -S` will help.
Comment: Added the config files and output. Don't know if it helps though :(
Answer: To make it stop listening on 443 comment out the "Listen 188.8.131.52:443" and the associated NameVirtualHost line. You should probably comment out the rewrite rule in 000_any_80__shadow.conf or just get rid or just exclude that file completely if you're not going to use it.
Odd thing, though, is that your apachectl -S command had no output. That should have shown those Virtual hosts. If you check the bottom of your main httpd.conf file, it should have a bunch of Include lines. Can you verify that it's even using all of those extra .conf files that you've posted?
Comment: Yes, all files are included properly. I don't want it to stop listening, I need the service on this IP. Just not on the second IP. Thanks!
Comment: Sorry, misunderstood the question


Sets of morphisms that behave "like" epimorphisms/monomorphisms in a balanced category.

Question:
Question. Let $\mathbf{C}$ denote a category, and suppose $E$ and $M$ are wide subcategories such that:

$g \circ f \in E \rightarrow g \in E$
$g \circ f \in M \rightarrow f \in M$
$g \in E \cap M \leftrightarrow g \mbox{ is an isomorphism}$

Does it follow that every $e \in E$ is epic and every $m \in M$ is monic?

Motivation. These conditions ensure that if we're given a factorization into an $E$-morphism followed by an $M$-morphism, then the $E$-morphism is the coimage and $M$-morphism is the image.
Answer: Let $\mathcal{C}$ be the category generated by the diagram

(source: presheaf.com)
and the relation $pe=qe$. Let $M$ be the subcategory with morphisms $\{p,q,\mathrm{id}_A,\mathrm{id}_B,\mathrm{id}_C\}$ and let $E$ be the subcategory with morphisms $\{e,\mathrm{id}_A,\mathrm{id}_B,\mathrm{id}_C\}$. $E$ and $M$ satisfy the above conditions, yet $e$ is not epic. You  need to impose some saturation conditions to guarantee that morphisms in $E$ are epimorphisms.
On the other hand, as you may already know, all split epimorphisms (resp. split monomorphisms) belong to $E$ (resp. $M$).
Comment: Any idea about what those saturation conditions ought to be? Nice observation regarding sections and retractions. (I didn't know it.)


Unable to edit comments in Tridion UGC

Question: I have a problem with a recent install of UGC on a development Tridion environment.  I'm unable to edit comments from the CMS.  I can add comments fine but editing a comment in the GUI results in an error message appearing in the GUI - "Saving comment failed".  No errors are generated in the logs - or at least the logs that I think it should be logging to.  Can anyone give me any pointers?  Does the editing use a different configuration?  My datasource in the webui configuration is below if this is useful:-
<code><DataSource>
<Key>1</Key>
<Match>^(ugc:|oe:|tcm:)+</Match>
<Url>http://new.ugc.service/odata.svc</Url>
<TimeOut>100000</TimeOut>
<Threshold>0</Threshold>
<RatingMinimum>-1</RatingMinimum>
<RatingMaximum>5</RatingMaximum>
<OAuthEnabled>false</OAuthEnabled>
<Locale>en-us</Locale>
<ClientId></ClientId>
<ClientSecret></ClientSecret>
<EventSystemClientId></EventSystemClientId>
<EventSystemClientSecret></EventSystemClientSecret>
<AccessTokenUrl></AccessTokenUrl>
</DataSource>
</code>
MTIA
John
Comment: Guess I would expect to see an error on the cd_core log for the odata endpoint. Anything there?
Comment: Thanks Nuno.  There are no errors in the cd_core log although I have just noticed that when the UGC web service is restarted then the first time the comments section is opened in the CMS then I get a warning in the log - AmbientDataContext - There is no current ambient data context - the ambient data framework is not properly initialised.  No subsequent errors are reported when attempting to edit comments but I'm assuming the ambient framework will be the issue?  Is the AmbientDataContext not needed for posting comments but it is for editing?
Comment: This AmbientDataContext error is very common, that's probably not it. You say that you are able to add comments. Can you confirm that they are really saved to the UGC database? E.g. by closing the component edit window and opening it again?
Comment: Hi Quirijn, thanks for the reply.  I can confirm that the comments and ratings are saved to the database.  We have this working from both the CMS and front end web site.  All comments and ratings are being stored in the database and we have the UGC web service set up to pull UGC items and display them.  The only thing that we don't have working is the editing of comments.
Comment: Just for further information I've identified that the error I'm getting is - The remote server returned an error: (405) Method Not Allowed.","StackTrace":"   at Tridion.UGC.Model.Services.UGC.PutData.  The json it's trying to send through is data={"d":{"Content":"TEST 1","Status":1,"ItemPublicationId":"68","ItemId":"17793","ItemType":"16","Id":67,"LastModifiedDate":"","CreationDate":"","Score":0,"ModeratedDate":"\/Date(1359645973916)\/","Moderator":"CMSTRIDION%5Cipadmin","User":{"Id":"CMSTRIDIO%5Cipadmin"}}}  I'm thinking it's something to do with security and the Moderator value?
Answer: Ok.  This is now resolved.  The WebDAVModule needed removing from the UGC web service in IIS!  Ok, ok...it's in the docs, but still! ;)  If anybody knows why this would only prevent editing of comments I'd be interested in the answer.  Thanks, John.

Unable to edit comments in Tridion UGC


Why is this normal probability plot graph skewed right?

Question: First, I apologize for the bad image, but it's the best I can do with a mouse. Anyways, here it is:

So the data is skewed right, but the normal probability plot bends up and over what would be the approximate linear equation. According to different websites1, 2, a normal probability plot with data skewed right goes under the approximate line of best fit, and my graph looks more like it's skewed left. What am I misunderstanding?
1: itl.nist.gov/div898/handbook/eda/section3/normprp4.htm
2: www.basic.northwestern.edu/statguidefiles/probplots.html#Data%20Skewed%20to%20Right
Comment: Is that a frequency histogram at the top? If you best want to understand your question, try making the normal probability plot yourself, without a computer.
Comment: The graph is impossible to understand without labels and scales for the axes.
Comment: It's a normal probability plot from -3 to 3 on the y-axis and time on the x axis.
Comment: Assuming time increases left to right and y increases bottom to top and that the normal plotting positions have been correctly computed, this is a plot of right-skewed times.  Why does it look skewed left to you?
Comment: The websites show that right skewed graphs don't look like that, while it looks like the examples for left skewed graphs.
Answer: This graph interchanges the axes compared to the cited websites, that's all.
In general, to read a probability plot, ask yourself "what changes in the data would be required to line the points up diagonally?"  In this case, the data are shown on the x-axis, so changing the data would slide points horizontally along the x-axis while retaining their vertical positions.  To get the points into a diagonal line we would have to slide the largest (rightmost) times to the left (that is, pull them in towards their middle) and we would have to slide the smallest (leftmost) times a little to the left as well (that is, push them away from the middle time value).  That tells us the large times are too big compared to a normal distribution: they are skewed towards large values (considered the "right," no matter how the plot is drawn; better terminology is "positively skewed").  (For reading q-q plots in general, I have posted a more elaborate explanation with illustrations.)
When the axes are reversed, the times (or, generally, the data) are plotted vertically and the sliding has to happen in the vertical direction.  There's no chance of confusion, though--provided the axes are clearly labeled!
Answer: That looks a lot like the efficient frontier from modern portfolio theory.  The efficient frontier is a set of attainable portfolios, the x-axis being the scale of risk with higher risk to the right, and y-axis being the scale of return with higher return being higher.  The frontier line is  made up of theoretical portfolios of all risky assets.


How to achieve this kind of Operation in Vue JS?

Question: I'm  Building a tree-like structure in vue. I tried to do this with the data function but in that case, all the elements in the same level of the tree getting these classes although I just want clicked element to achieve this I tried this with the ref but don't know how to achieve that parent element selector part with it as I'm new to Vue till now i don't know how to tackle this .
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");

Answer: Please take a look at one of solutions (if I understood you correctly) in following snippet

new Vue({
  el: '#demo',
  data() {
    return {
      tree: [
        {parent: 'AAA', childs: []},
        {parent: 'BBB', childs: [{child: 'bbb'}, {child: 'ccc'}]},
        {parent: 'CCC', childs: [{child: 'ddd'}, {child: 'eee'}, {child: 'fff'}]},
        {parent: 'DDD', childs: []}
      ],
      selected: null,
      active: null
    }
  },
  methods: {
    select(item, idx) {
      if (this.tree[idx].childs.length) {
        this.selected = idx
        this.active = null
      } else {
        this.active = item.parent + idx
        this.selected = null
      }
    },
    activate(itm, i) {
      this.active = itm.child + i
    }
  }
})
li {
 cursor: pointer;
}
.active {
  color: red;
}

{{ item.parent }}

{{ itm.child }}


Can I post a job from freelance website into issue queue at drupal.org issue queue list?

Question: I heard it's kind of illegal to post a paid job request in Drupal.org issue queue. Is it true?
I've emailed the maintainer, but they are busy to do a paid job.
Answer: I assume that, since you are asking about posting a request for a paid job in a project issue queue, the paid job is relative to the project. For example, you are willing to pay for adding a feature to the project.
In that case, if the maintainer doesn't have the contact tab accessible to every user, or you don't have any other way to contact him privately, you could open a support request in the project issue queue asking for the availability to do paid jobs, without adding too much details. If the maintainer is available for a paid job, you will get a way to contact the maintainer and provide more details about the paid job you are asking for.
If the request for the paid job is not relative to a project, or the maintainer of the project already answered not to be available for any paid job, you can post on the Paid Drupal services forum. Before posting, please see READ THIS FIRST: Recommendations for hiring a Drupal site developer and *** RULES FOR THIS FORUM *** read this so your posts don't get deleted, which contain useful information on how to post a request for paid work.


How to configure BPMN Activity job/task priority

Question: We are using the activity BPMN engine (version 5.20.0) to model workflow. Is any way to force/configure the framework to start some serviceTasks (jobs?) before others? The expected result is when many jobs are waiting to run activity executes first those with the highest priority.
Answer: The BPMN model should define the order of processing, if you are talking about parallel flow paths, you could use events to effectively release tasks to control order of processing. However, if you need to go to this level of effort, then why are the services modeled in parallel?


Check a number of form $a^b$.

Question: Given a number $n$, what is best efficient way to check if it is of $a^b$ form for some $a,b\geqslant2$.
Provided $n$ can be as large as $10^{16}$.
Comment: Note that more efficient algorithms exist, but they are more complicated. For example http://cr.yp.to/papers/powers-ams.pdf
Comment: @fkraiem i cant download the paper right now because of internet problem.Could you provide me algorithm here?
Answer: The idea is that there are very few possible values for $b$ (only about $\log n$), so it is okay to just brute force through them. And then for each $b$ the array $[1^b, 2^b, 3^b, \dots, n^b]$ is sorted in ascending order, so we can do a binary search for a value in it which is equal to $n$. Using fast exponentiation, this gives an algorithm which runs in $O(\log^2n\log\log n)$ multiplications mod $n$.
I'll leave the actual (pseudo)code as an exercise, and it can also be found (along with a complexity analysis) in Dietzfelbinger, Primality Testing in Polynomial Time (LNCS 3000), as Algorithm 2.3.5.

Check a number of form $a^b$.


Triple of primes satisfying 3 equations

Question: Let $P_1$, $P_2$, $P_3$ be $3$ distinct odd primes, and $n>1$, such that:
$$nP_1 \equiv P3 \pmod{P_2},\ nP_2 \equiv P_1 \pmod{P_3},\  nP_3 \equiv P_2 \pmod {P_1},$$
Take $n = 2$.
Question: Is there a triple $(P_1,P_2,P_3)$ satisfying the above $3$ equations?
Comment : I noticed that there are solutions $(P_1,P_2,P_3)$ if $n>2$ in general. But I could not find one triple with $n = 2$. Any comment will be helpful. Thank you.
Answer: There are no triples with $n = 2$. First, consider if $P_2$ is the largest prime. Your first congruence relation gives that, for some $k \in \mathbb{Z}$,
$$2P_1 \equiv P_3 \pmod{P_2} \implies 2P_1 - P_3 = kP_2 \tag{1}\label{eq1A}$$
Since $P_1 \lt P_2 \implies 2P_1 \lt 2P_2$, then $k \lt 2$. Also, $P_3 \lt P_2 \implies -P_3 \gt -P_2$, so $k \gt -1$. Thus, $k \in \{0, 1\}$. With $k = 0$, this gives $2P_1 = P_3$, which is not allowed. Thus, we must have $k = 1$ which gives
$$2P_1 - P_3 = P_2 \implies 4P_1 - 2P_2 = 2P_3 \implies -2P_2 \equiv 2P_3 \pmod{P_1} \tag{2}\label{eq2A}$$
Your third congruence equation then gives
$$2P_3 \equiv P_2 \pmod{P_1} \implies -2P_2 \equiv P_2 \pmod{P_1} \implies 3P_2 \equiv 0 \pmod{P_1} \tag{3}\label{eq3A}$$
Since the primes are distinct, this means $P_1 = 3$. The left side of \eqref{eq2A} gives
$$2P_1 = 6 = P_3 + P_2 \tag{4}\label{eq4A}$$
However, since $3$ is the smallest odd prime and the primes are distinct, then $P_2 \gt 3$ and $P_3 \gt 3$, so \eqref{eq4A} is not possible.
With $P_3$ being the largest prime instead, using similar arguments as before, your second congruence equation gives
$$2P_2 - P_1 = P_3 \implies 4P_2 - 2P_1 = 2P_3 \implies -2P_1 \equiv 2P_3 \pmod{P_2} \tag{5}\label{eq5A}$$
Thus, your first congruence equation gives
$$2P_1 \equiv P_3 \pmod{P_2} \implies -2P_3 \equiv P_3 \pmod{P_2} \implies 3P_3 \equiv 0 \pmod{P_2} \tag{6}\label{eq6A}$$
Thus, as done before, this means $P_2 = 3$, with the first part of \eqref{eq5A} giving a contradiction.
Finally, consider the case where $P_1$ is your largest prime. As done before, your third congruence equation results in
$$2P_3 - P_2 = P_1 \implies 4P_3 - 2P_2 = 2P_1 \implies -2P_2 \equiv 2P_1 \pmod{P_3} \tag{7}\label{eq7A}$$
Your second congruence equation now becomes
$$2P_2 \equiv P_1 \pmod{P_3} \implies -2P_1 \equiv P_1 \pmod{P_3} \implies 3P_1 \equiv 0 \pmod{P_3} \tag{8}\label{eq8A}$$
As was done earlier, this results in $P_3 = 3$, so the first part of \eqref{eq7A} gives a contradiction.
This covers all possibilities, showing there are no solutions for $n = 2$.

Triple of primes satisfying 3 equations


How to limit a user to specific OG groups based on user role?

Question: In a quite complex project page, I have several user roles (from Drupal core). Further, the page has an internal area which is built upon Organic Groups (OG). There are a lot of groups available, each group is part of a so-called "area". These areas correspond to user roles and what I want to achieve is that users of a role may only subscribe to groups of the area with the same name.
To visualize the concept, let's say I have three user roles (besides anonymous, authenticated and administrator): A, B and C.
There is a node type called "Group" which has a select field for area, the available options are A, B and C.
There are nine groups, called A1, A2, A3, B1, B2, B3, C1, C2 and C3. I don't want users to apply for a group but immediately join (subscribe) to it, but only if the group's area matches the user's role. So user Alex of role A may only see and join A1 through A3 but not any other group.
The OG group permissions only distinguishes between non-member, member and manager. There's the option to subscribe to a group without approval, which I want. But how to combine that with the Drupal user role?
Answer: Due to other restrictions in OG I couldn't overcome, I ended up using the Group module instead. In addition to other advantages for my use case, it offers some functions to easily add group memberships (these are entities) by using something like
$entity_type = 'group_membership';
$entity = entity_create($entity_type, array('gid' => $gid, 'uid' => $uid));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->status = 'active';
$wrapper->added_on = time();
$wrapper->added_by = 1;
$wrapper->save();

Adding that into a hook_user_update(&$edit, $account, $category) function, I am able to add and revoke memberships based on the updated account's roles.


Passing information from a collection view to a tableview

Question: Right now I have a table view that is an extension of a collection view.
Here is a picture of the storyboard.

The main premise of the app is similar to Apple Maps. I would like for a collectionView cell to be selected and then for the viewController to display a tableView that has all of the respected items from that category.
Here is my code for the collectionView.
 class ContentViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

let imageArray = [UIImage(named: "image 1"), UIImage(named: "image 2"), UIImage(named: "image 3")]

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
    cell.mapIconImage.image = imageArray[indexPath.row]
    cell.mapIconLabel.text! = imageNameArray[indexPath.row]
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: "ShowTableViewPlaces", sender: self)
}

class CustomCell: UICollectionViewCell {

@IBOutlet weak var mapIconImage: UIImageView!
@IBOutlet weak var mapIconLabel: UILabel!

}

Here is the code so far for the tableView.
import UIKit

struct PlacesInTableView {
var name: String

init(name: String) {
    self.name = name
}
}

class MapItemsTableViewController: UITableViewController {

var image1InTableView = [PlacesInTableView(name: "place 1"),
    PlacesInTableView(name: "place 2"),
    PlacesInTableView(name: "place 3")
]

var image2InTableView = [PlacesInTableView(name: "place 1")
]

var image3InTableView = [PlacesInTableView(name: "place 1"),
    PlacesInTableView(name: "place 2")
]

When a collection view is selected, I would like all of the locations in that respected category to occupy the contents of the tableview. How would I go about passing data from the collection view cell to a new tableView?
Comment: It's unclear how the *respected items from that category* are related to the data source array of the collection view. The code contains an array of images and an unknown `imageNameArray`. By the way using multiple arrays as data source is very bad practice and strongly discouraged.
Comment: Your explanation of the problem is not clear. For example, " display a tableView that has all of the respected items from that category". What do you mean "category"? You only mentioned collection view. How is that related to category? What do you mean "respected items" (from the category)? Can you give an example of a category and "respected items"?
Answer: As I understand, you wanna pass the name value to the MapItemsTableViewController ?
You can override prepare function :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let viewController = segue.destination as! MapItemsTableViewController

    viewController.name = // Data can input here

}

Answer: add storyboard id for table vc "MapItemsTableViewController" and add below code in ContentViewController
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let vc = self.storyboard?.instantiateViewController(withIdentifier: "MapItemsTableViewController") as? MapItemsTableViewController {
            vc.imageCate = indexPath.row
            self.present(vc, animated: true, completion: nil)
        }
}

and then you can implement as below for MapItemsTableViewController
class MapItemsTableViewController: UITableViewController {
    var imageCate:Int?
    var image1InTableView = [PlacesInTableView(name: "place 1"),
                             PlacesInTableView(name: "place 2"),
                             PlacesInTableView(name: "place 3")
    ]

    var image2InTableView = [PlacesInTableView(name: "place 1")
    ]

    var image3InTableView = [PlacesInTableView(name: "place 1"),
                             PlacesInTableView(name: "place 2")
    ]

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if imageCate == 0 {
           return image1InTableView.count
        }
        else if imageCate == 1{
            return image2InTableView.count
        }else if imageCate == 2{
            return image3InTableView.count
        }else{
            return 0
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()

        if imageCate == 0 {
            cell.textLabel?.text = image1InTableView[indexPath.row].name
        }
        else if imageCate == 1{
            cell.textLabel?.text = image2InTableView[indexPath.row].name
        }else if imageCate == 2{
            cell.textLabel?.text = image3InTableView[indexPath.row].name
        }else{

        }
        return cell
    }

}


Why final Chi Square value is too large while fitting goodness of fit for Poisson distribution?

Question: I have mean level spacing as input data. With this data I plot histogram using 10 bins. x ranges from 0 to 9 because bins are 10, f is the bin counts(means how many values in each bin). Then I calculate mean of the distribution using formula
$\mu = \frac{\sum_{i}^{10}(f\times x)}{\sum_{i=1}^{10}{f}}$ . After this I used formula of Poisson distribution $P=\frac{\mu^{x}\exp(-\mu)}{x!}$ and then calculated the expected frequency as $E=x \times \sum_{i=1}^{10}{f}$. After measuring expected frequency of Poisson distribution I used formula $\chi^2 = \sum_{1}^{10}\frac{(O -E)^2}{E}$. But my answer is 3000 that is extremely large as compared to the values given in Chisquare distribution table. Its hard for me to figure out that why it is too large. Where I'm wrong? I also want to menton that I'm working on machine learning project. Here is the histogram of my input data. For plotting this histogram I choosed 4000 samples and each single sample has 256 features so total values use to plot histogram are $4000 \times 256$. If I increase number of bins say 30,50 then the values in the last bins are too small approximately zero. So I preferred to choose only 10 bins to get meaningful result. There is one more thing that I want to mention that in each sample I measure measure nearest neighbor spacing $E_{N}-E_{N-1}$. After measuring nearest neighbout spacing in each sample 255 features will be left. After collecting 255 features of all the 4000 samples in a single list I divide it y mean value. What I want to say is that I used normalized level spacing to plot this histogram. My input data has both positive and negative values and the level spacing is also too small. My final $X^2 = 6.445144657597967\exp^{28}$ and
p_value= 0.0

Here is the plot for more bins. But here I plotted probability. The pupose of this graph is to show that if I increase number of bins values become zero and I read that chisquare test is not suitable for small values.
Comment: When it's so large, the null hypothesis is blatantly bad: you don't need the table to tell you that.  Another possibility is your calculation is incorrect.  You would need to supply more information to determine what's going on.
Comment: Can you edit your post to include your data and/or your histogram? Why do you believe a Poisson distribution would be appropriate for your binned data?
Comment: Sure i edit this
Comment: What else should I need to provide?
Answer: How do you condense $4,000\times 256$ two-dimensional data points into ten bins? And why do you believe the result should be Poisson distributed?
It seems like the answer simply is that it isn't, and that with your huge sample size, even small deviations from a posited distribution yield a very large test statistic (and correspondingly, a tiny p value).
Comment: Data is not 2 dimensional. I collected the $4000 \times 256$ values in a single list to plot histogram.  When I plot the histogram with normalized values it seems similar to Poisson. In my model I'm sure that at high temperature data it follows Poisson distribution.  Above 4000 samples are from high temperature . But there is also a probability of following semi-poisson distribution. Two distributions are quite similar. I want to proof with chisquare test that there is more evidence that it follows Poisson distribution.
Comment: Yes 10 bins are too small. But in higher bins data points are close to zero. I can show that figure.


Is it true that the image of a perfect set is perfect under a continuous map?

Question: It is well-known that the image of a compact set is compact and the image of a connected set is connected under a continuous map. Here $A$ is perfect if $A$ it is equal to the derived set of itself.
I would like to ask if this property holds for perfect set. i.e

The image of a perfect set is perfect under a continuous map.

Thank you so much!
Comment: And your definition of a set $A$ to be perfect is that $A'=A$ holds?
Comment: Hi @HennoBrandsma, Yeap  "$A$ is perfect if $A$ it is equal to the derived set of itself"
Comment: Or equivalently that $A$ is closed ($A'\subseteq A$) without isolated points ($A \subseteq A'$).
Answer: No, any compact metric space $X$ is the continuous image of $\{0,1\}^\mathbb{N}$, the Cantor cube, which is perfect. So also for the non-perfect $X=\{0,1\}$ (projection ) or the non-perfect $X=[0,1] \cup \{2\}$ etc.
This gives perfect maps from a perfect space with non-perfect image.
Answer: No, it is not true. Consider the image of $\Bbb R$ under $\arctan$ (as a subset of $\Bbb R$).
For compact sets, the boundedness property lets closed sets remain closed, so compactness is preserved. However, the property of no isolated points is not enough to preserve closedness, and thus perfect-ness (perfection? perfectity?) is not preserved in general.
Comment: The image of $\Bbb R$ is not closed in $\Bbb R$ (when I consider that to be the codomain of $\arctan$) so closedness is not preserved for unbounded sets.
Comment: @HennoBrandsma Preservation of closedness is like surjectivity, in that basically the same function can either have the property or not depending on exactly what you specify as the codomain.


From how deep in the corner can a free kick be spotted?

Question: Watching a match now, the forward was running toward the goal line, halfway toward the corner, protecting the ball, looking for a corner kick.
He was obviously fouled by the defender, pushed into the ball and it resulted in a goal kick.
I am wondering, if a foul was called (it was outside of the box), where would the free kick be placed?
What further muddies the water on this for me, I watched an old women's International match recently where a foul was called in the 6m box.  Instead of a penalty kick, a free kick was placed on the 18m line.  This is why I'm wondering if referees would have discretion to place a free kick elsewhere in the first example.
Here is the video queued up to that women's match.
Answer: The free kick awarded for a offence anywhere on the field is taken from the place where the foul occurred. It doesn't matter how close to the corner that is.
There are some exceptions,

a direct free kick to the attack inside the penalty area is a penalty kick

an indirect free kick to the attack inside the goal area is taken on the long edge of the goal area closest to where the offence occurred

a free kick to the defence inside the goal area may be taken anywhere inside the goal area

free kicks for offences off the field or involving non-players may have other placements according to Laws 3 or 12

Your confusion regarding USA-BRA (W) is easily resolved. The free kick is awarded for playing in a dangerous manner (PIADM). This is an offence which does not involve physical contact, and which is sanctioned with an indirect free kick.
It does not become a penalty kick (see first bullet point) but because it occurred inside the goal area, it is moved back to the line (see second bullet point).


Structured programming and Python generators?

Question: Update: What I really wanted all along were greenlets.

Note: This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather than continue to mutate it here, I will repose the question when I have it clearer in my head, as per Alex's suggestion.

Python generators are a thing of beauty, but how can I easily break one down into modules (structured programming)? I effectively want PEP 380, or at least something comparable in syntax burden, but in existing Python (e.g. 2.6)
As an (admittedly stupid) example, take the following:
def sillyGenerator():
  for i in xrange(10):
    yield i*i
  for i in xrange(12):
    yield i*i
  for i in xrange(8):
    yield i*i

Being an ardent believer in DRY, I spot the repeated pattern here and factor it out into a method:
def quadraticRange(n):
  for i in xrange(n)
    yield i*i

def sillyGenerator():
  quadraticRange(10)
  quadraticRange(12)
  quadraticRange(8)

...which of course doesn't work. The parent must call the new function in a loop, yielding the results:
def sillyGenerator():
  for i in quadraticRange(10):
    yield i
  for i in quadraticRange(12):
    yield i
  for i in quadraticRange(8):
    yield i

...which is even longer than before!
If I want to push part of a generator into a function, I always need this rather verbose, two-line wrapper to call it. It gets worse if I want to support send():
def sillyGeneratorRevisited():
  g = subgenerator()
  v = None
  try:
    while True:
      v = yield g.send(v)
  catch StopIteration:
    pass
  if v < 4:
    # ...
  else:
    # ...

And that's not taking into account passing in exceptions. The same boilerplate every time! Yet one cannot apply DRY and factor this identical code into a function, because...you'd need the boilerplate to call it! What I want is something like:
def sillyGenerator():
  yield from quadraticRange(10)
  yield from quadraticRange(12)
  yield from quadraticRange(8)

def sillyGeneratorRevisited():
  v = yield from subgenerator()
  if v < 4:
    # ...
  else:
    # ...

Does anyone have a solution to this problem? I have a first-pass attempt, but I'd like to know what others have come up with. Ultimately, any solution will have to tackle examples where the main generator performs complex logic based on the result of data sent into the generator, and potentially makes a very large number of calls to sub-generators: my use-case is generators used to implement long-running, complex state machines.
Comment: Could you simplify your real problem (not too much, just enough!) instead of making up one that doesn't seem to match it very well?
Comment: Example: not really. I just want an answer to how I can decompose a complex generator without a realm of boilerplate -- akin to the "yield from" statement described below, but in existing Python. Tricks that satisfy simple cases are not enough :(
Answer:
However, I'd like to make my
  reusability criteria one notch harder:
  what if I need a control structure
  around my repeated generation?

itertools often helps even there - you need to provide concrete examples where you think it doesn't.

For
  instance, I might want to call a
  subgenerator forever with different
  parameters.

itertools.chain.from_iterable.

Or my subgenerators might
  be very costly, and I only want to
  start them up as and when they are
  reached.

Both chain and chain_from_iterable do that -- no sub-iterator is "started up" until the very instant the first item from it is needed.

Or (and this is a real
  desire) I might want to vary what I do
  next based on what my controller
  passes me using send().

A specific example would be greatly appreciated. Anyway, worst case, you'll be coding for x in blargh: yield x where the suspended Pep3080 would let you code yield from blargh -- about 4 extra characters (not a tragedy;-).
And if some sophisticated coroutine-version of some itertools functionality (itertools mostly supports iterators - there's no equivalent coroutools module yet) becomes warranted, because a certain pattern of coroutine composition is often repeated in your code, then it's not too hard to code it yourself.
For example, suppose we often find ourselves doing something like: first yield a certain value; then, repeatedly, if we're sent 'foo', yield the next item from fooiter, if 'bla', from blaiter, if 'zop', from zopiter, anything else, from defiter.  As soon as we spot the second occurrence of this compositional pattern, we can code:
def corou_chaiters(initsend, defiter, val2itermap):
  currentiter = iter([initsend])
  while True:
    val = yield next(currentiter)
    currentiter = val2itermap(val, defiter)

and call this simple compositional function as and when needed.  If we need to compose other coroutines, rather than general iterators, we'll have a slightly different composer using the send method instead of the next built-in function; and so forth.
If you can offer an example that's not easily tamed by such techniques, I suggest you do so in a separate question (specifically targeted to coroutine-like generators), as there's already a lot of material on this one that will have little to do with your other, much more complex/sophisticated, example.
Answer: You want to chain several iterators together:
from itertools import chain

def sillyGenerator(a,b,c):
    return chain(quadraticRange(a),quadraticRange(b),quadraticRange(c))

Comment: `def sillyGenerator(*args): return chain(*map(quadraticRange, args))` to avoid repetition :)
Comment: Nice. Certainly solves the problem for simpler examples like the ones I initially proposed. This has forced me to extend my question, however, as the problems I'm really looking at have control logic around starting up generators :(
Answer: Impractical (unfortunately) answer:
from __future__ import PEP0380

def sillyGenerator():
    yield from quadraticRange(10)
    yield from quadraticRange(12)
    yield from quadraticRange(8)

Potentially practical reference: Syntax for delegating to a subgenerator
Unfortunately making this impractical: Python language moratorium
UPDATE Feb 2011:
The moratorium has been lifted, and PEP 380 is on the TODO list for Python 3.3. Hopefully this answer will be practical soon.
Read Guido's remarks on comp.python.devel
Comment: +1 for interesting and good link. Holding out for something of more immediate import though :)
Comment: Note that I am NOT advocating its use, but for the curious pep380 can be implemented in Pure Python with just a few modifications to make it syntactically valid: yield _from(quadraticRange(10)). http://code.activestate.com/recipes/577153-yet-another-python-implementation-of-pep-380-yield/
Answer: import itertools

def quadraticRange(n):
  for i in xrange(n)
    yield i*i

def sillyGenerator():
  return itertools.chain(
    quadraticRange(10),
    quadraticRange(12),
    quadraticRange(8),
  )

def sillyGenerator2():
  return itertools.chain.from_iterable(
    quadraticRange(n) for n in [10, 12, 8])

The last is useful if you want to make sure one iterator is exhausted before another starts (including its initialization code).
Comment: +1 Nice. I like the way this solves 99% of the use cases (infinite set of generators, costly generator construction.) However, I'm really thinking of use cases like coroutines, where the logic in the top-level function is complex and varies depending on what is sent in by the caller. My examples have turned out to be too trivial :(
Answer: There is a Python Enhancement Proposal for providing a yield from statement for "delegating generation".  Your example would be written as:
def sillyGenerator():
  sq = lambda i: i * i
  yield from map(sq, xrange(10))
  yield from map(sq, xrange(12))
  yield from map(sq, xrange(8))

Or better, in the spirit of DRY:
def sillyGenerator():
  for i in [10, 12, 8]:
    yield from quadraticRange(i)

The proposal is in draft status and its eventual inclusion is not certain, but it shows that other developers share your thoughts about generators.
Comment: You just beat me to it, while I was looking up reference syntax :)
Answer: For an arbitrary number of calls to quadraticRange:
from itertools import chain

def sillyGenerator(*args):
    return chain(*map(quadraticRange, args))

This code uses map and itertools.chain. It takes an arbitrary number of arguments and passes them in order to quadraticRange. The resulting iterators are then chained.
Answer: There is a pattern which I call "generator kernel" where generators don't yield directly to the user but to some "kernel" loop that treats (some of) their yields as "system calls" with special meaning.
You can apply it here by an intermediate function that accepts yielded generators and unrolls them automatically.  To make it easy to use, we'll create that intermediate function in a decorator:
import functools, types

def flatten(values_or_generators):
    for x in values_or_generators:
        if isinstance(x, GeneratorType):
            for y in x:
                yield y
        else:
            yield x

# Better name anyone?
def subgenerator(g):
    """Decorator making ``yield <gen>`` mean ``yield from <gen>``."""

    @functools.wraps(g)
    def flat_g(*args, **kw):
        return flatten(g(*args, **kw))
    return flat_g

and then you can just write:
def quadraticRange(n):
    for i in xrange(n)
        yield i*i

@subgenerator
def sillyGenerator():
    yield quadraticRange(10)
    yield quadraticRange(12)
    yield quadraticRange(8)

Note that subgenerator() is unrolling exactly one level of the hierarchy.  You could easily make it multi-level (by managing a manual stack, or just replacing the inner loop with for y in flatten(x): - but I think it's better as it is, so that every generator that wants to use this non-standard syntax has to be explicitly wrapped with @subgenerator.
Note also that detection of generators is imperfect!  It will detect things written as generators, but that's an implementation detail.  As a caller of a generator, all you care about is that it returns an iterator.  It could be a function returning some itertools object, and then this decorator would fail.
Checking whether the object has a .next() method is too broad - you won't be able to yield strings without them being taken apart.  So the most reliable way would be to check for some explicit marker, so you'd write e.g.:
@subgenerator
def sillyGenerator():
    yield 'from', quadraticRange(10)
    yield 'from', quadraticRange(12)
    yield 'from', quadraticRange(8)

Hey, that's almost like the PEP!
[credits: this answer gives a similar function - but it's deep (which I consider wrong) and is not a framed as a decorator]
Answer: class Communicator:
    def __init__(self, inflow):
        self.outflow = None
        self.inflow = inflow

Then you do:
c = Communicator(something)
yield c
response = c.outflow

And instead of the boilerplate code you can simply do:
 for i in run():
     something = i.inflow
     # ...
     i.outflow = value_to_return_back

It's simple enough code that works without much brain.


Kernel on two functions?

Question: I am curious whether there are any literatures considering kernel functions whose inputs are two functions. For example I would like consider two 1-Liptchiz mappings $\pi, \sigma:\mathbb{R}^M\rightarrow\mathbb{R}$, and maybe on possible kernel function on this space is $k(\pi, \sigma)=\int\pi(\bf{x})\sigma(x)dx$?
Answer: You may want to look at separable convolutions, or separable filters which are used in image processing.

Kernel on two functions?


how to find out number of leap years if you have entered date and some x seconds to add

Question: So let me explain:
On input u got:
e.g.:
5 7 1904 5 5 5
675876789
day,month,year hours,mins,secs and some number k.
At the output you need to get:
4.12.1925. 20:38:14
I'm constantly getting 5.12.1925 20:38:14 just because of leap years and my algorithm breaks there. I'm posting my code bellow if anyone knows how to help me?
#include<stdio.h>
int main()
{
    int D, M, G, H, m, s;
    unsigned int k;
    unsigned int ks,km,kH,kG,kM,kD;
    scanf("%d %d %d %d %d %d",&D,&M,&G,&H,&m,&s);
    while(G<1900 || G>2015)
    {
        scanf("%d %d %d %d %d %d",&D,&M,&G,&H,&m,&s);
    }
    int month;
    scanf("%u",&k);
    if(M == 1)
    {
        month=31;
    }
    if(M == 2 && G%4==0 && G%100!=0 && G%400==0)
    {
        month=29;
    }
    if(M == 2 && G%4!=0 && G%100!=0 && G%400!=0)
    {
        month=28;
    }
    if(M == 3)
    {
        month=31;
    }
    if(M == 4)
    {
        month=30;
    }
    if(M == 5)
    {
        month=31;
    }
    if(M == 6)
    {
        month=30;
    }
    if(M == 7)
    {
        month=31;
    }
    if(M == 8)
    {
        month=31;
    }
    if(M == 9)
    {
        month=30;
    }
    if(M == 10)
    {
        month=31;
    }
    if(M == 11)
    {
        month=30;
    }
    if(M == 12)
    {
        month=31;
    }
    kG=k/31536000;
    G=G+kG;
    k=k-kG*31536000;
    kM=k/(86400*month);
    k=k-kM*86400*month;
    kD=k/86400;
    k=k-kD*86400;
    kH=k/3600;
    k=k-kH*3600;
    km=k/60;
    ks=k-km*60;
    s=s+ks;
    m=m+km;
    H=H+kH;
    M=M+kM;
    while(s>=60)
    {
        m++;
        s-=60;
    }
    while(m>=60)
    {
        H++;
        m-=60;
    }
    while(H>=24)
    {
        D++;
        H-=24;
    }
    while(D>month)
    {
        M++;
        D-=31;
    }
    while(M>12)
    {
        G++;
        M-=12;
    }
    printf("%d.%d.%4d. %02d:%02d:%02d",D,M,G,H,m,s);
    return 0;
}

Comment: "how to find out number of leap years" is unclear.  How many leap year since when?  Since 2000, since 1970, since 1AD?  Or do you want to know if a given year is a leap year?
Answer: You should really use a decent library to do this. There are not only leap years; there is daylight savings time, and if you are asking about dates in the early last century, there will be a few calendar changes here and there, which you have no chance taking into account.
And at the very least you need to know the locale of the date, because daylight savings time is different from locale to locale.
That said, your logic for calculating which months are leap years is totally wrong. You need to learn the difference between && and ||. Try G = 2016 and M = 2: months (which is a misleading variable name for days in the month) will not be set at all.
Answer: Seems like here, you have 31 days in every month:
while(D>month)
{
    M++;
    D-=31;
}

And, unrelated to this problem, you should also check the rules for leap years and the year 2000 (which is an exception to an exception).
Comment: Can You be more specific about rules of leap years. Should i make for-loop from starting year to ending year and count how many leap years there is and then make a mid-value of those years or?
Answer: Condition for leap year
if the year is divisible by 100 it must be divisible by 400 to be leap year;
and if the year is not divisible by 100 it would be leap year only if the year is divisible by 4;
i.e,
if (((year%100==0) && (year%400==0)) || ((year%100!=0) && (year%4==0))
code to find leap years in a range:
int leapyears(int start_year, int ending_year)
{
int k=0;
while (start_year<=ending year)
{
//&& operator have higher preference than ||
if (start_year%4==0 && start_year%100!=0 || start_year%400==0)
k++;
start_year++;
}
return k;
}

Comment: Basic maths: If the year is divisible by 100 then it will _always_ be divisible by 4. It's the century that must be divisible by 4, so the year must be divisible by 400. That's why 2000 was a leap year, and 1900 wasn't, and 2100 won't be.


Autoscaling with Nodejs on Google Compute Engine

Question: I am trying to get my backend stuff up and running and I am looking into the best way to save money, my app does api request usually between 8:30 am and 8:30 at night, with the morning, lunch and night having huge peaks.
What I planned to do is set up autoscaling instance group on google compute engine, but I ran into trouble in setting it up.
At first I set it up with nginx on a instance, and multiple copies of my vm all load balanced, but that does not help me with peak hours as well as saving money.
So I looked into the autoscaling, the issue I have is, my VM uses docker containers, with 3 running containers, one for nginx, one for couchdb, and one for some other background stuff.
What I tried to do is create a instance-001 that has the base work, all the files, databases, and everything. Once that hits 70% load, it will duplicate itself, and then load balance between the two.
The issue is I cant get it to keep the data, and spin up a duplicate. After setting one instance all up and working, (instance-001), I hit it with some loads, forcing it above 70%, it then spun up two more instances, 002, and 003, both empty clean vms, and then once it went below 70%, and the VM's were being removed, 001, with the actual data was removed, and 003 was left over.
As of right now, I am unsure how to set it up to scale and load balance.
The VM's were just 1CPU 3G machines with a 10GB ssd for testing, and I was following https://www.youtube.com/watch?v=TfbEwfYjKl4
It is slightly outdated as before it allowed you to load from snapshots, which is how I did this before, now it wont.
My biggest thing is what is the best production style setup for scaling a couchdb getup.
Comment: Autoscaling works best for frontend instances. I would recommend having your database on a separate instance which is not part of autoscaling and use autoscaling for frontend instnaces only. In this way it will be easy to push updates to your database. You can refer to [this link](https://cloud.google.com/solutions/scalable-and-resilient-apps) for more information on building scalable application on Google Cloud Platform.
Comment: couchdb is horrible in production.  You can try to build enough infrastructure around couch that it won't be suck or switch to a production-quality DB like riak.
Comment: You can create an image from the disk with has data and configuration and use this image for your instance group template. I hope that helps.
Comment: @Faizan I sort of have it working your way, but what I want is a disk, that when I update the DB, if a VM spins up right away, it will have access to the new data, instead of me having to recreate an image from the in-use disk and then reapply that to the group.
Answer: To add visibility posting an answer based on Faizan's Comments.
As described in the first 2 minutes of this video,  the backend service can be autoscaled in a similar way as the frontend. The requirement for this is that the backend must be ¨stateless¨ (The database cannot live in the instance managed group that conform the backend).
The details can be found here for autoscaler and this additional article for the design.


Probability to answer all question of an exam correctly given 5 choices

Question:
Suppose a teacher gives his class a set of $10$ questions with the
information that the final exam will consist of a random selection of
$5$ of them. If a student has figured out how to solve $7$ of them,
what is the probability that he answers all of the questions
correctly? how about at least $4$ of the problems?

Attempt:
First, ${10 \choose 5}$ is the size of the sample space. Since it is given that he can do $7$ problems, then probaility that he answer a problem correctly must be $\frac{7}{10} = 0.7$.
Thus, probability that he answers all questions correctly is
$$ P(Q1 \; correct \; \; AND \; \; Q2 \; correct \; \; AND ... AND \; \; Q5 \; correct ) = 0.7 \times 0.7 \times ... \times 0.7 = 0.7^5 $$
Now, the probability that he answer a question wrong is $1 - 0.7 = 0.3$.
Thus,
$$ P(\text{at least 4 correct}) = P(\text{at most one wrong}) = P(\text{no wrong}) + P(\text{1 wrong}) = 0.7^5+0.3$$
But, I feel we we dont really need to know the size of sample space. Or, perhaps Im missing something here?
Comment: You determined the number of possible combinations correctly. To find the number of successful combinations, consider that all $5$ questions must be among the $7$ the student can solve.
Comment: Given that he knows how to do 7 of the problems, the number of ways that 5 of those 7 problems can appear on the test is $7 \choose 5$. Your sample size is correct.
Answer: There are $_7C_5 = 21$ ways to choose $5$ questions among the $7$ he knows how to solve. There are $_{10}C_5 = 252$ ways to choose $5$ questions from the $10$.
So, the probability of getting all $5$ right is $P_5 = 21/252 \doteq 0.083$.
For the second part, we need to add in the number of ways to get exactly $4$ questions that he knows how to do.
So, choose $4$ he knows how to do ($_7C_4 = 35$) and one he doesn't ($3$) for a total of $35 \cdot 3 = 105$ combinations.
Now, the probability of getting at least $4$ right is $$P_5 + P_4 = 21/252 + 105/252 = 126/252 = 0.5.$$
Comment: The probability of getting at least 4 is the same as getting exactly 4 OR exactly 5. You should know that in these kinds of situations "or" means addition and "and" means multiplication.
Comment: Good question. Once you count the number of ways to choose 4 from 7, you still need to choose 1 from the remaining 3 in order to have chosen a total of 5.When getting exactly 4 correct out of 5: $7 \choose 4$ to account for the ones he gets correct, AND $3 \choose 1$ to account for the one he must get incorrect.
Comment: it is unclear how you get the second probaility. why you adding?
Comment: But why do you multiply 35 time 3?
Comment: @JimmySabater I incorporated some of the comments JungleShrimp made into my answer.


Rationalising factor of $x^{1/3}+y^{1/3}+z^{1/3}$

Question: I am working on an exercise from a book, that asks to show that a Rationalising factor of $x^{1/3}+y^{1/3}+z^{1/3}$ is $$(x^{2/3}+y^{2/3}+z^{2/3}-y^{1/3}z^{1/3}-z^{1/3}x^{1/3}-x^{1/3}y^{1/3})\\ \times (x^{2/3}+y^{2/3}+z^{2/3}+2y^{1/3}z^{1/3}-z^{1/3}x^{1/3}-x^{1/3}y^{1/3}) \\ \times(x^{2/3}+y^{2/3}+z^{2/3}-y^{1/3}z^{1/3}+2z^{1/3}x^{1/3}-x^{1/3}y^{1/3}) \\ \times (x^{2/3}+y^{2/3}+z^{2/3}-y^{1/3}z^{1/3}-z^{1/3}x^{1/3}+2x^{1/3}y^{1/3})$$
I have tried conjugate multiplication such as $(x^{1/3}+y^{1/3}+z^{1/3}) \times (x^{1/3}+y^{1/3}-z^{1/3})$, however, this produces a negative $z^{2/3}$ term which is not like the above. Any idea by which terms they multiplied to get the above multiplication?
Comment: https://math.stackexchange.com/questions/2456028/rationalize-a-fraction?noredirect=1
Comment: Also, https://math.stackexchange.com/questions/3250105/rationalizing-frac1-sqrt3a-sqrt3b-sqrt3c?noredirect=1
Answer: HINT.- Since $x\to x^3$ is a bijection of $\mathbb R$ you can do the change of variables $(x,y,z)=(X^3,Y^3,Z^3)$ and try easier with the expression
$$(X^2+Y^2+Z^2-ZY-ZX -XY)(X^2+Y^2+Z^2+2ZY-ZX -XY)(X^2+Y^2+Z^2-ZY+2ZX -XY)(X^2+Y^2+Z^2-ZY-ZX +2XY)$$


Prove that the convolution is continuous

Question: I need some help with this exercise:

Let $f \in L^p(\Bbb R)$ and let $g$ be a continuous function with compact support. Prove that:
a) If $p=1$ or $p=+\infty$, then $f*g$ is continuous.
b) If $1\lt p \lt+\infty$, then $f*g$ is continous.

I have no idea how to solve this, but I know that if $1\le p \lt +\infty$ then the set of continuous functions with compact support is dense in $L^p(\Bbb R)$ so I guess that first I can suppose that $f$ is continuous with compact support and then I'll have to use this density property.
Also, given that the exercise is separated in two parts, I imagine that the solution is different in each case, is that right?
Answer: Here are the ideas. Try to work out the details on your own. It is enough to assume  that $1\leq p <\infty$. By  H\"older's  inequality and translation invariance of Lebesgue in $\mathbb{R}^n$
\begin{aligned}
|(f*g)(x+h)-(f*g)(x+k)|&\leq \int|(f(x+h-y)-f(x+k-y)||g(y)|\,dy\\
&\leq
\|\tau_{-(k-h)}f-f\|_p\|g\|_q.
\end{aligned}
where $\tau_h$ is the translation operator $\tau_hf(x)=f(x-h)$.  The result follows once you show that $\|\tau_hf-f\|_p\rightarrow0$ as $h\rightarrow0$. This is typically done by using approximations with continuous functions of compact support.
If $1<p<\infty$, by using continuous functions of compact support you can actually prove that $f*g\in\mathcal{C}_0(\mathbb{R}^n)$.


Return multiple tables specific to each column

Question: I would like to get a more simple query that runs through all columns of a table and returns the SAME number of tables for EACH column.
For example...
select distinct a from tbl;
select distinct b from tbl;
select distinct c from tbl;
select distinct d from tbl;

would return four tables if ran at once. This gives the results I would like but I would have to type out each column, being especially pesky if I had many many columns. How can I write a query that would go through all the columns and give me the same results without having to do this?
Comment: I can't think of a way to do this without using some dynamic TSQL.  Are you able to execute dynamic code on your server?
Comment: Just to clarify, you would like each column from your table returned as a separate result? So if your table had 10 columns, you would have 10 result sets?
Comment: Yes that's correct
Comment: Yes I am, I think that's the only option too but I'm inexperienced in that area
Answer: Based on our conversation in the comments, you are happy to use dynamic TSQL and you have permissions to execute it on your server.
Therefore, one way to achieve this is to enumerate the columns using a cursor and then execute some dynamic TSQL to get the result set for each column.
The following example shows how it can be done.  Simply modify @table to be the name of whichever table you want and it will output every column as a single result set:
DECLARE @column VARCHAR(100)
DECLARE @s VARCHAR(200)
DECLARE @table VARCHAR(50)
SET @table = 'tbl'

DECLARE curRead CURSOR FORWARD_ONLY READ_ONLY
  FOR
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @table

OPEN curRead
FETCH NEXT FROM curRead INTO @column

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @s = 'SELECT ' + @column + ' FROM ' + @table
    EXEC(@s)

    FETCH NEXT FROM curRead INTO @column
END
CLOSE curRead
DEALLOCATE curRead

In this case, the CURSOR enumerates all of the columns that belong to your table.
You then iterate through these, storing the column name (from COLUMN_NAME in a variable @column), build a piece of dynamic SQL (is @s) and then execute it.
Comment: @JosephYi It depends upon where you are running this code. Running in SQL Server Management Studio will output the tables as required.  If it's as a result set in an application then you may need to get the results into a DataSet.
Comment: i just tested this and it says "commands completed successfully" but no output appears. Am I missing something?


Why is the correlation coefficient a limited measure of dependence?

Question: To quote Kevin Murphy in his book "Machine Learning - A probabilistic perspective", correlation is "a very limited measure of dependence". He talks about this before he introduces the concept of mutual information.
Why is the correlation coefficient "a limited measure of dependence"? Are there some assumptions associated with its computation?
Comment: Once you get a comfortable feeling for Pearson's correlation coefficient, and how it describes linear association, you might want to read Reshef, D., Reshef, Y., Finucane, H., Grossman, S., McVean, G., Turnbaugh, P., Lander, E., Mitzenmacher, M., and Sabeti, P. (2011). [Detecting novel associations in large data sets](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3325791/pdf/nihms358982.pdf). *Science*, 334(6062):1518–1524, as it is an approachable motivation of a *really* different approach (maximal information) to understanding how knowing something about *X* can tell you something about *Y*.
Answer: This is explained in the Wikipedia entry for Correlation and Dependence. Correlation basically measures how close two variables are to having a linear relationship between them. Consider now $X \sim U(-1, 1)$, and $Y = X^2$. Then if you know $X$, you know $Y$ exactly, and if you know $Y$, you know $X$ up to its sign. Hence they are not independent. An easy calculation shows that their correlaton is 0, however.
Comment: If X depends non-linearly on Y, their correlation can be anything. Not necessarily 0.
Comment: @CrisLuengo That is correct, and thanks for the clarification. I think Upendra meant by "not linearly" completely not linearly, rather than not completely linearly.
Comment: So basically what I understood is that correlation measures if or not there could be a linear relationship between X and Y. For instance if X depends on Y but not linearly, then correlation value between them is zero even though there is a great deal of dependence between the two. Am I right with this
Comment: In addition, how do you account for "if you know Y, you know X up to its sign"?
Comment: @UpendraPratapSingh You statement in the first comment is correct, IMHO. As for your second comment, suppose you know that $Y = {1 \over 2}$, then $X = \pm \sqrt{1 \over 2}$, for example.
Comment: What does "completely not linearly" mean, though?
Answer: A simple example. The correlation between a random variable $x$ and its square $x^2$ is zero for any symmetrical distribution on $\mathbb{R}$.
Here's the means of a variable and its square:
$$\mu=\int x dF(x)=0$$
$$\sigma^2=\int x^2 dF(x)$$
Let's calculate Pearson correlation:
$$\rho=\frac{\int x x^2 dF(x)}{\mu \sigma^2}=\frac{\int x^3 dF(x)}{\mu \sigma^2}=\frac{0}{\mu \sigma^2}=0$$
However, if I know $x$ it tells me everything about $x^2$. That's one example where correlation does not reveal how much strong is the relationship between two variables.
Comment: +1 There's probably a nuance to add about *observed range of $x$*, since even for standard normal, there's a non-zero relationship for ranges of $x$ dominated by either positive or negative values.


Bootstrap 3 Alternative hover colour for specific row

Question: I have a class called 'table-green-hover' which when set on a table makes it so that the hover colour is LightGreen instead of the usual bootstrap colour
.table-green-hover > tbody > tr:hover > td,
.table-green-hover > tbody > tr:hover > th { background-color: LightGreen; }

However for 2 specific rows in my table (with a class of 'logout-hover') I want those to be a completely different colour, I thought of doing it as
.logout-hover > tr:hover > td { background-color: LightBlue; }

Though it doesn't seem to be doing anything at all, when I hover over those 2 specific rows they still show with the LightGreen.
Comment: can you create a demo/ provide all the related code?
Comment: Are both `table-green-hover `and `logout-hover` classes applied to the same `table`? Or is `logout-hover` class applied to the `tr` elements? Please show us your HTML.
Comment: table-green-hover is on the table element itself, logout-hover is on the specific tr element
Comment: example: http://www.bootply.com/0jErIpZxfK
Answer: Edit based on OP's comment:
.table-green-hover tr.logout-hover:hover > td { background-color: LightBlue; }

Old answer:
.logout-hover > tbody > tr:hover > td { background-color: LightBlue; }

The reason is because
.table-green-hover > tbody > tr:hover > th (1 class, 3 elements) is more specific than .logout-hover > tr:hover > td (1 class, 2 elements), and thus got higher priority.
Comment: The OP said it still show LightGreen, which is the color mentioned above, so I can be quite sure the table has both classes.
Comment: table-green-hover is on the table element itself, logout-hover is on the specific tr element
Comment: Same issue. Have created a bootply which shows the problem: http://www.bootply.com/0jErIpZxfK
Comment: Actually, fumble fingers, I had an extra '.' after the 'tr', your one worked perfectly, thankyou for that.


typescript class with static variable / singleton pattern

Question: well i have a question regarding the best way to code this situation:
i have a class where i need to have a static variable in all the project: connection
singleton without name space:
class Broker {
  static connection: Connection = undefined;
  static channel: Channel = undefined;
  static urli: string = process.env.RABBIT_URL || 'url';
  static start() {
    return new Promise<Connection>((resolve, reject) => {
      if (Broker.connection || !Broker.urli) {
        const message = !Broker.urli
          ? 'The host of rabbitmq was not found in the environment variables'
          : 'Connection has already been established';
        logger.info(message);
        reject(new Error(message));
      }
      retry<Connection>(() => connect(Broker.urli), 10, 1000)
        .then((conn) => {
          Broker.connection = conn;
          resolve(conn);
        })
        .catch((err) => reject(new Error(err)));
    });
  }
}
export const ConnectionMQ: Connection = Broker.connection;
export const ChannelMQ: Channel = Broker.channel;
export const start = () => {
  return Broker.start();
};

with namespace
//namespace
namespace Broker {
  export type QueuesToAssert = { queue: string; options?: Options.AssertQueue };
  export type ExchangesToAssert = {
    exchange: string;
    type: string;
    options?: Options.AssertExchange;
  };
  export type QueuesToBind = {
    queue: string;
    source: string;
    pattern: string;
    args?: any;
  };
  //static
  class BrokerMain {
    static connection: Connection = undefined;
    static channel: Channel = undefined;
    static urli: string = process.env.RABBIT_URL || 'url';
    static start() {
      return new Promise<Connection>((resolve, reject) => {
        if (BrokerMain.connection || !BrokerMain.urli) {
          const message = !BrokerMain.urli
            ? 'The host of rabbitmq was not found in the environment variables'
            : 'Connection has already been established';
          logger.info(message);
          reject(new Error(message));
        }
        retry<Connection>(() => connect(BrokerMain.urli), 10, 1000)
          .then((conn) => {
            this.connection = conn;
            resolve(conn);
          })
          .catch((err) => reject(new Error(err)));
      });
    }
  }
  export const Connection = BrokerMain.connection;
  export const Channel = BrokerMain.channel;
  export const start = () => {
    return BrokerMain.start();
  };
  export const close = () => {};
}
//usage
const connection = Broker.Connection ? Broker.start() : undefined;

I would like to know what is the best / correct option in this situation, or if I could apply another way to the situation.
remembering that I only need 2 unique variables of the class that are unique statics throughout the project.
I have doubts if the singleton is needed in this case or just static already solves
Comment: That's very close to what I meant but if you look at my last comment, you need to use `export let` for the connection and you need set it when you get the connection in your call back. The problem with your current implementation is that the value never gets updated. `export const ConnectionMQ: Connection = Broker.connection` will always be undefined.
Comment: Neither is appropriate. Use modules. Basically, remove the `namespace Broker {}` wrapper from the namespace example and he happy
Comment: but that way will my connection from the class Broker have a static value throughout the project?
Comment: Of course. But you would do `export let Connection: Connection`; then change `this.connection = conn` to `Connection = conn`. That will fix an existing bug and simply your code
Comment: I edited the code based on that, could you tell me if this is it?

the first code block
Comment: If you can also answer for me to give you +
Comment: @AluanHaddad Thank you, if you want to post a reply to vote for you, reply
Answer:
I would like to know what is the best / correct option in this situation,

I would definitely recommend the static class methods.
Reason
namespace is a TypeScript only feature and not supported by many tools out of the box e.g. Create React App.
Comment: basarat and in this situation where I said that I only need 2 static variables: connection and channel, that is, just one value in the entire project, would I need to use singleton for this? or just declaring the variable as static would solve it already?
Comment: A `static` is a singleton


Proof of "Taylor Series"

Question: We know that , according to the Taylor Series :

$$f(x)=f(a)+\frac {f'(a)}{1!} (x-a)+ \frac{f''(a)}{2!} (x-a)^2+\frac{f'''(a)}{3!}(x-a)^3+ \cdots \tag{1}$$

And then Maclaurin series as $a=0$.
But how to prove it?
I have googled it and searched for it in my books but I really have not come across any where where it gives the proof of $(1)$.
Please help ... Just links to the full proof is also appreciated..
Thanks!!
Comment: Assume that we can define a polynomial such that $$f(x)=a_0+a_1(x-a)+a_2(x-a)^2+...$$
If we put x=a, then we get $f(a)=a_0$. Now derive and put x=a in the derivative to get $f'(a)=a_1$ and so on.
Comment: @NeilRoy, we will find for example $a_3$. Deriving three times we get $$f'(x)=a_1+2a_2(x-a)+3a_3(x-a)^2+... \\ f''(x)=2a_2+3!a_3(x-a)+... \\ f'''(x)=3!a_3$$ hence $a_3=\frac{f'''(a)}{3!}$ and so on. As mentioned in comments and answers, this method assumes that the error approaches 0.
Comment: The proof depends on f(x) being an [analytic function](https://en.wikipedia.org/wiki/Analytic_function)  and (at an intuitive level at least) is then about finding the coefficients of the polynomial by repeated differentiation
Comment: @Galc127 Thanks!! But where did those $1!, 2!, 3! , \cdots$ come from?
Answer: No, we don't.
Taylor's theorem states that
$$f(x)=f(a)+\frac {f'(a)}{1!} (x-a)+ \frac{f''(a)}{2!} (x-a)^2+\ldots+\frac{f^{(n)}(a)}{n!}(x-a)^n+ R_n(x)$$
where quite a few things can be said about $R_n(x)$, for example
$$ \lim_{x\to a}\frac{R_n(x)}{(x-a)^n}=0$$
or
$$ \forall x\exists \xi\colon (a<\xi<x\lor x<\xi<a)\land R_n(x)=\frac{f^{(n+1)}(\xi)}{(n+1)!}(x-a)^{n+1}$$
But we do not have in general that $\lim_{n\to\infty}R_n(x)=0$, hence not necessarily
$$f(x)=f(a)+\frac {f'(a)}{1!} (x-a)+ \frac{f''(a)}{2!} (x-a)^2+\frac{f'''(a)}{3!}(x-a)^3+ \cdots $$
Answer: The way you state this is to imprecise to give a proof. The correct statement is that $$f(x) =\sum_{k=0}^N \frac{f^{(k)}(0)}{k!}x^k +r_N(x,\ldots)$$
Without the last term, the so called remainder (for which various different expressions are known, see this page, the statement is not correct. The proof of the statement with remainder (usually by induction) is rather easy using the fundamental theorem of calculus or the mean value theorem.
Edit (the representation of $f$ by an infinite sequence of this kind is only true for so called real analytical functions)
Answer: Take a look at chapters 7 and 11 (Specially section 11.9) of the well-known book:
Calculus, Vol. 1: One-Variable Calculus, with an Introduction to Linear Algebra
by Tom. M. Apostol.
There is a rigorous study of Taylor polynomials and series in those chapters.

Proof of "Taylor Series"


Linq to Entities - Contar elementos de uma query que referencie dois contextos

Question: Tenho a seguinte query:
<code>var query = (from q1 in query1
            join q2 in query1 on q1.idGenerico equals q2.idGenerico into q2Left
            from q2 in q2Left.DefaultIfEmpty()
            join q3 in query3 on q2.idGenerico equals q3.idGenerico  into q3Left
            from q3 in q3Left.DefaultIfEmpty()
            select new { q1, q2, q3});
</code>
Basicamente ela é uma query para agrupar outras, que são de contextos diferentes, a partir dela eu tenho que pegar o total de registros resultantes desse agrupamento, e popular uma lista de objetos que serão retornados pelo método da query.
meu problema é: Ao tentar fazer qualquer tipo de manipulação com a query, eu recebo a seguinte excessão:

"The specified LINQ expression contains references to queries that are
  associated with different contexts"

no SO eu encontrei a seguinte resposta (https://stackoverflow.com/questions/7332920/error-the-specified-linq-expression-contains-references-to-queries-that-are-as) que se encaixa no meu caso:

If they're on different databases but on the same instance, create a
  view on one of the databases that selects from the table on the other
  database, then add the local table and view to a single EDMX.

minha pergunta é: quais outras soluções eu tenho para esse problema? sou obrigado a criar uma view?
Comment: Não recomendo em casos de grande massa de dados, mas desde que você traga para memória o resultado das duas queries, os contextos se tornam irrelevantes.
Comment: O problema é exatamente esse, a massa de dados tem que ser levada em conta.
Answer: Eu reunião com um desenvolvedor mais experiente foi encontrada a seguinte solução:
Primeiramente eu consegui reduzir uma das querys por já existir uma view em banco com os dados da terceira.
Trabalhando com duas querys, de contextos diferentes, para pegar o total de registros (para paginar) e apenas uma amostra de registros (elementos de uma página) as consultas foram executadas na seguinte ordem:
1 - Executo a primeira query, atribuindo-a a um objeto Iqueryable.
2 - Aplico os filtros á primeira query (como são filtros dinâmicos, que podem ou não estarem preenchidos, não posso aplicá-los na consulta).
3 - Trago para uma Lista (LINQ To Objects) a chave que irá fazer o join entre os dois contextos. ex: query1.select(x => x.idTabelaOutroContexto).ToList();
4 - Executo a segunda query com base na lista acima.
5 - Aplico os filtros, também dinâmicos á segunda query.
6 - Atualizo a lista com as chaves com base dos registros da segunda query filtrada.
7 - Filtro a primeira query baseada na lista atualizada.
8 - Agora que filtrei a primeira query com base no retorno da segunda, alcanço o primeiro objetivo, o total de registros.. que é o count da primeira.
9 - Recolho as amostras das duas querys separadas trazendo para memória.
10 - Faço uma terceira query agrupando as listas criadas a partir da consulta das duas primeiras, e alcanço o segundo objetivo, que era coletar a amostra de dados.
Comment: O objeto iqueryable deve ficar enorme, mas a consulta é executada rapidamente e atende.


Finding the inverse image of a function

Question: While I was reading a Convex Optimization book, I found an example, which is attached below. What is confused me is that how the authors derived/concluded that the hyperbolic cone is the image inverse  of f(x).
Answer: Let $C = \{(x, t) | z^Tz \le t^2 | t \ge 0\}$ and $K := \{x|x^TPx \le (c^Tx)^2, c^Tx \ge 0\}$. It's straightforward to see that $C$ has the representation $C = \{(z, t) | \|z\|_2 \le t, t \ge 0\} = \text{epi}(\|.\|_2) \cap (\mathbb R^n \times \mathbb R_+)$, and is thus convex.
It should be clear that $f$ is affine, and it's a rather straightforward exercise to show that the pre-image of a convex set under an affine function is again convex. So we just need to show that $K = f^{-1}C$. Now, noting that $ x^TPx = (P^{1/2}x)^TP^{1/2}x = ||P^{1/2}x||_2^2$ (since $P \in \mathbb S^n_+$), we get
$$ K = \{x|\|P^{1/2}x\|_2 \le c^Tx, c^Tx \ge 0\} = \{x | f(x) \in C\} = f^{-1}C,$$
and we're done.
Comment: $x^TPx = x^TP^{1/2}P^{1/2}x = x^T(P^{1/2})^TP^{1/2}x = (P^{1/2}x)^TP^{1/2}x$, where we've used the fact that $P^{1/2}$ is be symmetric (in fact, it is positive semi-definite too!).
Comment: One more question: how (  transpose(x)Px = transpose(sqrt(P)x)sqrt(P)x ) ?

Finding the inverse image of a function


Adjust left / right angle of guitar neck?

Question: TL;DR: Can I adjust the left / right angle of my electric guitar's neck? Not the vertical angle that most of the related questions seem to ask about.
I've recently inherited an old Squier Bullet that I'd like to put in reasonable working condition.  After tuning and playing it a bit I discovered the intonation is off: in standard tuning the low E octave was ~168 Hz instead of ~165.  Other strings needed similar adjustment on the octave.
Guitar maintenance is pretty new to me, but with some Googling I discovered how I can adjust the saddle screws on my bridge.  This let me fix the intonation on all strings except the outer two, the low E and the high e.
The low E is still out of intonation (the octave is now at ~166-167 Hz) since I've run out of screw: the saddle for that string is now all the way up against the bridge (sans a small spring that I suspect I probably should not remove.)  The high e has a similar problem; it is so flat that to get the saddle out far enough I'd need a longer screw.
After tuning my saddle positions the best I can it seems my saddles in fact form a line, with the low E at the closest position to the bridge and the high e closest to the neck, with the others spread evenly between the two.
It's almost as if my entire guitar neck is leaning too far to the left (towards my face as I hold it.)
Most of the discussion I see about adjusting neck angle has to do with the truss rod and how high or low the headstock is relative to the body when the guitar is laying flat.  I don't think this applies to my problem.
Is there a way to adjust the left / right angle of my neck?  Or something else I could do to fix this old guitar's intonation?
Answer: The quick answer to this question is ... No, There is nothing built into the guitar that can adjust the angles to the left or right.
Now the long answer is... it sounds like your neck is slightly warped but you'll have to confirm this yourself.
Now there are are few consideration to take note of when checking for a warped neck.

is it a fanned fretboard? I'll that answer that question and tell you
no it isn't.
Is the warp significant?  in my experience  a slightly warped neck generally does not effect the intonation significantly.

Now assuming that the warp is significant most or at least myself and a quite a few other guitar players usually replace the neck instead of paying someone else to reset the neck or attempting a DIY solution which by the way is something you shouldn't do mainly do the amount of time and the high percent chance you are going mess up.
As for your intonation issue the few things that do standout to me when I am checking are:

health/gauge of the string.
quality of the hardware and what type of hardware is installed on the guitar.
How much relief/tension there is on the neck. a and c are interrelated to be
clear.
the age of the guitar in question. Age is not necessarily a factor but it does change expectations.

There is a lot more to this issue such as the placement of the bridge and so forth but the above are at least controllable... except time of coarse.
Also, take note that the average human being is not going to be able to tell the difference between 166-167 vs 164-165 where the 164-65 range is the ideal. In other words don't waste a large amount of time in getting the hertz "perfect". Also a fyi, even the most expensive well crafted guitar have intonation problems. Never played a guitar with perfect intonation and this list of played guitar does include a suhr.
Comment: Thanks. It's true, I couldn't tell the difference personally; the guitar is plugged into a video game that noticed.  Particularly, 168 Hz is closer to the 13th fret than the 12th.
Answer: First thing I'd do is put some decent strings on it. Maybe you've already done this.Different gauge strings will need different saddle positioning. You say the saddles are in a sort of diagonal line - sounds about right, except B is usually a little closer to the string end.
Assuming the action is good, I'd take off the spring on low E, or put a shorter one in. The top E can use a longer screw, maybe with a longer spring (or use two), to give it the adjustment needed. Also check the intonation on fret 19 against the harmonic.
Answer: I'm not 100% sure if you are talking about wanting to adjust the rotation of the neck relative to the body or the angle at which the neck sits in the pocket, thus changing the angle at which the strings project from the bridge toward the headstock.  With a bolt-on neck, either one is possible, within a small range.
If you are talking about changing the rotation of the neck along the length of the neck (in effect, rotating the fretboard, relative to the body), you could add a shim to the neck pocket to do this.  That's not a common reason to add a shim, but there's no reason you couldn't do it.  You would just have to make sure that the shim was made such that it raised one side of the neck more than the other.
If you are talking about changing the angle at which the neck connects with the body, there is usually enough play in the bolt holes in a bolt-on neck to make a little bit of an adjustment.  You would want to loosen the bolts (after first loosening the string tension), then using light hand pressure to move the neck in which you want it to move.  Don't push too hard or you may end up breaking something.  Then re-tighten the bolts and re-tension the strings.  You don't have to tune the strings perfectly to pitch to see if you are in the ballpark with the adjustment.  Usually a very slight adjustment will do the trick.
If, as Asterisk suggested, your neck is warped, then none of this will help much, and you are better off replacing the neck.  Good replacement bolt-on necks can be bought for very affordable prices.