text:
Q: Does "correlation" also mean the slope in regression analysis? I'm reading a paper and the author wrote:

The effect of A,B, C on Y was studied through the use of multiple regression analysis. A,B,C were entered into the regression equation with Y as the dependent variable. The analysis of variance is presented in Table 3.
  The effect of B on Y was significant, with B correlating .27 with Y.

English is not my mother tongue and I got really confused here.
First, he said he would run a regression analysis, then he showed us the analysis of variance. Why?
And then he wrote about the correlation coefficient, is that not from correlation analysis? Or this word could also be used to describe regression slope?

A:
First, he said he would run a regression analysis, then he showed us the analysis of variance. Why?

The analysis of variance table is a summary of part of the information you can get from regression. (What you may think of as an analysis of variance is a special case of regression. In either case you can partition the sums of squares into components that can be used to test various hypotheses, and this is called an analysis of variance table.)

And then he wrote about the correlation coefficient, is that not from correlation analysis? Or this word could also be used to describe regression slope?

The correlation is not the same thing as regression slope, but the two are related. However, unless they left a word (or perhaps several words) out, the pairwise correlation of B with Y doesn't tell you directly about the significance of the slope in the multiple regression. In a simple regression, the two are directly related, and such a relationship does hold. In multiple regression partial correlations are related to slopes in the corresponding way.

A: I am providing codes in R just an example, you can just see answers if you do not have experience with R. I just want to make some cases with examples.
correlation vs regression
Simple linear correlation and regression with one Y and one X:
The model:
y = a + betaX + error (residual)

Let's say we have only two variables:
X = c(4,5,8,6,12,15)
Y = c(3,6,9,8,6, 18)
plot(X,Y, pch = 19)

On a scatter diagram, the closer the points lie to a straight line, the stronger the linear relationship between two variables.

Let's see linear correlation.
cor(X,Y)
0.7828747

Now linear regression and pull-out R squared values.
    reg1 <- lm(Y~X)
   summary(reg1)$r.squared
     0.6128929

Thus coefficients of the model are:
reg1$coefficients
(Intercept)           X
  2.2535971   0.7877698

The beta for X is 0.7877698. Thus out model will be:
  Y = 2.2535971 + 0.7877698 * X

Square root of the R-squared value in regression is same as r in linear regression.
sqrt(summary(reg1)$r.squared)
[1] 0.7828747

Let's see scale effect on regression slope and correlation using the same above example and multiply X with a constant say 12.
    X = c(4,5,8,6,12,15)
    Y = c(3,6,9,8,6, 18)
    X12 <- X*12

    cor(X12,Y)
   [1] 0.7828747

The correlation remain unchanged as do R-squared.
    reg12 <- lm(Y~X12)
    summary(reg12)$r.squared
     [1] 0.6128929
     reg12$coefficients
(Intercept)         X12
 0.53571429  0.07797619

You can see the regression coefficients changed but not R-square. Now another experiment lets add a constant to X and see what this will have effect.
    X = c(4,5,8,6,12,15)
    Y = c(3,6,9,8,6, 18)
    X5 <- X+5

    cor(X5,Y)
   [1] 0.7828747

Correlation is still not changed after adding 5. Let's see how this will have effect on regression coefficients.
        reg5 <- lm(Y~X5)
        summary(reg5)$r.squared
         [1] 0.6128929
         reg5$coefficients
(Intercept)          X5
 -4.1428571   0.9357143

The R-square and correlation do not have scale effect but intercept and slope do. So slope is not same as correlation coefficient (unless variables are standardized with mean 0 and variance 1).
what is ANOVA and Why we do ANOVA ?
ANOVA is technique where we compare variances to make decisions. The response variable (called Y) is quantitative variable while X can quantitative or qualitative (factor with different levels). Both X and Y can be one or more in number. Usually we say ANOVA for qualitative variables, ANOVA in regression context is less discussed. May be this may be cause of your confusion. The null hypothesis in qualitative variable (factors eg. groups) is that mean of groups is not different / equal while in regression analysis we test whether slope of line is significantly different from 0.
Let's see an example where we can do both regression analysis and qualitative factor ANOVA as both X and Y are quantitative, but we can treat X as factor.
    X1 <- rep(1:5, each = 5)
    Y1 <- c(12,14,18,12,14,  21,22,23,24,18,  25,23,20,25,26, 29,29,28,30,25, 29,30,32,28,27)
   myd <- data.frame (X1,Y1)

The data looks like follows.
   X1 Y1
1   1 12
2   1 14
3   1 18
4   1 12
5   1 14
6   2 21
7   2 22
8   2 23
9   2 24
10  2 18
11  3 25
12  3 23
13  3 20
14  3 25
15  3 26
16  4 29
17  4 29
18  4 28
19  4 30
20  4 25
21  5 29
22  5 30
23  5 32
24  5 28
25  5 27

Now we do both regression and ANOVA. First regression:
 reg <- lm(Y1~X1, data=myd)
 anova(reg)

Analysis of Variance Table

Response: Y1
          Df Sum Sq Mean Sq F value    Pr(>F)
X1         1 684.50  684.50   101.4 6.703e-10 ***
Residuals 23 155.26    6.75
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

reg$coefficients
(Intercept)          X1
      12.26        3.70

Now conventional ANOVA (mean ANOVA for factor/qualitative variable) by converting X1 to factor.
myd$X1f <- as.factor (myd$X1)
     regf <- lm(Y1~X1f, data=myd)
     anova(regf)
Analysis of Variance Table

Response: Y1
          Df Sum Sq Mean Sq F value    Pr(>F)
X1f        4 742.16  185.54   38.02 4.424e-09 ***
Residuals 20  97.60    4.88
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

You can see changed X1f Df which is 4 instead of 1 in above case.
In contrast to ANOVA for qualitative variables, in context of quantitative variables where we do regression analysis - Analysis of Variance (ANOVA) consists of calculations that provide information about levels of variability within a regression model and form a basis for tests of significance.
Basically ANOVA tests the null hypothesis beta = 0 (with alternative hypothesis beta is not equal to 0). Here we do F test which ratio of variability explained by the model vs error (residual variance). Model variance comes from the amount explained by the line you fit while residual comes from the value that is not explained by the model. A significant F means that beta value is not equal to zero, means that there is significant relationship between two variables.
 > anova(reg1)
    Analysis of Variance Table

    Response: Y
              Df Sum Sq Mean Sq F value Pr(>F)
    X          1 81.719  81.719  6.3331 0.0656 .
    Residuals  4 51.614  12.904
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Here we can see high correlation or R-squared but still not significant result. Sometime you may get a result where low correlation still significant correlation. The reason of non significant relation in this case is that we do not have enough data (n = 6, residual df = 4), so the F should be looked at F distribution with numerator 1 df vs 4 denomerator df. So this case we could not rule out slope is not equal to 0.
Let's see another example:
 X = c(4,5,8,6,2,  5,6,4,2,3,   8,2,5,6,3,  8,9,3,5,10)
    Y = c(3,6,9,8,6,  8,6,8,10,5,  3,3,2,4,3,  11,12,4,2,14)
    reg3 <- lm(Y~X)
    anova(reg3)

     Analysis of Variance Table

    Response: Y
              Df  Sum Sq Mean Sq F value  Pr(>F)
    X          1  69.009  69.009   7.414 0.01396 *
    Residuals 18 167.541   9.308
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-square value for this new data:
 summary(reg3)$r.squared
 [1] 0.2917296
cor(X,Y)
[1] 0.54012

Although the correlation is lower than previous case we got a significant slope. More data increases df and provides enough information so that we can rule out null hypothesis that slope is not equal to zero.
Lets take another example where there is negate correlation:
 X1 = c(4,5,8,6,12,15)
    Y1 = c(18,16,2,4,2, 8)
   # correlation
    cor(X1,Y1)
 -0.5266847
   # r-square using regression
    reg2 <- lm(Y1~X1)
   summary(reg2)$r.squared
 0.2773967
  sqrt(summary(reg2)$r.squared)
[1] 0.5266847

As values were squared square root will not provide information about positive or negative relationship here. But the magnitude is the same.
Multiple regression case:
Multiple linear regression attempts to model the relationship between two or more explanatory variables and a response variable by fitting a linear equation to observed data. The above discussion can be extended to multiple regression case. In this case we have multiple beta in the term:
y = a + beta1X1 + beta2X2 + beta2X3 + ................+ betapXp + error

Example:
    X1 = c(4,5,8,6,2,  5,6,4,2,3,   8,2,5,6,3,  8,9,3,5,10)
    X2 = c(14,15,8,16,2,  15,3,2,4,7,   9,12,5,6,3,  12,19,13,15,20)
    Y = c(3,6,9,8,6,  8,6,8,10,5,  3,3,2,4,3,  11,12,4,2,14)
    reg4 <- lm(Y~X1+X2)

Let's see the coefficients of the model:
reg4$coefficients

(Intercept)          X1          X2
 2.04055116  0.72169350  0.05566427

Thus your multiple linear regression model would be:
Y = 2.04055116 + 0.72169350 * X1 + 0.05566427* X2

Now lets test if the beta for X1 and X2 are greater than 0.
 anova(reg4)
    Analysis of Variance Table

    Response: Y
              Df  Sum Sq Mean Sq F value  Pr(>F)
    X1         1  69.009  69.009  7.0655 0.01656 *
    X2         1   1.504   1.504  0.1540 0.69965
    Residuals 17 166.038   9.767
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Here we say that the slope of X1 is greater than 0 while we could not rule that the slope of X2 being greater than 0.
Please note that slope is not correlation between X1 and Y or X2 and Y.
> cor(Y, X1)
[1] 0.54012
> cor(Y,X2)
[1] 0.3361571

