OpenVPN (Tunnelblick and Viscosity) connections drop at almost exactly 10 minutes

Question: Original question here:
https://apple.stackexchange.com/questions/77245/viscosity-openvpn-tunnelblick-connect-but-all-rdp-connections-go-dead-after-abou
My VPN connection seems to be fine for almost exactly 10 minutes.
Here's the log:
 Jan 08 09:37:05: Viscosity Mac 1.4.2 (1092)
Jan 08 09:37:05: Viscosity OpenVPN Engine Started
Jan 08 09:37:05: Running on Mac OS X 10.8.2
Jan 08 09:37:05: ---------
Jan 08 09:37:05: Checking reachability status of connection...
Jan 08 09:37:05: Connection is reachable. Starting connection attempt.
Jan 08 09:37:08: OpenVPN 2.2.1 x86_64-apple-darwin10.8.0 [SSL] [LZO2] [PKCS11] [eurephia] built on Aug  1 2011
Jan 08 09:37:07: IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Jan 08 09:37:07: WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.
Jan 08 09:37:07: NOTE: OpenVPN 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables
Jan 08 09:37:09: WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
Jan 08 09:37:09: LZO compression initialized
Jan 08 09:37:09: UDPv4 link local (bound): [undef]:1194
Jan 08 09:37:09: UDPv4 link remote: 188.8.131.52:1194
Jan 08 09:37:10: [vpp-vpn001.verrus.com] Peer Connection Initiated with 126.96.36.199:1194
Jan 08 09:37:12: TUN/TAP device /dev/tun0 opened
Jan 08 09:37:12: /sbin/ifconfig tun0 delete
Jan 08 09:37:12: NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if failure
Jan 08 09:37:12: /sbin/ifconfig tun0 10.103.11.145 10.103.11.146 mtu 1500 netmask 255.255.255.255 up
Jan 08 09:37:12: Initialization Sequence Completed
Jan 08 09:57:15: [vpp-vpn001.verrus.com] Inactivity timeout (--ping-restart), restarting
Jan 08 09:57:15: SIGUSR1[soft,ping-restart] received, process restarting
Jan 08 09:57:16: IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Jan 08 09:57:16: WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.
Jan 08 09:57:16: NOTE: OpenVPN 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables
Jan 08 09:57:16: LZO compression initialized
Jan 08 09:57:16: UDPv4 link local (bound): [undef]:1194
Jan 08 09:57:16: UDPv4 link remote: 126.96.36.199:1194
Jan 08 09:57:17: [vpp-vpn001.verrus.com] Peer Connection Initiated with 184.108.40.206:1194
Jan 08 09:57:19: TUN/TAP device /dev/tun0 opened
Jan 08 09:57:19: /sbin/ifconfig tun0 delete
Jan 08 09:57:19: NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if failure
Jan 08 09:57:19: /sbin/ifconfig tun0 10.103.11.145 10.103.11.146 mtu 1500 netmask 255.255.255.255 up
Jan 08 09:57:19: Initialization Sequence Completed

It seems to take about 10 minutes for Viscosity to notice that the connection has failed and attempt to renegotiate.  My routing table doesn't appear to change.  I've attempted and been able to replicate this behavior in both Tunnelblick and Viscosity.
I can actually watch the throughput drop to 0 within 10 seconds of the 10 minute mark.
My theory is that it centers around DHCP lease time but I haven't been able to figure out how to check that on OSX with an OpenVPN tun interface.
Answer: Jan 08 09:57:15: [vpp-vpn001.verrus.com] Inactivity timeout (--ping-restart), restarting

From this line it's pretty much clear that there is a idle timeout set on the server side. So, when someone doesn't do anything for 20 minutes (it's not 10 minutes, what I can see from the logs), then the server resets the connection.
Can you please check the server side for this.
May be something like keepalive 10 120. Not sure though. That you need to look into server.conf file.
Comment: I thought I wrote this out yesterday.  Figured out the problem and it was me.  I have multiple machines that I connect from and one of them is a VM that is pretty much always on and always connected.  As soon as I turned off that VM everything works fine.
Comment: Great. Glad you found the fix.


Não estou conseguindo chamar class no css do modo convencional

Question: Estou começando  a usar o vs code agora, porém, quando tento fazer referência à uma classe criada no código em html, pelo css, preciso fazer sem ponto, não consigo entender que tipo de erro pode ser esse. segue os 3 códigos(index.html, footer.css e index.css).
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>MInha Pagina</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" media="screen" href="./Assets/css/index.css" />

    **

           green

    **

@import url('./footer.css');
@import url('./header.css');
@import url('./reset.css');
@import url('./section.css');

Código que deveria funcionar:
.footer {
   color:green;
 }

Código que está funcionando (sem o ponto):
footer {
  color:green;
}

Comment: Agora notei, deu tudo certo!
Answer: Está correto.
Não irá funcionar com o ponto na frente pois seu html não possui nenhum elemento com class="footer", somente o elemento

.footer { color: red } /* classe */
footer { color: blue } /* elemento */
Footer I
Footer II


Add discount to single product in cart

Question: After struggling attempting to fix a bundle price whilst remaining VAT calculations, my next attempt to resolve the issue is to apply a discount to the bundle to reduce it to the fixed amount.
<?php

class XXX_Fixedbundlediscount_Model_Observer
{
    public function setDiscount($observer)
    {
    Mage::log('settingDiscount');
    $quote = $observer->getEvent()->getQuote();
    $quoteid = $quote->getId();
    if ($quoteid) {
        foreach ($quote->getAllItems() as $item) {
            $product = $item->getProduct();
            $fixed_price_attribute = (float)Mage::getResourceModel('catalog/product')->getAttributeRawValue($product->getId(), 'giftset_fixed_price', Mage::app()->getStore()->getStoreId());
            if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !$fixed_price_attribute) {
                continue;
            }
        $lineTotal = (float)$item->getPriceInclTax();
        $item->setBaseDiscountAmount(0);
        $item->setDiscountAmount(0);
        if ($lineTotal > $fixed_price_attribute) {
            $item->setDiscountAmount(-($lineTotal - $fixed_price_attribute));
            $item->setDiscountDescription('Gift Set');
                    $item->setBaseDiscountAmount(-($lineTotal - $fixed_price_attribute))->save();
            Mage::log('xxxx');
        }
        Mage::log($fixed_price_attribute);
        Mage::log($lineTotal);
        Mage::log(($fixed_price_attribute > $lineTotal) ? 'Yes' : 'No');
        }
    }
    }
}

I've set up a custom attribute on the Bundled products which specifies the fixed cost. As you can see from the above, the idea is to detect this, calculate the cost of the bundle and add the difference of that between the attribute value as a discount.
Unfortunately it's not adding any discounts what so ever...
Can any one suggest anything that may be of any use?
Thanks
Gav
Answer: I managed to find a way in the end:
<?php

class XXX_Fixedbundlediscount_Model_Observer
{
    public function setDiscount($observer)
    {
        $quote = $observer->getEvent()->getQuote();
        $quoteid = $quote->getId();
        $discountAmount = 0;
        if ($quoteid) {

            foreach ($quote->getAllItems() as $item) {
                $product = $item->getProduct();
                $fixed_price_attribute = (float)Mage::getResourceModel('catalog/product')->getAttributeRawValue($product->getId(), 'giftset_fixed_price', Mage::app()->getStore()->getStoreId());
                if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !$fixed_price_attribute) {
                    continue;
                }
                if ($item->getPriceInclTax() > $fixed_price_attribute) {
                    $discountAmount += $item->getQty() * ($item->getPriceInclTax() - $fixed_price_attribute);
                }
            }

            if ($discountAmount > 0) {
                $total = $quote->getBaseSubtotal();
                $quote->setSubtotal(0);
                $quote->setBaseSubtotal(0);

                $quote->setSubtotalWithDiscount(0);
                $quote->setBaseSubtotalWithDiscount(0);

                $quote->setGrandTotal(0);
                $quote->setBaseGrandTotal(0);

                $canAddItems = $quote->isVirtual() ? ('billing') : ('shipping');
                foreach ($quote->getAllAddresses() as $address) {

                    $address->setSubtotal(0);
                    $address->setBaseSubtotal(0);

                    $address->setGrandTotal(0);
                    $address->setBaseGrandTotal(0);

                    $address->collectTotals();

                    $quote->setSubtotal((float)$quote->getSubtotal() + $address->getSubtotal());
                    $quote->setBaseSubtotal((float)$quote->getBaseSubtotal() + $address->getBaseSubtotal());

                    $quote->setSubtotalWithDiscount(
                        (float)$quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount()
                    );
                    $quote->setBaseSubtotalWithDiscount(
                        (float)$quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount()
                    );

                    $quote->setGrandTotal((float)$quote->getGrandTotal() + $address->getGrandTotal());
                    $quote->setBaseGrandTotal((float)$quote->getBaseGrandTotal() + $address->getBaseGrandTotal());

                    $quote->save();

                    $quote->setGrandTotal($quote->getGrandTotal() - ($discountAmount / 2))
                        ->setBaseGrandTotal($quote->getBaseGrandTotal() - $discountAmount)
                        ->setSubtotalWithDiscount($quote->getSubtotalWithDiscount() - $discountAmount)
                        ->setBaseSubtotalWithDiscount($quote->getBaseSubtotalWithDiscount() - $discountAmount)
                        ->save();

                    if ($address->getAddressType() == $canAddItems) {

                        $address->setSubtotalWithDiscount((float)$address->getSubtotalWithDiscount() - $discountAmount);
                        $address->setGrandTotal((float)$address->getGrandTotal() - $discountAmount);
                        $address->setBaseSubtotalWithDiscount((float)$address->getBaseSubtotalWithDiscount() - $discountAmount);
                        $address->setBaseGrandTotal((float)$address->getBaseGrandTotal() - $discountAmount);

                        if ($address->getDiscountDescription()) {
                            $address->setDiscountAmount(-($address->getDiscountAmount() - $discountAmount));
                            $address->setDiscountDescription($address->getDiscountDescription() . ', Gift Sets');
                            $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount() - $discountAmount));
                        } else {
                            $address->setDiscountAmount(-($discountAmount));
                            $address->setDiscountDescription('Gift Sets');
                            $address->setBaseDiscountAmount(-($discountAmount));
                        }
                        $address->save();
                    }
                }

                foreach ($quote->getAllItems() as $item) {
                    $product = $item->getProduct();
                    $fixed_price_attribute = (float)Mage::getResourceModel('catalog/product')->getAttributeRawValue($product->getId(), 'giftset_fixed_price', Mage::app()->getStore()->getStoreId());
                    if ($product->getTypeId() !== Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || !$fixed_price_attribute) {
                        continue;
                    }

                    $lineDiscount = 0;
                    if ($item->getPriceInclTax() > $fixed_price_attribute) {
                        $lineDiscount = $item->getQty() * ($item->getPriceInclTax() - $fixed_price_attribute);
                    }

                    $item->setDiscountAmount($lineDiscount);
                    $item->setBaseDiscountAmount($lineDiscount)->save();
                }
            }
        }
    }
}

The above simply allows the bundled product to remain dynamic whilst having a fixed price. If the dynamic value is more than the fixed price, it will add a discount to reduce it back to the fixed price.
I'll update this shortly with code that excludes extra products added to the bundle.

Add discount to single product in cart


