text:
Q: How can I condense these import lines of code? from wisconsion1 import *
from alaska1 import *
from texas1 import *
from indiana1 import *

Is there some way to simplify this? Esp if I'm going to add more in the future.

A: Yes, you can simplify and clean up the code it as follows:
import * from wisconsion1, alaska1, texas1, indiana1


text:
Q: Regex.IsMatch for postcode I need a Regex which can satisfy all my three conditions for zip-code:

*

*can be length 10

*can't numbers 0 or 2

*in index [5] cant 5

A: ^[13-9]{4}[1346-9][13-9]{5}$

You can try this.See demo.
https://regex101.com/r/wX9fR1/12

redpajama_set_name: RedPajamaStackExchange


text:
Q: Manual garbage collection in Python Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call gc.collect()? Working in Python 3.0

A: If the GC is refusing to destroy it, it's because you have a reference to it somewhere. Get rid of the reference and it will (eventually) go. For example:
myRef = None

Keep in mind that GC may not necessarily destroy your object unless it needs to.
If your object is holding resources not under the management of Python (e.g., some trickery with C code called from Python), the object should provide a resource release call so you can do it when you want rather than when Python decides.

A: del Or None are your only friends
>>> a = "Hello"
>>> a = None
Or
>>> del a

A: Per the docs, gc.get_referrers(thatobject) will tell you why the object is still alive (do it right after a gc.collect() to make sure the undesired "liveness" is gonna be persistent).  After that, it's somehow of a black art;-).  You'll often find that some of the referrers are lists (so WHY is that list referring to thatobject? you can .remove it in an emergency mode, but making the normal code sound is better...), and, even more often, dicts (many of whose may be __dict__s of some class instance or other -- often not trivial to find out which one... again, brute-force removal is sometimes an expedient emergency solution, but never a sustainable long-range one!-).

A: It depends on what your Python is running on. Here's good article that explains the details
Quoting:
In current releases of CPython, each new assignment to x inside the loop will release the previously allocated resource. Using GC, this is not guaranteed. If you want to write code that will work with any Python implementation, you should explicitly close the resource; this will work regardless of GC:
for name in big_list:
    x = Resource()
    do something with x
    x.close()


text:
Q: PowerBI: How to exclude Visual from Filter? I have a Table with revenues by year and month from several units. To calculate the revenue by month i use a measure to add all revenues from all units. This measure i use then to calculate the current sum of all revenues and want to compare this to a target. Everything is working fine. But on the same Page i would like to have a table with all revenues from my last years. for this im trying to remove the page filter but its not working.
CalcRevenue = TOTALYTD([RevenueMeasure], Revenue[Date].[Date])
when im applying all filters so select all years, it shows the correct visual but naturaly all other visuals are then showing wrong things.
how can i exclude a visual from page filters


text:
Q: $\int_0^\frac{\pi}{2}\frac{\ln(\sin(x))\ln(\cos(x))}{\tan(x)}dx$ I have the problem below:
$$\int_0^\frac{\pi}{2}\frac{\ln(\sin(x))\ln(\cos(x))}{\tan(x)}dx$$
I have tried $u=\ln(\sin(x))$ so $dx=\tan(x)du$
so the integral becomes:
$$\int_{-\infty}^0u\ln(\cos(x))du$$
but I cannot find a simple way of getting rid of this $\ln(\cos(x))$
I also tried using the substitution $v=x-\frac{\pi}{2}$
so the integral becomes:
$$\int_{-\frac{\pi}{2}}^0\frac{\ln(\cos(v))\ln(\cos(v+\frac{\pi}{2}))}{\tan(v+\frac{\pi}{2})}dv$$
but this does not seems to lead anywhere useful
EDIT to follow up
$$B(\alpha,\beta)=\int_0^{\pi/2}\sin^{\alpha-1}(x)\cos^{\beta+1}(x)dx$$
$$\frac{\partial^2}{\partial_\alpha\partial_\beta}B(\alpha,\beta)=\int_0^{\pi/2}\sin^{\alpha-1}(x)\cos^{\beta+1}(x)\ln(\sin(x))\ln(\cos(x))dx$$
so I see that when $\alpha\to1$ and $\beta\to-1$ that this is the form that we want, so do we now have to take partial derivates of the non-integral form of the beta function then take the double integral for our chosen values?

A: You may consider that
$$ f(\alpha,\beta) = \int_{0}^{\pi/2}\sin^{\alpha-1}(x)\cos^{\beta+1}(x)\,dx = \frac{\Gamma\left(\frac{a}{2}\right)\Gamma\left(1+\frac{b}{2}\right)}{2\,\Gamma\left(1+\frac{a+b}{2}\right)}$$
by Euler's Beta function. By applying $\frac{\partial^2}{\partial\alpha\,\partial\beta}$ to both sides, then considering the limit as $\beta\to 0$ and $\alpha\to 0^+$, we have
$$ \int_{0}^{\pi/2}\frac{\log\sin(x)\log\cos(x)}{\tan(x)}\,dx = -\frac{1}{12}\psi''(1) = \color{red}{\frac{\zeta(3)}{8}}.$$
By enforcing the substitutions $x\mapsto\arctan(x)$ or $x\mapsto 2\arctan(x)$ in the original integral we get interesting identities for nasty (poly)logarithmic integrals.

A: \begin{equation}
 \int_0^\frac{\pi}{2}\frac{\ln(\sin(x))\ln(\cos(x))}{\tan(x)}dx
 =
 \int_0^\frac{\pi}{2}
 \cos x
 \frac{\ln(\sin(x))\ln(\sqrt{1 - \sin^2 x})}{\sin(x)}dx
\end{equation}
Take
\begin{equation}
 u = \sin x
\end{equation}
so
\begin{equation}
 du = \cos x dx
\end{equation}
You get
\begin{equation}
 \int_0^1 \ln u \ln(\sqrt{1- u^2}) \frac{1}{u} du
\end{equation}
Take $u = e^v$, you get
\begin{equation}
 \frac{1}{2}
 \int_{-\infty}^0
 v \ln(1 - e^{2v}) dv
\end{equation}
Integration by parts will give you
\begin{equation}
 \frac{1}{2}
 [\frac{1}{2}v^2 \ln(1 - e^{2v})]_{-\infty}^0
 -
 \frac{1}{2}
 \int_{-\infty}^0
 \frac{v^2}{1- e^{2v}}
 (-2e^{2v}) dv
\end{equation}
The term $ [\frac{1}{2}v^2 \ln(1 - e^{2v})]_{-\infty}^0$ is zero so
\begin{equation}
 -
 \frac{1}{2}
 \int_{-\infty}^0
 \frac{v^2}{1- e^{2v}}
 (-2e^{2v}) dv
\end{equation}
Take the following change of variable
\begin{equation}
 k = -v
\end{equation}
So we get
\begin{equation}
 \frac{1}{2}
 \int_0^{\infty}
 \frac{k^2}{e^{2k} - 1} dK
\end{equation}
Take now
\begin{equation}
 n = 2k
\end{equation}
as change of variable, you get
\begin{equation}
 \frac{1}{2}
 \int_0^{\infty}
 \frac{k^2}{e^{2k} - 1} dk
 =
 \frac{1}{16}
 \int_0^{\infty}
 \frac{n^2}{e^n - 1}
\end{equation}
Using the Riemann Zeta function
\begin{equation}
 \zeta(x)
 =
 \frac{1}{\Gamma(x)}
 \int_0^{\infty}
 \frac{u^{x-1}}{e^u - 1}
 du
\end{equation}
or
\begin{equation}
 \zeta(x)\Gamma(x)
 =
 \int_0^{\infty}
 \frac{u^{x-1}}{e^u - 1}
 du
\end{equation}
Using the above integral for $u = n$ and $x = 3$ you will get that your integral evaluates to
\begin{equation}
 \frac{1}{2}
 \int_0^{\infty}
 \frac{k^2}{e^{2k} - 1} dk
 =
 \frac{1}{16}
 \int_0^{\infty}
 \frac{n^2}{e^n - 1}
 =
 \frac{\overbrace{\Gamma(3)}^{2!}\zeta(3)}{16}
 =
 \frac{\zeta(3)}{8}
\end{equation}


text:
Q: Unable to add a class On click of the Addons Button , and selection and unselection of checkboxes , a specific class namely
ui-checkbox-on and ui-checkbox-off is added dynamically to the label element .
This is my code