In multiple variate situation (where the variable are greater than two Partial correlation comes into the play. Partial correlation is the correlation of two variables while controlling for a third or more other variables.
source("http://www.yilab.gatech.edu/pcor.R")
pcor.test(X1, Y,X2)
   estimate    p.value statistic  n gn  Method            Use
1 0.4567979 0.03424027  2.117231 20  1 Pearson Var-Cov matrix
pcor.test(X2, Y,X1)
    estimate   p.value statistic  n gn  Method            Use
1 0.09473812 0.6947774 0.3923801 20  1 Pearson Var-Cov matrix

A:
First, he said he would run a regression analysis, then he showed us
  the analysis of variance. Why?

Analysis of variance (ANOVA) is just a technique comparing the variance explained by the model versus the variance not explained by the model. Since regression models have both the explained and unexplained component, it's natural that ANOVA can be applied to them. In many software packages, ANOVA results are routinely reported with linear regression. Regression is also a very versatile technique. In fact, both t-test and ANOVA can be expressed in regression form; they are just a special case of regression.
For example, here is a sample regression output. The outcome is miles per gallon of some cars and the independent variable is whether the car was domestic or foreign:
      Source |       SS       df       MS              Number of obs =      74
-------------+------------------------------           F(  1,    72) =   13.18
       Model |  378.153515     1  378.153515           Prob > F      =  0.0005
    Residual |  2065.30594    72  28.6848048           R-squared     =  0.1548
-------------+------------------------------           Adj R-squared =  0.1430
       Total |  2443.45946    73  33.4720474           Root MSE      =  5.3558

------------------------------------------------------------------------------
         mpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
   1.foreign |   4.945804   1.362162     3.63   0.001     2.230384    7.661225
       _cons |   19.82692   .7427186    26.70   0.000     18.34634    21.30751
------------------------------------------------------------------------------

You can see the ANOVA reported at top left. The overall F-statistics is 13.18, with a p-value of 0.0005, indicating the model being predictive. And here is the ANOVA output:
                       Number of obs =      74     R-squared     =  0.1548
                       Root MSE      = 5.35582     Adj R-squared =  0.1430

              Source |  Partial SS    df       MS           F     Prob > F
          -----------+----------------------------------------------------
               Model |  378.153515     1  378.153515      13.18     0.0005
                     |
             foreign |  378.153515     1  378.153515      13.18     0.0005
                     |
            Residual |  2065.30594    72  28.6848048
          -----------+----------------------------------------------------
               Total |  2443.45946    73  33.4720474

Notice that you can recover the same F-statistics and p-value there.

And then he wrote about the correlation coefficient, is that not from
  correlation analysis? Or this word could also be used to describe
  regression slope?

Assuming the analysis involved using only B and Y, technically I would not agree with the word choice. In most of the cases, slope and correlation coefficient cannot be used interchangeably. In one special case, these two are the same, that is when both the independent and dependent variables are standardized (aka in the unit of z-score.)
For example, let's correlate miles per gallon and the price of the car:
             |    price      mpg
-------------+------------------
       price |   1.0000
         mpg |  -0.4686   1.0000

And here is the same test, using the standardized variables, you can see the correlation coefficient remains unchanged:
             |  sdprice    sdmpg
-------------+------------------
     sdprice |   1.0000
       sdmpg |  -0.4686   1.0000

Now, here are the two regression models using the original variables:
. reg mpg price

      Source |       SS       df       MS              Number of obs =      74
-------------+------------------------------           F(  1,    72) =   20.26
       Model |  536.541807     1  536.541807           Prob > F      =  0.0000
    Residual |  1906.91765    72  26.4849674           R-squared     =  0.2196
-------------+------------------------------           Adj R-squared =  0.2087
       Total |  2443.45946    73  33.4720474           Root MSE      =  5.1464

------------------------------------------------------------------------------
         mpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       price |  -.0009192   .0002042    -4.50   0.000    -.0013263   -.0005121
       _cons |   26.96417   1.393952    19.34   0.000     24.18538    29.74297
------------------------------------------------------------------------------

... and here is the one with standardized variables:
. reg sdmpg sdprice

      Source |       SS       df       MS              Number of obs =      74
-------------+------------------------------           F(  1,    72) =   20.26
       Model |  16.0295482     1  16.0295482           Prob > F      =  0.0000
    Residual |  56.9704514    72  .791256269           R-squared     =  0.2196
-------------+------------------------------           Adj R-squared =  0.2087
       Total |  72.9999996    73  .999999994           Root MSE      =  .88953

------------------------------------------------------------------------------
       sdmpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
     sdprice |  -.4685967   .1041111    -4.50   0.000    -.6761384   -.2610549
       _cons |  -7.22e-09   .1034053    -0.00   1.000    -.2061347    .2061347
------------------------------------------------------------------------------

As you can see, the slope of the original variables is -0.0009192, and the one with standardized variables is -0.4686, which is also the correlation coefficient.
So, unless the A, B, C, and Y are standardized, I would not agree with the article's "correlating." Instead, I'd just opt of a one unit increase in B is associated with the average of Y being 0.27 higher.
In more complicated situation, where more than one independent variable is involved, the phenomenon described above will no longer be true.

A: Analysis of variance (ANOVA) and regression are actually very similar (some would say they are the same thing).
In Analysis of variance, typically you have some categories (groups) and a quantitative response variable.  You calculate the amount of overall error, the amount of error within a group and the amount of error between groups.
In regression, you don't necessarily have groups anymore, but you can still partition the amount of error into an overall error, the amount of error explained by your regression model and error unexplained by your regression model.  Regression models are often displayed using ANOVA tables and it's an easy way of seeing how much variation is explained by your model.


text:
Q: Tabbar more view controller iPhone I would like to know if there is a way to ensure that every time user presses on the "More" button in tabbar, he or she will be presented with list of views that are in there, not to show current view in which user is in. What I would like to get is always have the list of views on every time user press the "More" button.

A: This seems to work, but there may be some edge cases that I didn't consider.
In the appDelegate:
self.tabBarController.delegate = self;

...

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
   [[viewController navigationController] popToRootViewControllerAnimated:NO];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Datagrid Headers all appearing in one column when CSS Style is used I have a datagrid in my screen display, defined as follows:-

    <asp:DataGrid id="ItemsGrid"
                  BorderWidth="1"
                  CellPadding="3"
                  AutoGenerateColumns="true"
                  runat="server">
        <HeaderStyle CssClass="subHeader"></HeaderStyle>
        <ItemStyle CssClass="normalText"></ItemStyle >
    </asp:DataGrid>

This is displayed like this:-

Without the HeaderStyle item the grid is displayed as I would expect:-

(although the titles are styled wrongly). The CSS is thus:-
.subHeader
{
    clear:both;
    float: left;
    display: block;
    overflow: hidden;
    margin: 0;
    border: 0;
    border-width: 0px;
    border-right-style: solid;
    font-size: small;
    font-family: Verdana;
}

Does anyone know what I am doing wrong here? I have tried the suggestion here but it doesn't make any difference.
Edit
As requested here is the HTML output, first for the version with the HeaderStyle entry:-

        Grade	Kurznamen	Discard Length

        13004	21CRNIMO2-2-2	23.17

and without:-

    Grade	Kurznamen	Discard Length

    13004	21CRNIMO2-2-2	23.17

A: Remove the clear and float rules and you should be good to go.
Also, in case you are not faimiliar with CSS, I recommend you to take a look on some sites like this: http://www.csstutorial.net/


text:
Q: Text animation when hovering [part 2] Previously asked here for some help in regards to fading in some text when hovering over an image, as I couldn't figure out how to make the text float above the images.
Now I've figured it out on my own, but I'm still having issues with the text itself.
You can see a live version of the page here.
What it currently does is it positions every sentence in each language in distinctive rows. What I would like it to do is to show all the lines at a specific point on the page (below the logo, and above the flags)
Also it seems that when I hover the mouse over where the sentences are, they fade in, while I wanted that to happen only when hovering over the flags.
#en {
    height: 150px;
    line-height: 0px;
    color: transparent;
    font-size: 25px;
    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-weight: 300;
    text-align: center;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
}

#en:hover {
    line-height: 150px;
    line-height: 20px;
    color: #e0e0e0;
}

#en img{
    width: 118px;
    height: 78px;
    position: absolute;
    float: bottom;
    clear: bottom;
    bottom: 20px;
    left: 29.8%;
    }

Here's the code on jsfiddle as somebody asked for it last time:
https://jsfiddle.net/f0gfqe6e/4/
Thanks in advance.

A: here you go just put the color as transparent on hover over text

Welcome to Stefan's Gallery, click to proceed to the english version of the site.

CSS
 .en:hover {
         color: transparent;
    }

just give the same to remaining text fields too.

A: I would try making the text a child of the flag and then set the flags to relative position (also probably inline-block from the look of it) and the children to absolute and all at the same top property.  Then use this kind of CSS:
#en-flag > span {
   opacity:0;
   transition:1s;
}

#en-flag:hover > span {
   opacity:1;
}

Since the flags are just images, you can make them background images so the div can be empty for the span.


text:
Q: How to list the contents of a function? A function I have defined has scrolled off hundreds of lines off the console screen.  How do I recall it to display its contents?
I want to achieve like in PowerShell: get-content function:myfunction.


text:
Q: Guice: Why must @Singleton-annotated classes be immutable/thread safe? NOTE:  This question is not about Singleton classes as described in Gamma94 (ensuring only one object ever gets instantiated.)
I read the Guice documentation about the @Singleton attribute:
Classes annotated @Singleton and @SessionScoped must be threadsafe.

Is this the case even if I don't intend to access the object from more than one thread?  If so, why?

A: If an object is only ever accessed from a single thread, it doesn't need to be threadsafe even it's a Guice @Singleton. Guice doesn't do any multithreading internally that could cause a non-threadsafe singleton to break... the process of building the Injector is all done on the thread that calls Guice.createInjector and any dynamic provisioning is done on the thread that calls provider.get(). Of course, a singleton is only going to be created once and then just returned each time it's needed... when it's created depends on whether it's bound as an eager singleton (always created at startup) and whether the Injector is created in Stage.DEVELOPMENT (created only if and when needed) or Stage.PRODUCTION (created at startup).
It's very often the case that singletons can be accessed from multiple threads at the same time though (particularly in web applications), hence the warning. While many developers will understand that a singleton needs to be threadsafe in that case, others may not and I imagine it was considered worth it to warn them.


text:
Q: Subtract a value from previous cell with sum and offset function In Excel, I have a column with different values.
In this column, I want to subtract the value in A1 from the value in A2, the value in A3 from A4 and so on. I then want the result to show in the B column.

I found that this can be accomplished with SUM and OFFSET.
Can someone show me how exactly?

A: No SUM or OFFSET needed. Just put nothing in B1 and '=A2-A1' in B2. Next, select B1 and B2. Then copy-paste down (drag tge black square at the lower right of your selection or just select copy from the menu and select the target area an click paste).
The copy-paste copies the altering cell with nothing and the cell with the formula down below as far as you tell it to do.

A: For what it is worth,
the formula in B2 may also be set to be =SUM(OFFSET(B2,-1,-1,2,1))
- which might come in handy if you (for some reason) need to have it reference no other cells than itself.
The numbers in OFFSET() says this:  -1,-1 - 'move up and left 1 step each', 2,1 - 'include two rows and one colum'... and then you have SUM() on these cells as OFFSET() is inside its parenthesis.


text:
Q: Boolean Algebra - Demorgan Laws I am given the problem:
!((!A * B) * !((!B + C) * (!C * !D)))
where ! = NOT, * = AND, and + = OR and I tried simplifying it using only Demorgan Laws (no absorption) and I got:
(A + !B) + ((!B + C) + (C + D))
and I was just wondering if it was correct. Any help would be greatly appreciated.