How to check in $\{x,\cos(x),1\}$ is linearly independent or dependent.

Question: I have been working on this question about how to check whether $\{x,\cos(x),1\}$ is linearly independent or not.
My attempt:
We need to show $c_{1}x + c_{2}\cos(x) + c_{3} = 0$
When $x=0$
$$ c_{2} + c_{3} = 0 $$
When $x=\pi$
$$ c_{1}\pi - c_{2} + c_{3} = 0 $$
$$ c_{1} = \frac{2c_{2}}{\pi} $$
After this I do not know where to go or what we can say about linear independence based on these relationships. I would appreciate any help.
Comment: Cf. the [Wronskian](https://en.m.wikipedia.org/wiki/Wronskian)
Comment: And when $x=2\pi$?
Comment: If we choose the order of the functions appropriately, the matrix whose determinant is the Wronskian is triangular, making it especially easy to compute the Wronskian.
Comment: Take your linear relation $c_{1}x + c_{2}\cos(x) + c_{3} = 0$.  Apply derivative operator twice to confirm $c_2=0$, once to confirm $c_1=0$ and no times to confirm $c_3=0$
Answer: We also have for $x=\frac \pi 2$
$$c_{1}\frac \pi 2 + c_{2}0 + c_{3} = 0 \implies c_3=-\frac \pi 2 c_1$$
which with $c_{2} + c_{3} = 0$ and $c_{1} = \frac{2c_{2}}{\pi}$ implies $c_1=1$, $c_2=\frac \pi 2$, $c_3=-\frac \pi 2$, but for $x=2\pi$
$$2\pi + \frac \pi 2 -\frac \pi 2 = 2\pi \neq 0$$
The latter would require $c_1=0$ which with the previous conditions would imply also $c_2=c_3=0$.
Therefore since we can't find $c_1$, $c_2$ and $c_3$ all simultanously not equal to zero such that $c_1x+c_2\cos(x)+c_3=0$ for all $x$, the given functions are linearly independent.
Comment: So does this mean that this is independent?
Comment: @IllesMoshe Yes because we can't find $c_1$, $c_2$ and $c_3$ not all simultanously equal to zero such that $c_{1}x + c_{2}\cos(x) + c_{3} = 0$ for all $x$.
Comment: Technically, you've just shown $c_1 \neq 1$.  We'd need another argument to conclude.
 Yes, it's a rather simple argument, but I'm not sure someone asking this question would be able to see it so simply.
Comment: @BrianMoehring Are you referring that for the latter we need $c_1=0$ which with the previous conditions implies $c_2=c_3=0$?
Comment: Yes.  Specifically, some students at this level have trouble making sense of "Assume $c_1 \neq 0$, so WLOG $c_1=1$," even though it's a common simplification.  I presume that's your [unstated] argument?
Comment: @BrianMoehring Thanks a lot! I add this part too
Answer: I will continue from where you have stopped.
Now at x= $\frac{\pi}{3}$, you have $c_1$$\frac{\pi}{3}$=$\frac{c_2}{2}$. Which when solved for $c_1$ and $c_2$ using your last equation gives $c_1$=$c_2$=0, but as you pointed out $c_2$+$c_3$=0. This gives $c_1$=$c_2$=$c_3$=0.


Tangent bundle of the incidence variety and its Chern class

Question: I am trying to learn about Thom polynomials and I often find arguments in the literature that just make no real sense to me. Maybe it is due to my lack of knowledge in $K$ - theory. I apologize for the lengthy post, but maybe someone knows these things well.
Let $P := \mathbb{C}P^n$, $N := \mathbb{C}P^{n*}$ and set $X := P\times N$. Denote by $p_1:X\rightarrow P$ and $p_2: X\rightarrow N$ the natural projections. Let $V = \mathbb{V}(F)\subset P$ be a hypersurface of degree $d$ and $H = \{(x,a^*)\in P\times N:\text{ }a^*(x) = 0\}$ be the incidence variety of points and lines in $P$. In fact, $H$ can be realized as the zero-set (zero-scheme) of a section of the line bundle $p_1^*\mathcal{O}_P(1)\otimes p_2^*\mathcal{O}_N(1)$ over $X$.
Also, the polynomial $F$ defines a section of the line bundle $p_1^*\mathcal{O}_P(d)$ over $X$. Hence, there is an induced section of the rank $2$ vector bundle $E =p_1^*\mathcal{O}_P(d)\oplus (p_1^*\mathcal{O}_P(1)\otimes p_2^*\mathcal{O}_N(1))$ over $X$. Its zero-set (zero-scheme) is the subvariety $M :=\{ (x,a^*)\in V\times N:\text{ }a^*(x) =0\}$, i.e. the incidence variety of points in $V$ and lines in $P$.
Define $f:M\rightarrow N$ by composing $p_2:X\rightarrow N$ with the inclusion $i:M\hookrightarrow X$, i.e. $f = p_2\circ i$. I am interested in computing the total Chern class $c(f^*TN-TM)$, where $f^*TM-TN$ is the virtual bundle living in the $K$ - group of $M$.
The claim is: $$TM = i^*(TX-E)\text{ and hence } f^{*}TN - TM = i^{*}(E - p_1^*TP).$$
It appears to me that these are just standard calculations in $K$ - groups but I don't get it.
Answer: I now have some idea on how to prove these relations. Consider a real vector bundle $\pi:E\rightarrow X$ of rank $k$, where $E$ and $X$ are $C^\infty$ manifolds and let $X$ be $n$,-,dimensional. If $s$ is a section transverse to the zero - section, then its zero set $Z(s) = \{x\in X|\text{ }s(x)=0_x\in E_x\}$ is a submanifold of $X$. What's more, on local bundle charts $U\subset X$, the restriction $s|U$ is a submersion in points $x\in U$ with $s(x) = 0$, meaning $\text{im}(ds(x))= \mathbb{R}^k$.
Let $M := Z(s)$, then the tangent space $T_xM$ can be identified with $\text{ker}(ds(x))$ and the normal space is isomorphic to $\mathbb{R}^k$, which follows from the canonical exact sequence
$$0\rightarrow T_xM = \text{ker}(ds(x))\rightarrow T_xX\rightarrow N_xM = T_xX/T_xM\rightarrow 0.$$
Hence, $TX = TM \oplus i^*E$, where $i:M\hookrightarrow X$ is the inclusion. This proves $$TM = TX-i^*E\in K_0(X)$$
The second identity follows from $TX = TP\oplus TN$.
Although the computation above is valid for real vector bundles, I think we can interpret any complex vector bundle as a real vector bundle of twice the rank. Also $\mathbb{C}P^n$ is a $2n$ - dimensional real manifold...


Efficient Proof for all cases of triangle inequality

Question: The question asks Find an efficient proof for all the cases at once by first demonstrating
$$
(a+b)^2 \leq (|a|+|b|)^2
$$
My attempt at the proof:
for $a,b\in\mathbb{R}$
$$
\begin{align*}
|a+b|^2 =&(a+b)^2 \text{ (Since $\forall x\in\mathbb{R}$, $x^2=|x|^2$)}\\
 =& a^2+2ab+b^2\\
 \leq&|a|^2+2|a||b|+|b|^2 \text{( Since $\forall x\in\mathbb{R}, x\leq |x|$)}\\
=&(|a| +|b|)^2
\end{align*}
$$
But this is where I get stuck, I can arrive at the inequality but I do not know how to continue you from here. The question states that this should be efficient proof for all the cases, but jumping from that step to $|a+b|\leq |a|+|b|$ seems like a big jump with some steps missing. Any push in the right direction would be appreciated!
Answer: Note that for positive numbers $a$ and $b$, $$a^2 \le b^2 \implies a\le b $$
Thus $$|a+b|^2 \le (|a|+|b|)^2 \implies |a+b|\le|a|+|b|$$
Comment: We do not need $a$ or $b$ to be positive, but we know that $|a+b|$ is positive
Comment: But how do we know $a$ and $b$ are positive?
Comment: Of course! Thank you! I really appreciate.
Answer: All you need to say is that if $0<r^2<s^2$, then $r<s$. This follows from the fact that $r\geq s>0$ implies $r^2\geq s^2$.
Also, you are missing a square on $|a|$, and your last $\leq$ should be $=$.


Partial Dependency plots and Gradient boosting (GBM package)

Question: Is it possible to plot a partial dependency plot to display the class probability and estimate the effects of a predictor for a GBM model?
Something similar to partialPlot from randomForest package.

According to this article, a partial plot is doable with gbm.
Thanks in advance for your help.
Answer: Yes, it's really easy. Check out ?plot.gbm. The usage goes like this:
 plot(gbm.model, i.var = 1, lwd = 2, col = "blue", main = "")

and looks like

i.var controls the index of the variable to plot. You can also do two (or more) way plots using
 plot(gbm.model, i.var = c(1,2), lwd = 2, col = "blue", main = "")

Comment: thank you, i really appreciate your efforts and time here and in your blog.


Why is correlation not used while splitting in Decision Trees?

Question: Say we have data where we have temperature, humidity, wind and rain for deciding whether we go and play tennis or not.
While selecting best feature to split upon initially, we use ID3 or Gini index. My question is why not use correlation ie when the features have maximum correlation with the output, split on that feature.
It seems obvious, but I can't find spit using correlation anywhere.
Answer: First of all, decision Trees can easily use categorical features with entropy and gini index, but (Pearson) correlation is defined for only numeric attributes. Using correlation with one-hot encoded versions of these categorical features also makes no sense. Secondly, In classification tasks, correlation between a, let's say binary output (e.g. $0,1$), and a numeric attribute may not make much sense as it normally does in regression problems. And, when it makes sense, it tries to capture the linear relationships by definition. (e.g. when $x=y^2$ and $x$ is symmetric for example, correlation is very low or zero)
For example, let's say we have a relationship $Y=1$ only when $X>0$, else $Y=0$. If we have small negative $X$, but comparably large positive $X$, as positive $X$'s move in positive/negative direction correlation changes because of their numeric values. But, actually this feature perfectly classifies the data.
While others are not perfect heuristics, correlation might be quite misleading when assessing the utility of the feature.
Comment: You just helped 20+ students. Thanks a lot.
Answer: As already pointed out by @gunes correlation would only be available if both the dependent variable and the regressor or splitting variable is numeric. But in that situation it certainly makes sense to consider correlation because it will perform well in capturing monotonic associations. Hence, the CTree algorithm Hothorn et al. (2006) available in the R package partykit (and its predecessor "party") uses this criterion by default for the numeric-vs-numeric situation (suitably standardized). See this discussion for more details: What is the test statistics used for a conditional inference regression tree?
The formulation of the splitting criteria in CTree is also such that it generalizes to other association tests when one or both of the variables are not numeric. For example, in the categorical-vs-categorical situation a $\chi^2$ statistic is used.
If it is a potential concern that associations are not monotonic, one potential idea is to use a maximally-selected statistic over all possible split points. This is also possible, see: Explanation of different testtype and teststats in ctree in party package of R
Comment: You just helped 20+ students. Thanks a lot.
Comment: Wow, glad I could help.


Can list comprehensions make groups?

Question: I have a list that looks like
[(1,2,5),(2,10,13),(5,24,56),(1,8,10),(2,3,11)]

How can I produce a dictionary by grouping by first element of tuples and finding min element in second elements and max element in third elements:
{1:(2,10),2:(3,13),5:{24,56}]

Comment: Why does it have to be a list comprehension (or rather a dictionary comprehension) here? Especially when you have to produce both a minimum *and* a maximum value, the expression will get ugly and large fast. A proper loop will make the code a lot more readable, *and* more efficient as you then don't have to sort.
Answer: You can, if you first sort on the grouping element, then use itertools.groupby() to group your elements and test for minimum and maximum values. Because the groups are generators, you need to jump through an extra hoop to turn that into a list you can reuse for the min() and max() functions:
from itertools import groupby
from operator import itemgetter

result = {k: (min(item[1] for item in gv), max(item[2] for item in gv))
         for k, g in groupby(sorted(inputlist, key=itemgetter(0)), itemgetter(0))
         for gv in (list(g),)}

Note that this sorts (O(NlogN)) then loops over each group twice to find the minimum and maximum of each group, adding another 2N to the total.
The additional for gv in (list(g),) loop assigns a list to gv containing all elements from the g group.
The simple loop version would be:
result = {}
for key, v1, v2 in inputlist:
    minimum, maximum = result.get(key, (float('inf'), float('-inf')))
    if v1 < minimum:
        minimum = v1
    if v2 > maximum:
        maximum = v2
    result[key] = (minimum, maximum)

This is a straightforward O(N) loop, and more readable to boot.
Demo of the two approaches:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> inputlist = [(1,2,5),(2,10,13),(5,24,56),(1,8,10),(2,3,11)]
>>> {k: (min(item[1] for item in gv), max(item[2] for item in gv))
...          for k, g in groupby(sorted(inputlist, key=itemgetter(0)), itemgetter(0))
...          for gv in (list(g),)}
{1: (2, 10), 2: (3, 13), 5: (24, 56)}

and
>>> result = {}
>>> for key, v1, v2 in inputlist:
...     minimum, maximum = result.get(key, (float('inf'), float('-inf')))
...     if v1 < minimum:
...         minimum = v1
...     if v2 > maximum:
...         maximum = v2
...     result[key] = (minimum, maximum)
...
>>> result
{1: (2, 10), 2: (3, 13), 5: (24, 56)}

Answer: In [9]: ll = [(1,2,5),(2,10,13),(5,24,56),(1,8,10),(2,3,11)]

In [10]: {k[0]: ( min([kk[1] for kk in ll if kk[0] == k[0]]), max([kk[2] for kk in ll if kk[0] == k[0]]) ) for k in ll}
Out[10]: {1: (2, 10), 2: (3, 13), 5: (24, 56)}

or
In [11]: {k[0]: (v[0], v[-1]) for k in ll for v in [sorted([x for y in [[kk[1], kk[2]] for kk in ll if kk[0] == k[0] ] for  x in y])] }
Out[11]: {1: (2, 10), 2: (3, 13), 5: (24, 56)}

Comment: This'll work, but will show quadratic behaviour and so isn't useful for long lists.

Can list comprehensions make groups?


A good introduction to Elliptical Curves from an advanced High School background.

Question: I am looking for a manageable introduction to elliptical curves from a High School background. I am willing to read material. I'm aiming for a introductory undergraduate level of understanding of such curves and their properties. I want to do a little personal research into these curves and maybe explore some simple properties on my own. I came across them because I heard that this was the math behind some cryptographic methods and also the blockchain concept uses this.
Thank you
Comment: You should really learn the more basic higher math first, that way you'll get more out of any textbook. Have you taken complex analysis yet? Try it.
Comment: I think it may be very difficult, and even discouraging, to try to tackle such a stuff without first having *at least* some basics in abstract algebra and complex analysis...not to mention some mathematical maturity. Don't do that to yourself. Better, imo, try to tackle the undergraduate basic material needed to understand elliptic curves.
Comment: @mtheorylord I would love to but don't have the time right now. I don't know if you recognize it but I study in the IB curriculum and was considering this for a Math HL IA. (it's like a mini project where you 'explore' or 'investigate' a topic.)
Comment: @DonAntonio I don't know if you recognize it but I study in the IB curriculum and was considering this for a Math HL IA. (it's like a mini project where you 'explore' or 'investigate' a topic.) This is mainly because they seemed interesting when I looked it up. I think some of the complexity and difficultly was hidden behind the relatively simple introduction found on Wikipedia.
Comment: Nop, I don't recognize it, but I just read now that is a baccalaurate studies, and to me this sounds like high school level. Anyway, the very basic stuff needed there involve group theory, advanced analytic geometry, real (and pretty soon also complex) analysis, etc.
Comment: @DonAntonio Ah well. I guess I'll go look for something interesting in real analysis. Do you have any starting points? Something that is accessible by someone of my level and could feasibly be the topic of a mini project of sorts.
Comment: Since you have an interest in math related to cryptography, you might also be interested in focusing on the algorithms behind RSA or Diffie-Hellman key exchange. The math is much simpler than what would be needed for elliptic curves, and should be well suited for a high school student. They also introduce some basic concepts which are used throughout number theory and algebra such as modular arithmetic and group theory.
Comment: @TobErnack Thanks, I'll look into it. I actually did initially arrive at RSA but my only concern was that it's a topic that has been exhausted by others before me. (I don't know if you recognize it but I study in the IB curriculum and was considering this for a Math HL IA. (it's like a mini project where you 'explore' or 'investigate' a topic.)) So I guess I will rack my head trying to find an original approach to this. I know this is kinda going off topic, but calculus is of great interest to me as well.
Comment: @TobErnack However, due to its sheer size and vastness, I get hopelessly lost trying to find a challenging yet doable idea for such a project. I either end up on the research page of some university where I don't understand a word or I find something too elementary. Do you know a good 'middle ground' that you might point me towards. It would be of immense help.
Comment: Try googling ["elliptic curve" AND "honors thesis"](https://www.google.com/search?q=%22elliptic+curve%22+%22honors+thesis%22) (or substitute something else for "elliptic curve" if you want to consider other topics).
Answer: Rational Points on Elliptic Curves
Authors: Silverman, Joseph H., Tate, John T.
May still be a bit advanced but would probably be the most approachable.
Comment: Is this accessible to a HS student (IB diploma math HL if you recognize it)
Comment: I thank you for the answer though and I will definitely look for a copy and try getting through it.
Comment: The authors state "Our main goal in doing this has been to write a textbook in a technically difficult field which is "readable" by the average undergraduate mathematics major."
Comment: Well I think this is the closest I'll get, I'll take a look. Thanks


How do I factor a polynomial over the reals?

Question: $$2x^4-5x^3-4x^2+15x-6$$
I got that there are 3 positive roots, and 1 negative root.
I also got that the possible rational roots are $$\pm\frac{1}{2},\pm1,\pm2,\pm\frac{3}{2},\pm3,\pm6$$
Am I just supposed to plug everything in?
Comment: Try using the possible rational roots you found.  If one of those is a root $r$, then divide that polynomial by $x-r$ to get a lower degree.  Repeat for cubic.  Then quadratic polynomials you can use the quadratic formula.
Comment: Indeed ${}{}{}$
Comment: @Euler....IS_ALIVE Just to make sure, when I plug them in, and 0 is the result, it's a root right?
Comment: The Maple command $$factor(2*x^4-5*x^3-4*x^2+15*x-6) $$produces $$(x-2)(2x-1)(x^2-3) .$$
Answer: $2x^{4}-5x^{3}-4x^{2}+15x-6=2(x^{4}-2x^{2}-3)-5x(x^{2}-3)=2(x^{2}-3)(x^{2}+1)-5x(x^{2}-3)$
$=(x^{2}-3)(2(x^{2}+1)-5x)=(x-\sqrt{3})(x+\sqrt{3})(2x^{2}-5x+2)=(x-\sqrt{3})(x+\sqrt{3})(2x-1)(x-2)$
Comment: Brilliant, but you kind to got to see that. (I did not) Fortunately there are real zeros to factor this problem
Answer: Sometimes, you'll "see" something clever you can do, as did user71352 found. That can save one a good amount of work.
However, when inspiration has escaped us, one more methodological route to go with this type of a problem is to "test out" possible rational roots $x_i$ of your polynomial $p(x) = 2x^4-5x^3-4x^2+15x-6$, by substituting "candidates" into $p(x)$ and testing if $p(x_i) = 0.\;$ You've done a nice job of determining the candidates. Testing promising roots, you'll find that $x_1 = \frac 12$ and $x_2 = 2$ are both roots.
Once you have even just one root, say $x = a$, divide a given polynomial by the factor $(x - a)$. In our case, we know two factors, each factor corresponding to one of the two roots we have: $(x - \frac 12)$ and $(x - 2)$.
So we can divide your polynomial $p(x)$ by the product of the factors  $$\left(x - \frac 12\right)(x - 2) =x^2 - \frac 52 x + 1$$ to determine the remaining quadratic:$$\frac{2x^4-5x^3-4x^2+15x-6}{x^2 - \frac 52 x + 1} = 2x^2 - 6 = 2(x^2 - 3).$$ This is a difference of squares, which factors nicely, thus revealing the roots $x_3,\; x_4 = \pm \sqrt 3,\,$respectively, which are the two remaining roots of $p(x)$.
To summarize, we have the polynomial $$p(x) =  2x^4-5x^3-4x^2+15x-6 = 2\left(x - \frac 12\right)(x -2)(x + \sqrt 3)(x -\sqrt 3)$$ with roots $$x_1 = \frac 12, \;\;x_2 = 2,\;\;x_3 = -\sqrt 3,\;\;x_4 = \sqrt 3$$


Performance for mongo aggregation query with match (2 fields) and sort (1 fields from matching)

Question: I have a lot of records in mongo database. And I try to perform aggregation query.
My query is:
db.collection.aggregate([
 {
    "$match": {
       "$or": [
          {
             "field1": {
                "$regex": ".*\\Q...\\E.*", // where ... - any text
                "$options": "i"
             }
          },
          {
             "field2": {
                "$regex": ".*\\Q...\\E.*", // where ... - any text
                "$options": "i"
             }
          }
       ]
    }
 },
 {
    "$sort": {
       "field1": 1
    }
 },
 // another operations, such as limit, skip
])

But I have a problem, this matching is very slow.
I have following indexes:
{
   "field1": 1
}

{
   "field2": 1
}

{
   "field1": 1,
   "field2": 1
}

But when I remove match for field2 this query works faster
In all my cases the regex in match the same for field1 and field2, therefore I try to unite this field into one field as field1AndField2 on the application level and add index for this field. Also this works slow, but when I use this field in sort, the query works faster, but I can't use this field in sort, it's affect final result.
Do you have any idea about this issue?
UPDATE 07.06
Added explain of the aggregation query with compound index:
{
  "stages": [
    {
      "$cursor": {
        "query": {
          "$or": [
            ... // or with two fields
          ]
        },
        "sort": {
          ... // sort with field1
        },
        "queryPlanner": {
          ...
          "parsedQuery": {
            "$or": [
              ... // or with two fields
            ]
          },
          "winningPlan": {
            "stage": "SUBPLAN",
            "inputStage": {
              "stage": "FETCH",
              "filter": {
                "$or": [
                  ... // or with two fields
                ]
              },
              "inputStage": {
                "stage": "IXSCAN",
                "keyPattern": {
                  "field1": 1,
                  "field2": 1
                },
                "indexName": "...", // index name
                "multiKeyPaths": {
                  "field1": [],
                  "field2": []
                },
                ...
                "indexBounds": {
                  "field1": [
                    "[MinKey, MaxKey]"
                  ],
                  "field2": [
                    "[MinKey, MaxKey]"
                  ]
                }
              }
            }
          },
          "rejectedPlans": []
        }
      }
    }
  ]
}

Comment: What does explain() tell you, e.g.:
`aggregate([ your pipeline ], {explain:true})`
If you are not seeing 2 input stages for the OR both using IXSCAN, then something else is going on.
Comment: @BuzzMoschetti Thank you for your interest. I updated my question with additional information, which contains explanation about the aggregation query with compound index for field1 and field2. If you want more additional information, please notify me about this.
Answer: Did you try by changing $or and $match positioning?
db.collection.aggregate([
     {
      "$or": [
        {
          "$match" : {
            "field1": {
              "$regex": ".*\\Q...\\E.*", // where ... - any text
              "$options": "i"
            }
          }
        },
        {
          "$match": {
            "field2": {
              "$regex": ".*\\Q...\\E.*", // where ... - any text
              "$options": "i"
            }
          }
        }
      ]
     },
     {
        "$sort": {
           "field1": 1
        }
     },
     // another operation, such as limit, skip
    ])

Comment: Thanks for your advice. But it's leads to error : unrecognized pipeline stage name '$or'


Do SCCM 2012 R2 Maintenance Windows Inherit?

Question: Does anyone know if Maintenance Windows Inherit in SCCM 2012 R2?
Lets say I create a Device Collection called Monday Updates that has a Maintenance Window of 2100 to 0400 Monday morning.
If I then create another Device collection Called Windows Server 2008 R2 that references the Monday Updates Device Collection but does not have a Maintenance Window, will the Windows Server 2008 R2 Device Collection inherit the Maintenance Window from the Monday Updates Device Collection?
Answer: You use a Collection to apply a Maintenance Window to machines. Once that Window is applied to a machine, then it's applied to that machine, any Deployments on any Collection that machine is also a member of can take advantage of any Maintenance Window that the machine has picked up.
During that maintenance window the machine will look for any active, applicable Deployments that fit within the Maintenance Window (by comparing the Max run time set on the patch or install to the remaining time left in the Maintenance Window) and then run them one by one (re-evaluating the remaining time at the end of each install).
It doesn't matter which Collection applied the Maintenance Window, or which Collection applied the Deployment, just so long as the machine is a member of both Collections.
So it depends what you mean by "references a collection". When you double click the collection in the console and see the list of machines that match its rules does the machine in question show up in that list? If so it will pick up any MWs or Deployments set on that collection, if not then it won't. Inheritance isn't the important thing, whether a machine is a member of a collection is.
Comment: That does kind of answer my question.  What I meant by "references a collection" was that, when I created the Windows Server 2008 R2 collection, for membership rules I choose the "Include Collections" option and selected the Monday Updates device collection.
Comment: In your response you said that "During that maintenance window the machine will look for any active, applicable Deployments ... and run them".  Does this include optional updates or only required?
Comment: I can't 100% say (as there's no overlap between where we have maintenance windows and where we have optional deployments) but I would be pretty sure that only required deployments would be automatically installed during a maintenance windows. After all it's a bit irrelevant to optional deployments as a human on the machine effectively clicks a button to say "I want this on here now", so they're making the decision about when is OK for maintenance.