$(document).on('click', '.remove', function (e) {
    $("#addonsWrap").find("label.ui-checkbox-on").removeClass('ui-checkbox-on');
});
.pageMidLogo {
    width:100%;
    float:left;
    text-align:center;
}
.createAccountWrap {
    width:100%;
    float:left;
    height:auto;
    padding:20px;
}
.createAccountWrap .h3_head {
    float: left;
    text-align: center;
    width: 100%;
    margin-bottom: 25px !important;
}
.iLabel {
    font-size: 13px;
    line-height: 16px;
    width: 100%;
    float: left;
}
.insideInput {
    width:100%;
    float:left;
    position:relative;
}
.tooltipIcon {
    width: 27px;
    height: 27px;
    position: absolute;
    right: 8px;
    top: 16px;
    background: #ababab;
    -webkit-border-radius: 25px;
    border-radius: 25px;
}
.tooltipIcon:before {
    font-size: 19px;
    margin-top: 4px;
    color:#fff;
}
.pop_tooltipIcon {
    font-size: 36px;
    text-align: center;
    width: 100%;
    float: left;
    margin-bottom: 10px;
    color:#d03e43;
}
.iconPinReload {
    /*background: url(../images/icon-capthareload.png) 10px 10px no-repeat #f6f6f6;
 border-left: 1px solid #ddd;
 width: 52px;
 height: 41px;*/
    position: absolute;
    top: -20px;
    right: 0px;
    cursor: pointer;
    font-size: 15px;
}
/*.iconPinReload:hover{
 background: url(../images/icon-capthareload.png) 10px 10px no-repeat #f0f0f0;
}*/
 .tpMenuWrap {
    position:absolute;
    top:0px;
    width: 88%;
}
.btMenuWrap {
    position:absolute;
    bottom:0px;
    width: 88%;
}
.ul_menu {
    padding:0px;
    margin:0px;
    width:100%;
    list-style:none;
}
.ul_menu li {
    padding: 10px 0px;
    margin: 0px;
    width: 100%;
    list-style: none;
    font-size: 24px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.ul_menu li a {
    font-weight: 500;
    color:#ddd;
}
.ul_menu li a:hover {
    color:#fff;
}
.panelCloseBtn {
    float: right;
    margin-bottom: 15px;
    width: 100%;
    text-align: right;
    margin-top: 15px;
    font-size: 20px;
    color: #777 !important;
}
.panelCloseBtn:hover {
    color: #999 !important;
}
.homeListMenuWrap {
    padding:0px !important;
    margin:0px;
    width:100%;
    list-style:none;
}
.homeListMenuWrap li {
    padding:25px 25px 20px 25px;
    margin:0px;
    width:100%;
    list-style:none;
    border-bottom:1px solid #ddd;
}
.homeListMenuWrap li a:hover {
    color:#d03e43;
}
.homeListMenuWrap li .qrcode {
    background:url(../images/icon-QRcode.png) left top no-repeat;
    padding-left: 120px;
    display: block;
    color:#314158;
    min-height:110px;
}
.homeListMenuWrap li .homedeliver {
    background:url(../images/icon-homedelivery.png) left top no-repeat;
    padding-left: 120px;
    display: block;
    color:#314158;
    min-height:110px;
}
.homeListMenuWrap li .qrcode p, .homeListMenuWrap li .homedeliver p {
    font-size:15px;
}
.qrcode_errorWrap {
    width:100%;
    float:left;
    height:auto;
    padding:20px;
}
.qrcode_errorWrap .qrcodeError {
    float: left;
    text-align: center;
    width: 100%;
    font-size:26px !important;
    margin-bottom: 25px !important;
    font-weight: 400 !important;
}
.orDivider {
    width: 100%;
    float: left;
    text-align: center;
    font-size: 22px !important;
    font-style: italic;
    position:relative;
    margin: 25px 0;
}
.orDivider span {
    background: #fff;
    position: relative;
    z-index: 1;
    padding: 0 15px;
}
.orDivider .hr {
    position: absolute;
    top: 5px;
    width: 100%;
    background: #eee;
    border: 1px solid #eee;
}
/* Tree Menu Start */
 .TreeMenu {
    width:100%;
}
.TreeMenu .ui-collapsible-heading {
    margin:0px !important;
}
.TreeMenu .ui-collapsible-heading a {
    border-left:0px;
    border-right:0px;
    border-bottom:1px solid #e6e6e6;
    border-top:1px solid #e6e6e6;
    border-radius: 0px;
}
.TreeMenu .ui-collapsible-heading-toggle {
    font-size:20px;
}
.TreeMenu .ui-collapsible-content {
    margin: 0;
    padding: 0px 20px;
    border: 0px !important;
    background: #fff;
}
.TreeMenu_Content {
    width:100%;
    height:auto;
    padding: 15px 0px 0px 0px;
    display: inline-block;
}
.TreeMenu_Content .lastItm_Wrap {
    width:100%;
    float:left;
    height:auto;
    margin-bottom:5px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_left_aside {
    width:60%;
    float:left;
}
.TreeMenu_Content .lastItm_Wrap .Itm_dtsl {
    width:75%;
    float:left;
}
.TreeMenu_Content .lastItm_Wrap .Itm_dtsl .vegLabel {
    background:url(../images/veg_labels.png) left 3px no-repeat;
    padding-left: 25px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_dtsl .nonvegLabel {
    background:url(../images/nonveg_labels.png) left 3px no-repeat;
    padding-left: 25px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_dtsl h3 {
    font-size:16px;
    white-space: nowrap;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    position:relative;
    padding-right: 50px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_dtsl h3 .prdDiscription {
    position: absolute;
    right: 0px;
    top: 1px;
    width: auto !important;
    border-radius: 20px;
    padding: 0px 8px;
    font-size: 14px;
    margin: 0px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_dtsl .addonsList {
    font-size: 14px;
    opacity: 0.7;
    width: 100%;
    float: left;
}
.TreeMenu_Content .lastItm_Wrap .Itm_img {
    width:74px;
    height:74px;
    float:left;
    background:#ddd;
    margin-right:10px;
    overflow:hidden;
}
.TreeMenu_Content .lastItm_Wrap .Itm_img img {
    width:100%;
    float:left;
    height:100%;
    border:0px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_right_aside {
    width:30%;
    float:right;
    text-align:right;
}
.TreeMenu_Content .lastItm_Wrap .Itm_right_aside .trashBtn {
    font-size:20px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_right_aside p {
    font-size:16px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_right_aside p strike {
    margin-right:10px;
}
.TreeMenu_Content .lastItm_Wrap .Itm_right_aside p b {
    font-weight:600;
}
/* Tree Child */
 .TreeMenuChild .ui-collapsible-content {
    padding:0px;
}
.TreeMenuChild .ui-icon-plus:after {
    background-image: url(images/icons-png/carat-r-black.png) !important;
}
.TreeMenuChild .ui-icon-minus:after {
    background-image: url(images/icons-png/carat-d-white.png) !important;
    background-color:#d03e43;
}
.TreeMenuChild .ui-collapsible-heading-toggle {
    background-color:#fff !important;
    font-size:18px;
}
.TreeMenuChild .ui-collapsible-heading-toggle:last-child {
    margin-top:-1px;
}
.addonsBtn {
    width: auto !important;
    float: left;
    padding: 5px 20px;
    border-radius: 20px !important;
    font-size:13px;
}
.addonsBtn a {
    color:#333 !important;
}
.Itm_discrp {
    width:100%;
    float:left;
    height:auto;
    margin-top:10px;
}
.Itm_discrp h3 {
    margin-bottom: 10px !important;
    padding: 0px;
}
.Itm_discrp p {
    text-align: justify;
}
.Qty_Wrap {
    width:100%;
    float:left;
}
.Qty_Wrap .QtyBtn {
    float: left;
    width: 33px;
    border-radius: 34px;
    padding: 5px;
    font-size: 14px;
}
.Qty_Wrap .QtyBtn:before {
    margin-top:4px;
}
.Qty_Wrap .ui-input-text {
    float: left;
    border: 0px;
    box-shadow: none;
    background: #fff;
    width: 50px;
    font-size: 24px;
    padding: 0px;
    margin: 0px 2px 0px 0px;
    text-align: center;
}
.Qty_Wrap .QtyInput {
    float: left;
    width: 100%;
    padding: 0px;
    margin: 0px;
    text-align: center;
    min-height: 1.6em;
}
.addonsContent h2 {
    font-size:18px;
}
.addonsContent .rightAction {
    float: right;
    font-size: 13px;
    margin-top: -28px;
}
.addonsContent .rightAction a {
    padding-right:20px;
}
.addonsContent .rightAction a.tick {
    font-size: 22px;
    padding-right:0px;
}
.addonsContent .rightAction a.remove {
    color:#333;
    opacity:0.7;
}
.addonsContent .addonsQtyWrap {
    width:100%;
    padding: 0 15px;
    margin-bottom:20px;
}
.addonsContent .addonsQtyWrap ul {
    width:100%;
    float:left;
    padding: 0px;
    margin: 0px 0px 10px 0px;
}
.addonsContent .addonsQtyWrap ul li {
    list-style: none;
    float: left;
    font-size: 14px;
    font-weight: bold;
    border: 1px solid #ddd;
    padding: 5px 20px;
    margin-right: 10px;
    margin-top: 10px;
    border-radius: 4px;
    cursor:pointer;
}
.addonsContent .addonsQtyWrap ul li:hover {
    background:#eee;
}
.addonsContent .addonsQtyWrap ul li.active {
    border:1px solid #d03e43;
    color:#d03e43;
}
.addonsContent .popup_content_addonsWrap {
    width:100%;
    height:300px;
    overflow:auto;
}
.addonsContent .addonsListWrap {
    width:100%;
}
.addonsContent .addonsListWrap h3 {
    font-size: 14px;
    margin: 0px;
    padding: 0px;
    text-transform: uppercase;
    margin-bottom: 10px;
}
.addonsContent .addonsListWrap ul {
    list-style: none;
    padding: 0px;
    margin: 0px;
}
.addonsContent .addonsListWrap ul li {
    list-style: none;
    padding: 0px;
    margin: 0px;
    font-size: 14px;
}
.addonsContent .addonsListWrap ul li form {
    padding: 0px;
    margin: 0px;
    height: auto;
    display: -webkit-inline-box;
}
.addonsContent .addonsListWrap ul li .ui-mini {
    margin: 0px;
}
.addonsContent .addonsListWrap ul li .ui-mini label {
    background:#fff !important;
    border:0px;
    margin-left:-5px;
    font-weight: normal;
    font-size: 14px;
}
.myOrderPanel_footer {
    width:100%;
    height:auto;
    bottom:0px;
    left: 0px;
    position:fixed;
    background:rgba(208, 62, 67, 0.9);
    border-top:2px solid #d03e43;
    padding:10px;
    color:#fff;
    z-index:999;
}
.myOrderPanel_footer:hover {
    background:rgba(208, 62, 67, 1);
}
.myOrderPanel_footer .myOrderPanel_inner {
    width: 100%;
    float: left;
    position: relative;
}
.myOrderPanel_footer .myOrderPanel_inner:after {
    content:'\e988';
    font-family:"fontello";
    display: inline-block;
    top: 0px;
    right: 0px;
    font-size: 37px;
    position:absolute;
}
.myOrderPanel_footer .myOrderPanel_inner .myorders, .myOrderPanel_footer .myOrderPanel_inner .subtotal {
    float:left;
}
.myOrderPanel_footer .myOrderPanel_inner .myorders {
    padding: 12px 0px;
    font-size:18px;
    margin-right:10px;
}
.myOrderPanel_footer .myOrderPanel_inner .myorders i {
    font-weight: bold;
    font-style: normal;
    background: rgba(0, 0, 0, 0.4);
    padding: 7px;
    border-radius: 120px;
    margin-left:5px;
    margin-right:15px;
}
.myOrderPanel_footer .myOrderPanel_inner .subtotal {
    line-height: 20px;
    margin-top:4px;
}
.myOrderPanel_footer .myOrderPanel_inner .subtotal b {
    font-size:16px;
}
.myOrderPanel_footer .myOrderPanel_inner .subtotal b span {
    font-size:22px;
}
.myOrderPanel_footer .myOrderPanel_inner .subtotal .minOrder {
    font-size:13px;
    opacity:0.7;
}
/*.myOrderPanel_footer .myOrderPanel_right{
 width:85%;
 float:left;
 padding-left: 12px;
}*/

/*.myOrderPanel_footer .myOrderPanel_right .subtotal{
 font-size:18px;
}
.myOrderPanel_footer .myOrderPanel_right .subtotal span{
 margin-left:10px;
 font-size:24px;
}
.myOrderPanel_footer .myOrderPanel_right .subtotal i{
 width:100%;
 float:left;
 font-size:13px;
 font-style:normal;
}*/

/* My Order page start */
 .MyOrdersPage {
    width:100%;
    float:left;
    height:auto;
}
.MyOrdersPage .TreeMenu_Content .lastItm_Wrap {
    border-bottom:1px solid #eee;
    margin-bottom: 20px;
    margin-top: 10px;
    padding-bottom: 20px;
}
.vendorNameDtsl {
    width:100%;
    float:left;
    height:auto;
    background:rgba(0, 0, 0, 0.04);
    padding:10px 20px;
    border-bottom:1px solid #eee;
}
.vendorNameDtsl h6 {
    font-size: 16px;
    float: left;
    margin:0px !important;
    padding-top:4px !important;
}
.vendorNameDtsl span {
    font-size: 14px;
    float: right;
    padding:2px 20px;
    border:1px solid rgba(0, 0, 0, 0.1);
    border-radius: 20px;
}
.orderSummary_priceDtsl {
    width:100%;
    float:left;
    height:auto;
    padding-bottom: 10px;
}
.orderSummary_priceDtsl li {
    list-style:none;
    text-align:right;
    font-size:16px;
    margin-bottom:10px;
}
.orderSummary_priceDtsl li span {
    font-weight: bold;
    margin-left: 10px;
    width: 100px;
    float: right;
}
.orderSummary_priceDtsl li.totalsection {
    padding-top:17px;
    border-top:2px solid #ddd;
    font-size:20px;
    color:#d03e43;
    margin-top:20px;
}
/*.orderSummary_priceDtsl .inclusiveTax{
 width:100%;
 text-align:center;
 margin:30px 0px !important;
}*/
 .customerNameDtl {
    width:100%;
    float:left;
    height:auto;
    padding:0 20px;
    margin-bottom:20px;
}
.customerNameDtl_left {
    font-size:16px;
    line-height:26px;
    width:auto;
    text-align:left;
    float:left;
}
.customerNameDtl_right {
    float:right;
    width:auto;
    text-align:right;
}
.customerNameDtl_right .totalsection {
    font-size:20px !important;
    color:#d03e43;
}
.customerNameDtl_right .totalsection span {
    font-weight: bold;
    margin-left: 20px;
}
.customerNameDtl_right button {
    padding:8px;
    font-size:17px;
}
/* My Order page end */
 .placeorderimg {
    width:176px;
    margin:0 auto;
    padding-bottom:50px;
}
.cancelOrder {
    width: 100% !important;
    float: left;
    padding: 18px 0px !important;
    font-size: 16px;
}
.commentWrap {
    width:100%;
    float:left;
    height:auto;
    margin:15px 0px;
}
.commentWrap textarea {
    width:100%;
    float:left;
    height:90px;
    margin:15px 0px;
    padding:15px;
}

                                                            <button class="btn-d addonsBtn ui-btn ui-shadow ui-corner-all">Addons</button>

Addons

                        Remove All

Qty-1

Toppings

                                    <form>

Topping items <input type="checkbox" name="checkbox-mini-0" id="checkbox-mini-0" data-mini="true"/>

                                    </form>

Crust

                                    <form>

Crust items <input type="checkbox" name="checkbox-mini-0" id="checkbox-mini-4" data-mini="true"/>

                                    </form>

Could you please let me know whats the issue ??

A: That is because you are only removing the class and not unchecking the checkboxes. You can rather trigger click of on checkboxes:
$(document).on('click', '.remove', function (e) {
  $("#addonsWrap").find("label.ui-checkbox-on").click();
});

Working Demo


text:
Q: Simple code for phi(k) correlation matrix in Python I am looking for a simple way (2 or 3 lines of code) to generate a Phi(k) correlation matrix in Python.
That should be possible since pandas_profiling is doing it, and it works fine.
But I want to be able to do it without pandas_profiling which is too heavy and computes things I don't need.
pandas_profiling is using phik library.
I tried phik library (didn't find anything else)
I don't understand the error I got :
TypeError: sequence item 0: expected str instance, int found
I have no int in my dataframe.
Seems like a bug in phik, but then how does pandas profiling do, since it's using it too ?
What's happening here ?
Many thanks
I have this code :
import numpy as np
import pandas as pd

import phik

NB_SAMPLES = 200
NB_VARIABLES = 3

rand_mat = np.random.uniform(low=0.5, high=15, size=(NB_SAMPLES,NB_VARIABLES))
df = pd.DataFrame(rand_mat)
df['cat_column'] = pd.cut(df[0], bins=5, labels=['F1','F2','F3','F4','F5'])
print(df)
df.phik_matrix()

Result :
                 0          1          2 cat_column
0     0.911098   8.549206   9.270484         F1
1    13.591250   9.161498   5.614470         F5
2     3.308305   1.589402   5.394675         F1
3    12.031064   9.968686   7.519628         F5
4    14.427813   1.533533   2.352659         F5
..         ...        ...        ...        ...
195  10.556285   3.541869   4.804826         F4
196   5.721784  11.783908  13.104844         F2
197   7.336637  14.512256  14.993096         F3
198   4.375895  11.881784   1.129816         F2
199   0.519900   6.624423   9.239070         F1

[200 rows x 4 columns]
interval_cols not set, guessing: [0, 1, 2]

---------------------------------------------------------------------------
_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py", line 418, in _process_worker
    r = call_item()
  File "/opt/conda/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py", line 272, in __call__
    return self.fn(*self.args, **self.kwargs)
  File "/opt/conda/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 608, in __call__
    return self.func(*args, **kwargs)
  File "/opt/conda/lib/python3.7/site-packages/joblib/parallel.py", line 256, in __call__
    for func, args, kwargs in self.items]
  File "/opt/conda/lib/python3.7/site-packages/joblib/parallel.py", line 256, in <listcomp>
    for func, args, kwargs in self.items]
  File "/opt/conda/lib/python3.7/site-packages/phik/phik.py", line 162, in _calc_phik
    combi = ':'.join(comb)
TypeError: sequence item 0: expected str instance, int found
"""

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-31-398c72b34799> in <module>
     11 df['cat_column'] = pd.cut(df[0], bins=5, labels=['F1','F2','F3','F4','F5'])
     12 print(df)
---> 13 df.phik_matrix()

/opt/conda/lib/python3.7/site-packages/phik/phik.py in phik_matrix(df, interval_cols, bins, quantile, noise_correction, dropna, drop_underflow, drop_overflow)
    215     data_binned, binning_dict = bin_data(df_clean, cols=interval_cols_clean, bins=bins, quantile=quantile, retbins=True)
    216     return phik_from_rebinned_df(data_binned, noise_correction, dropna=dropna, drop_underflow=drop_underflow,
--> 217                                  drop_overflow=drop_overflow)
    218
    219

/opt/conda/lib/python3.7/site-packages/phik/phik.py in phik_from_rebinned_df(data_binned, noise_correction, dropna, drop_underflow, drop_overflow)
    145
    146     phik_list = Parallel(n_jobs=NCORES)(delayed(_calc_phik)(co, data_binned[list(co)], noise_correction)
--> 147                                         for co in itertools.combinations_with_replacement(data_binned.columns.values, 2))
    148
    149     phik_overview = create_correlation_overview_table(dict(phik_list))

/opt/conda/lib/python3.7/site-packages/joblib/parallel.py in __call__(self, iterable)
   1015
   1016             with self._backend.retrieval_context():
-> 1017                 self.retrieve()
   1018             # Make sure that we get a last message telling us we are done
   1019             elapsed_time = time.time() - self._start_time

/opt/conda/lib/python3.7/site-packages/joblib/parallel.py in retrieve(self)
    907             try:
    908                 if getattr(self._backend, 'supports_timeout', False):
--> 909                     self._output.extend(job.get(timeout=self.timeout))
    910                 else:
    911                     self._output.extend(job.get())

/opt/conda/lib/python3.7/site-packages/joblib/_parallel_backends.py in wrap_future_result(future, timeout)
    560         AsyncResults.get from multiprocessing."""
    561         try:
--> 562             return future.result(timeout=timeout)
    563         except LokyTimeoutError:
    564             raise TimeoutError()

/opt/conda/lib/python3.7/concurrent/futures/_base.py in result(self, timeout)
    433                 raise CancelledError()
    434             elif self._state == FINISHED:
--> 435                 return self.__get_result()
    436             else:
    437                 raise TimeoutError()

/opt/conda/lib/python3.7/concurrent/futures/_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

TypeError: sequence item 0: expected str instance, int found

A: Try to reinstall the phik module as the following:
pip install phik==0.10.0

Then, your code together with sns.heatmap results the following:


text:
Q: Dexie.js - ordering with more than one index I am using dexie.js to interface with IndexedDB. I am wondering if it is possible to orderby or sortby using more than one index at once (eg. db.people.orderBy( index1, desc : index2, asc )...
If it is possible, what is the correct syntax?

A: Either use compound indexes, or use Collection.and().
If you can live with only targeting Chrome, Firefox or Opera, you can use compound indexes. If it must work on Safari, IndexedDBShim, Edge or IE, you cannot use compound indexes today. There's a shim that enables it for IE/Edge though, but it is still in beta, so I would recommend to instead use Collection.and() for those cases.
Let' say you have a form where users can fill in various attributes of friends:
<form>
  <input name="name"/>
  <input name="age"/>
  <input name="shoeSize" />
</form>

Using Collection.and()
First, pick the most probably index to start your search on. In this case, "name" would be a perfect index that wouldn't match so many items, while age or shoeSize would probably match more friends.
Schema:
db.version(X).stores({
    friends: "id, name, age, shoeSize"
});

Query:
function prepareQuery () {
    // Pick a good index. The picked index will filter out with IndexedDB's built-in keyrange
    var query;
    if (form.name.value) {
        query = db.friends.where('name').equals(form.name.value);
    } else if (form.age.value) {
        query = db.friends.where('age').equals(parseInt(form.age.value));
    } else if (form.shoeSize.value) {
        query = db.friends.where('shoeSize').equals(parseInt(form.shoeSize.value));
    } else {
        query = db.friends.toCollection();
    }

    // Then manually filter the result. May filter a field that the DB has already filtered out,
    // but the time that takes is negligible.
    return query.and (function (friend) {
        return (
            (!form.name.value || friend.name === form.name.value) &&
            (!form.age.value || friend.age == form.age.value) &&
            (!form.shoeSize.value || friend.shoeSize == form.shoeSize.value));
    });
}

// Run the query:
form.onsubmit = function () {
    prepareQuery() // Returns a Collection
        .limit(25) // Optionally add a limit onto the Collection
        .toArray(function (result) { // Execute query
            alert (JSON.stringify(result, null, 4));
        })
        .catch (function (e) {
            alert ("Oops: " + e);
        });
}

Using compound indexes
As written above, compound indexes code will only work on mozilla- and chromium based browsers.
db.version(x).stores({
    friends: "id, name, age, shoeSize," +
        "[name+age+shoeSize]," +
        "[name+shoeSize]," +
        "[name+age]," +
        "[age+shoeSize]"
});

The prepareQuery() function when using compound indexes:
function prepareQuery() {
    var indexes = []; // Array of Array[index, key]
    if (form.name.value)
        indexes.push(["name", form.name.value]);
    if (form.age.value)
        indexes.push(["age", parseInt(form.age.value)]);
    if (form.shoeSize.value)
        indexes.push(["shoeSize", parseInt(form.shoeSize.value)]);

    var index = indexes.map(x => x[0]).join('+'),
        keys = indexes.map(x => x[1]);

    if (indexes.length === 0) {
        // No field filled in. Return unfiltered Collection
        return db.friends.toCollection();
    } else if (indexes.length === 1) {
        // Single field filled in. Use simple index:
        return db.friends.where(index).equals(keys[0]);
    } else {
        // Multiple fields filled in. Use compound index:
        return db.friends.where("[" + index + "]").equals(keys);
    }
}

// Run the query:
form.onsubmit = function () {
    prepareQuery() // Returns a Collection
        .limit(25) // Optionally add a limit onto the Collection
        .toArray(function (result) { // Execute query
            alert (JSON.stringify(result, null, 4));
        })
        .catch (function (e) {
            alert ("Oops: " + e);
        });
}

Using arrow functions here to make it more readable. Also, you're targeting chromium or firefox and they support it already.


text:
Q: Net Core Scaffold-DBContext CustomCandidateNamingService doesn't work in version 2.0.0-preview1 I am using Scaffold-DBContext commnand in order to create a model from my database.
I implemented
public class CustomCandidateNamingService : CandidateNamingService
{
    public override string GenerateCandidateIdentifier(string original)
    {
        return original.ToUpper();
    }
}

because I want to return the property name all uppercase.
This works in version 1.1.2 but doesn't work in version 2.0.0-preview1-final.
Do I have to change something?
Thanks.

A: Let's check this repository.
https://github.com/arichika/EFCore2.0-Scaffold-DBContext-CustomCandidateNamingService
You need to change the code.
First, It is necessary to create a new class that inherits IDesignTimeServices.
e.g.
public class MyScaffoldingDesignTimeServices: IDesignTimeServices
    {
        public void ConfigureDesignTimeServices(IServiceCollection services)
        {
            services.AddSingleton<ICandidateNamingService,
                                   MyScaffoldingCandidateNamingService>();
        }
    }

Second, Do this.
e.g.
public class MyScaffoldingCandidateNamingService : CandidateNamingService
{
    public override string GenerateCandidateIdentifier(string original)
    {
        return original.ToUpper();
    }
}

Sample is here. https://github.com/arichika/EFCore2.0-Scaffold-DBContext-CustomCandidateNamingService/blob/master/src/ScaffoldMyDb/MyScaffoldingDesignTimeServices.cs


text:
Q: Split feature (MultiLine) not working as expected - newist QGIS user (version 2.18.13) I would like to split a GPX track (saved as a SHP file multiline feature) at a specific location. The track has several incidents of overlapping line segments (double-backing on trail).
When using the "Split feature" tool, QGIS splits the track at every crisscross in addition to the desired split.  I end up with 330 features, not 2 features). This question appears to have been asked before, but not answered.  What am I doing wrong, or is there a better tool?


text:
Q: Transpiling JSX for use in InternJS Tests I'm implementing (or trying to implement) unit/functional tests for our app and would like to use InternJS as a test runner with the Enzyme testing utility.
To unit test our components the JSX needs to be transpiled. The Intern docs contain a React example but with the deprecation of JSXTransformer the example is no longer relevant.
So I've tried to use Babel via the SystemJS plugin, systemjs-plugin-babel and used the recommended loader configuration.
When I run the tests the following error occurs:
$ node_modules/.bin/intern-client config=tests/config/local
Error: (SystemJS) SyntaxError: Unexpected token < at Object.exports.runInThisContext (vm.js:53:16)
Evaluating path/to/tests/unit/button.test.js
Error loading path/to/tests/unit/button.test.js
No stack or location

Removing the JSX from the tests shows the error is related to the JSX in the tests.
Is it possible to use Intern with Enzyme to test React components? And if so, how do you configure Intern to prep the components for testing?


text:
Q: Laravel booking system design I want to create a booking system in Laravel where user chooses Date and one of the timeslots given. My idea right now is to store in database table (MySQL), the booking_date in one field and the booking_timeslot in another. The problem with this design is that I do not know how to prevent another user from choosing the same date and timeslot, or how to render the timeslot chosen on a particular day non-usable again.
Please I would really appreciate any advice. Thank you in advance.

A: Many ways to achieve your goal but one interesting way is generating all booking with dates and 24 hours in one table with blank order id and when order come reserve them with order id


text:
Q: How do I distinguish RadioButtons? I have a for-loop with a RadioButton at each iteration. My problem is I don't know how to distinguish every single RadioButton once I validate my form (how to retrieve their value?) . I have a model for printers :
public class Printer{
     public int id{ get; get;}
     public string printerName { get; set; }
}

Which itself is part of another model :
public class FinalSiteModel
{
    public string name{ get; set; }
    public List<Printer> printers{ get; set; }
    public bool selected { get; set; }
}

Then as I pass it to the view :
for(var i = 0; i < Model.printers.Count() ; i++)
{
    @Html.RadioButtonFor(m => m.selected, new {  Name = "groupRadio"});
    @Html.Label(Model.printers[i].printerName);
}

I think something is wrong with the way I wrote my RadioButton. I initially used the boolean selected inside of the PrinterModel but my problem then came from the fact that the radiobuttons didn't group since I used
@Html.RadioButtonFor(m => m.printers[i].selected, new {  Name = "groupRadio"});

and this bit : m => m.printers[i].selected created a different name for each radiobutton, hence when I check several radiobuttons at the same time, which I don't want.
I'm guessing I should add a parameter to RadioButtonFor ?

A: Your radio buttons need a value to bind to your selected property. However that property needs to be int, not bool
public class FinalSiteModel
{
    ...
    public List<Printer> Printers { get; set; }
    public int SelectedPrinter { get; set; }
}

and then in the view
foreach(var printer in Model.Printers)
{
    <label>
        @Html.RadioButtonFor(m => m.SelectedPrinter, printer.Id, new { id = "" })
        <span>@printer.Name</span>
    </label>
}

Note the 2nd parameter of RadioButtonFor() adds the value attribute based on the Id property of Printer, and the new { id = "" } removes the id attribute which would otherwise be invalid because the method generates duplicates
The value of SelectedPrinter will now contain the Id of the selected Printer when you POST your form.
As a side note, never attempt to change the name attribute using new {  Name = "groupRadio" } - it would not bind to your model.


text:
Q: VBA Access 2007 dependent autoincrement I'm a little new at this so bear with me. :)
I'm trying to add an event to one of my forms in an Access 2007 database.
The idea is that by entering a value in the CustomerNumber field, the OrderNumber field will automatically figure out the next order number for that customer. (If that customer has two previous orders, then OrderNumber will be a 3)
For example, suppose we have the table:
Orders
CustomerNumber    OrderNumber    Description
1                  1              Whatever
1                  2              Blah
2                  1              Yada
5                  1              Yada
2                  2              Yada
1                  3              Foo

In this case, if we type CustomerNumber =1 then the OrderNumber will see that there are three previous orders for that customer, and therefore OrderNumber =4.
Similarly, if CustomerNumber = 2, then the OrderNumber = 3.
I've got the following code, but I'm having issues with setting up a reference to the Orders table (variable y) so that it can count the number of orders for that customer.
Any ideas?
Private Sub CustomerNumber_AfterUpdate()
Dim CustNo As Integer
Dim x As Integer
Dim y As Object
CustNo = CustomerNumber.Value
y = Nz(DLookup("CustomerNumber", "Orders"), "")
x = DCount("OrderNumber", "Orders", CustNo = y)
OrderNumber = x + 1
End Sub

Thanks in advance,
Cabral

A: I'm not entirely sure why you are attempting to count it the way you are but if your only goal is to get the order count for a given customer number what you need is
DCount("OrderNumber", "Orders", "CustomerNumber = " & myCustNo)

A: I got it to work. I think I was headed off in the wrong direction when I made that initial post. It was easy enough to do in sql so I created a vba code to run the sql version.
Thanks,
Cabral
Private Sub CustomerNumber_AfterUpdate()
Dim CustNo As Integer
Dim sqlQuery As Object
CustNo = CustomerNumber.Value
Set sqlQuery = CurrentDb.OpenRecordset("SELECT COUNT(Orders.CustomerNumber)as Count FROM Orders WHERE CustomerNumber = " & CustNo & ";")
OrderNumber = sqlQuery.Count + 1
End Sub


text:
Q: How can I use indexof and substring and string.format to add random numbers/text in specific place in text? This is my original code and it's working fine but the text content is already in the editor in a Text UI and therefore it's also in the variable textField.
So I don't want to type the text over again also inside the code. For example the word toBeSearched is "almost" so using the string format it will generate new random number each time I press on space between the words: "almost" and  "hours".
But since the text is already in the textField variable I want to parse the place I want to add the random numbers automatic using indexof and substring.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CustomText : MonoBehaviour
{
    public string toBeSearched;
    public Text textField;

    private void Start()
    {
        GenerateRandomHour();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GenerateRandomHour();
        }
    }

    private void GenerateRandomHour()
    {
        string numberName = Random.Range(1, 10).ToString();
        textField.text = string.Format("Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.", numberName);
    }
}

This is the code with the indexof and substring I tried to use but it#s not working good.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CustomText : MonoBehaviour
{
    public string toBeSearched;
    public Text textField;

    private void Start()
    {
        GenerateRandomHour();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GenerateRandomHour();
        }
    }

    private void GenerateRandomHour()
    {
        string result = null;
        string result1 = null;
        int ix = textField.text.IndexOf(toBeSearched);

        if (ix != -1)
        {
            result = textField.text.Substring(0, ix + toBeSearched.Length);
            result1 = textField.text.Substring(ix + toBeSearched.Length, textField.text.Length - (ix + toBeSearched.Length));
        }

        result1 = result1.TrimStart();

        string numberName = Random.Range(1, 10).ToString();
        textField.text = string.Format(result + " {0} " + result1, numberName);
    }
}

Again the word toBeSearched is "almost" and I used a breakpoint and result contain the text until almost: "Hello my friend, It's about time to wakeup. You were sleeping for almost" and the variable result1 contain the rest of the text: "hours. My name is NAVI and i'm your navigation helper in the game."
But now when I'm pressing the space key it's inserting each time a new random number but it's not replacing the whole text like in the original code above.
So the result is many numbers in the text.
Not sure why it's not working like the original code.

A: The reason why it's not working is because you're changing the value of textField.text, so when you repeat the process the substrings are generated with this new value, including the number. You shouldn't give up your first solution, it's much cleaner. Store the original value of the text field on Start:
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CustomText : MonoBehaviour
{
    public string toBeSearched;
    public Text textField;
    private string defaultValue;

    private void Start()
    {
        defaultValue = textField.text;
        GenerateRandomHour();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GenerateRandomHour();
        }
    }

    private void GenerateRandomHour()
    {
        string numberName = Random.Range(1, 10).ToString();
        textField.text = string.Format(defaultValue, numberName);
    }
}

Add the {0} directly to your text field value in the inspector:
Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.

A: The problem is when you are adding a number in a specified spot, so every time you press space, it is using the existing text as the template and thus the old number stays,along with adding a new one.
Instead, you want to search between the two words "almost" and "hours" so you can replace whatevers between them. You can do this the by adding another indexOf search, but itll be easier using regex.
string result = Regex.Replace(textField.text, "(? <=almost).+?(?=hours)" , numberName);
textField.text = result;

Although your first solution looks cleaner, and if you want to keep the text in the inspector, Nathalia's answer would work


text:
Q: Check if a point can be written as a linear combination with coefficients $\in[0,1]$ Given a finite number of points $x_1,x_2,x_3,...,x_n$ in the real 2D vector space, a linear combination of these points is a point of the form $\alpha_1x_1+\alpha_2x_2+...+\alpha_nx_n$.
Suppose a set of points $x_1,x_2,x_3,...,x_n$ and a point $x$ are given. What is a method to check whether $x$ can be written as a linear combination (with coefficients $\in[0,1]$) of all the points from the given set?

A: The codomain of the linear combination is the convex hull of the points that are obtained by saturating the alphas. There are $2^n$ of them. (You can visualize this shape as a projection of an hyper-parallelipiped from $n$D space to 2D.)
$x$ can be reached when it is inside that hull, which is a convex polygon of $2n$ vertices.
In the figure, $n=4$.

You can check if a point is inside a convex polygon of $n$ sides in $O(\log n)$ operations, seeing it as two monotone chains.
You can build the hull of the $n$ projected vectors incrementally, by adding the new point to every vertex of the current hull, unless the sum falls inside the hull. This should be doable in $O(n\log n)$ operations.


text:
Q: C -error: expected ';', ',' or ')' before '=' token I need help. It's displaying "error: expected ';', ',' or ')' before '=' token"
at line 5 (at the getRandom method) when i try to build and then run it. I've gone through it several times over and over again and i can't seem to figure out what the problem could be
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

double getRandom (double min = -1, double max = 1) {
    return min + (rand() * (max - min) / RAND_MAX);
}

int totalPoints = 0;
int pointsInCircle = 0;

void *countPoints (void *X) {
    for (int i = 0; i < totalPoints; i++) {
        double X = getRandom();
        double Y = getRandom();
        if (X*X + Y*Y <= 1)pointsInCircle++;
    }
    return NULL;
}

int main()
{
    srand(time(NULL));
    pthread_t thread;
    printf ("Enter total points for experiment : ");
    scanf  ("%d" , totalPoints);
    pthread_create(&thread, NULL, &countPoints, NULL);
    pthread_join(thread, NULL);

    double PI = (4.0 * pointsInCircle) / totalPoints;
    printf ("Approximate value for PI for total points %d is: %d " , totalPoints, PI);

    return 0;
}

A: double getRandom (double min = -1, double max = 1) {
    return min + (rand() * (max - min) / RAND_MAX);
}

This is not C.
double getRandom (double min, double max) {
    return min + (rand() * (max - min) / RAND_MAX);
}

When you call it with no actual arguments in your code
    double X = getRandom();
    double Y = getRandom();

you should replace these calls with
    double X = getRandom(-1, 1);
    double Y = getRandom(-1, 1);


text:
Q: How to bypass Java not being able to extend from multiple classes I think I have a design problem in my Java app, but I cannot figure out how to solve or bypass it.
Say I have an interface and an abstract class implementing it as follows:
public interface IntegerCollection extends Collection<Integer> {
  public int sum();
}

public abstract class AbstractIntegerCollection
                extends AbstractCollection<Integer> implements IntegerCollection {
  public int sum() {
    // fancy code to calculate the sum of all collection members (just an example)
  }
}

Now I would want to make this class instantiable by using the existing implementations of Collection (e.g., LinkedList); something like this:
public class IntegerLinkedList extends AbstractIntegerCollection, LinkedList<Integer> {

}

IntegerCollection ic = new IntegerLinkedList();

However, this does not work because Java does not support extending several  classes. Also it looks quite ugly to me, as there is a mixture of hierarchies.
Of course, I could let IntegerLinkedList implement IntegerCollection instead of letting it extend AbstractIntegerCollection. But then, I would have to repeat the code for sum() in all other implementations (e.g., IntegerArrayList).
Is there a better way to do this?

A: I'm not sure what exactly, you are trying to achieve, but rather you could implements List instead of extending LinkedList
public class IntegerLinkedList
             extends AbstractIntegerCollection
             implements List<Integer>
 {

 }

But, you need to implements all abstract method of List.

A: Since java 8 it has been possible to include implementations in an interface by using the default keyword. Therefore you don't need AbstractIntegerCollection - all the common code can be put in the interface. Here is an example:
import java.util.Collection;
import java.util.LinkedList;

public class Main {

    interface IntegerCollection extends Collection<Integer> {

        default int sum() {
            int sum = 0;
            for (int a : this)
                sum += a;
            return sum;
        }
    }

    static class IntegerLinkedList extends LinkedList<Integer> implements IntegerCollection {

    }

    public static void main(String[] args) {
        IntegerCollection list = new IntegerLinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println(list.sum());     // Prints 6
    }
}

This works, but I'm not sure it's a good idea. I'd think very carefully before extending a class like LinkedList. Some people also consider it an anti-pattern to extend generic classes with non-generic ones.
Another thing to be aware of is that it is not possible to write default methods for the methods of Object like equals and toString etc.
Since you are using Java 7, the above solution is not available. However, with a load of tedious forwarding methods, you can do it using composition rather than inheritance. Josh Bloch's book Effective Java gives a very good explanation of why composition is preferable anyway. Here is an (incomplete) example - you'll need to add a few more forwarding methods to avoid UnsupportedOperationExceptions when you try doing other things with the list.
import java.util.*;

public class Main {

    abstract static class AbstractIntegerCollection extends AbstractCollection<Integer> {

        public int sum() {
            int sum = 0;
            for (int a : this)
                sum += a;
            return sum;
        }
    }

    static class IntegerLinkedList extends AbstractIntegerCollection implements List<Integer> {

        private final List<Integer> list = new LinkedList<>();

        @Override
        public Iterator<Integer> iterator() {
            return list.iterator();
        }

        @Override
        public int size() {
            return list.size();
        }

        @Override
        public boolean addAll(int index, Collection<? extends Integer> c) {
            return list.addAll(index, c);
        }

        @Override
        public Integer get(int index) {
            return list.get(index);
        }

        @Override
        public Integer set(int index, Integer element) {
            return list.set(index, element);
        }

        @Override
        public boolean add(Integer element) {
            return list.add(element);
        }

        @Override
        public void add(int index, Integer element) {
            list.add(index, element);
        }

        @Override
        public Integer remove(int index) {
            return list.remove(index);
        }

        @Override
        public int indexOf(Object o) {
            return list.indexOf(o);
        }

        @Override
        public int lastIndexOf(Object o) {
            return list.lastIndexOf(o);
        }

        @Override
        public ListIterator<Integer> listIterator() {
            return list.listIterator();
        }

        @Override
        public ListIterator<Integer> listIterator(int index) {
            return list.listIterator(index);
        }

        @Override
        public List<Integer> subList(int fromIndex, int toIndex) {
            return list.subList(fromIndex, toIndex);
        }

        // More of these
    }

    public static void main(String[] args) {
        IntegerLinkedList list = new IntegerLinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println(list.sum());     // Prints 6
    }
}

This solution is far from perfect. For one thing, it would be better if IntegerLinkedList extended AbstractList<Integer> rather than just AbstractCollection<Integer>, but then you couldn't extend AbstractIntegerCollection too.


text:
Q: Jfreechart piechart generation I am trying to generate a piechart from an existing application but am getting errors.
The latest error is:
createPieChart(java.lang.String,org.jfree.data.general.PieDataset,org.jfree.chart.labels.PieSectionLabelGenerator) in efa.util.chart.ChartUtil cannot be applied to (java.lang.String,org.jfree.data.general.PieDataset)
[javac]             sectorChart = ChartUtil.createPieChart("",xy);
[javac]                                    ^
Besides this, I also need to add a third argument in the function call, which is PieSectionLabelGenerator labelGenerator. However, I don't know how to do that. Have read the docs/api but still am unsure. What would you advise?
The code I am using is
imports (please see below)
declaration in the code is JFreeChart sectorChart;

the function:

private void genChart(){
  DefaultPieDataset pieDataset = new DefaultPieDataset();
  pieDataset.setValue("JavaWorld", new Integer(75));
  pieDataset.setValue("Other", new Integer(25));

  PieDataset xy = pieDataset;
  sectorChart = ChartUtil.createPieChart("",xy,);
}

I don't think there is anything wrong with my imports, nor declaration of the object. Please let me know if you'd like to see these, I'm leaving them out for brevity of this post.
I'm unable to make the answer below work for my app specifically. But I have this fragment of code in my ChartUtil.java file
public static JFreeChart createPieChart(final String title,
            final PieDataset dataset, PieSectionLabelGenerator labelGenerator) {

        final JFreeChart chart = ChartFactory.createPieChart(title, dataset,
                false, true, true);

        labelGenerator = labelGenerator != null ? labelGenerator
                : new StandardPieSectionLabelGenerator("{2} {0}",
                        NumberFormat.getNumberInstance(),
                        NumberFormat.getPercentInstance());

        PiePlot plot = (PiePlot) chart.getPlot();
        ChartUtil.formatPiePlot(plot);
        plot.setLabelGenerator(labelGenerator);

        PieRenderer renderer = new PieRenderer();
        renderer.setColor((PiePlot) chart.getPlot(), dataset);

        return chart;

    }

I believe we need to figure out how to pass a PieSectionLabelGenerator into the function as an argument...

A: Regarding your edit:
There is a class that implements the interface you require, the StandardPieSectionLabelGenerator which when passed to your method should allow for chart creation.  The alternative is creating a class to implement the method yourself.  I think it depends on exactly what you are trying to achieve with the labels.
public class SO {
public static void main(String[] args){
      DefaultPieDataset pieDataset = new DefaultPieDataset();
      pieDataset.setValue("JavaWorld", new Integer(75));
      pieDataset.setValue("Other", new Integer(25));

      JFreeChart chart = SO.createPieChart("Pie", pieDataset, new StandardPieSectionLabelGenerator());
      JFrame frame = new JFrame("Pie");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(new ChartPanel(chart));
      frame.pack();
      RefineryUtilities.centerFrameOnScreen(frame);
      frame.setVisible(true);
}

public static JFreeChart createPieChart(final String title,
        final PieDataset dataset, PieSectionLabelGenerator labelGenerator) {

    final JFreeChart chart = ChartFactory.createPieChart(title, dataset, false, true, true);
    PiePlot plot = (PiePlot) chart.getPlot();
    ChartUtil.formatPiePlot(plot);
    plot.setLabelGenerator(labelGenerator);
    PieRenderer renderer = new PieRenderer();
    renderer.setColor((PiePlot) chart.getPlot(), dataset);
    return chart;
}
}


text:
Q: Is there any way to preserve the actual function, even after wrapping up with a decorator in python?     @dec_sub
    def sub(a, b):
        c= a-b
        return c

    def dec_sub(func):
        def wrapper(a, b):
            if a<b:
                a, b = b, a
            return func(a, b)
        return wrapper

    print(sub(48, 9)) # first digit is bigger than the second one yields positive return
    print(sub(1, 8)) # second digit is bigger than the first one also yields positive return

#Output : 39
          7

In the above code, how to use the function 'sub' in a usual way without the influence of the decorator?

A: You don't need to use decorator syntax to create a decorated function.
def sub(a, b):
    c = a - b
    return c

wrapped_sub = dec_sub(sub)

Or, you can use func_tools.wraps to create an object that exposes a reference to the original function.
from functools import wraps

def dec_sub(func):
    @wraps(func)
    def wrapper(a, b):
        if a<b:
            a, b = b, a
        return func(a, b)
    return wrapper

@dec_sub
def sub(a, b):
    c = a - b
    return c

sub(48, 9)   # the decorated function
sub.__wrapped__(48, 9)  # the original function


text:
Q: GNU screen color and pine I use GNU screen to run pine mail reader. I use external aspell to do spellchecking for the e-mails I sent. The problem is that when aspell finishes, pine restores the old content of the terminal, but the color is all wrong. The font becomes white instead of black, which looks very bad on the the gray background. After typing something for a while, pine redraws parts of the screen, and that looks ok, but initially it looks very hard to read.
The problem does not exist when pine is run directly, not from within screen. I do not know how to begin the troubleshooting. Any ideas?
Pine version: Alpine 2.00 (LRH 1167 2008-08-23)
GNU screen version: Screen version 4.00.03 (FAU) 23-Oct-06

Update 11 Dec 2011:
The problem also occurs in some cases when resuming composition with Ctrl+O (no aspell involed).
The following do not help:

*

*Ctrl+L in pine to refesh screen,

*adding "altscreen on" in ~/.screenrc

*adding "bce on" or "bce off" in ~/.screenrc (I tried both, as I am not sure what the default is)

*Starting screen with TERM=xterm-256color screen

A: I think I have resolved it. phunehehe was right about trying to change the terminal type. However, "TERM=xterm-256color screen" does not work because the TERM variable only tells screen what kind of terminal screen is run in. It does not tell screen to emulate that particular terminal. So, the solution was to include
term "screen-256color"

in ~/.screenrc configuration file. This seemed to solve the problem, but....
Update 12 December 2011: Actually doing the above fixed the color problem, but created another problem: Delete key no longer works in pine. It turned out that the computer on which screen is running lacks "screen-256color" terminfo file, and since it cannot find it, it reverts to the basic vt100 terminal. After trying several term settings, I found that "xterm-color" has neither Delete-key nor color problem. I do not understand why or how it works.


text:
Q: Организация полнотекстного поиска Не могу пока сообразить, как (вернее в каком виде) построить индекс(ы) для организации полнотекстного поиска по документам. Если есть варианты - прошу поделиться.
Исходные данные

*

*Документы помещаются в таблицу в виде BLOB'ов;

*Перед занесением в таблицу - документ сжимается по алгоритму LZMA и/или PPMd/PPMz, в зависимости чем сожмется лучше;

*Нужно обеспечить поиск по части слова. Например, по строке поиска "мам" должен быть найден документ, содержащий "Мама мыла раму";

*Нужно обеспечить сортировку найденных документов в зависимости от "расстояния" между найденными словами. Например, по строке поиска "мама рам", среди найденных документов "Мама мыла раму" и "Мама мыла белую раму" - первый документ в сортировке должен быть выше, так как между "мама" и "рам" у него слов меньше, чем во втором;

A: Можно последовать примеру PostgreSQL
В нём для полнотекстового поиска используется GIN-индекс по tsvector'ам документов. Сами tsvector'ы хранить большой необходимости нет... с одной оговоркой, о ней далее.

*

*tsvector это отсортированный массив основ слов (слов, обработанных стеммером) из документа.

*

*Он отсортирован ради ускорения поиска и не содержит одинаковых слов по нескольку раз, поэтому ещё и меньше места занимает.

*Стеммер преобразовывает разные формы одного слова в одинаковые строки, так обеспечивается поиск с учётом разных форм одних и тех же слов. Он обычно сильно специфичен для конкретного языка, как алгоритмами, так и словарями.

*Обычно они ещё фильтруются от стоп-слов (которые не отражают содержание документа и нужны больше для структуры), потому что в поиске от них больше вреда, чем пользы. Разумеется, тоже зависит от языка.

*GIN-индекс это отображение из отдельных элементов некоего значения (в котором есть много элементов, вроде массива, коим является и tsvector) в множества строк, в значениях которых эти элементы имеются. То есть, дерево поиска, в котором ключ это основа слова, а значение это множество идентификаторов документов.
Имея tsvector запроса, поиск по описанному индексу производится путём свёртки (fold, reduce) пересечением отдельных множеств из индекса по элементам tsvector из запроса.

*

*PostgreSQL на самом деле использует для запросов другой тип, tsquery, с поддержкой операторов поиска, но я рассматриваю упрощённый случай.

Описанное решение, впрочем, никак не учитывает ранжирования по расстоянию между словами, но это весьма непросто проверять эффективно. Во всяком случае, сходу я ничего назвать не могу.
Сходу в голову приходит только сортировка по расстоянию Левенштейна между tsvector'ами без сортировки (массивами основ слов без стоп-слов) запроса и совпадения. Но мне это видится очень неэффективным решением, особенно для больших документов (на них Левенштейн будет фактически сортировать по возрастанию размера).


text:
Q: c# - pull records from database without timeout i have a sql query with multiple joins & it pulls data from a database for processing. This is supposed to be running on some scheduled basis. So day 1, it might pull 500, day 2 say 400.
Now, if the service is stopped for some reason & the data not processed, then on day3 there could be as much as 1000 records to process. This is causing timeout on the sql query.
How best to handle this situation without causing timeout & gradually reducing workload to process?
TIA

A: Look at your query, it could be that its not optimised, put indexes where appropriate. Without seeing your table structure, query, cant help any more.

A: create a batch process.  Allow no more than say n records to process.  Lets say n = 100 ...
then make your select queries to only select top 100 until there are no more records to process.
YourCommandObject.CommandTimeout = 0;

This will allow your command to run forever.
Note this could cause database locks and other issues.  If you use the batch process I described above and determine the longest running query you can set your connect timeout to what is necessary.

A: One practical solution would be to increase the command timeout:
var com = yourConnection.CreateCommand();
com.CommandTimeout = 0;
...

The CommandTimeout property is the time (in seconds) to wait for the command to execute. The default is 30 seconds.  A value of 0 indicates no limit, and should be avoided in a CommandTimeout because an attempt to execute a command will wait indefinitely.


text:
Q: Google Cloud Endpoint no result via JavaScript Client I am hosting an GAE Application and try to get Google Clound Endpoints to work. Now everything is setup and tested with curl:
curl http://localhost:8888/_ah/api/myendpoint/v1/queryData

Returns exactly 1 item which is correct:
{
  "items" : [ {
    "id" : "220",
    "timestamp" : "1371475009682951",
    "identifier" : "test1.0",
    "value" : "523"
  } ]
}

For no reason the same call through my JavaScript client returns nothing:
gapi.client.myendpoint.queryData().execute( function(result) {
        console.log("result: " + result);
});

The output I get is:
result: [object Object]

What am I missing out?
Thanks for your help.

A: result is already a JSON Object and not a string.
With "result: " + result you force casting the object to a string and [object Object] is just the way this is displayed by default.
For example console.log("result: " + {"name": "I'm an object!"}) will give you exactly the same output
Try console.log(result) instead and you should see the real contents of the response.


text:
Q: Upload file and post JSON together to an API I am developing a macro to compress PDF files, for this purpose I am using ILovePDF API.
https://developer.ilovepdf.com/docs/api-reference#upload.
I am just unable to figure out how I can POST JSON Data and Upload a file.
This is a snippet of code:
task = "task id here"
server = "url here"
token = "token here"
file_to_upload = "this is the real deal"

With CreateObject("MSXML2.ServerXMLHTTP")
            'Upload
            .Open "POST", "https://" & server & "/v1/upload", False
            .setRequestHeader "Authorization", "Bearer " & token
            .setRequestHeader "Content-type", "application/json"
            .send ("{""task"": """ & task & """,""file"": """ & file_to_upload & """}")

As you can see, need to POST task and file. The task is a string and file is the PDF file stored in my local storage.
Can anyone help me with this?
Thanks!


text:
Q: How to properly modify the contents of an LVM Logical Vollume that is being use by a Virtual machine Q1 - How to properly modify the contents of an LVM Logical Vollume that is being use by a Virtual machine?.
Q2 - On Xen?.
Q3 - On VirtualBox?.
Q4 - On KVM?.
Thanks for our time.

A: You don't: you have to shut down the vm.  Or at the very least, make sure the vm does not have the partition mounted that you are trying to mount in the host.


text:
Q: Django - Store unescaped html in model I am trying to store raw, unescaped HTML inside one of my Django models for display on my home page. However, when I store it in a TextField it gets escaped, and ends up just being displayed as raw text. How can I store raw HTML in a Django model?
** EDIT **
It seems as if its not getting escaped in the model layer, but in the Template layer. Is there a special tag I should use? I checked the value in the shell and it's just fine, but for some reason when i did {{ block.html } (html is the attribute of the block object that stores the actual HTML) in the template, it comes out like this:

This is a very important block

it has very significant content!

A: You can use the safe filter to present unescaped text, or escape filter to present escaped text. You can also use autoescape tag to set a block. ({% autoescape on %} or {% autoescape off %})


text:
Q: Information File Store I am looking for the best possible way to create a file store.  In this file store I will be storing information on contact details etc. I will need to modify the details in the text file.  I just wanted to get some opinions of what would be the best way to do this?

A: It depends on the size of the project.

*

*For small projects: you can use something simple like XML, JSON, etc...

*For bigger projects: you should use an SQL database, like MySQL, SQLite (very handy!)

And it is always nice to use SQLite! It is a simple SQL database library that stores the databases in one single file.

Since you have to use something simple with basic File IO, I would suggest taking one of the simple formats, like XML, JSON, CSV. Or to score better, write your own binary files, using DataOutputStream and DataInputStream.
Your file format could be something like this:

*

*arbitrary number of bytes: fixed header (like: "PendoContactsFormat")

*4 bytes (ie: int), number of contacts

*

*(for each contact:)

*2 bytes (ie: short), number of fields in this contact

*

*(for each field in this contact:)

*2 bytes: size of the field header

*n bytes: field header

*2 bytes: size of the field value

*n bytes: field value

A: CSV may be the right format, if you want to be able to edit this file manually and let non-programmers to edit it.


text:
Q: How can I simultaneously run two instances of Firefox on different computers using the same profile? I have a roaming profile set up for myself on my network (via Group Policy based redirection of My Docs and Desktop).  Sometimes, I need to access a remote computer via RDC with the same credentials I am logged on to my local computer with, so I effectively have my own profile open twice on two computers.
I've noticed two peculiar (and frustrating!) outcomes of this:

*

*Firefox always asks to check my add-ons are compatible with the current version of FF when I go to a different workstation

*When I try to open Firefox simultaneously on the local and remote machine I get the message "Firefox is already open but not responding".

Any way to avoid this?

A: First Update to the same version on both sides. This should fix issue 1.
Second When you open Firefox it creates a Parent.lock in the sub folder of "%APPDATA%\Mozilla\Profiles"  this is what causes that message. It can't be deleted while Firefox is open easily.
I don't know if your second request is plausible, if someone else knows a way let me know, so I'd recommend Multiple profiles:
Modify your firefox shortcut to be:
"...\firefox.exe" -p -no-remote

This will allow you to open a second profile which you could name Remote, for instance and have the two separate profiles open on each computer.
As far as I know Firefox will not let you open the same profile twice as this could cause some major corruption.


text:
Q: nav-tabs won't change with click in bootstrap I made two tabs for Fixtures and Results, but when I click on Result tab nothing has change and it remains on Fixtures tab !
This is my code:

Fixtures

Results

                            Manchester United
                            vs
                            Tottenham
                            12:45

                            Manchester United
                            5-2
                            Tottenham
                            Report

How can I fix this to switch between tabs and show its content ?

A: You placed #service-one and #service-two in two different tab contents. That is why its not working.
Place them inside #myTabContent

        Fixtures

        Results

        .....

        .....

Here is a demo


text:
Q: Android app custom event history log For an Android app I want to make a custom history event log which I can display on a screen.   N.B.  - the events in this are NOT for debugging and have nothing to do with LogCat.  These are application-domain events related to the ordinary user's use of the program.   This application runs in an industrial environment and may stay running for several days during which time about a thousand log entries might be collected.  Each entry would be a string about 100-150 characters long, so the total size of this log would be well under 1M.
This log should be persistable so if the device is shut off or suffers battery failure or a crash, the log can still be read the next time it's started.  The user can clear the log if he wants.
I'm thinking of creating a class that implements Serializable and "has-a" string array of some kind for the events, then serializing that class out to a file for persistent storage.  The class would have methods for adding new events, clearing events, reading events sorted or filtered by time/date, type, or user (all fields in the event string). When the app is started it would read it in, and every time a new event is logged it would write out a new copy.   For displaying it I would probably use a ListView.
Is this an OK way to do this?    Does Android already have any built-in classes for doing this so I don't have to reinvent the wheel?

A: short answer:
that sounds like something where you should use sqlite for
detail:
I would not go for for serializing a class with a string as you describe for the following reasons:

*

*you write the same data over and over again ( consumes more resources than needed )

*you would have to be careful when writing to not loose data - especially if you write over your old serialized file in your described scenario of phone-shut down ..

*you would have to implement the needed sorting - you would get all this for free and established with a database
All you describe sounds really that you should go for a DB here - just to put it on the plate there is also the option to use SharedPreferences - but with your descibed data-size and your need for sorting and stuff I would go for the DB


text:
Q: Defining a time varying uniform charge density I am having trouble identifying the best manner to define my problem.  More specifically, suppose one has a three dimensional, spherical surface charge density.  The density is uniform, meaning it is just a constant value $\rho$ everywhere on the surface $S$.  This surface can easily be defined by the following parametrization:
$$
S = R\sin\theta\cos\phi \hat{a}_x + R\sin\theta\sin\phi \hat{a}_y + R\cos\theta\hat{a}_z
$$
Thus, we can simply state the following to define the surface charge density:
$$
\rho(\mathbf{r})=
\begin{cases}
\rho,\text{for }(x,y,z)\in S\\
0,\text{otherwise}
\end{cases}
$$
However, now suppose that we wish to oscillate the sphere up and down sinusoidally in the $z$ direction according to:
$$
M(t)=\Delta z \cos(\omega t)
$$
In other words, the surface becomes:
$$
S = R\sin\theta\cos\phi \hat{a}_x + R\sin\theta\sin\phi \hat{a}_y + (R\cos\theta+M(t))\hat{a}_z
$$
The surface charge density is still defined as shown above in the piecewise function, only now $S$ has changed form a bit.
So now here is the main point of the question.  Let's suppose I want to calculate $\frac{\partial \rho(\mathbf{r})}{\partial t}$.  $\rho$ isn't actually an explicit function of the coordinates or time other than how its defined in the piecewise function, so how can I calculate the temporal derivative?  I thought maybe I can use Heaviside step functions but it is tricky with an infinitesimally thin surface.  I then thought perhaps use Dirac delta functions such as:
$$
\rho(\mathbf{r},t) = \rho\left( \delta(x-R\sin\theta \cos\phi)\delta(y-R\sin\theta\sin\phi)\delta(z-R\cos\theta-M(t)) \right)
$$
But this doesn't  really seem correct , as it seems like a sloppy use of the Dirac Delta (i.e., treating it like the Kronecker delta when it is more nuanced than that).
If I write out the total derivative, it seems like all of the terms go to zero because it necessarily involves derivatives of $\rho$ with respect to the spatial coordinates, which is zero because it is simply equal to a constant value within the specified domain.

A: Some points are never reached by the oscillating sphere. Here the charge density is always zero, and so you can say the time derivative is zero at these points. Other points, such as $(0,0,R+ \frac{\Delta z}2)$ are reached periodically. At one instant at such a point, the charge density is $\rho,$ while immediately after its zero. The charge density at such points is discontinuous in time, and hence the time derivative doesn't exist.
Added: For example, for a spherical shell with inner radius $r_1$ and outer radius $r_2$, define the function $f: \mathbb{R}^4 \to \mathbb{R}$ by
$$f(x,y,z,t) = \begin{cases} \rho \Psi(x^2+y^2+(z-M(t))^2), &r_1^2< x^2+y^2+(z-M(t))^2 < r_2^2\\ 0 &\text{otherwise},\end{cases}$$
where $\Psi$ is a bump function with domain $(r_1^2,r_2^2)$ as on the wiki page. In short, it is a function which is zero outside $(r_1^2,r_2^2)$ which quickly goes to $1$ inside  $(r_1^2,r_2^2)$, in such a way that the function is smooth (infinitely differentiable). Try to verify that this function represents a oscillating spherical shell, and try to intuitively see that it should be differentiable as $\Psi$ is differentiable. If you find it worth the time, you could try to write out a rigorous argument that $f$ is time-differentiable.


text:
Q: Is it possible to set a JavaFX static property in CSS? Sample FXML with the BorderPanel.alignment "static property":
<BorderPane>
  <top>
    <Label text="My Label" BorderPanel.alignment="CENTER"/>
  </top>
</BorderPane>

The CSS-supported version:
<BorderPane stylesheets="Style.css">
   <top>
     <Label text="My Label" styleClass="labelClass"/>
   </top>
</BorderPane>

Style.css would be:
.labelClass
 {
   -fx-borderpanel-alignement: center
 }

A: For JavaFX versions 2.0 to 2.2 => no you cannot set the static layout properties via css.
You can create a feature request in the JavaFX jira to ask this functionality be implemented in a future JavaFX version.

A: You can apply it programatically. For example if you want to center all the widgets of a GridPane, instead of writing GridPane.halignment="CENTER" in the XML declaration of each widget, you can do this in Java :
for(Node node : gridPane.getChildren())
{
    GridPane.setHalignment(node, HPos.CENTER);
}

Unfortunately I don't think you can factorize layouts as in Android :(


text:
Q: Not able to see Usage History under Azure Service connection for yaml pipeline Background -
I have created one multi-stage yaml pipeline which contains the stages - BUILD, DeployToDEV, DeployToUAT, DeployToPROD. For deployment to azure web services, I used deployment job in the stages. In those deployment jobs, I'm using separate Service connections for different stages.
Issue -
If I create the release using classic UI and used the Service connections, then I can see the Usage history of releases under Service Connections. But for multi-stage yaml pipeline in which I'm deploying the web apps through multiple stages, I can't see the entry of same under usage history of the service connection. Though these service connections are getting used by the deployment jobs of the stages. So how we can resolve this issue.


text:
Q: sample android app does not deploy in android device I'm just starting to learn developing in android. I'm following the nativescript getting started guide but can't seem to proceed. It mentions to run tns run android while the phone is connected. but this doesn't seem to work. USB debugging is enabled on my phone and developer options.
at this point the project builds but does not appear on my phone. (I tried using the genymotion emulator before, maybe I'm wrong with my assumption that it would just appear in my android phone just like how genymotion does it)
check with tns devic command, it detects my android phone but says unreachable. what does that mean?
also would there be other specific options in my phone that I need to set in order to have this app deployed on my phone?

A: I would suggest you try using ADB directly first. Following are the steps that can be used to push your app to your phone.

*

*First connect your phone to the linux machine using the USB port.

*Start adb server using adb start-server

*Run adb devices. This should list your phone below with a phone code or name.

*Transfer the apk to your phone using adb -s <device code> push <app_name>.apk

*The app should now be available on your phone.

You can also specify a location on your phone where you want your app to be pushed. Alternatively you can also use adb to install the app directly on your phone by using the following command : - adb install <app_name>.apk
Hope this helps.

A: You probably haven't turned on ADB debug mode on your phone.
Edit
Try to install an apk using adb directly. If that works tns is the problem. If that doesn't work, your setup is the problem.

A: If the adb is running and you are still not connectiong to your device after BUILD SUCCESSFUL you might want to try the following command
tns run android --log trace

This will give you addition debug information which you can shows us here in order to help you further.

A: I'm super late, but! if none of these options work, make sure you're using a proper USB cord to connect your device (try different cords)! That's why my device was undetected, even though the abd was running fine!


text:
Q: How to print Subprocess.popen to Pyqt4 textbox I have been trying to make a small PyQt4 widget, but i have trouble pasting the subprocess into the textbox of the widget.
self.textEdit_2 = QtGui.QTextEdit(self.tab_Logcat)
self.textEdit_2.setGeometry(QtCore.QRect(0, 0, 781, 731))
self.textEdit_2.setObjectName(_fromUtf8("textEdit_2"))

def paster(self):
    from subprocess import Popen, PIPE
    cat = subprocess.Popen('adb', stdout=PIPE)
    self.textEdit_2.setText(str(cat))

No matter what i try, it paste to the shell insteed.
i have looked at the other similar thread
How to redirect print result from python shell into qtextedit pyqt?
But it dosent seem to work with subprocess.


text:
Q: Query returns different results depending on column list in SELECT I have the following view:
CREATE OR REPLACE VIEW FRM_STATAGGREGATE_VIEW AS
SELECT a.id aggregate_id,
       SUM(S.PROD_TIME) PROD_TIME1,
       SUM(S.PROD_TIME) PROD_TIME2
FROM wms_aggregate a
LEFT JOIN wms_stat_user s
ON a.id = s.aggregate_id
GROUP BY a.id;

And I have the following query:
SELECT prod_time1, NULL
FROM FRM_StatAggregate_VIEW
WHERE aggregate_id = 183
UNION ALL
SELECT prod_time1, prod_time2
FROM FRM_StatAggregate_VIEW
WHERE aggregate_id = 183;

The query produces the following results:
PROD_TIME1  PROD_TIME2
60  <NULL>
0   0

In other words, when I include both columns in query, they return value of 0, but when only one is included, the return value (60) is correct.
When I clone table used in view and recreate the view, the results are correct.
My question is: is this an Oracle bug? Or are these results possible due to any database/table/view configuration, indexes, etc.?


text:
Q: Is a call to PreferenceManager.setDefaultValues() necessary for clearing preferences? Until now the "Reset to Default" button in the PreferenceActivity of my app did something like this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

That's been working fine, but recently I saw the setDefaultValues method in the PreferenceManager class. The note at the end of the function says that I should call this function after clearing the preferences to set them back to their defaults. So I'm wondering why the documentation is telling me to call this method if everything has been working fine without calling it?
It also doesn't logically seem to be necessary. If you clear the preferences, it's going to do the same thing it did when your application ran for the first time. It's going to use the defaultValue attributes in the preferences to fill in all the values. So it seems redundant to call this extra method.
So is it necessary?

A: In general, this extra call is necessary, but in your particular case, it is basically redundant.
I may be wrong, but the editor method you are using with editor.clear() sets all preferences to null, not their defaults. It is not until the user inflates the PreferenceActivity that the preferences.xml is read and the defaults are set.
Basically, what calling SetDefaultValues() does is set the preferences to the default value only if the preferences are set to null. Say you have a preference called "Age", which the default is set in your xml to "21". Assuming the user has never inflated the pref menu,depending on how you query the preferences, it may give you a null response. This is why querying in the form prefs.getString("prefkey", "defaultvalue"); is good practice. Making this call (and passing in true)prior to the query will set "Age" to the default value of "21". Note: Once the user has set a preference, or inflated the menu, this call has no effect.
However, since you are calling editor.clear() from your preference activity, the preferences are automatically repopulated with the default values from the preferences.xml, and therefore making the call would not be necessary. However, if you made the call from some other activity, it would be required to do so, or all your preferences will be null. For completeness, I would suggest you add the call just as belt and suspenders, and this way, if you ever decide to move your function out of this activity, you won't be wondering why all your preferences are null. It shouldn't have any impact, performance-wise.
Also, not related, but you could save yourself some lines of code by replacing the last 3 lines in your example with preferences.edit().clear().commit();

A: Kindly see the note in that where it says that using true will not erase the set values and reset with the default values.
for that purpose you need to first clear the set values and then call
PreferenceManager.setDefaultValues
to set the default values.
i hope this clears further.


text:
Q: How to convert this Firebase v8 code to v9 code i am new to firebase v9 can anybody help me convert this code to import data from firebase collection-firebase Collection Import

A: As per @Dharmaraj says on the link that he provides you may check this sample code below for v9. You may refer to this documentation.
import database from './firebase';
import { doc, onSnapshot, collection, query, where, onSnapshot } from "firebase/firestore";

    const [posts,setPosts] = useStat([]);

    useEffect(() => {
      const q = query(collection(db, "buddies"))
      const unsub = onSnapshot(q, (querySnapshot) => {
        console.log("Data", querySnapshot.docs.map(d => doc.data()));
      });
    }, [])


text:
Q: Blog posts not showing while using the FOR loop I have the following .js code but when i test the site, it only displays the wordings as seen in each  but no contents. What i want to achieve at the end is to be able to display 5 posts and also add a link at the bottom to display more mosts:
$(document).ready(function(){
    url = 'http://hopexxx.com/category/daily-devotion/feed/';
    $.ajax({
        type: "GET",
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
        dataType: 'json',
        error: function(){
            alert('Unable to load feed, Incorrect path or invalid feed');
        },
        success: function(data){
            var postlist = data.responseData.feed.entries;
            var html = '
';
            for (var i = 0; i < 5; i++) {
                html += '
';
                html += '';
                html += '
entry.title
';
                html += '
author
';
                html += '
publishedDate
';
                html += '
contentSnippet
';
                html += '';
                html += '
';
            }
            html += '
';
            $("#postlist").append(html);
            $("#postlist ul[data-role=listview]").listview();

        }});
    });

A: try a $.each loop on data.responseData.feed.entries, see here for details

A: If you know that your postlist is not null, and that each entry has properties 'title', 'author', 'publishedDate' and 'contentSnippet' try this:
var postlist = data.responseData.feed.entries;
var html = '
';
for (var i = 0; i < 5; i++) {

    var entry = postlist[i];

    html += '
';
    html += '';
    html += '
' + entry.title + '
';
    html += '
' + entry.author + '
';
    html += '
' + entry.publishedDate + '
';
    html += '
' + entry.contentSnippet + '
';
    html += '';
    html += '
';
}
    html += '
';
    $("#postlist").append(html);


text:
Q: How to map Unevaluated over a list I have a list {a1, a2, ...... , an}, in which all as have been initialized to a number. I want to get:
 {Unevaluated[a1], Unevaluated[a2], ...... , Unevaluated[an]}

Is there a simple way to achieve this using Map, without getting a list of Unevaluated[value of ai]?

A: you can try also:
{a1, a2, a3} = {1, 2, 3};
Unevaluated /@ Unevaluated@{a1, a2, a3}

(*{Unevaluated[a1], Unevaluated[a2], Unevaluated[a3]}*)

A: First a link to a presentation everyone should read:

*

*Working with Unevaluated Expressions - Robby Villegas
Now some additional methods:
List @@ Unevaluated /@ Hold[a1, a2, a3]

Unevaluated /@ Unevaluated @ {a1, a2, a3}

More contrived:
Unevaluated @@@ Thread @ Hold[{a1, a2, a3}]

{Unevaluated /@ Hold[a1, a2, a3]} // ReleaseHold

Delete[{Unevaluated /@ Hold[a1, a2, a3]}, {1, 0}]

A: unevaluatedF = Function[{x}, Unevaluated@x, {HoldFirst, Listable}];

{a1, a2, a3} = {1, 2, 3};
unevaluatedF@{a1, a2, a3}

{Unevaluated[a1], Unevaluated[a2], Unevaluated[a3]}

A: Is this what you're seeking?
Unevaluated /@ {a1, a2, a3, a4}

(*
{Unevaluated[a1], Unevaluated[a2], Unevaluated[a3], Unevaluated[a4]}
*)


text:
Q: use the signature of a generic function dependent on a non-type template argument as template template argument The small program below, which compiles and runs, allows to bridge a runtime variable index of type unsigned with a set of template functions having one template argument J of type unsigned.
In case further clarifications are needed, this is better explained in this question.
The auxiliary functions I wrote use a template template argument, to infer as much info as possible from the original function. The problem is that I could not find a better way to define the template template argument FunWrap other than creating the 2 wrappers wrap_foo and wrap_zoo, whereas I would have liked to use as template template argument directly foo and zoo. Is there a way to do that?
#include <iostream>
#include <utility>
#include <array>
using namespace std;

// boiler plate stuff

template <template <unsigned J> typename FunWrap, unsigned... Is>
decltype(auto) get_fun_ptr_aux(std::integer_sequence<unsigned, Is...>, unsigned i)
{
    typedef decltype(&FunWrap<1>::run) FunPtr;
    constexpr static std::array<FunPtr, sizeof...(Is)> fun_ptrs = { &FunWrap<Is>::run... };
    return fun_ptrs[i];
}

template <template <unsigned J> typename FunWrap, unsigned N>
decltype(auto) get_fun_ptr(unsigned i)
{
    return get_fun_ptr_aux<FunWrap>(std::make_integer_sequence<unsigned, N>{}, i);
}

// template functions to be bridged with runtime arguments
// two functions with same template arguments but different signature

template <unsigned J>
void foo() {  cout << J << "\n"; }

template <unsigned J>
double zoo(double x) { return x + J; }

// 1 wrapper per each function

template <unsigned J>
struct wrap_foo {
    static void *run() { foo<J>(); }  // same signature as foo
};

template <unsigned J>
struct wrap_zoo {
    static double run(double x) { return zoo<J>(x); } // same signature as zoo
};

int main()
{
    unsigned index = 5;
    (*get_fun_ptr<wrap_foo,10>(index))();
    cout << (*get_fun_ptr<wrap_zoo,10>(index))(3.5) << "\n";
    return 0;
}

A:
I would have liked to use as template template argument directly foo and zoo. Is there a way to do that?

As foo and zoo are template functions, I'm afraid the answer is no. C++ is notoriously bad at dealing with overload sets/templates. Example: Disambiguate overloaded member function pointer being passed as template parameter


text:
Q: xpages set value to field before action=newDocument I have a simple button with the eventHandler:
<xp:eventHandler event="onclick" submit="true" refreshMode="complete">
        <xp:this.action>
            <xp:openPage target="newDocument" name="/doc.xsp"></xp:openPage>
        </xp:this.action>
</xp:eventHandler>

In lotusScript I would add a value to a field, before composing the form, using:
Call doc_new.ReplaceItemValue("txt_codformularmain","01")
....
....
Set uidoc = w.EditDocument ( True, doc_new )

I tried in the postNewDocument event of the doc.xsp
<xp:this.data>
    <xp:dominoDocument var="Contr" formName="(fmFormularCIP)">
        <xp:this.postNewDocument><![CDATA[#{javascript:Contr.replaceItemValue("txt_codformularmain", "01")}]]></xp:this.postNewDocument></xp:dominoDocument>
</xp:this.data>

I don't want every time the doc is created that value to be, let say, 01, BUT only when the doc. is composed by a specific button. Some other button will have the chance to add the 02 value for that field, and so on.
How can I achieve this in xpages development? Thanks for your time.

A: This is a little bit tricky in Web application development, because what you did in classical Notes development cannot be applied here. I had a lot of issues in this.
The classical scenario is that you have a Page X with some value (say txt_codformularmain will be 01). How do you decide this value "01"?
In some cases, this value is something you have in the page X. So you want to pass a specific value to the target page. One option could be using a query parameter (doc.xsp?myValue=01) and consume it on doc.xsp with param.myValue. Or, you might put a sessionScope variable before going to the target page and consume it by sessionScope.myValue.
It depends on what you need. Query parameter is somewhat safer, because the user might use the same button twice and sessionScope variable causes inconsistent behaviour. On the other hand, query parameter can be changed by the user, so you might have a breach in your application.
Some cases, you want to populate some values at the second page. Simple values (e.g. creation date, user names, etc.) can be populated with forms (i.e. compute value on load). Sometimes it would be more complicated (e.g. the department of the user where you have to lookup some views). For such cases, you need to use postNewDocument event at the target page.
After you have passed the value to the doc.xsp page, you will consume in the way you need. If it's not going to be edited on the page, you may again use postNewDocument event and set value by dataSourceName.replaceItemValue('itemName', param.myValue). If the value can be edited, you would use it as a default value on your field component.
One problem I have experienced: Once you set a value in postNewDocument, you may have problems to change it later, until the document data source saved. This is happening on specific cases. If you experience such a problem, you might use some editable field with readonly attribute. Just keep in mind :)


text:
Q: Simulating Manet using ns2 I'm simulating MANETs, I need the node to be able to broadcast periodic messages and unicast service messages at the same time. Could you please help me learn how to do that.
Also, I would like to have an eavesdropper (Man in the middle) that can intercept both the broadcasted and the unicasted messages. I would appreciate it if you help me connect this node correctly in between.
Best regards.


text:
Q: Point spring bootstrap project to websitename.com/ I have a fully functioning bootstrap project. Whenever I want to access it locally I go to localhost:8080
Now I would like to run it on my server under domain name websitename.com and I want to be able to access first page of my bootstrap project without having to type websitename.com:8080 and instead just type websitename.com/
Is there any way to configure the server to do so? Or is this bootstrap configuration?

A: You have to change your port from 8080 to 80. This is the default http port recognized by browsers.
To achieve that you have to add line
server.port = 80
to your application.properties config file (find details in the documentation)
Note: Depending on operation system usage of 80 port might be restricted to only root user. You'll probably have to run the app with sudo or set up http proxy.