A: If you just want to do the DeMorgan's law portion of the simplification, (using your notation)
!((!A * B) * !((!B + C) * (!C * !D)))
 <==> !(!A*B) + !!((!B + C) * (!C * !D)) (first round of DeMorgan's law usage)
 <==> (A + !B) + !!((!B + C) * (!C * !D)) (second round of DeMorgan's law usage)
Now, if we want to finish simplifying,
(A + !B) + !!((!B + C) * (!C * !D))
 <==> A + !B + (!B + C) * (!C * !D)   (simplifying the !!)
 <==> A + !B + (!B * !C * !D) + (!C * C * !D)    (distribution)
 <==> A + !B + (!B * !C * !D) + 0    (!C * C * !D is equivalent to 0)
 <==> A + !B + (!B * !C * !D)
 <==> A + !B   (using the unavailable absorption law you mentioned)

A: If we let $\overline{A}$ signify "$\text{not}\ A$", then I get the following
$$\phantom{\iff\quad} !((!A * B) * !((!B + C) * (!C * !D)))$$
$$\iff\quad \overline{(\overline{A} * B) * \overline{(\overline{B} + C) * (\overline{C} * \overline{D}))}}$$
$$\iff\quad \overline{(\overline{A} * B)} + (\overline{B} + C) * (\overline{C} * \overline{D}))$$
$$\iff\quad (A + \overline{B}) + (\overline{B} + C) * (\overline{C} * \overline{D}))$$
$$\iff\quad (A * !B) + ((!B + C) * (!C * !D))$$
This is slightly different from the answer you got.


text:
Q: Selected checkbox value uses ajax to repopulate select My form has checkboxes with user roles, and a select box with users. I need a select box to repopulate based on the checkbox value(s) when clicked. The checkboxes allow selection of either "all" (in which case the select options need not change) OR any combination of "cm", "adv", "cd" values.
Once the checkbox(es) get clicked, the select box should repopulate dynamically (all this before form gets submitted).
<cfquery datasource="datasourceName" name="qry_staff">
  SELECT userID, lastname + ', ' + firstname AS staffName
  FROM   userTable
  WHERE  role IN('cm','adv','cd')
</cfquery>

<form>
  <input type="checkbox" name="assignedRole" id="checkedAll" value="all">All

  <input type="checkbox" name="assignedRole" id="assignedRole" value="cm" class="checkSingle">Case managers

  <input type="checkbox" name="assignedRole" id="assignedRole" value="adv" class="checkSingle">Advisors

  <input type="checkbox" name="assignedRole" id="assignedRole" value="cd" class="checkSingle">Career developers

  <select name="staff>
    <cfloop query="qry_staff" multiple="multiple">
      <cfoutput>
        <option value="#qry_staff.userID#">#qry_staff.staffName#</option>
      </cfoutput>
    </cfloop>
  </select>
  <input type="submit">
</form>

I don't want the entire page to reload every time a user changes text box selection(s). I haven't been able to find a suitable solution, and am in an intense time crunch. I'm jquery knowledgeable, but not Ajax. What I've been able to find makes me think Ajax would really be the way to go here, but would be thrilled to use jquery if possible. I'd greatly appreciate help with an example of how to accomplish this, using code supplied here.

A: change your main page to this.
<form>
    <input type="checkbox" name="assignedRole" id="checkedAll" value="all">All

    <input type="checkbox" name="assignedRole" id="assignedRole" value="cm" class="checkSingle">Case managers

    <input type="checkbox" name="assignedRole" id="assignedRole" value="adv" class="checkSingle">Advisors

    <input type="checkbox" name="assignedRole" id="assignedRole" value="cd" class="checkSingle">Career developers

    <select name="staff"></select>
    <input type="submit">
</form>

make a separate file called thecall.cfm
<cfset return_struct = StructNew() />
<cfquery datasource="datasourceName" name="qry_staff">
  SELECT userID, lastname + ', ' + firstname AS staffName
  FROM   userTable
  WHERE  role = '#form.assignedRole#'
</cfquery>

<cfset data = [] />

<cfoutput query="qry_staff">
  <cfset obj = {"optionValue" = userID, "optionDisplay" = staffName} />
  <cfset arrayappend(data, obj) />
</cfoutput>
<cfoutput>#serializeJSON(data)# </cfoutput>


text:
Q: Google Analytics Real Time events - How long does an event stay 'current'? I am using Google analytics events to track what users are searching for within a particular dataset on a single page (the value of an input box when they click search).
I am accessing the real time events using the 'Real Time Reporting API' using the metric rt:totalEvents and the dimension rt:eventLabel. When I query the data I get a response such as:
["Los Angeles, CA",
 "37"
],
[
 "San Francisco, CA",
 "29"
],
[
 "Las Vegas, NV",
 "21"
],

I doubt these figures are be the number of events at the exact time of the query, each event must stay current for a period of time, what is this time frame?
Thank you in advance for your assistance.

A: if memory serves its the last five minutes.   However you can easily find out by adding rt:minutesAgo to your request.

A: OK, I did a little testing and it turns out that the 'real time' events stay current for 30 minutes.
Thanks @DalmTo for recommending the "rt:minutesAgo" dimension as that is very useful!


text:
Q: how to JSON serialize form fields with data-* properties I have a form with fields with data-* attributes.  I used formData = $('#userAnswersForm').serializeArray().  It only serialized the name and value attributes.  Below is a sample fragment of the rendered form and Json data.  How do I get the data-* attributes and their respective value into the result?  Thanks.

    <fieldset>

            <input name="Q8" class="custom-control-input" id="Q8-25" type="radio" value="25" data-useranswerid="" data-userid="0">
          Yes

            <input name="Q8" class="custom-control-input" id="Q8-26" type="radio" checked="" value="26" data-useranswerid="9" data-userid="0">
          No

    </fieldset>

[{
    "name": "Q1",
    "value": ""
  },
  {
    "name": "Q5",
    "value": ""
  },
  {
    "name": "Q6",
    "value": "25"
  },
  {
    "name": "Q8",
    "value": "26"
  },
  {
    "name": "Q11",
    "value": "one of the committee(s)"
  },
  {
    "name": "CSRF-TOKEN-MY-TOKEN",
    "value": "CfDJ8Ko6GnaLDwVBtvo4KV3EVp159qlxOvH96mT41L2szq0QwcocKo5ArhFJuSL7xMoW8hRMKCnJNagD0HRfT6-YqcJzOdPaUrtLRLs2uuIxhz4J5UyWoLo2oWZmcM-sSMy-m-7nU6fkVLIPhymD5T8yrW0"
  }
]

A: Yes, it requires manual construction of the JSON object.  I also have to create a C# postback model to be bound to the JSON. I set all properties in the model to string because if form element has data it the property in the item will be int.  If no value, the property in the item will be string.  Here is my code.

$("#submit").click(function(e) {
  e.preventDefault();
  let formPostBackUrl: string = $("form[id='userAnswersForm']").attr("action");

  if ($("form[id='userAnswersForm']").valid()) {
    let formData: Array < any > = new Array();
    let stringfiedFormData: string = "";

    //formData = serializeTheForm($("form[id='userAnswersForm']"));
    formData = manuallyCreateTheJson();
    if (formData.length > 0) {
      stringfiedFormData = JSON.stringify(formData);
      console.log('stringfiedFormData', stringfiedFormData);

      $.ajax({
        type: "POST",
        url: formPostBackUrl,
        data: stringfiedFormData,
        headers: {
          "CSRF-TOKEN-PCC-FIT": $('input[name="CSRF-TOKEN-PCC-FIT"]').val(),
          'Accept': 'application/json',
        },
        contentType: "application/json;charset=utf-8"
      }).done(function(result) {
        console.log('postback result', result.message);
        alert(result.message);
      }).fail(function(error) {
        console.log('postback error', error.message);
        alert(error.message);
      });
    }
  }
});

function manuallyCreateTheJson() {
  const userID: string = $('form #userID').val();
  const facilityRelationshipID: string = $('form #facilityRelationshipID').val();
  const facilityID: string = $('form #facilityID').val();
  const fiscalYear: string = $('form #fiscalYear').val();

  const target = $("select, textarea, input:checked, input[type='number'], input[type='text']");

  let userAnswers: Array < any > = new Array();
  target.each(function() {
    let thisTargetElement: any = $(this).get(0);
    let $this: any = $(this);
    console.log('$this', $this);

    let item = {};

    item['Name'] = $this.attr('name');
    item['FacilityRelationshipID'] = facilityRelationshipID;
    item['FacilityID'] = facilityID;
    item['FiscalYear'] = fiscalYear;
    item['UserID'] = userID;

    if ($this.data('useranswerid'))
      item['UserAnswerID'] = $this.data('useranswerid').toString();
    else
      item['UserAnswerID'] = '';

    switch (thisTargetElement.tagName.toLowerCase()) {
      case 'select':
        if ($this.val()) {
          item['Value'] = $this.val();
        }
        break;
      case 'textarea':
        if ($this.text().trim().length !== 0) {
          item['Value'] = $this.text();
        }
        break;
      case 'input':
        if ($this.val()) {
          item['Value'] = $this.val();
        }
        break;
    }

    if (item['Value']) //has value
      userAnswers.push(item);

  });
  console.log('userAnswers', userAnswers);
  return userAnswers;
}

///
/// Edit user answer to a question with AJAX post of JSON object
/// ToDo: need to allow multiple choices to be nested in the payload
///
/// <param name="collection"></param>
/// <returns></returns>
//resumbit user answers to questionnaire
// POST: UserAnswer/Edit/5
[HttpPost]
//[ValidateAntiForgeryToken]
public IActionResult Edit([FromBody] IList < JsonPostBackModel > collection) {
  if (collection == null || collection.Count() == 0) {
    Response.StatusCode = 200;
    return new JsonResult(new {
      message = "Nothing answered so nothing saved"
    });
  } else {
    try {
      foreach(JsonPostBackModel answer in collection) {
        if (!string.IsNullOrEmpty(answer.Value)) {
          UserAnswer thisAnswer = new UserAnswer();
          //ToDo: exam each answer before executing the post method in the repository to post to the database
        }
      }

      Response.StatusCode = 200;
      return new JsonResult(new {
        message = "Answers are saved"
      });
    } catch (Exception ex) {
      Debug.Print(ex.Message);
      Response.StatusCode = 500;
      return new JsonResult(new {
        message = ex.Message
      });
    }
  }
}


text:
Q: Highcharts Polar Chart Manually setting individual slice widths Is it possible to set the width of individual slices/sectors of a polar chart in Highcharts?  What I'm looking for is something akin to setting a tickPositions array and then filling between each tick position with a data slice (as opposed to setting a uniform pointInterval).
I've tried setting the pointPadding & groupPadding to 0.  Also tried setting the x value for each data point.  With that, I can get each slices to start where I want it, but I've not figured out away to control how many degrees around the circle it should go from that start.
Any help - even a "can't be done" - would be greatly appreciated.  Thanks for your time.