Why connecting to a high SSH port number takes longer than a lower port number?

Question: I have a Linux server to SSH, and the old port number was 1818. Recently there's been a network issue in my country that I had issue reaching my server port 1818. So I decided to change it to another port, like 46000. I then changed it to lower port number like 1994, and it worked well too.
But the issue is time I wait to get the first response when trying to do SSH port number 46000 is much longer than time spending on 1994.
Let me first explain my assumption: when I use ssh root@ip -p1994, my network checks the ports from 1 to 65535, and because 1994 is lower than 46000, so it takes less time to connect than 46000. My assumption is something like this:

check if port is correct:
is 1 SSH port? if no, ignore; else connect.
is 2 SSH port? if no, ignore; else connect.
...
is 1994 SSH port? so I (my network) and the server connect to each other.

While 46000 is much more down in my assumption, then it takes much longer to connect.
Is my assumption for this issue correct? If no, then what is the logic of this delay in connecting?
Thanks in advance
Comment: Your assumption is wrong. There should be no difference, regardless of the selected port.
Comment: Thanks, but you mean the time it takes to connect to another server's port number 1 should be the same as 65535? I did not find any articles or question whether my assumption is right or wrong. The you mean they should have the same time? Do you believe there's an issue in my network that takes time?
Answer:
Let me first explain my assumption: when I use ssh root@ip -p1994, my
  network checks the ports from 1 to 65535