A: This can be done using type of 'column' by setting pointStart and pointRange for each member of the series
series: [{
        name: 'a1',
        type: 'column',
        pointStart: 7.5,
        pointRange: 15,
        data: [65]
    }, {
        name: 'a2',
        type: 'column',
        pointStart: 7.5,
        pointRange: 15,
        data: [72],
    }, {
        name: 'b1',
        type: 'column',
        pointStart: 55,
        pointRange: 80,
        data: [55]
    }, {
        name: 'b2',
        type: 'column',
        pointStart: 55,
        pointRange: 80,
        data: [50]
    }]

see: http://jsfiddle.net/Hrgfy/
Note that with pointPlacement of 'on' your slices will be centered, as describe here: https://stackoverflow.com/a/17532841/958896


text:
Q: Odd situation for "cannot reference this before supertype constructor has been called" Why doesn't this code compile?
public class A {
    public class B extends A {
        public B(A a) { }
    }
    void foo() {
        A a = new A();
        new B(a) { };
    }
}

A.java:[7,17] cannot reference this before supertype constructor has been called
Compilation is successful if either of these changes are made:

*

*B is private instead of public

*line 7 reads new B(A); instead of new B(A) { }
Using javac version: 1.6.0_20

A: It should be noted that Eclipse, javac, and Intellij IDEA exhibit differences in behaviors with regards to these snippets. javac and the Java Puzzlers behavior is used for reference in this discussion.
I was able to cut down the snippet to the following:
public class A {
    class B extends A {
    }
    void foo() {
        new B() { }; // DOES NOT COMPILE!!
    }
}

This scenario is discussed in Java Puzzlers, Puzzle 90: It's Absurd, It's a Pain, It's Superclass!
The snippet given is the following:
public class Outer {                   // "A"
    class Inner1 extends Outer  {}     // "B"
    class Inner2 extends Inner1 {}     // "B" anonymous
}
// DOES NOT COMPILE!!

The problem is that due to how default constructor is defined, we really have the following:
// Same as above but with default constructor included explicitly
public class Outer {
    class Inner1 extends Outer  {
        Inner1() { super(); }
    }
    class Inner2 extends Inner1 {
        Inner2() { super(); }
    }
}
// STILL DOES NOT COMPILE!!

The problem is that Inner2's superclass is itself an inner class Inner1, thus making Inner2's default constructor illegal since it requires an enclosing instance to be supplied to the constructor.
The "brute-force" way to fix the problem is to provide this explicitly with a qualified-this expression:
// "brute-force" fix
public class Outer {
    class Inner1 extends Outer  {
        Inner1() { super(); }
    }
    class Inner2 extends Inner1 {
        Inner2() { Outer.this.super(); }
    }
}
// NOW COMPILES!

However, the puzzle prescribes that such complicated situation is best avoided in the first place. Here are some quotes:

This compiles, but it is mind-numbingly complex. There is a better solution: Whenever you write a member class, ask yourself, Does this class really need an enclosing instance? If the answer is no, make it static. Inner classes are sometimes useful, but they can easily introduce complications that make a program difficult to understand. They have complex interactions with generics (Puzzle 89), reflection (Puzzle 80), and inheritance (this puzzle). If you declare Inner1 to be static, the problem goes away. If you also declare Inner2 to be static, you can actually understand what the program does: a nice bonus indeed.
In summary, it is rarely appropriate for one class to be both an inner class and a subclass of another. More generally, it is rarely appropriate to extend an inner class; if you must, think long and hard about the enclosing instance. Also, prefer static nested classes to non-static. Most member classes can and should be declared static.

A: Not sure what the goal is exactly, but try this.  Note I also cut out the passing of A as an argument as being non-static classes they are already linked.   I included the syntax for referring to the outer class "this" for those situations were the inner class may cover up an outer class field/method
public class A {

    protected String field = "a";

    public class B extends A {
        protected String field = "b";

        public B() {
            System.out.println("" + A.this.field + " " + this.field);
        }

        @Override
        void foo() {
            System.out.println("b.foo()");
        }
    }

    void foo() {
        A a = new A();
        a.field = "a2";
        B b = a.new B() {
            @Override
            void foo() {
                System.out.println("b.anon.foo()");
            }
        };

        b.foo();
    }

    public static void main(String[] args) {
        new A().foo();
    }
}

Running this will output:
a2 b
b.anon.foo()

Hope this helps!


text:
Q: element chapter: validity error : Element chapter content does not follow the DTD, expecting I have openembedded that has a docs directory and the README instructs me to run
make <type>

type can be pdf,dvi, html,txt, etc etc
xsltproc and docbook-utils are required to generate the documentation.
Both are installed.
U have make pdf and the error generated was:
./usermanual.xml:91: element chapter: validity error : Element chapter content
 does not follow the DTD, expecting (beginpage? , chapterinfo? , (title ,
subtitle? , titleabbrev?) , (toc ...
title CDATA CDATA CDATA CDATA CDATA CDATA CDATA CDATA CDATA CDATA CDATA CDATA
CDATA CDATA CDATA )
Document ./usermanual.xml does not validate
make: *** [lint] Error 3

I have absolutely 0-experience with XML files, dtdfiles. And I suspect a clash in version of docbook-utils I have and the source requires.

A: The error message is truncated, so it's not possible to know exactly what the requirements for the <chapter> element are, but it says that the contents of your <chapter> element do not match the DTD and because of that will not validate. It details the problem stating that the <chapter> element requires certain elements, in a certain order.
The commas in the error message mean a sequence. From the part of the error message that is shown above it is possible to know that, inside a <chapter> element:

*

*You can have zero or one <beginpage> elements, and if present, it must come first.

*You can have zero or one <chapterinfo> elements, and if present, it must come before the other elements but after <beginpage> (if present).

*Following <beginpage> and <chapterinfo>, you must have a <title> and you can have at most one <subtitle> or <titleabbrev>.

If any of the rules above are not being followed in your source XML, validation will fail.
The rest of the DTD description of the message seems to be abbreviated, so it's not possible to conclude anything. You should check the full DTD to know what is wrong. It's not so difficult to read a DTD. Most ot the time you just have to understand sequences which are comma separated names: <!ELEMENT name (title?, first, middle*, last)> (name allows zero or one title, must have a first, may have zero or unbounded middle and must have last, in this order), and choices which are separated by |: <!ELEMENT contact (email | phone)> (contact must contain either email or phone) or <!ELEMENT contact (email | phone)*> (contact can be empty, can contain many choices of email or phone, in any order).
You might want to read a quick DTD tutorial.


text:
Q: Estimating fixed effects for ordinal regression I am running a model when the response variable (behaviour) is an ordinal factor (levels: $0,1,2,3,4$) and I am testing the relationship with two fixed effect factors (year: $A,B,C,D$; colony; $X_1$,$X_2$).
I want to extract the estimates of the effect of year and colony on behaviour. In a normal GLM, I understand that this is simple, but for an ordinal model, I am not sure how to incorporate the cut points for the ordinal levels with the fixed effect estimates. From reading about ordinal models, it seems that maybe you get a matrix of probabilities such that you get for colony a $2 \times 5$ matrix and for year a $4 \times 5$.  Am I understanding this correctly?  And if so, it does not seem possible to extract any kind of residual value for behaviour controlling for fixed effects?


text:
Q: Windows-Server-2019 - Raid 1 Software - Could not convert Disk to Dynamic security enabled on Disk I installed a fresh Windows Server 2019 on ONE of two identical Crucial CT1000MX500SSD1M.
I don't have an integrated RAID controller on my MB ASUS_H110m-A/M.2 so I wanted to try a software RAID 1, just mirroring.
How I read everywere, is quite simple to do it, just open Disk Management and do these simple 2 operations:

*

*convert the Disk 0 (where Windows is actually installed) to Dynamic

*add Mirror to every volume of the disk 0 using the space of the Disk 1

In my case I always obtain the same result: "The disk could not be converted to dynamic because security is enabled in one or more partition"
Of course I tryed from command line and from graphical interface, of course I tried using both GPT and MBR schema... Nothing worked!
What's the problem?
Thanks to everybody can give me help!
Screen of error message. Click to view


text:
Q: Symfony / API Platform - Custom Operation - PUT method for file replacement using VichUploaderBundle I am using Vich Uploader Bundle in combination with API Platform to store files. I've followed the instructions from the official documentation
https://api-platform.com/docs/core/file-upload/#handling-file-upload
Everything works well except I want to include PUT calls to replace existing MediaObject entities. My attempt was as follows:
I have created a custom operationand mapped it to the PUT method in the entity as follows:

<?php
// api/src/Entity/MediaObject.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Controller\CreateMediaObject;
use App\Controller\EditMediaObject;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity
 * @ApiResource(
 *
 *     ...
 *
 *     itemOperations={
 *         "get",
 *         "put"={
 *             "controller"=EditMediaObject::class,
 *             "deserialize"=false,
 *             "validation_groups"={"Default", "media_object_create"},
 *             "swagger_context"={
 *                 "consumes"={
 *                     "multipart/form-data",
 *                 },
 *                 "parameters"={
 *                     {
 *                         "in"="formData",
 *                         "name"="file",
 *                         "type"="file",
 *                         "description"="The file to upload",
 *                     },
 *                 },
 *             },
 *         },
 *         "delete"
 *     },
 * )
 * @Vich\Uploadable
 */
class MediaObject
{
    /**
     * @var int|null
     *
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     * @ORM\Id
     */
    protected $id;

    /**
     * @var string|null
     *
     * @ApiProperty(iri="http://schema.org/contentUrl")
     * @Groups({"media_object_read"})
     */
    public $contentUrl;

    /**
     * @var File|null
     *
     * @Assert\NotNull(groups={"media_object_create"})
     * @Vich\UploadableField(mapping="media_object", fileNameProperty="filePath")
     */
    public $file;

    /**
     * @var string|null
     *
     * @ORM\Column(nullable=true)
     */
    public $filePath;

    public function getId(): ?int
    {
        return $this->id;
    }
}

The correponding Controller:
<?php
// api/src/Controller/EditMediaObject.php

namespace App\Controller;

use App\Entity\MediaObject;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

final class EditMediaObject
{
    /**
    * @var RequestStack
    */
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }
    public function __invoke(MediaObject $data): MediaObject
    {
        $request = $this->requestStack->getCurrentRequest();
        $uploadedFile = $request->attributes->get('file');
        if (!$uploadedFile) {
            throw new BadRequestHttpException ('"file" is required');
        }
        $data->file = $uploadedFile;

        return $data;
    }
}

The $data object is susccessfully populated. However I dont have access to the initial request parameters (particularly 'file').
Is this because of the preliminary OPTIONS call? If so, how can I forward / preserve the file to attach it to the MediaObject?
Thanks in advance
Edit:
In case anyone is interested, it is NOT possible to send file parameters over PUT requests in PHP. (source: PHP multipart form data PUT request?)

A: Why are you looking at $request->attributes?
You should be looking at $request->files.
See https://symfony.com/doc/current/components/http_foundation.html#accessing-request-data

A: You need to send a POST request with an extra parameter, _method = PUT, It will change the POST request as if it is a PUT request.

A: I have recently had a very similar problem, though, I'm not using the entire symfony library, I'm using the HttpFoundation/Request and HttpFoundation/Response objects.
At first I was puzzled by how the request seemed completely empty.
After spending more time than I would have liked looking into it, this is an issue that can be traced back to the internals of PHP.
I managed to find this PECL extension
I'm not really very familiar with pecl, and couldn't seem to get it working using pear. but I'm using CentOS and Remi PHP which has a yum package.
I ran yum install php-pecl-apfd and it literally fixed the issue straight away. I believe there are other packages in various flavours of linux and I'm sure anybody with more knowledge of pear/pecl/general php extensions could get it running on windows or mac with no issue.
By fixed, I mean, my request object was populated as expected (request->all() and request->files for example).
This seems to have worked for both PUT and PATCH requests with and without files (using multipart forms).
If you're using Docker, you'll need to restart your containers.


text:
Q: Understanding warning message My code is as follows:
m<-c(9,17,33,65,129,257,513)
results<-matrix(,7,5)
results[,1]<-m

#methods
trap<-function(a,b,m,func)
{
  h=(b-a)/(m-1)
  x<-seq(a,b,h)
  y<-function(x) {
    z<-eval(parse(text=func))
    return(z)
  }
  result<-h*(0.5* y(x[1]) + sum(y(x[2:(length(x)-1)]))+ 0.5*y(x[length(x)]) )
  result
}