This assumption is incorrect. Packets will be sent to port 1994 immediately.  No need to do anything like a port scan.
An analogy: there is no need to check every apartment in a residential building before mailing a parcel to a street address. The mail piece just goes straight to the destination.

Ask your service provider which port you can run a ssh service on, ideally 22/tcp. Colocated datacenter hosting or public clouds tend to rely on ssh and allow it.  Residential Internet services tend to discourage running "servers".


Create an unbreakable ideal image/snapshot of an operating system, save that to the external hard disk, and load an operating system from that disk

Question: I am technical maintainer of 60 computers.
The purpose: I want to have the computers that are not volunerable from naive actions of users and virures.
Implementation: to have an operating system loaded from an image(here, image does not refer to some specific file image format, it's just an abstraction).
So every time when the operating system (for example windows) will be loaded the content of OS , installed programs, everything will be load from the saved image.
Again, the question is not about how to install windows to 60 computers, the question is how to make the single image and then load operating system from it on 60 computers.
Of course I wanna to be able to modify the image, if I disliked some installed program, I can uninstall that from image. So there will be some kind of audit mode. After entering to audit mode I can do changes, then save the image. And next time it will load the new image.
Again, if you want to suggest acronis true image, then, probably you haven't understand the question. as I know,acronis true image is only for fast system cloning .
Also the image should be stored in some unmarked(no letter) parition which is not seen from windows or ubuntu.
It will be good if the image can load grub, and then using grub I can load Windows or Linux.
So the image will be kinda virtualization of hard disk.
Edit: Additonally, it will be good to make loading an OS from central server using network.
Thanks,
Nusrat
Comment: Are you saying you want the computer to boot from an image that cannot be modified by the end-users each time they start the machine? Or are you wanting to create an image for deployment?
Comment: Does it have to be windows ?
Comment: Windows is mandatory. Windows + Ubuntu is optional.
Comment: Does it need to be for physical PCs, or can it be a VM-centric solution?
Comment: @Raystafarian First one, an image that cannot be modified by the end users each time they start machine. However, an easy deployment of unmodifyable image is an additional great bonus.
Comment: Then why not create a virtual environment for your users? Whether it's connecting to a virtual server or making them run a virtual machine? That seems to be what you want.
Comment: @MichaelKjörling Yes, it need to be for physical PCs. Also the physical mahcines are almost have same hardware configuration. What is Virtual Machine-centric solution? what do you mean?
Comment: I suppose that answers @Raystafarian's question, too.
Comment: @Raystafarian What is a virtual environment? Could you provide conrete examples? What is the complexity of virtual environment implementation? And the most important what is the speed of virtual environment (Computers have only 2gigs of ram and 2.6 Ghz of Core2)? Is virtual environment good, if the en-users are developers, students?
Comment: [I'd start here with desktop virtualization](http://en.wikipedia.org/wiki/Desktop_virtualization)
Comment: http://technet.microsoft.com/en-us/library/gg176676%28WS.10%29.aspx
Answer: Your description looks like Windows 7 SteadyState solution: http://blogs.technet.com/b/panosm/archive/2011/07/07/windows-7-steadystate-solution-simplified.aspx


H2 Database Primary Key Violation

Question: I am trying to make inserts on a table with a Primary key composed of 2 attributes. However when I try to make an insert and one of the attributes in the primary key is identical to one already inserted I get the following error:
Unique index or primary key violation: "CONSTRAINT_INDEX_CCC ON PUBLIC.ABWESENHEIT(DATUM) VALUES

Here is my table:
Create TABLE Abwesenheit (

    s_id INTEGER NOT NULL REFERENCES Schueler(id) ON DELETE CASCADE,
    entschuldigt BOOLEAN DEFAULT FALSE,
    datum TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    kommentar VARCHAR(40),
    kalendereintrag_id VARCHAR(40) REFERENCES Schoolsubject(name) ON DELETE CASCADE,
    deleted BOOLEAN DEFAULT FALSE,
    PRIMARY KEY (s_id,datum)

);

And here are 2 inserts which reproduce the problem:
insert into Abwesenheit (s_id, entschuldigt, kommentar,datum,kalendereintrag_id) values (1,'false','','2015-12-21 11:59:00.0','Geschichte');
insert into Abwesenheit (s_id, entschuldigt, kommentar,datum,kalendereintrag_id) values (2,'false','','2015-12-21 11:59:00.0','Geschichte');

Even though the "datum" attribute defaults to CURRENT_TIMESTAMP, I need to be able to insert custom timestamps (i.e. for retroactive entries)
.
Given the fact that the "s_id" is different in the two inserts they should work. However they do not. Any ideas on what might be causing the problem?
Thanks in advance!
Comment: CONSTRAINT_INDEX_CCC suggests it may not be the primary key that is raising this error.  Do you have a 2nd unique index on your table?
Comment: Perhaps a constraint instead?  You can test if datum is limiting you to unqiue values by changing one of the date/times to 12:00:00.  I'm sure you've already checked this, but it is also worth double checking you don't have any existing records that conflict.
Comment: I did that and yes it lets me insert it. Datum appears to be the problem but I don't understand why it acts this way.
Answer: The problem was caused by another table which was referencing my table, under the assumption that the dates in the table Abwesenheit were unique.

H2 Database Primary Key Violation


Memory space of kernel arguments in CUDA __global__ function

Question: In a CUDA function like the following:
__global__ void Kernel(int value) {
    value += 1;
    ...
}

void Host() {
    Kernel<<<10, 10>>>(123);
}

Is the memory space of value inside Kernel device (global), shared, or local?
If one thread modifies it, will that modification become visible to other threads? Or is the variable located on the stack of each thread, as with variables defined inside the function?
Comment: @AnderBiguri: Arguments to kernels are stored in a dedicated constant memory bank on all hardware except compute 1.x, which used shared memory. No registers involved
Comment: None of the above
Comment: `value` is passed by value to each kernel, generally its stored in a register. If the kernel has too many registers in use, it may store in a form of global variable, but in any case, when passed by value, the value is local to each kernel.
Comment: My mistake! thanks for the clarification!
Answer:
Is the memory space of value inside Kernel device (global), shared, or local?

It is in the logical local space.  Kernel parameters start out in a particular bank of __constant__ memory as part of the kernel launch process.  However for most actual usage, the parameter will first be copied to a thread-local register, which is part of the logical local space.  Even for SASS instructions that are not LD but can refer to the __constant__ memory, the usage is effectively local, per-thread, just like registers are local, per-thread.

If one thread modifies it, will that modification become visible to other threads?

Modifications in one thread will not be visible to other threads.  If you modify it, the modification will be performed (first) on its value in a thread-local register.

Or is the variable located on the stack of each thread, as with variables defined inside the function?

The stack is in the logical local space for a thread, so I'm not sure what is the purpose of that question.  A stack from one thread is not shared with another thread.  The only way such a variable would show up on the stack in my experience is if it were used as part of a function call process (i.e. not the thread itself as it is initially spawned by the kernel launch process, but a function call originating from that thread).
Also, variables defined inside a function (e.g. local variables) do not necessarily show up on the stack either.  This will mostly be a function of compiler decisions.  They could be in registers, they could appear (e.g. due to a spill) in actual device memory (but still in the logical local space) or they could be in the stack, at some point, perhaps as part of a function call.
This should be mostly verifiable using the CUDA binary utilities.


If $f \in F[x]$ irreducible, ${\rm char}(F) = p$, then $f(x) = g(x^{p^e})$ and every root of $f$ has multiplicity $p^e$ in some splitting field

Question:
Let $f(x)$ be irreducible in $F[x]$, $F$ of characteristic $p>0$. Show that $f(x)$ can be written as $g(x^{p^e})$ where $g(x)$ is irreducible and separable. Use this to show that every root of $f(x)$ has the same multiplicity $p^e$ (in a splitting field).

I have been able to prove that $f$ can be expressed in terms of $g(x^{p^e})$, where $g$ is irreducible and separable. Also what is the relation between the splitting field of $g(x)$ over $F$ and the splitting field of $f(x)$ over $F$?
Comment: to get  your case, put g=f and e=0
Comment: Note that since $p$ is prime, $p\mid {p^e\choose n}$ for all $0 < n < p^e$. Then consider $(x - \omega)^{p^e} \mod p$.
Answer: Hint: Prove that for all $h\in F[x]$ you have $h(x^{p^e})=\operatorname{Frob}^eh(x)^{p^e}$.
Details: For every prime number $p$ and every positive integer $e$ the binomial coefficient $\tbinom{p^e}{k}$ is divisible by $p$ for all integers $k$ with $1<k<p^e$. It follows that for all $c\in\Bbb{F}_{p^e}$ and all $r\in\Bbb{F}_{p^e}[x]$ you have
$$(cx^n+r(x))^{p^e}=c^{p^e}(x^n)^{p^e}+r(x)^{p^e}=\operatorname{Frob}^e(c)(x^{p^e})^n+r(x)^{p^e}.$$
By induction on the degree of $h$ it follows that $h(x)^{p^e}=\operatorname{Frob}^eh(x^{p^e})$ for all $h\in\Bbb{F}_{p^e}[x]$. In particular, this shows that every root of $h(x^{p^e})$ has multiplicity $p^e$, or a multiple thereof, and if $g\in F[x]$ is separable then every root of $g(x^{p^e})$ has the same multiplicity $p^e$.
Comment: How do you show that h(x^(p^e))=h(x)^(p^e)? I'm trying but I'm not getting it.
Comment: @tony I have added a few details. I see that I assumed that $F\subset\Bbb{F}_{p^e}$ earlier, which is of course not true in general; I've edited to cover your more general setting.
Comment: I have come across the Frob concept. Is there no other way to proceed?
Comment: @tony All you need to know for this question is that the map $c\ \mapsto\ c^{p^e}$ is an injective endomorphism of $F$, which is not hard to show.


"Connection was reset" accesing apache2 virtualhost through wsl1 and /etc/hosts

Question: I am new with linux but am trying to install koha (a library management system) through  Debian 10 on my laptop using windows 10 ver.1903 (build 18362.900) and  wsl1 as a test for installing it in my library.
I followed the instructions here: https://wiki.koha-community.org/wiki/Koha_on_Debian and managed to get up to installing apache2. The version I have is apache 2.4.38
I then set up the domain through virtual hosts using this: https://wiki.koha-community.org/wiki/How_to_set_up_a_domain_name_for_Koha.
So debian /etc/hosts file was setup like so (I also put the same in the windows /etc/hosts file):
127.0.0.1 localhost
127.0.1.1 LAPTOP.localdomain LAPTOP
192.168.x.y lmc.mydomain.org
192.168.x.y lmc.mydomain.org

However  when  I try to access it through the browser Firefox says "Connection  was reset." localhost loads the apache2 default webpage correctly however, and when I input the ip  directly, it loads the default apache2 web page instead.
Here is the apache2/sites-enabled/lmc.conf file generated by koha
https://i.stack.imgur.com/MgYxJ.jpg
apache2ctl -S shows the proper domain (rootfile) relationships:
VirtualHost configuration:
*:80 is a NameVirtualHost
default server LAPTOP.localdomain (/etc/apache2/sites-enabled/000-default.conf:1)
port 80 namevhost LAPTOP.localdomain (etc/apache2/sites-enabled/000-default.conf:1)
port 80 namevhost lmc.mydomain.org (/etc/apache2/sites-enabled/library.conf.:4)
port 80 namevhost lmc.mydomain.org(/etc/apache2/sites-enabled/library.conf:22)

apache2/error.log shows the following whenever I try to connect through browser:
[timestamp]  [mpm_itk:warn] [pid 82] (itkmpm:pid=82 uid=33, gid=33)  itk_post_perdir_config() : initgroups(library-koha), 1001) : Operation  not permitted
[timestamp] [mpm_itk:warn] [pid 82] Couldn't set uid/gid/priority, closing connection.

When I start apache2 it shows:
apache2[timestamp] [core:warn] [pid139] (92)Protocol not available : AH00076: Failed to enable APR_TCP_DEFER_ACCEPT
.ok

However  since it shows green ok, I figured that particualar warning is ok to  ignore..? localhost default webpage works correctly anyhow.
I tried clearing the cache, added exceptions/turned off windows firewall and antivirus but those didn't work.
I'm  pretty much been stuck by more than a week on what to do, could someone please provide me some help on how I proceed? I don't need ssh connection (through that would be a bonus), just need it to work locally (hence the use  of /etc/hosts). Any help would be much appreciated, thank you!
Answer: Why are you using mpm_itk? This doesn't work on WSL (and probably never will) as the error messages indicate. I also don't see anything in the wiki you linked to that would explain why it is necessary.
You should remove this package:
apt purge libapache2-mpm-itk
a2enmod mpm_prefork

If you really intentionally installed mpm_itk for a specific reason, then you should stop using WSL and create a virtual machine instead. You should probably do that anyway.


What does the degree of freedom (df) mean in the results of log-likelihood `logLik`

Question: After doing the regression using lm for fixed effect model or lmer for mixed effects model, I pass the results to the logLik. Besides the value of log-likelihood, the function always returns a df, i.e. the degree of freedom.
However, the degree of freedom does not equal to the number of parameters in the model, df always larger. So what does the df mean exactly?
The reason I care about the df is that later I will use the BIC (Bayesian Information Criterion) to do the model selection. The BIC is defined as
BIC=-2*logLik+k*log(n) where k is the number of parameters and n is the number of observations. When I pass my logLik value to the expression of BIC, the result is exactly the same when I use the build in BIC function in R if I specify the number of parameters as the df in logLik. Which means, in the build in BIC function, they also use the df as k when they calculate BIC.
Comment: Possible duplicate of [How to understand degrees of freedom?](https://stats.stackexchange.com/questions/16921/how-to-understand-degrees-of-freedom)
Comment: Usually it is something like sample size minus number of parameters estimated. It can be a little more complicated though. Read the suggested question yours is a duplicate of.
Answer: The help file for the logLik() function mentions that it returns the number of (estimated) parameters in the model as the degrees of freedom (df).
If you fit a linear model like the one below:
m <- lm(mpg ~ hp, data = mtcars)

summary(m)

logLik(m)

you will see that the model includes an intercept parameter, a slope parameter quantifying the effect of the predictor hp on mpg and an error variance (or standard deviation) parameter. These add up to three parameters, which is exactly what logLik() returns for the model.
If you fit a linear mixed effects model like this:
require(nlme)

M <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)

summary(M)

logLik(M)

then you'll see that the model includes the following parameters: a fixed effect intercept, a fixed effect of age, a fixed effect of Sex, a parameter denoting the standard deviation of the random intercept and a standard deviation of the within-subject model errors. That makes for five parameters, which is what the logLik() returns.


Functions and Algebra question

Question: Given that $f(t) = 2t^2 + 4$, $f(4x + 2) = 2(16x^2 + 4) = 32x^2 + 12$.
This is incorrect and I have no idea why, the correct answer is
$2(16x^2 + 16x + 4) = 32x^2 + 32x + 12$.  I can't work out where $16x$ came from.
Answer: You have to square the whole thing! What is $(a+b)^2$?
Here is how to deduce the correct answer, see if you can justify each step:
$(4x+2)= t \implies f(t)=2t^2+4=2(4x+2)^2+4=2(16x^2+16x+4)+4$.
Answer: Guide:
Evaluate $$2(4x+2)^2+4$$ again.
Note that $(A+B)^2 = A^2+2AB+B^2$.
Answer: \begin{eqnarray*}
f(t)&=&2t^2+4 \\
f( \color{blue}{4x+2})&=& 2(\color{blue}{4x+2})^2+4.
\end{eqnarray*}
Answer: You've made the mistake of thinking that $(4x+2)^2$ is $16x^2 +4$.
That would work if the "$+$" were "$\times$", but exponents don't distribute over terms in a sum.
Instead, remember that
$$(4x+2)^2=(4x+2)(4x+2)$$
$$=4x(4x+2) +2(4x+2)$$
$$=(16x^2+8x) +(8x+4)$$
$$=16x^2 + 16x +4$$
and proceed from there.

Functions and Algebra question


Checking two ranges in different workbooks (run time error 424)

Question: I am trying to check whether the values in workbook1-sheet1-A are matched in workbook2-sheet2-E. If there is a match workbook1-sheet1-Y receives a 'x'.
This is the code I have so far and gives me Run time error 424 - Object required error on the if loop.
Sub Check()
'
Application.ScreenUpdating = False

endRow = Range("A" & Rows.Count).End(xlUp).Row

wkbSLA = ("F:\Workbook2")

For i = 2 To endRow
    If Cells(i, 1).Value = wkbSLA.Sheets("Sheet2").Range("E2:E575").Value Then
        Range("Y" & i) = "x"
    End If
Next i

'
End Sub

Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Comment: What line is the exception being thrown on?  Also, is `wkbSLA' already open?
Comment: @Trisped, wkbSLA doesn't need to be opened, it's a dump file. It's being thrown at `If Cells(i, 1).Value = wkbSLA.Sheets("Sheet2").Range("E2:E575").Value`
Answer: To ensure your code is doing everything you expect it to it, make sure you qualify your objects with variables.
Also, you cannot use the .Value property on multi-cell range. That is probably where your error is hitting. A better way to approach this is with the .Find method.
If you write the code something like this, it should work for you ... though you may need to tweak it a bit to meet your needs.
Option Explicit

Sub Check()

Application.ScreenUpdating = False

Dim wkb1 as Workbook, wkb2 as workbook
Set wkb1 = Workbooks("workbook1")
Set wkb2 = Workbooks("F:\Workbook2")
' -> do you need Workbooks.Open("F:\Workbook2") here?
' Seems you may if the workbook you want to access is closed

Dim wks1 as Worksheet, wks2 as Worksheet
Set wks1 = wkb1.Sheets(1) 'may need to change this reference for your needs
Set wks2 = wkb2.Sheets("Sheet2")

With wks1

    Dim endRow as Long
    endRow = .Range("A" & Rows.Count).End(xlUp).Row

    Dim i as Long
    For i = 2 To endRow

        Dim rng as Range
        Set rng = wks2.Range("E2:E575").Find .Cells(i,1).Value lookat:=xlWhole

        If Not rng Is Nothing Then .Range("Y" & i) = "x"

    Next i

End With

End Sub

Comment: Is it possible you're missing something in the `IF`? Do you need to open the workbook to be able to search the content?
Comment: @t.thielemans -> I can't tell if the workbook is open or not. I left that comment in the code. That's for the OP to distinguish. AFAIK, a workbook has to be opened to search through, at least in VBA. Am I wrong about that?
Comment: I don't know, that's why I was asking you ;) but I receive an error on `If wks2.Range("E2:E575").Find cells(i,1).Value lookat:=xlWhole Then .Range("Y" & i) = "x"`, as if something were missing
Comment: @t.thielemans -> something was missing. In fact 2 things. 1) the error trap, 2) the `.` in front `Cells`. Both are updated in my edit :)
Comment: @t.thielemans -> can you verify if you need the workbook open to search the content. I am almost positive you do.


VBA - Object doesn't support this property or method

Question: I am receiving the error "Object doesn't support this property or method",  in Excel after I changed part of my code. The line that is throwing the error is "With odoc.MailMerge" Here is the code:
<code>  strBookName = "\" & "PM MailMerge.xlsm"
  strBookPath = ActiveWorkbook.Path
  strBook = strBookPath & strBookName

'Opens Word.Application

  Set ObjWord = CreateObject("Word.Application")
  Set odoc = GetObject(strBook)

'Executes a Hidden Mail Merge

  ObjWord.Visible = False
  With odoc.MailMerge
  .Destination = wdSendToNewDocument
  With .DataSource
  .FirstRecord = 1
  .LastRecord = 1
   odoc.MailMerge.Execute
   Set odoc2 = odoc.Application.documents("Form Letters1")
   odoc.Close True
End With
End With
</code>
Answer: Try
<code>option explicit

Dim objWord as Word.Application
Dim oDoc as As Word.Document

Set ObjWord = CreateObject("Word.Application")
set oDoc = objWord.documents.Open strBook
</code>
Don't forget to reference the Word library in the menu: tools > references.
By the way: Dim all your variables (force with option explicit).
Edit:
Note: the file that you mention in your code sample is an Excel .xlsm, not a Word .doc...
Answer: Set odoc = GetObject(strBook) is this a workbook for excel?  if so there is no MailMerge method for a workbook object.  You need to reference a word document to use the MailMerge Method of the Document objet
Comment: Here is an example http://stackoverflow.com/questions/1357121/executing-word-mail-merge/10188431#10188431
Comment: Yes it is an excel workbook. The only part I have changed in my code was the **"Set odoc="** and then it stopped working


Can I override the title attributes on an H2 tag within a specific drupal region or block?

Question: I have a region within a site theme I'm working on, and would like the H2 title attribute to be white as opposed to the rest of the theme which calls for a blue. Can I use CSS to assign specific font size and color attributes to the title tag for that specific region/s within the theme?
Answer: You can use CSS to style the H2 tag inside a specific block.
Your block should have a unique ID, based on the name of the block.
Your CSS would look something like this:
<code><style>
#block-your-blockname h2 {
 color: white !important;
}
</style>
</code>
Note: you may not need "!important", and that CSS can go in your main CSS file if you want.
Comment: I'm sorry I missed this, thank you very much for responding, it was of course the right solution!


Link to load external content into DIV

Question: http://jsfiddle.net/9BCrs/5/
I have this set up to load a file into a DIV using the two links in the left DIV but it requires a unique copy of the same JQuery code each time there is a new link.
Is there a way of connecting the file being called and the DIV it is being called from to the link via some kind of variable maybe so that the code has to be included only once?
$(function() {
$(".link1").click(function() {
    $(".load_space").load("helloworld.txt", function() {
        //Insert contents of file wherever
        $(".block1").stop(true, true).animate({ left: -400 }, 200);
        $(".block2").stop(true, true).animate({ left: 25 }, 200);
    });
});

$(".link2").click(function() {
    $(".load_space").load("hellouniverse.txt", function() {
        //Insert contents of file wherever
        $(".block1").stop(true, true).animate({ left: -400 }, 200);
        $(".block2").stop(true, true).animate({ left: 25 }, 200);
    });
});

$(".link3").click(function() {
    $(".block2").stop(true, true).animate({ left: 450 }, 200);
    $(".block1").stop(true, true).animate({ left: 25 }, 200);
});
});

Answer: You can define your function once
var load_fct = function() {
    //Insert contents of file wherever
    $(".block1").stop(true, true).animate({ left: -400 }, 200);
    $(".block2").stop(true, true).animate({ left: 25 }, 200);
}

And reuse it where you need it:
$(".link1").click(function() {
    $(".load_space").load("helloworld.txt", load_fct);
});

Answer: There are a couple of ways.

Use a map in your code.
You could have a map in your code that tells you that link1 => helloworld.txt and link2 => hellouniverse.txt, like this:
var map = {
    link1: "helloworld.txt",
    link2: "hellouniverse.txt"
};

Then:
$(".link1, .link2").click(function() {
    var file = map[this.className]; // <=== Assumption here, see below
    $(".load_space").load(file, function() {
        //Insert contents of file wherever
        $(".block1").stop(true, true).animate({ left: -400 }, 200);
        $(".block2").stop(true, true).animate({ left: 25 }, 200);
    });
});

That assumes that the link1 or link2 class will be the only class on the element. If that won't be the case, you may have to massage className a bit before using it to look up the file.
Use data-* attributes.
Add a data-file attribute to your link elements, e.g.:

...

Then:
$(".link1, .link2").click(function() {
    var file = $(this).attr('data-file');
    $(".load_space").load(file, function() {
        //Insert contents of file wherever
        $(".block1").stop(true, true).animate({ left: -400 }, 200);
        $(".block2").stop(true, true).animate({ left: 25 }, 200);
    });
});

or instead of the $(".link1, .link2") selector, you could just use $("*[data-file]") or better yet, something a bit more targeted (since selecting purely on an attribute selector is a bit heavy). So perhaps $(".links[data-file]") for any element with class "links" that has a data-file attribute.
Comment: Awesome, I'm using #2 but I like both. Great help.

Link to load external content into DIV


Views Rewrite Results Shows "Delete Comment" shows as text to anonymous users

Question: I'm using a views to show my comments.
I've  Rewrite Results and add a delete comment field.
When users login they can click on the link
and delete the comment
But when a user is logout
any user can see [delete_comment] token
How do I hide the [delete_comment]token from anonymous users please?
Comment: what does it rewrite? is it the Delete Link Field? that field should obey permissions, so that if the user doesn't have permission to delete the content, the link doesn't show - but if you used a different method, you will have to include some php code or other functionality to perform a check manually I think
Answer: set the permissions for anonymous users that they can't see or delete the comment.
Comment: Where are the "permissions for anonymous users that they can't see or delete the comment" please? Because it's not in the admin/people/permissions settings. Thanks for your help


Is there a canonical "inverse" of Abelianization?

Question: We know that the abelianization of a free product is the direct sum, for example $Ab(\mathbb{Z}*\mathbb{Z})=\mathbb{Z}\oplus\mathbb{Z}$.
Is there a "canonical" (or even non-canonical) operator that reverses the process of Abelianization?
(For instance, it may goes from direct sum to free product?)
Thanks.
Comment: If you want a group with a given abelianization $A$, one choice is $A$. That is boring, but you're unlikely to get an interesting answer in a canonical way.
Answer: The abelianization functor, from the category of groups to the category of abelian groups, has a right adjoint, which is the forgetful functor, in other words the functor that sends an abelian group $A$ to the group $A$ itself. I guess this is as close to an "inverse" as you can reasonably hope.
Comment: Thanks for this answer.

Is there a canonical “inverse” of Abelianization?


Determining the equivalence of different subsets, unions and intersections?

Question: I'm currently working on some discrete mathematics work and I've encountered a question I'm not sure how to answer exactly. Precisely, I'm trying to prove that three separate statements are logically equivalent and my understanding of how to do that doesn't seem to be enough. The statements in question go as follows:

Prove that the three statements $A \subseteq E$, $A \cap \bar{E} =
 \varnothing$, and $\bar{A} \cup E = U$, where $U$ is a universal set,
  are equivalent.

Should I make some form of example set to better understand how these statements are equivalent? Any help is appreciated.
Comment: Draw a Venn Diagram. Then the solution will more or less write itself.
Answer: \begin{align}
A\subseteq E
&=\left\{x\in U|x\in A\to x\in E\right\}\\
&=\left\{x\in U|x\not\in A\lor x\in E\right\}\equiv\bar{A}\cup E\\
&=\left\{x\in U|\neg\left(x\in A\land x\not\in E\right)\right\}\\
&=\left\{x\in U|\neg\left(x\in A\land x\not\in E\right)\lor x\in\emptyset\right\}\\
&=\left\{x\in U|\left(x\in A\land x\not\in E\right)\to x\in\emptyset\right\}\equiv\left(A\cap\bar{E}=\emptyset\right)\Box
\end{align}


How to repeat in R

Question: I am a newbie in R, now I have a vector H(0.6,0.045,3), I want to create a matrix A, the number of rows of this matrix can be determined by myself, each row is the value of this vector:0.6,0.045,3. like this:
A (0.6,0.045,3,
   0.6,0.045,3,
   0.6,0.045,3,
   0.6,0.045,3,
  ............)

Answer: You can specify number of rows and columns in matrix function.
vec <- c(0.6,0.045,3)
nr <- 4
matrix(vec, nrow = nr, ncol = length(vec), byrow = TRUE)

#      [,1]  [,2] [,3]
#[1,]  0.6 0.045    3
#[2,]  0.6 0.045    3
#[3,]  0.6 0.045    3
#[4,]  0.6 0.045    3

Another option is to use replicate :
t(replicate(nr, vec))

How to repeat in R


Why bootstrap 3 only works in symfony2 dev mode, not in prod mode?

Question: just a silly quick question, i set up Bootstrap 3 follow by the steps from here. It works at dev mode but no prod mode. Just want to ask what kind of problem can cause that? If need codes, I will show it later. Thank you.
Comment: Did you run `app/console --env=prod assets:install web´ and ´app/console --env=prod assetic:dump´ on production server ?
Comment: what do you mean with "It not works in prod mode" - what does exactly not working? more information would be helpful.
Comment: You all right, I have to dump assets in prod mod. Cause I set "use_controller" as false. THX
Answer: You have to dump your assets on production. During development, assetic converts the assets each time you request them. Because that'll cost some time, it doesn't do this in production. So, you have to dump the assets (which means assetic only converts the assets once) in production.
<code>$ php app/console assetic:dump --env=prod --no-debug
</code>
Read more about this in http://symfony.com/doc/current/cookbook/assetic/asset_management.html#dumping-asset-files-in-the-prod-environment
Comment: Thanks, it's solved! In dev, I dont wanna dump the assets, it makes a lot files. But in prod, it seems better to use dump, its faster


How to add a user-friendly option to link to nodes from body text or text-field?

Question: I'm looking for an option or module that provides the possibility to link to other internal nodes avoiding the usage of full html in a text field. Users should be able to highlight a term and assign a link to it. It would be nice to have a kind of select-list containing the available nodes to link to.
I have done this before, but only for external links and with a minified editor. But i have no idea how to put a list of nodes there. Is there an alternative to achieve this?
Answer: Sounds like you're looking for the LinkIt module.

Linkit provides an easy interface for internal and external linking.
  Linkit links to nodes, users, managed files, terms and have basic
  support for all entities by default, using an autocomplete field. In
  7.x-2.4 there is also support for fields (text, textarea, and link).

If you have pretty paths I'd also suggest combining it with Pathologic, that way your links will have their path aliases applied rather than their direct links (i.e. node/123 will become about-us)
Comment: Thanks, Chapabu. That's exactly what I'm looking for. How could i miss that thang? :) I really did an extended search before...
Comment: It's easy to do sometimes :)