when I run the following command: trap(0,5,results[,1],"x^2")
I get the intended output, but I also get a nasty warning message:
Warning messages:
1: In if (n < 0L) stop("wrong sign in 'by'
argument") :   the condition has length > 1 and only the first element
will be used
2: In if (n > .Machine$integer.max) stop("'by' argument
is much too small") :   the condition has length > 1 and only the
first element will be used
3: In 0L:n : numerical expression has 7
elements: only the first used
4: In (0L:n) * by :   longer object
length is not a multiple of shorter object length
5: In if (by > 0)
pmin(x, to) else pmax(x, to) :   the condition has length > 1 and only
the first element will be used

So I set about trying to understand what is going, and it seems everything points to this: x<-seq(a,b,h) but my sequence by should never be negative, it should always create a length greater than 1 (I'm not sure what the other warning messages mean).
Can someone help me understand this message, so I can correct whatever I am being warned about?

A: You can trigger errors so that traceback() will be available for debugging of warnings, athough that is mprobably not needed here;
 options(warn=2) # usual setting is 1

Type this to see what your function is seeing for the arguments:
> c(a=0, b=5,m= results[,1])
  a   b  m1  m2  m3  m4  m5  m6  m7
  0   5   9  17  33  65 129 257 513

So that's where the first warning about seq( , , by=.) getting an excessively long argument comes from, (since h will be as long as the 'm' argument was. I think that mostly explains the other warnings as well. I do not know of a way to get the warn() mechanism to skip the first or up to the n-th waring but if you dropped into the browser you could do that:
?browser

You could also search SO for best practices for [r] debugging

A: Are you sure you are getting the intended output? Any way I read ?seq, it looks like the "by" parameter should be a number, not a vector as in your example. This is the reason you get the nasty warning, because h is not a single number but a vector.
And the sequence you get from seq(a,b,h) is very strange:
> seq(a,b,h)
[1] 0.00000000 0.31250000 0.31250000 0.23437500 0.15625000 0.09765625 0.05859375
[8] 4.37500000 2.50000000

I think seq is designed for generating monotonic sequences, but what comes out of your example is neither monotonic nor making any sense...
Are you really sure the final result is what you expected? In any case this looks like a misuse of seq, unless I'm missing something.


text:
Q: Exacttarget SOAP API - How to retrieve list from Job ID? Is there a way to supply the Job ID and retrieve the lists the mailing was sent to?
for example, if i have a job ID (12344556), i would like to do a call to the API to know what list that specific Job was sent to.

A: You need to do a retrieve on the ListSend object. An example of this can be found here... https://help.exacttarget.com/en/technical_library/web_service_guide/technical_articles/retrieving_all_lists_for_a_send


text:
Q: How to apply 2fa, ACL for IAM in GCP Recently, the IAM key of GCP was exposed, and miner was installed.
In the case of AWS, 2fa can be set when accessing with an access key, or access can be made only from a specific IP.
If there was such a setting, the accident would not have occurred immediately even if the key was exposed.
I searched for ACL and 2FA settings in GCP, but there is no key setting, only the instance access setting is checked.
Is it possible to set up GCP's Web Console access, 2FA for access to IAM key, and IP ACL?
In addition, an IP-based ACL is required for BigQuery, but it is impossible to access the ACL for BigQuery access when contacting other teams, and it is only controlled by IAM.
If IAM is exposed by user error, is there any way GCP can prevent this?

A: You can enforce 2fa and IP control on IAM service (with IAM conditions and context-aware access).
Google helps you as it can:

*

*The support contact you in case of abnormal activity, such as miner installed your VM and thus suspicious network activity

*The public repository, such as Github, are periodically scanned by google and in case of service account key file found, you are notified

*Platform proposes you solution to mitigate the risk

*

*Context aware accesss

*IAM condition

*Organisation policy to disable the capacity to generate service account key file. Only a small group of users are able to generate them after the validation of the user request. The target is to limit the number of key and to generate them only when the use case require them

*SCC (Security Command Center) findings can raise primitive role on service account: too much roles, use predefined role instead

*IAM recommender that propose you to reduce the permission scope based on the 90 last days of activities

So a set of tools to be proactive and reactive to events.

A: You can set up 2 step-verification(2sv) which is triggerd when trying to access GCP vm instances.
Follow this guide to set up 2sv to your instance.
Also, VPC service control can add additional sercurity layer for managed service like bigQuery.
You can block specific IP address bia this service.
This article will help you a lot in using VPC Service Control.


text:
Q: How do I post a select list value with ASP.NET MVC DropDownListFor()? I'm having an issue using the DropDownListFor() function with ASP.NET MVC:
Model:
public class ShoeSizeModel
{
    public List<ShoeModel> ShoeListModel { get; set; }
    public List<SizeModel> Sizes { get; set; }
    public int SelectedSizeId { get; set; }

    public IEnumerable<SelectListItem> SizesSelectList
    {
        get
        {
            return new SelectList(Sizes, "SizeId", "Size");
        }
    }

View:
    @model Models.ShoeSizeModel

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shoe Selection</title>
    <link rel="stylesheet" href="../../Scripts/css/base.css">
    <link rel="stylesheet" href="../../Scripts/css/gallery.css">

    @Html.AntiForgeryToken()

    @using (Html.BeginForm("FilterBySize", "Shoe", FormMethod.Post))
    {

            @Html.DropDownListFor(
                     model => model.SelectedSizeId,
                     Model.SizesSelectList,
                     "Size",
                     new { onchange = "this.form.submit();" })

    }
    ...

Controller:
[HttpPost]
public ActionResult FilterBySize(int sizeId)
{
    return View();
}

If I try to pass the SizeId from the SelectList to the FilterBySize method, I get a null value:

Interestingly, if I try to pass it as a model instead, the select list value passes just fine:

I'm probably just missing something obvious here, and it's not the end of the world if I just have to pass the model and take the value from there, but I'd rather just pass the value if I can. Please can someone explain to me what I'm doing wrong?

A: you will have to bind your dropdownlist with model and pass model to controller on post method.

    @model BindMvcDropdownList.Models.CategoryModel

Bind MVC DropDownList with Model

@Html.DropDownListFor(x => x.selected, Model.lstCategory)


text:
Q: Validation of the youtube address I have to do a plugin that allows you to insert videos from youtube in website. For this purpose I have encountered a problem, I want to validate the correctness of the url address from youtube. I want to check the correctness of the address, under the account:
- check if the id of the movie is included in the address
- Check if the address contains (youtube.com or youtu.be)
My code only checks if the url contains (youtu.be or youtube.com). I do not know how to check if the address has a movie id of 11 characters long. Do you have any idea?
<?php
$url = 'https://www.youtube.com/watch?v=knfrxj0T5NY';
if (strpos($url, 'youtube.com') || strpos($url, 'youtu.be')){
    echo 'ok';
}else{
    echo 'no';
}
?>

A: Method using cURL:
function isValidYoutubeURL($url) {
    // Let's check the host first
    $host = parse_url($url, PHP_URL_HOST);
    if (!in_array($host, array('youtube.com', 'www.youtube.com'))) {
        return false;
    }

    $ch = curl_init('www.youtube.com/oembed?url='.urlencode($url).'&format=json');
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_exec($ch);

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ($status !== 404);
}


text:
Q: How do I change the amount of whitespace between sections in Latex? How do I modify the distance between the end of a section and the header of the next section in a Latex document?

A: You can configure the style of section headings, including spacing, using the titlesec package. There's a 'compact' option for simple reduction of space, or you can specify specific values using the more advanced options (see the documentation on the linked page for the gory details).

A: An alternative to titlesec is to redefine the section command, as in the following snippet.  Note that beforeskip and afterskip are the variables you're interested in.  The code itself is just the first few lines.  It's followed by a lengthy comment to remind me of the definitions when I cut and paste the whole thing from one document to another.  The code, by the way, is more or less from the indispensable book, The LaTeX Companion, Second Edition.
\makeatletter
 \renewcommand\section{\@startsection {section}{1}{\z@}%
     {-2.5ex \@plus -1ex \@minus -.2ex}%
     {1.3ex \@plus.2ex}%
    {\centering\bfseries}}
% \@startsection {NAME}{LEVEL}{INDENT}{BEFORESKIP}{AFTERSKIP}{STYLE}
%            optional * [ALTHEADING]{HEADING}
%    Generic command to start a section.
%    NAME       : e.g., 'subsection'
%    LEVEL      : a number, denoting depth of section -- e.g., chapter=1,
%                 section = 2, etc.  A section number will be printed if
%                 and only if LEVEL gt or eq the value of the secnumdepth
%                 counter.
%    INDENT     : Indentation of heading from left margin
%    BEFORESKIP : Absolute value = skip to leave above the heading.
%                 If negative, then paragraph indent of text following
%                 heading is suppressed.
%    AFTERSKIP  : if positive, then skip to leave below heading,
%                       else - skip to leave to right of run-in heading.
%    STYLE      : commands to set style
%  If '*' missing, then increments the counter.  If it is present, then
%  there should be no [ALTHEADING] argument.  A sectioning command
%  is normally defined to \@startsection + its first six arguments.
\makeatother


text:
Q: New ASP.NET Core project has random attribute added to elements I have created a new ASP.NET Core project with Visual Studio 2022.  I've run the application and looked at the source of the home page.  Several of the elements from the _Layout page have a random attribute added.
Here's a snippet of the generated html when the application is running:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Home page - WebApplication1</title>
    <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/css/site.css?v=AKvNjO3dCPPS0eSU1Ez8T2wI280i08yGycV9ndytL-c" />
    <link rel="stylesheet" href="/WebApplication1.styles.css?v=bORd7i_49MmkY_u045aCr39djituvpXrqrsQ_3TezVg" />

                WebApplication1
                <button b-g6ltozs93r class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Home

                            Privacy

Notice the b-g6ltozs93r in several of the elements.  This is not in the source!
The source for the HTML above from _Layout.cshtml is as follows:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebApplication1</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/WebApplication1.styles.css" asp-append-version="true" />

                WebApplication1
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Home

                            Privacy

Why is that random attribute being added!?
Thanks.


text:
Q: Adding Alert for Expiration Date of Membership or ID Card Good morning, it's the first time on Stack Overflow and I hope to ask the question in a proper way.
Here's my problem:
I want to add an expire user notification for two events: Annual Membership and ID Card.
Expire User Alert for Annual Membership: my idea is to use Expire Users plugin and set automatically the expire date from Order Completed status in Woocommerce to 365 days.
Expire User Alert for ID Card: my idea is to set an alert based on expiration date of the id card. This data is already set during the checkout phase by the customer.
The problem I have is all due to how to code this, my php is very very basic, if you can help me by code I'll build a Golden Statue, if you have some solution or articles related to read I'll build a Silver Statue :D
Waiting for your kind reply, thanks in advance
21/07/2021 15:23
// update user data with order completed date, I use shipping_address_1 to store it, I'm not using the original address in my site

add_action( 'woocommerce_thankyou', 'checkout_save_user_meta' );

function checkout_save_user_meta( $order_id ) {
   $order = wc_get_order( $order_id );
   $orderday = $order->get_date_completed;

   $user_id = $order->get_user_id();
   if ( $order->get_date_completed() ) {
      update_user_meta( $user_id, 'shipping_address_1', $orderday );
   }
}

//take the updated data to set an alert via mail in 365 days
 if (!function_exists('expirationalert')) {

            function expirationalert($user_id) {
                $blogusers = get_users('role=client');
                // Array of WP_User objects.
                foreach ($blogusers as $user) {

                    //$user->user_registered;
                    // $user_id=$user->ID;
                    $user->user_registered;

                    $user_id = $user->ID;

                    $user_login = $user->user_login;

                    $user_email = $user->user_email;

                    $startingdate = $user->shipping_address_1;

                    /* input expire date format -> Y-m-d */
                    list($y, $m, $d) = explode('-', $startingdate);
                    $nowdate = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
                    $expirationdate = mktime(0, 0, 0, $m, $d, date("Y"));

                    if ($expirationdate < $nowdate)
                        $expirationdate = $expirationdate + (60 * 60 * 24 * 365);

                    $daycount = intval(($expirationdate - $nowdate) / (60 * 60 * 24));

                    //echo $daycount;

                    if ($daycount < 349) {

                        /* echo $user->user_registered;
                          echo "
";
                          echo $user_id=$user->ID;
                          echo "
";
                          echo $user_login=$user->user_login;
                          echo "
";
                          echo $user_email=$user->user_email;
                          echo "
"; */

                        $message = sprintf(__('your Account will be expired in next 15 days %s:'), get_option('blogname')) . "\r\n\r\n";
                        $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
                        $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";

                        @wp_mail(
                                        $user_email, sprintf(__('[%s] Account Expiration alert'), get_option('blogname')), $message
                        );
                    }
                }
            }

The second part is inspired from this thread I want to create a wordpress user registration function so that both user and admin should get email alert after every year
I'm 100% it's not the right code or pretending it'll work, I think it can be the starting point to polish it and make it work.
The code is only for the product part, I presume if I can make it work, for the second code I have just to refer to my custom field with the ID Card Expiration Date.


text:
Q: Calling Templates on demand in SPA In my current SPA application, the index page shows  Login form (default router) which doesn't have header & footer ,
When User Logs in account , router takes user to after login page and  Header & footer are shown ( as per app requirement). My index.html looks like

     <ng-view></ng-view>

but there is a problem. When User Routes to Default Login, fraction of a second The header & footer gets displayed. is there any best way to achieve result
Please guide how to fix this ?

A: What I would do is to add an ng-include in my  footer and header to selectively load what I need
Check this demo from angular page. It may help:
http://docs.angularjs.org/api/ng.directive:ngInclude

A: I think you're looking for ng-cloak: http://docs.angularjs.org/api/ng.directive:ngCloak. Your header and footer are briefly flashing because the hide class isn't applied until the ng-class expression is parsed.


text:
Q: Building application logic with SPARQL Insert statements? I am working with a small team on a project using an RDF triplestore. The application we are building loads RDF data into an Ontotext Graph-DB repository, and then uses a set of rules to manipulate the data. For awhile we were using RDF4J to interact with the database, but found the performance to be slow, as our workflow involved pulling the relevant data onto a local machine, making manipulations, and then sending it back to the database server.
We quickly discovered that by sending a series of sequential SPARQL Insert statements to our database server, we could perform the same tasks in a fraction of the time. Instead of looping through the data in JVM land, we are now sending graph patterns and creating new graph patterns. Since all operations now occur by sending "instructions" rather than data, we can avoid the network overhead of passing data back and forth between the local machine and the server.
However, we also noted some downsides to this approach. SPARQL is decidedly non-modular, as we are hard-coding our Insert statements as Scala strings. Thus, we have found that for adding functionality which would be easy in an OOP paradigm, we have had to create whole new statements.
I would like to hear from the community whether anybody has ever tried using SPARQL as their source of application logic, and what the results were. Is this a tried and true approach, or is it generally outside of the normal use case for SPARQL? Is there a way we can use SPARQL more like an Object-Oriented language besides literally concatenating strings? Are there any other technologies which we may not have heard of which can interact with a triplestore efficiently and modularly?


text:
Q: Error in Xamarin Studio: need latest version of Android Support Repository I installed the latest SDK platforms for Android 6 and 7. Upon installing and launching Xamarin studio, I got two error message saying to install the latest version of "Google Repository" and "Android Support Repository". I installed the latest version and the error message for "Google Repository" went away but other didn't.
I tried deleting "Android Support Repository" and re-installing, re-booting and none help.
Is their way to fix this error?
Error Message:
Partial Download Failed for one or more parts
A task was canceled.
Please open the Android SDK Manager and install the latest version of 'Android Support Repository' from the 'Extras' section, and then reload your solution.


text:
Q: Best way to handle return types during catching exceptions in Scala How do you handle return types when we are catching exceptions? Are there any best practices?
class Test {

  val emptymap = Map[Int,Int]()
  val divisor = 100
  def handleInt ( i : Int) : Map[Int, Int] = {
    try {

      val output = divisor / i
      Map(divisor -> output)
    } catch {
      case e : ArithmeticException => e.printStackTrace(); emptymap
      case e : NumberFormatException => e.printStackTrace(); emptymap
    }
  }

  def handleIntTry ( i : Int) : Map[Int, Int] = {
    val answer = Try(divisor / i)
    answer match {
      case x : Success[Int] => Map(divisor -> answer.get)
      case x : ArithmeticException => { x.printStackTrace(); emptymap}
      case x : NumberFormatException => { x.printStackTrace(); emptymap}
    }
  }
}

Are they both correct? which would be the better way to handle these situations?

A: The second is incorrect but for reasons which have nothing to do with "handling return types when we are catching exceptions".

*

*It's pointless to use Try and then immediately match on the answer; it's just a more verbose and slower version of try-catch. Try is useful when you are going to pass it somewhere, or maybe combine multiple calculations.

*Even neglecting that, the correct match would be
answer match {
  case Success(x) => Map(divisor -> x)
  case Failure(x) => { x.printStackTrace(); emptymap}
}

(no need to handle ArithmeticException and NumberFormatException separately if you are going to do the same in both cases).
What applies to both versions:

*you create emptymap in advance, even if the exception isn't thrown.

A: Either way works. Here's a 3rd option.
def handleInt(i :Int) :Map[Int,Int] =
  Try(divisor / i).fold({
    case x : ArithmeticException   => x.printStackTrace(); emptymap
    case x : NumberFormatException => x.printStackTrace(); emptymap
  }, answer => Map(divisor -> answer))


text:
Q: Apache/PHP to Nginx/Tornado/Python Our website has developed a need for real-time updates, and we are considering various comet/long-polling solutions.  After researching, we have settled on nginx as a reverse proxy to 4 tornado instances (hosted on Amazon EC2).  We are currently using the traditional LAMP stack and have written a substantial amount of code in PHP.  We are willing to convert our PHP code to Python to better support this solution.  Here are my questions:

*

*Assuming a quad-core processor, is it ok for nginx to be running on the same server as the 4 tornado instances, or is it recommended to run two separate servers: one for nginx and one for the 4 tornado processes?

*Is there a benefit to using HAProxy in front of Nginx?  Doesn't Nginx handle load-balancing very well by itself?

*From my research, Nginx doesn't appear to have a great URL redirecting module.  Is it preferred to use Redis for redirects?  If so, should Redis be in front of Nginx, or behind?

*A large portion of our application code will not be involved in real-time updates.  This code contains several database queries and filesystem reads, so it clearly isn't suitable for a non-blocking app server.  From my research, I've read that the blocking issue is mitigated simply by having multiple Tornado instances, while others suggest using a separate app server (ex. Gunicorn/Django/Flask) for blocking calls.  What is the best way to handle blocking calls when using a non-blocking server?

*Converting our code from PHP to Python will be a lengthy process.  Is it acceptable to simultaneously run Apache/PHP and Tornado behind Nginx, or should we just stick to on language (either tornado with gunicorn/django/flask or tornado by itself)?

A: I'll go point by point:

*

*Yes. It's ok to run tornado and nginx on one server. You can use nginx as reverse proxy for tornado also.

*Haproxy will give you benefit, if you have more than one server instances. Also it will allow you to proxy websockets directly to tornado.

*Actually, nginx can be used for redirects, with no problems. I haven't heard about using redis for redirects - it's key/value storage... may be you mean something else?

*Again, you can write blocking part in django and non-blocking part in tornado. Also tornado has some non-blocking libs for db queries. Not sure that you need powers of django here.

*Yes, it's ok to run apache behind nginx. A lot of projects use nginx in front of apache for serving static files.
Actually question is very basic - answer also. I can be more detailed on any of the point if you wish.


text:
Q: Not able to resume a stopped cloud on AWS instances I have been working on installing solr cloud over AWS. As fresh run everything works fine and since i have used Hadoop as one of the dependencies it is understood that there is high availability.. So taking this base of though, i tried to stop the cloudera manager (essentially freezing hadoop , solr, other components). Then stop the instances come back next day to resume the working.. But this theory never works.. Below are the step by step things i do before i switch off and resume.

*

*7:55, created folders for every datanode and in ~/recovery directory and also checked each nodes health

*copied the namenode current directory nn + dn from all 9 hosts with the help 2.*.sh script

*Stopped the cloudera manager & ready to switch off the cluster

*AT 8:04 cluster is stopped in cloudera manager. Made sure enough time is there between event 2 & 3 above.

*Physically stopping the aws instances at 8:05.

*Everything is stopped at 8:08

*Starting all the nodes again.. at 8:12

*started all all fine.. HDFS lost some blocks, some corrupted and some missing

*Solr cloud failed.. totally because it is observed most of the blocks belong to solr cloud..

As you see i have taken all the precautions even i have redistributed the nn + dd which i have saved before switch off. But it did not work..
This i have failed the 4th time, and restoring the cloud is a painful procedure.
Why i want to do this, i want to save the client some valuable money when we are not undergoing any testing.
I am still not sure why i can resume from my physical machine and not from aws.. And why only Solr looses bytes.


text:
Q: Tensorial Proof that $\det(F^{\mu\nu})=(\vec{E}\cdot\vec{B})^2$? I am trying to understand why
$$\det(F^{\mu\nu})=(\vec{E}\cdot\vec{B})^2\tag{1}.$$
Of course one can just calculate the determinant of $F^{\mu\nu}$ expressed as a matrix with components given in terms of $E_x, E_y, ...$, etc., but I am looking for something a bit more insightful. In particular, I understand that $\vec{E}\cdot\vec{B}$ can be written as
$$\vec{E}\cdot\vec{B}=-\frac{1}{8}\epsilon_{\mu\nu\rho\sigma}F^{\mu\nu}F^{\rho\sigma}.\tag{2}$$
This seems promising because then
$$(\vec{E}\cdot\vec{B})^2=\frac{1}{64}\epsilon_{\mu\nu\rho\sigma}\epsilon_{\alpha\beta\gamma\delta}F^{\mu\nu}F^{\rho\sigma}F^{\alpha\beta}F^{\gamma\delta},\tag{3}$$
which looks awfully like the expression for the determinant of $F$ in terms of Levi-Civita tensors,
$$\det(F^{\mu\nu})=\frac{1}{4!}\epsilon_{\mu\nu\rho\sigma}\epsilon_{\alpha\beta\gamma\delta}F^{\mu\alpha}F^{\nu\beta}F^{\rho\gamma}F^{\sigma\delta}.\tag{4}$$
But I can't figure out how to connect these two expressions. Since $F$ is antisymmetric, one can flip the two indices of any single $F$ at the cost of a minus sign, but I need a way to permute indices between different $F$'s. I'm also not sure how a factor of 3 could possibly enter in to change the 1/64 into a 1/24.

A: The two expressions are only superficially similar; they have to be by dimensional analysis. The index structure is completely different, and I don't think you can convert one to the other without essentially undoing everything you did to get to the first result, then inserting the standard proof of the second result. Such a proof would be unenlightening since it'd just be unnecessarily complicated.
So let me just give a simple derivation of the result you want, directly. The determinant is
$$\det F^{\mu\nu} = \epsilon_{\mu\nu\rho\sigma} F^{\mu 0} F^{\nu 1} F^{\rho 2} F^{\sigma 3}$$
There are naively $4!$ terms, but the only nonzero terms are those where $\mu \neq 0$, $\nu \neq 1$, $\rho \neq 2$, $\sigma \neq 3$. That is, we need to count the number of derangements of a 4-element set. It is easy to show by casework there are $9$.
Each of these $9$ terms is quadratic in $\mathbf{E}$, since there are two indices equal to zero, and hence quadratic in $\mathbf{B}$. Moreover, the sum of all $9$ terms is a tensorial invariant. There are only two independent invariants: $E^2 - B^2$ and $\mathbf{E} \cdot \mathbf{B}$. We can't use the first one, because otherwise our terms wouldn't all have the same degree in $E$ and $B$. Then the answer must be proportional to $(\mathbf{E} \cdot \mathbf{B})^2$, but since $(\mathbf{E} \cdot \mathbf{B})^2$ has $9$ terms, they must simply be equal.
You might complain I used components, but I had to because your expression is not tensorial. The fields $\mathbf{E}$ and $\mathbf{B}$ are not Lorentz tensors, but rather a way of writing components of $F_{\mu\nu}$. You can't expect to prove a statement about components without expanding in components.

A: OP's eq. (2) is (minus) the Pfaffian ${\rm Pf}(F)$, and OP's eq. (4) is the determinant ${\rm Det}(F)$. The sought-for relation (1) follows because the square of the Pfaffian is the determinant:
$$ {\rm Pf}(F)^2~=~{\rm Det}(F). \tag{A}$$
A proof of eq. (A) is given in my Math.SE answer here.

A: The determinant on the left is invariant under (proper) Lorentz transformations, so you can easily calculate it in a frame of reference where $E^2=E^3=0$, it equals $(E^1 H^1)^2=(\vec{E}\vec{H})^2 $. As $\vec{E}\vec{H} $ is an invariant under proper Lorentz transformations, this proves your formula in a general case.

A: Quoting myself from an old PhysicsForums post

If I am not mistaken, (someone check my math)
  you can calculate the principal invariants of a tensor:
  $$F^a{}_a,\quad F^a{}_{[a} F^b{}_{b]},\quad F^a{}_{[a} F^b{}_{b}F^c{}_{c]},\quad F^a{}_{[a} F^b{}_{b} F^c{}_{c}F^d{}_{d]}$$
  in 4-dimensions.
  You'd get the trace (sum of the eigenvalues), sum of products-of-pairs of eigenvalues, sum of products-of-triples, and finally, the product-of-the-4-eigenvalues (the determinant).

  For a real antisymmetric matrix, the eigenvalues are imaginary.
  So, only those with sums of products of even-numbers-of-eigenvalues will be nonzero.

(Higher combinations like $F^a{}_{[a} F^b{}_{b} F^c{}_{c}F^d{}_{d}F^e{}_{e}F^f{}_{f]}$ vanish since it would have more than 4 factors being antisymmetrized). So, all but two are identically zero.
At some point in your calculation, you would probably have to make use of the epsilon-delta identities [sometimes written as determinants with delta-entries] (like this contracted combination $\epsilon_{abmn}\epsilon^{cdmn}=-4\delta_a{}^{[c}\delta_b{}^{d]}$ (up to sign conventions, based on signature and dimensionality)). Together with the antisymmetry of $F_{ab}=F_{[ab]}$, I think the index-gynmastics will work out.


text:
Q: I want override animate effect on html & body Suppose below is my code. i am not responsible to make change directly to code. hence i am doing it via console. and i want to unbind this html & body animation but someotherFunction() should work as it is. there may be too many functions as well beyond my imagination like below and i want all to work as it is but only animate should be unbind.
$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
   someOtherFunction();
   someMoreFunctionIDontKnowAbout();
});

A: Answer
We will unbind the .click event then we will add the new binding.

$('#button').unbind("click");
$('#button').click(function() {
   someOtherFunction();
   someMoreFunctionIDontKnowAbout();
});

Side Note
I recommend if this is something you will be doing a lot and only want for yourself that you should install tampermonkey or a similar tool to run jquery/javascript of your own on a specific domain.


text:
Q: Explanation of this integral's solution While doodling around with circles and associated geometry, I've stumbled across this integral (I'm led to believe it is correct but I have not found or created any proof):
$$2\int_{-r}^{r}\sqrt{r^2-x^2}dx=\pi r^2;r \ge 0 \tag 1$$
(edit, changed $\sqrt{r-x^2}$ to $\sqrt{r^2-x^2}$ as the former is not correct geometrically)
If it isn't immediately clear, this resulted from using an infinite series of parallel chords to compute area. I'm aware there are simpler approaches, however this one is intriguing, knowing the result... I've tried integrating it by hand, couldn't figure out how to approach it.
Wolfram Alpha (for lack of human assistance at my disposal) gave me this fascinating indefinite integral for $r=1$:
$$F(x)=\int\sqrt{1-x^2}dx=\frac{1}2(x\sqrt{1-x^2}+\arcsin x) \tag 2$$
It is apparent that: $2(F(1)-F(-1))=(\arcsin{1}) - (\arcsin{-1}) = \pi$
I understand why to expect $\arcsin$ to appear in the result, after all $\sqrt{1-x^2}=\cos\arcsin x$, but I don't understand why it has appeared in the result or its significance. I can see already that any definite integral for (1) will cancel itself out leaving only the arcsin term...
A step-by-step solution to (1) or (2) would be most helpful but not required.

A: By recalling
$$\sin^2 x + \cos^2 x = 1,$$
we are tempted to make a substitution $x = \sin t$ in $(2)$. Then, the indefinite integral becomes
$$\int \sqrt{1-\sin^2t} \cos t \,dt = \int \cos^2 t \, dt.$$
Using integration by parts you will get your desired result.
What similar substitution can you do in order to solve $(1)$?

A: Defining $x=r\cos(\theta)$ we can find that $\text{d}x=-r\sin(\theta)\text{d}\theta$ and $\theta$ goes from $\pi$ to $0$ the integral becomes $$\int_{-r}^{r}\sqrt{r^2-x^2}\text{d}x=-r\int_{\pi}^{0}\sqrt{r^2-r^2\cos^2(\theta)}\sin(\theta)\text{d}\theta=-r^2\int_{\pi}^{0}\sin^2(\theta)\text{d}\theta$$ and you may continue.

A: By decomposition, then by parts,
$$\int\sqrt{1-x^2}dx=\int\frac{dx}{\sqrt{1-x^2}}-\int\frac{x^2\,dx}{\sqrt{1-x^2}}=\arcsin(x)+x\sqrt{1-x^2}-\int\sqrt{1-x^2}\,dx.$$
You can conclude.

A: The integral that you want to compute is the area of a circle segment defined by intersecting the trigonometric circle with a vertical at $x$.

This area is that of the sector, equal to the subtended angle, minus the triangle.
$$A=2\int_{-1}^x\sqrt{1-x^2}\,dx=2\arcsin(x)+x\sqrt{1-x^2}.$$


text:
Q: How to get product attributes with values How can I get all attributes of product with its values?
I mean attributes like size, color, gender and like that, but not availablity, quantity or sku. I need to use them for filters, how can I get it?

A: you have write on block class file
<?php
namespace Pradip\Magegig\Block;
class Products extends \Magento\Framework\View\Element\Template
{
    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    )
    {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3);
        return $collection;
    }
}
?>

in Phtml file you will getting all attribute along with product
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());
    echo "<br>";
}