Understanding the YOLO algorithm

Question: I am trying to understand the logic behind object detection and the YOLO algorithm.  I have read numerous blogs, tutorials, videos, papers, yet I am still not sure if I understood it correctly.  Let's assume our network can predict three classes ---cat, dog, bird--- and we want to have $10 \times 10$ boxes.
1) We create CNN without FC layers, instead we use $1 \times 1$ Dimension Convolution layer.
2) We train it to input a $10 \times 10$ image, and output a vector with dimension of $1 \times 1 \times 5 \times 8$, where 5 is the number of anchor boxes and 8 is the number of features (the features are a confidence score, measuring how sure CNN is something is there, x, y, width, height, and indicator variables for the classes). In training, we say the object belongs to $10 \times 10$ that contains its center.
Questions: Do we put anchor boxes there or do we just train CNN to output random boxes there?  If we do the latter, while training it, how do we label them?  For example, if there is one small bird, do we divide him into these boxes or what's the trick?  How do we say the image belongs to some $10 \times 10$ boxes?  Also wouldn't this mean that all $10 \times 10$ boxes that does not contain center would get confidence score of zero?
3) We input our image into our CNN networks (that takes a $10 \times 10$ image).  Thanks to convolution the output will be $K \times K$, where $\forall i\in{K}$ is actually our vector of features.
4) We remove all boxes that have confidence scores $< 0.6$.
5) We use nonmax suppression to retrieve our boxes
Question: Is this correct?  Have I made any mistakes?
Comment: I have made a major edit to attempt to make this question clearer, and improve spelling and grammar.  There are still several aspects of the question that are unclear to me, where I was not sure how to edit.  @Darlyn: Please review my edit to ensure that it preserves what you want to ask.
Comment: https://www.youtube.com/watch?v=n9_XyCGr-MI
Answer: You have sort of lost me from the start. There are two notions of "boxes": one is the set of "grid cells", which the image is split into from the start, while the second is the set of bounding boxes which actually implement the detection of the objects. I will use the phrase "box to refer to the latter. I assume you meant the grid cells to be 10 by 10, since the bounding boxes do not have a fixed width or height.
(1) The pretraining is done with FC layers that are later discarded in favour of newly trained ones, but in all cases FC layers are present. See page 3 of the paper.
(2) I am not sure what you mean here, but it sounds like you think the network operates on one grid cell at a time. This is not the case, e.g. see page 2 of the paper:

Unlike sliding window and region
  proposal-based techniques, YOLO sees the entire image
  during training and test time so it implicitly encodes contextual
  information about classes as well as their appearance.

In essence, the network operates on the whole image simultaneously. More specifically, given an image cut into $S\times S$ grid cells, we output $BS^2$ bounding boxes (i.e. $B$ boxes per grid cell, where $B$ is a fixed constant), a total number which is constant across images (meaning the size of the FC layers can be constant). The boxes are not confined to that grid cell, rather, as noted on page 2:

The width and height are predicted relative to the whole image.

In essence, the centre of the output boxes (per grid cell) are confined to that grid cell, but the box itself can grow outside that boundary.
So, regarding your question "while training how do we label them", we do two things: (a) the object should be detected by the specific grid cell in which its centre resides, meaning boxes centered in other grid cells will ignore it (this is implemented in the loss function's masks), (b) the "label" consists of the properties of the ground truth object class and its class, which is learned by minimizing several losses: (i) matching the coordinates of the centres and the size of the box, (ii) being confident in an object existing only if an object is actually present (and vice versa if one is not), and (iii) a classification loss for which object is actually there.
Regarding the loss function, check out these two questions: [1] and [2].
With respect to your question "If there is for example one small bird, do we divide him into these boxes or whats the trick?", here's what will happen in various cases. If she is entirely in one grid cell, we will try to produce one box centered on the bird, that exactly encapsulates it. If she crosses between two grid cells (i.e. lies on a boundary), we will try to produce a box whose center is in the same box as here, but the box itself spills outside the grid cell.
We prevent multiple boxes per object by (I) only having the grid cell containing the target's centre predict it, (II) during training time only having the predicted box with the best overlap be considered in the loss (i.e. the training itself encourages specialization of local boxes), and (III) non-maximum suppression (especially useful when she is near the boundary).
Notice that because $B$ is constant, we can run into issues if there are many little birds in one box; as the authors note (page 4):

YOLO imposes strong spatial constraints on bounding
  box predictions since each grid cell only predicts two boxes
  and can only have one class. This spatial constraint limits
  the number of nearby objects that our model can predict.
  Our model struggles with small objects that appear in
  groups, such as flocks of birds.

(3) Again, the whole image is processed by the network at once. In other words, the entire predictor can be viewed as a single function
$$f : \mathcal{I} \rightarrow \mathbb{R}^{S\times S\times(5B+|C|)} $$
where $\mathcal{I}$ is the space of RGB images and $C$ is the set of categories considered by the classifier.
(4-5) Seems fine.
Hopefully that helps.

Understanding the YOLO algorithm


Problema apresentação de textos no php com editor tinymce

Question: Tenho um gestor com o editor HTML tinymce, mas cada vez que insiro uma informação no banco, ao apresentar na página através do PHP o texto aparece sem parágrafos e com algumas tags estanhas não sei por que acontece isto.

Como podem ver na imagem aparece essas tags que por si aparecem também na página quando chamo por PHP a visualização do conteúdo.
Comment: Eu usava esse componente, mais achei um muito melhor e mais facil de implementar.
olhe se goste: http://www.sceditor.com/
Comment: Vou analisar a sugestão.obrigado
Comment: Ok, certeza que vai gostar mais.
Answer: Bem pessoal entretanto consegui resolver reparei que tinha uma problema de configuração do editor comparado as fonts que tinha adicionado acabei a resolver com o seguinte código deixo para se alguém passar por o mesmo problema.
<code><script type="text/javascript">
tinymce.init({
    selector: "textarea.editme",
    theme: "modern",
    plugins: [
        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars code fullscreen",
        "insertdatetime media nonbreaking save table contextmenu directionality",
        "emoticons template paste textcolor colorpicker textpattern"
    ],
    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
    toolbar2: "print preview media | forecolor backcolor emoticons",
    image_advtab: true,
    templates: [
        {title: 'Test template 1', content: 'Test 1'},
        {title: 'Test template 2', content: 'Test 2'}
    ]
});
</script>
</code>
Isso vai activar todas as funções do editor // NOTA E PARA A VERSÃO 4 DO EDITOR


Cyclic integration in music

Question: In a book that I'm reading there is a term called cyclic integration, as follows:

In the genres that are the main carriers of classical sonata-form evolution, Mozart began to achieve a marked degree of independence from his models toward the end of 1773 in such works as the String Quintet in B-flat, K. 174, the Piano Concerto in D, K. 175, the G-minor Symphony, K. 183, and the A-major Symphony, K. 201/186a of the following April.24 These are works that are studied for the ways in which they bear upon the evolution of classical style in general and the sonata forms in particular, seen primarily in terms of such issues as formal symmetry, thematic development, harmonic trajectory, cyclic integration, coherence, organicism, and motivic work.

My question is: What is cyclic integration? Does it mean that the composer added some interval that is played again sometimes in the work?
Answer: Cyclic integration is making the movements of a multi-movement work more similar to each other. This is typically done by having later movements quote themes from earlier movements--the start of the last movement of Beethoven's 9th Symphony is a great example, as it starts off by semi-quoting the first 3 movements. This paper tries to argue that cyclic integration can involve elements looser than entire themes, such as rhythmic cells (cyclic integration of that kind can arguably be found in Beethoven's 5th Symphony, where the 3rd movement and 1st movement both use relatively static short-short-short-long rhythms a la "the fate motif"), harmonies, and phrase structures.
Answer: The cycle in cyclic integration refers to the cycle of movements in a multi-movement piece.  Cyclic integration is the way in which the composer relates the movements to one another.  For example, a composer may wish to integrate the same thematic subject into the two outer movements in a three-movement cycle.  This is cyclic integration.