A: Please check the link.
Which have all the answer of your question.
Thanks


text:
Q: Find sum of a variable I am attempting to read a .txt file and have output print on a single line.  The .txt file has random integers written to it.  My code writes those numbers, but does not write them on the same line.  I am also attempting to find the sum of those integers and print them.  I'm not sure how close my code is, but I am stuck right now.  Any help would be appreciated.
def main():
    # Open a file for reading.
    infile = open('numbers.txt', 'r')
    file_contents = infile.read()
    infile.close()
    total = (sum,file_contents)
    print(file_contents,'\n',end='')
    print(total)

main()

Here is the code that wrote the numbers.txt file if that helps
import random

def main():
    nums = open('numbers.txt','w') #Opens and assigns numbers.txt
    #Generates integer random integer between 4 and 7
    file_size = random.randint(4, 7)
    #Takes the file_size integer and generates that amount
    #of random integers between 5 and 19.
    for num in range(file_size):
       random_num = random.randrange(5,20,2)
       if random_num % 2 ==1:
           nums.write(str(random_num)+'\n')
    nums.close()
    print('Data has been written.')

main()

I've updated the code, still with no luck unfortunately.
    def main():
    # Open a file for reading.

    infile = open('numbers.txt', 'r')

    file_contents = infile.read()

    total += sum(int(file_contents.strip()))

    infile.close()

    print(file_contents)
    print(total)