Cyclic integration in music


Allow read-only access to Windows Services

Question: Is it possible to allow read-only mode so that someone to use management console to 'connect to another computer' and see the services running?
This is a Win2008 server, and the users will not have any rights except to be able to see the windows services.
Or is there a better way of achieving the same thing?
Answer: Each service has a ACL. This controls who can see the status, stop/start and configure. There is no inbuilt UI to give access to it, but sc.exe sdshow service" will show the ACL in [SDDL][1] form, thesdsetcommand forsc.exe` allows the ACL to be set.
Based on the default for one service I looked at ("Windows Search"), all interactive users can query this service, but for Windows Update the access is different and based on all users (i.e. remote as well as logged in locally).
Since the access rights flags are expanded symbolically, but generically it will be necessary to work out the underlying bit pattern to translate to service ACE flag names.
(There is an interactive services ACL editor when using Group Policy to enforce services configuration.)
Answer: http://www.windowsecurity.com/articles/Group-Policy-related-changes-Windows-Server-2008-Part3.html
Last entry in "Table 2..."


Determining the MVUE of $\theta$ when $f(x;\theta) = \theta^x (1-\theta)$

Question: The Statement of the Problem:
Let $X_1, X_2, ... , X_n$ be a random sample from
$$ f(x;\theta) = \theta^x (1-\theta) \quad x = 0,1,2,... $$
(a) Find the ML estimator of $\theta$.
(b) Show that $T = \sum_{i=1}^n X_i$ is a sufficient statistic for $\theta$.
(c) Determine the MVUE of $\theta$.
Where I Am:
I've taken care of parts (a) and (b) but am a bit stuck on part (c). In order to find a MVUE, I have to find an unbiased estimator, which I can't seem to figure out. My MLE, which is the following:
$$ \hat\theta_{\text{mle}} = \frac{\sum_{i=1}^n X_i}{n + \sum_{i=1}^n X_i} $$
seems to be biased (although, honestly, I got stuck trying to find its expectation). So, I've tried making an unbiased estimator from scratch... with no luck. Any tips here would be helpful. Thanks.
Answer: Use Lehmann-Scheffe Theorem (or Rao-Blackwellization). You have $T(\bf{X}$$)=\sum X_i$ to be complete-sufficient. Now find a simple unbiased estimator $\delta_0=I(X_1>0)$. Yes with just $X_1$ only! Then find $E[\delta_o|T(\bf{X})]$. I think you can figure it out from here. Let me know if you've further doubt/query.
Comment: Yeah, that was my plan (as I'd already shown that $T$ was complete-sufficient). However, I got stuck trying to find the unbiased estimator. Does the $I$ in $\delta _0 = I(X_1 > 0)$ refer to the Fisher information of $X_1$?
Comment: No...Indicator $E(\delta_0)=P(X_1>0)$
Comment: Ok. Yes, that makes more sense. Thanks. I'll give it a shot!


Differences between variations of GARCH (EGARCH, APARCH, ...)

Question: I want to know the differences between EGARCH, APARCH, TGARCH, QGARCH, GJRGARCH, IGARCH, AVGARCH, PGARCH, GARCH-M and the standard GARCH. I tried to find the information by myself but I cannot find the answer, so I really need your help. My work is find the different thing of GARCH and other GARCH model that why make their work or paper not use only standard GARCH for example i found this GARCH model cannot capture asymmetric and leverage effect and also explain negative and positive shock have effect in same direction, but EGARCH can capture asymmetric and explain negative and positive shocks
Comment: Hello. As of now, this is certainly very broad. Please narrow down your scope and add your relevant specifications, your requirements.
Comment: See Bollerslev ["Glossary to ARCH"](http://public.econ.duke.edu/~boller/Papers/glossary_arch.pdf) (2009) and Ghalanos ["Introduction to the rugarch package"](https://cran.r-project.org/web/packages/rugarch/vignettes/Introduction_to_the_rugarch_package.pdf) (2022).
Comment: My work is find the different thing of GARCH and other GARCH model that why make their work or paper not use only standard GARCH for example i found this GARCH model cannot capture asymmetric and leverage effect and also explain negative and positive shock have effect in same direction, but EGARCH can capture asymmetric and explain negative and positive shocks.
Comment: @Tharinwat please add any relevant info in your question body and not as a comment.
Answer: The question requires either an article-long answer or some references. I will provide the latter. For an extensive overview of different GARCH models, see Bollerslev "Glossary to ARCH (GARCH)" (2009) and Ghalanos "Introduction to the rugarch package" (2022).
Comment: This is a good approach: provide a useful reference. +1.
Comment: @Richard thanks a lot for your help
Comment: @Tharinwat if you think Richard's post answered your query, please upvote and [accept](https://stats.stackexchange.com/help/accepted-answer) it by clicking the tick symbol alongside the post.


Square pyramid with integer measurements.

Question: A right square pyramid has the following dimensions:

Length of the base square: $2a$
Height (distance from the vertex to the base center): $h$
Distance from the vertex to the middle point of the base edge: $b$
Length of the pyramid's edge: $c$

The following relations hold: $ h^2+a^2=b^2$, $a^2+b^2=c^2$.
Is there a way for the two triples $(h,a,b)$ , $(a,b,c)$ to be both pythagorean?
If the answer is affirmative, can a parametrized family of such pairs of triples be found?
Answer: For this to work, $\space  1)\space$ the hypotenuse $\space (b)\space$ of one triangle must be a "leg" of the other and
$\space 2)\space$ a leg
$\space (a_1)\space$
of one triangle must equal the corresponding leg
$\space (a_2)\space$ of the other. Here, we let
$\space  a_1=a_2.$
\begin{align*}
 h^2+a^2=b^2 &\space ,\space a^2+b^2=c^2\\
\implies b^2-h^2&=c^2-b^2
\qquad  h, a<b<c
\end{align*}
The problem is in condition $2)$ where
$\space a_1=a_2,\space a_1,a_2\in\mathbb{N}.\space $
It would be easy if $\space a_1 \ne a_2\space $ and we let
$\space a_1\space$ be the distance from the middle of the pyramid to the  base and let $\space a_2\space$ be the [different] half-length of the base such as
\begin{align*}
(h,a_1,b)=(3,4,5),\space
     (b,a_2,c)=(5,12,13)&\implies base=6a_1\space \space \\
(h,a_1,b)=(5,12,13),\space
    (b,a_2,c)=(13,84,85)&\implies base=14a_1\\
(h,a_1,b)=(7,24,25),\space
    (b,a_2,c)=(25,312,313)&\implies base=26a_1\\
(h,a_1,b)=(9,40,41),\space
    (b,a_2,c)=(41,840,841)&\implies base=42a_1\\
(h,a_1,b)=(15,8,17),\space
    (b,a_2,c)=(17,144,145)&\implies base=36a_1\\
(h,a_1,b)=(21,20,29),\space
    (b,a_2,c)=(29,420,421)&\implies base=42a_1\\
\end{align*}
There are an infinite number of these where, for
$A^2+B^2=C^2,\quad $
$\space C_n=A_{n+1}\space $
If $a_1 = a_2\space$ can be non-integers, we do have tuples that
are not Pythagorean triples (which require all sides to be integers) but which do fit the Pythagorean Theorem,  e.g.
<code> a^2    h   b   c
 24     1   5   7
 96     2   10  14
 216    3   15  21
 129    7   13  17
 240    7   17  23
</code>
but, if the "rem" is removed from the program lines below, no integer values for $\space (a)\space $ are found in testing $h,a<b<c \le 100,000$.
<code> 110 print " Hi number";
 120 input x1
 130 print "a^2",,"h ","b ","c "
 140  for h5 = 1 to x1
 150  for b5 = h5+1 to x1
 160  for c5 = b5+1 to x1
 170     if b5^2-h5^2 = c5^2-b5^2
 180         a5 = sqr(c5^2-b5^2)
 190  rem if a5 = int(a5)
 200         print c5^2-b5^2,;
 210         if c5^2-b5^2 < 100 : print ,; : endif
 220         print h5,b5,c5
 230  rem  endif
 240    endif
 250    next c5
 260    next b5
 270    next h5
</code>
Comment: @Phoenix Dactylifera   Has any of this been useful or is there more to your question?


Finding the volume of a cone by integration of parabolic conic sections

Question: I am working on a purely academic way of finding the volume of a right circular cone of height $h$ and radius $r$, (assume $h > r$), using integration of parabolic conic sections (conic sections parallel to the side of the cone). The end result being the geometric equation for the volume of a cone
$$v=\frac{π r^{2}h}{3}$$
The part I'm having trouble with is figuring out and write the equation for the parabolas.
I know that:

$h$ = height of the cone
$r$ = radius of the cone,
$s$ = side length of the cone = $\sqrt{r^{2} + h^{2}}$.

Limits of integration

I found the limits of integration to be from $0$ to $D$, where $D = cos(90 - \theta)2r$. Where $\theta$ is the angle from the base (viewing the cone from the side, giving me a triangular cross section) to the side $s$ of the cone.

I arrived at the upper limit of integration being $cos(90 - \theta)2r$ by creating a right triangle where the hypotenuse is the base $2r$, the short side is part of side $s$, and the long side is a line perpendicular to $s$, from $s$ to the opposite corner of the triangular cross section of the cone $\theta_2$.

Using this triangle I can find the length of the perpendicular line by stating that $cos(\theta_2) = \frac {adj}{hyp}$ where $adj$ is the adjacent side of the right triangle to $\theta_2$, and $hyp$ is the hypotenuse of the right triangle

I know that $\theta_2=180 - 90 - \theta$, therefor $\theta_2 = 90 - \theta$. I also know the base is $2r$ so I can say $cos(\theta_2) = \frac {D}{2r}$ (where $D=$the adjacent side) and as such $cos(90 - \theta)=\frac{D}{2r}$. When I rearrange this I get $D=cos(90 - \theta)2r$

So my limits of integration would run the distance from one side of the cone to the opposite corner $D$ in other words from $0$ to $D$

Equation for the parabolas

$$\int_0^{D}(?)dx$$
This is the part I'm having trouble figuring out (assuming I found the limits of integration correctly). I'm not sure how to find and write the equation for the parabolas in a way that I can integrate it across the entire cone to get the volume.
Comment: And pictures there were! These are great :) As a partial answer to your question, you would need to know the distance from the vertex of each parabola to the base of the cone, and then the inside would be the area contained inside that section of the parabola. The easy way would just to use calculus, but there are purely geometric ways of doing this: see [this post] (http://math.stackexchange.com/questions/305268/how-to-calculate-the-area-closed-by-a-parabola-and-a-line-without-calculus) for details.
Comment: A picture would be very helpful here.
Comment: Thanks! How would I go about doing it with calculus? Because I want to do it via calculus and integration, and have the end result of that be the geometric formula.
Answer: The volume may be calculated with Cavalieri's principle and a bit of care.
Place the cone with the center of its base at the origin. For $-r \leq x \leq r$, let $A(x)$ denote the area of the parabolic cross-section "at $x$".

Note that:

The area under the parabola is two-thirds the area of the circumscribing rectangle.
The width of the circumscribing rectangle is $2\sqrt{r^{2} - x^{2}}$.
A longitudinal section of the cone has sides $\sqrt{r^{2} + h^{2}}$ and base $2r$, so by similar triangles the circumscribing rectangle has slant height $(r - x)\sqrt{r^{2} + h^{2}}/(2r)$.

Consequently,
$$
A(x) = \tfrac{2}{3} \cdot 2\sqrt{r^{2} - x^{2}} \cdot (r - x) \frac{\sqrt{r^{2} + h^{2}}}{2r}
  = \frac{2\sqrt{r^{2} + h^{2}}}{3r}\, \sqrt{r^{2} - x^{2}}\, (r - x).
\tag{1}
$$
Now for the bit of care: A thin planar slice meeting the cone's diameter at $x$ and $x + dx$ is tilted with respect to the $x$-axis, and by similar triangles has thickness
$$
dv = \frac{h}{\sqrt{r^{2} + h^{2}}}\, dx
\tag{2}
$$
rather than $dx$. Multiplying (1) and (2), the volume of the planar slice of cone at location $x$, with $-r \leq x \leq r$, is
$$
dV = A(x)\, dv
  = \frac{2h}{3r}\, \sqrt{r^{2} - x^{2}}\, (r - x)\, dx.
\tag{3}
$$
The volume of the cone is the integral
$$
\text{Vol}
  = \int_{-r}^{r} \frac{2h}{3r}\, \sqrt{r^{2} - x^{2}}\, (r - x)\, dx
  = \frac{2h}{3} \int_{-r}^{r} \sqrt{r^{2} - x^{2}}\, dx
  - \frac{2h}{3r} \int_{-r}^{r} x \sqrt{r^{2} - x^{2}}\, dx.
$$
The first integral is the area of a half-disk of radius $r$, namely $\frac{1}{2}\pi r^{2}$, while the second vanishes as the integral of an odd function over a symmetric interval. That is, $\text{Vol} = \frac{1}{3} \pi r^{2}h$.
Answer: To be honest, I have no clue on how to help you or on how to get a result from your way of doing it, but have you tried the much simpler way of integrating a solid of revolution?
Consider a straight line in a two-dimensional coordinate system, with y-intercept $r$ and x-intercept $h$. If you rotate this straight line around the x-axis, you get your cone, and using a simple integration rule you get your formula.
Since $r$ is the y-intercept and $h$ the x-intercept, your function is: $$f(x) = -\frac{rx}{h} + r$$
Using the formula for volumes of solids of revolution, you get:
$$V = \pi \int_{0}^{h} (-\frac{rx}{h} + r)^{2}dx = \frac{\pi h r^{2}}{3}$$