main()

A: import sys
sum = 0
for lineno, line in enumerate(open("numbers.txt","r")):
    try:
        sum += int(line.strip())
        sys.stdout.write(str(sum)+" ")
    except ValueError:
        print ("error in line %d"%lineno)
sys.stdout.flush()
print("sum=",sum)

Update example, so that it also prints the numbers

A: total = sum(map(int,file_contents.split()))

explanation:
split() - splits the contents of the file along every whitespace (including '\n'
map(int, ....) - converts every element of previous result to int
sum() - takes in iterable, return sum. its a builtin function

A: The numbers you wrote in numbers.txt are stored in string format, so when you read them from the this file, you will get them back as string, this means you need to convert them back to int but you need first to strip any white space character, because you save them with \n at then end.
I want to add another thing, according to Python documentation when dealing with File I/O operation:

It is good practice to use the with keyword when dealing with file
  objects. This has the advantage that the file is properly closed after
  its suite finishes, even if an exception is raised on the way. It is
  also much shorter than writing equivalent try-finally blocks,

So, the code can be as follows:
def main():
total = 0
# Open a file for reading.
with open('numbers.txt', 'r') as infile:
   line = infile.readline()
   while (line):
      total += int(line.strip())
      line = infile.readline()
print(total)

main()


text:
Q: UnboundLocalError: local variable 'money' referenced before assignment I'm trying to get rid of a error in python but so far every method i've tried hasn't worked. Any help would be greatly appreciated.
The code:
from sense_hat import SenseHat
import random
from guizero import App, PushButton,Text
import time
import pygame.mixer
from pygame.mixer import Sound
pygame.mixer.init()
sense = SenseHat()
app = App(title="Fruity Fruit Machine", bgcolor="yellow")
mario = Sound("SuperMarioBros.ogg")
money = 30.00
casino = 100.00
global money
global casino
def machine():
     sense.clear(0,0,0)
     images = ["apple.png", "orange.png", "lemon.png"]
     fruit = []
     money = money - 1.00
     for i in range(3):
          img = random.choice(images)
          fruit.append(img)
          sense.load_image(img)
          time.sleep(3)
          sense.clear(0,0,0)
     if all_same(fruit) == True:
          sense.show_message("You won £20!")
          casino = casino - 20.00
          money = money + 20.00
          display_casino()
          dispaly_money()
          dc = "Casino money: " + casino
          cm.set(dc)
          md = "Your money: " + money
          m.set(md)
     else:
          sense.show_message("You got 30p!")
          money = money + 00.30
          casino = casino + 00.70
          display_casino()
          display_money()
          dc = "Casino money: " + casino
          cm.set(dc)
          md = "Your money: " + money
          m.set(md)

def play_mario():
     mario.play()
def all_same(items):
     return all(x == items[0] for x in items)

button = PushButton(app, command=machine, text="SPIN")
button2 = PushButton(app, command=play_mario, text="Play Music")
cm = Text(app, text="",align="left")
m = Text(app, text="",align="right")

The error is: UnboundLocalError: local variable 'money' referenced before assignment. Python also sometimes comes up with a syntax warning: SyntaxWarning: name 'casino' is assigned to before global declaration

A: You need to put global money and global casino within machine. Putting it outside a function does nothing. For an explanation of why, take a look at this answer.

A: Try moving the global declarations inside your function:
from sense_hat import SenseHat
import random
from guizero import App, PushButton,Text
import time
import pygame.mixer
from pygame.mixer import Sound
pygame.mixer.init()
sense = SenseHat()
app = App(title="Fruity Fruit Machine", bgcolor="yellow")
mario = Sound("SuperMarioBros.ogg")
money = 30.00
casino = 100.00
def machine():
    global money
    global casino
    sense.clear(0,0,0)
    images = ["apple.png", "orange.png", "lemon.png"]
    fruit = []
    money = money - 1.00
    for i in range(3):
        img = random.choice(images)
        fruit.append(img)
        sense.load_image(img)
        time.sleep(3)
        sense.clear(0,0,0)
    if all_same(fruit) == True:
        sense.show_message("You won £20!")
        casino = casino - 20.00
        money = money + 20.00
        display_casino()
        dispaly_money()
        dc = "Casino money: " + casino
        cm.set(dc)
        md = "Your money: " + money
        m.set(md)
    else:
        sense.show_message("You got 30p!")
        money = money + 00.30


text:
Q: cannot run condition if-else in django I want to check if the user is logged in:
{% if userprofile.is_autenticated %}

{{ user.get_username }}

Sign Out

{% else %}

 Login

{% endif %}

But when I'm already logged in, it uses this code:

 Login

I made a custom user model to manage the users.

A: You need to set the AUTH_USER_MODEL in settings and you can read this for more info.


text:
Q: Keep CakePHP Session after browser is closed How to keep CakePHP 1.3 session after browser is closed?

A: Seems there are ways to increase the time for the session to live on through an overridden configuration value. (At the PHP level -- via CakePHP Manual). Using the code below you could change 0 to the number of seconds you'd like the session to live on for.
// Cookie is now destroyed when browser is closed, doesn't
// persist for days as it does by default for security
// low and medium
ini_set('session.cookie_lifetime', 0);

Example for 2 weeks:
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 14);

The above code snippet would be written to a configuration file that you create in app/config. To get CakePHP to read that file on initialization add the following to app/config/core.php
Configure::write('Session.save','my_session');

Where my_session is the name of your configuration file.

A: You would have to transform it into a cookie, as sessions are automatically removed when the browser is closed. See this.

A: Set $this->Session->cookieLifeTime = $timeToLive;, where $timeToLive is the length in seconds you would like the session to last. This is the total length, so if the browser window closes it will not be deleted, but note that it is not measured from the time the browser closed.

A: Cookie is not destroyed when browser is closed.


text:
Q: React-bootstrap - TABS component - render children components I'm trying to render children components in every react-bootstrap's tab like this. But I really don't understand how it works. Check it out.
I'm trying to render de component subNavbarDashboard inside the first tab.
import React, { Component } from 'react';
import './navbar.css'
import Tabs from 'react-bootstrap/lib/Tabs';
import Tab from 'react-bootstrap/lib/Tab';
import SubNavbarDashboard from '../SubNavbar/subNavbar';

const ControlledTabs = React.createClass({
    getInitialState() {
        return {
            key: 1
        };
    },

    handleSelect(key) {
        this.setState({ key });
        if (key === 1) {
            alert(1);
            this.setState(<SubNavbarDashboard />);

        }
    },

    render(props) {
        return (

                    <Tabs activeKey={this.state.key} onSelect={this.handleSelect} id="">
                        <Tab eventKey={1} title="Dashboard">Dashboard</Tab>
                        <Tab eventKey={2} title="Feedback">Feedback</Tab>
                        <Tab eventKey={3} title="Historial" >Historial</Tab>
                    </Tabs>

                        hola

                        hola 2

                        hola 3

        );
    }
});

class Navbar extends Component {
    render() {
        return (

                <ControlledTabs
                    dashboard={
                        <SubNavbarDashboard />
                    }
                />

        );
    }
}
export default Navbar;

A: Generally we manipulate the component on tab click at run-time
    const ControlledTabs = React.createClass({
        getInitialState() {
            return {
                key: 1
            };
        },
        handleSelect(key) {
            this.setState({ key });
        },

        render(props) {
            let component;
            if(this.state.key == 1)
               component=
<SubNavbarDashboard />

            return (

                        <Tabs activeKey={this.state.key} onSelect={this.handleSelect} id="">
                            <Tab eventKey={1} title="Dashboard">Dashboard</Tab>
                            <Tab eventKey={2} title="Feedback">Feedback</Tab>
                            <Tab eventKey={3} title="Historial" >Historial</Tab>
                        </Tabs>
                        {component}

            );
        }
    });


text:
Q: Inserting a row into only column B I've written a macro to copy a row from Sheet 2 and inset that row into Sheet 1. My problem is that I only wish to insert the row starting at Column B on the active row. Here is the macro:
Sub addTestProductRow()
Sheets("Macro templates").Range("B2:J2").Copy
Selection.Insert Shift:=xlDown
End Sub

Currently my macro does this:
If the user has selected the cell K2 and executes the macro, the Row will be inserted from K2 to S2
What I want the macro to do:
If the user has selected cell K2 and executes the macro, the Row will be inserted from B2 to J2
Things to note:
The row contains a check box so that has to be copied across, currently my macro does copy and paste the check box correctly.

A: Change:
Selection.Insert Shift:=xlDown
to:
Sheets("nameOfOtherSheetGoesHere").Range("B2").Insert Shift:=xlDown
Rather than relying on the selection, specify the sheet and range where you want the insert to take place


text:
Q: manipulate jquery object from AJAX $.get So I would like to know how to manipulate the Data I'm getting as a return from a $.get Method call to a link.
Example:
$.get('/index.php?id='+before+'&type=110', function(data){
    var result = $(data).find('#ul1999 > *');
    console.log(result);
},'text');

The response of the Webpage would be similar to this:

            something something

            got a sub

                      i'm the sub

            something 2

And my returned value looks like this:
Object[li, li, li, li, li.last]

I now want to remove the parent element of id "ta200", so the entire li containing this id.
I tried to remove it with
var result = $(data).find('#ul1999 > *').not('#ta200').parent();

but it didn't work.
Maybe someone could tell me how to access the actual object and search for the id?

A: It should be as simple as this:
$(data).find("#ta200").parent().remove();

Here's a JSFiddle to better illustrate how you can manipulate an in-memory DOM like that and then retrieve the modified HTML: http://jsfiddle.net/troygizzi/xu6d3xhp/