Managing Vuex state using with NuxtJs on 'universal' mode

Question: I get used to using localStorage with Vuex but as you know on SSR we can not use localeStorage. So I searched a solution to keep Vuex state on page refresh and run into vuex-persistedstate using with js-cookie many times.
My question is that do I need really vuex-persistedstate? I mean that can I just use js-cookie just like the following:
import Cookie from 'js-cookie'

const state = {
  firstName: Cookie.get('firstName)
}

const mutations = {
  setFirstName(state, name) {
    state.firstName = name;
    Cookie.set('firstName', name)
}

etc.
Comment: I use cookies in nuxt and I've never used vuex-persistedstate. Never even heard of it. I use 'js-cookie' to set cookies and 'cookie' to get them. Just the way I learnt it.
Comment: @Andrew1325 So I can use like the my example above?
Answer: Following your comment question. Your example in the question is ok at least for setting the cookie. I set mine in an action first and then commit the mutation to set the state only. As for getting your cookies, you might need a bit more than just setting the state. As I said i use 'cookie' (see here) for getting my cookies and I get them through nuxtServerInit, like this:
nuxtServerInit({dispatch}, context) {
              return Promise.all([
                dispatch('get_cookies', context),
                //other actions
              ]);
            },

and the action itself as follows:
get_cookies (vuexContext, context) {
              return new Promise((resolve, reject) => {
                const cookieConst = cookie.parse(context.req.headers.cookie || '')
                if (cookieConst.hasOwnProperty('YourCookieName')) {
                    //commit mutations here
                }
                else {
                    resolve(false)
                }
              })
            },

Obviously you need to import:
import cookies from 'js-cookie'
import cookie from 'cookie'

You can put a fair bit of stuff into cookies, I set user details and shopping cart. I also store an access token in my cookies and validate it in my backend so I can persist an auth state.


How to deal with interruption in time series analysis?

Question: I am probing a time series data of transactions. Basically, I want to see the pattern of the number of transactions in each time slice.
First of all, I looked at hourly data. However, the opening hour is 9am to 9pm thus no data in another 12 hours in each day.
Secondly, I looked at daily data (i.e. by date). No transaction occurred on Sunday and holiday so the data does not contain these date.

I read a book saying that:

One of the assumption of time-series analysis is data points are taken at equally spaced time steps, with no missing data points.

So should I fill the time (in hourly data) or date (in daily data) and interpolate the values (i.e. the number of transactions) to fulfill the assumption?
Comment: You should get a better book.  Seriously. Maybe that's as assumption made in that book, but not in general. You situation is quite common
Comment: @MarkL.Stone Thank you. I think that I do not really understand the connotation of the assumption. But I will refer to other sources. Your advice helps.
Comment: The connotation is that the book you quoted from must not be a good book.  So get a better book.
Answer: Definitely don't interpolate the transactions! That would be equivalent to saying you're doing business on Sunday at 6 AM. Just take those time points out; since we know for certain there cannot be any transactions outside of business hours, then we know there's no statistical information. Also, if there are any transactions outside of the appropriate hours, it must be a bug in the system or an unscrupulous employee doing some shady business by night.
The book passage that you read needs to be taken with a grain of salt; the author probably assumed that the data you got was processed in a logical manner to remove any excess stuff you didn't need. For example, if I have a data set which lists smartphone sales over the last 100 years, I'm definitely going to cut off anything before, say, 2000, because I am quite certain that nothing that we would call a 'smartphone' today existed back then on the market. This is a similar sort of data transformation.
For a more practical reason why you should take out the non-business hours data and then stitch together the remaining pieces, consider the following time series analysis problem. If we were to construct an autoregressive model of transactions, then there would be enormous error for the model in predicting the first hour of the day, as the preceding 11 time steps would all be zero. There's no way to add together multiples of zero to create a nonzero sum! Unless your ARMA includes a constant, that is.
There's also a bit of a problem with investigating this time series on an hourly basis since there is discontinuity between sales at 9PM and 9AM. Maybe something interesting can come out of analyzing it, but a more appropriate way to phrase this question is to look at each day as a member of a population of days with transaction data and then ignore the fact that each day is ordered. I say this because I would expect there to be little effect (on an hourly basis!) of something that happened on the preceding day. Unless, of course, there's that one really smelly employee who checks in, leaves a foul odor which then decays slowly over the next few days with regards to time.
TLDR: Don't interpolate! Either take out the offending hours and stitch the remaining data together, or consider each business day of transactions as a separate entity and compute population statistics on that group. Also, if you take out the holidays then the daily data should be perfectly fine to work with.


Golden Angle Golden Spiral

Question: Note. The answer must produce something self-similar that progresses in such a manner regardless of whether positive or negative values are graphed.
Note. The "distance between 'arcs'" I'm talking about is defined in my image (the red dotted line represents such a distance between 'arcs').
The parametric equations, $x,\ y=\sin(t)·φ^{t/π},\ \cos(t)·φ^{t/π}$, yield a spiral where the distance between the 'arcs' grows (/shrinks) gradually reaching powers of $φ$ at every multiple of $π$ (every $180$ degrees). (See My Graph.)
I want to find parametric equations for a spiral where this distance grows (/shrinks) by powers of φ in exactly the same way relative to multiples of the golden angle, that is, $\frac{2π}{φ}$ (Instead of doing so relative to π). ($φ$ is defined as $φ=\left(\frac{1+5^{1/2}}{2}\right)$ herein!)
Such a thing seems totally possible; however I have had little luck thus far. So, I'd be thankful for some help! Thanks.

Graph:
https://www.desmos.com/calculator/0iotz6gmdu
Comment: In polar coordinates, $(r,\theta)=(f(t),t)$, it appears that you want $$f(k\omega)-f(k\omega-2\pi) = \phi^{k+c}$$ for integer $k$, where $\omega:=2\pi/\phi$ (or whatever angular step you'd care to take) and $c$ is there just to match the desired multiple of $\omega$ with the desired power of $\phi$. The continuous, $k$-less version of the target relation would be $$f(t)-f(t-2\pi)=\phi^{(t/\omega)+c}$$ Does this seem correct to you?
Comment: **If you don't understand something about my post, please feel free to ask!**
Comment: @Blue Yes. That perfectly formalizes what I want!
Comment: You, @Blue are awesome, it must be said! Also, an interesting thing I noted is that when I tried to derive the function myself, whenever I modified it to yield a good approximation on one part of the spiral, the other parts were way off (this happened for multiple strategies): I wonder what this will turn out to mean in the context of the correct function!?
Answer: You may parametrize the proposed spiral as
$$x=\sin(t)·\phi^{\frac{t\phi}{2\pi}},\>\>\>\>\>y =\cos(t)·\phi^{\frac{t\phi}{2\pi}}$$
which yields the distance between the arcs grows/shrinks gradually reaching powers of $\phi$ at every multiple of $\frac{2\pi}\phi$.
Comment: @JinnyEcckle - Yeah, it's tricky. Let me take another look.
Comment: @JinnyEcckle - I removed the cancelling factor in the two trig functions. I think it should work now. Give it a try.
Comment: Unfortunately, this function (which I've measured in the past), appears to give powers of phi from 'arcs' to the origin, but **not** in the distances between 'arcs.'
Comment: Thank you for the answer, @Quanto, but you seem to have inverted what I asked about: I want a spiral that grows / shrinks by powers of $ϕ$ at multiples of the golden angle, not one that grows by powers of the golden angle at multiples of $π$.
Comment: Anyhow, thank you.
Comment: see my *updated* question.
Comment: @JinnyEcckle - Thanks for clarification. I modified the answer accordingly.
Comment: Thank you, When you say, "which yields the distance between the arcs grows/shrinks gradually reaching powers of ϕ at every multiple of ϕ." Do you mean every multiple of $\frac{2π}{φ}$?
Comment: @JinnyEcckle - I assume multiple of $\phi$. I guess you need multiples of $2\pi/\phi$. I modified.
Comment: unfortunately, this spiral does not have the property described.
Comment: See link, https://www.desmos.com/calculator/5zohp8vdon @Quanto .
Comment: this is a tricky one, isn't it?! Also, note, if you try to work on it more, I'd rather parameterize it outside of the the sine / cosine functions, that is, I'd like: $x, \ y = f(t)⋅\sin(t), \ f(t)⋅\sin(t)$.
Comment: The issue you ran into here, it seems to me, is that when you use $ϕ$ as you do, the instances cancel out, thus making the whole the the same as $x,\ y=\sin(t)·φ^{t/π},\ \cos(t)·φ^{t/π}$.
Comment: Thank You! :) I appreciate the work!
Comment: Nevertheless thank you for all the effort, it is an extremely tricky function to formulate!
Answer: Expanding-upon comment, if we consider polar coordinates $(r,\theta)=(f(t),t)$, with initial condition that the curve passes through $(x,y)=(b,0)$, then the curve's defining relation is
$$f(k\omega) - f(k\omega-2\pi) = \phi^{k+c} = \exp_\phi(k+c) \qquad\qquad f(0) = b\tag{1}$$
where $\omega := 2\pi/\phi$, $k$ is an integer, and $c$ is there just to make sure the multiples of $\omega$ match with the appropriate powers of $\phi$. The continuous, $k$-free version of $(1)$ is

$$f(t)-f(t-2\pi) = \exp_\phi\left(\frac{t}{\omega}+c\right) \qquad\qquad f(0)=b \tag{2}$$

Suppose the solution has the form
$$f(t) = a\left(\phi^{t/\omega}-1\right) + b \tag{3}$$
Then $(2)$ requires
$$\exp_\phi\left(\frac{t}{\omega}+c\right) = a\exp_\phi\left(\frac{t}{\omega}\right) - a\exp_\phi\left(\frac{t}{\omega}-\frac{2\pi}{\omega}\right)
= a\exp_\phi\left(\frac{t}{\omega}\right) - a\exp_\phi\left(\frac{t}{\omega}-\phi\right) \tag{4}$$
Dividing the left-most and right-most expressions by $\phi^{t/\omega}$,
$$\phi^c = a - a\phi^{-\phi} \qquad\to\qquad a = \frac{\phi^{\phi+c}}{\phi^\phi-1}
\tag{5}$$
so that $(3)$ becomes

$$f(t) = \frac{\phi^{\phi+c}}{\phi^\phi-1}\left(\phi^{t/\omega}-1\right) + b \tag{$\star$}$$
Comment: @JinnyEcckle: I don't understand what you mean. Be that as it may ... Since you emphatically agreed with my comment's formalization of your question, changing the conditions after the fact is bad form. You should post (yet another :) new question.
Answer: If I understand correctly you are seeking a spiral that increases by a factor of $\varphi$ for every angular change of $2\pi/\varphi$. This is the very definition of the logarithmic spiral, which is given in complex and Cartesian coordinates as follows
$$
z=e^{(b+i)\theta}\\
x=e^{b\theta}\cos\theta\\
y=e^{b\theta}\sin\theta
$$
where $b$ is the flair coefficient, which is defined as the logarithm of the growth rate, say $p$, divided by the angular change, say $\Delta\theta$, thus
$$b=\ln(p)/\Delta\theta$$
For example, for the golden spiral we have $b=2\ln\varphi/\pi$, or a growth of $\varphi$ per $90^{\circ}$. In your case, the solution is
$$b=\frac{\varphi\ln\varphi}{2\pi}$$
The figure below shows a comparison of these two spirals. Clearly, the golden spiral grows at a much faster rate, namely, $4/\varphi$.

Golden Angle Golden Spiral


Puppet ensure file is directory OR link. Or ensure directory only if absent?

Question: 2 CentOS servers that I'd like to apply the same manifest to. The manifest creates a user with a custom home directory location under /var/username
Problem is on one of the servers /var/username has to be a symlink off to /data/username. So simply running ensure => 'directory', would attempt to overwrite the symlink.
And I can't use ensure => 'present' because that creates a file by default if it doesn't exist. So for new servers that this manifest applies to a blank file will be created when I actually need it to be a directory.

Is there a way of doing ensure directory or link? So that if it's absent a directory is created. And if it's a link, then just leave it alone? By default the Puppet file type creates a file when doing ensure => 'present'.
Or a way of doing if absent ensure directory else leave it alone?

What about exec, doing a simple bash if /var/username not exist then mkdir sort of thing?
Nasty but it would work.
The ideal solution is probably to avoid special cases from the start. Having multiple config variants in a single manifest does seem a bit wrong. So eventually I will either:

normalise the VMs (might switch from a symlink to a bind mount for example)
give them separate manifests, since the configuration between them is different

But for the purposes of this question I would like to know if there are any options/syntax within Puppet that I currently don't know about.
Answer: You could always use $hostname or $certname to handle the exception:
file { "/var/username":
mode    => 440,
ensure  => $hostname ? {
  'oddballserver' => link,
  default  => directory,
  },
target => $hostname ? {
  'oddballserver' => '/data/username',
}

That's untested, but based on logic I use for a variety of things in our manifests.  YMMV.
Answer: Good afternoon, you need to create a link in the /usr/share/applications/desktop Astra Linux directory from the root user. With the name of the link, the path where it leads and the shortcut. How can this be implemented by puppet manifest? I read the documentation and tried, but nothing came out(


GLM or beta regression, with proportion data, and many 0 and 1

Question: I am trying to see if some anthropic variables (e.g., PopdensityAvg) explain animals' distribution. My dependent variable is the area occupied (non_null_cells) over the total area of interest (PAR), which can be expressed both as a percentage (range_perc, continuous variable, range: 0-100; e.g., 87.9) and as a proportion (range_prop, ranging 0-1, e.g. 0.87).
Each species has also a status (Establishment, discrete variable; i.e., 0/1), and I expect to have different influences of each independent variable, based on species' status. For instance, for a species with status 0, I expect no influence of Roads, while for a species with status 1, I expect an influence of Roads.
The values of the independent variables are averaged and measured throughout the species distribution range. Some of these independent variables can have a negative value (e.g., PopgrowthAvg). The data looks like this:
              Binomial Establishment      PAR non_null_cells range_prop range_perc PopdensityAvg PopgrowthAvg  Railways    Roads
1    Ammotragus_lervia             1 10840225       10762611  0.9928402   99.28402      68.68320    1.8325691 0.5568174 2.265508
2 Ammotragus_lervia_NE             0 10699087       10621473  0.9927457   99.27457      69.58296    1.8520451 0.5631284 2.288850
3  Apodemus_sylvaticus             1  2334776        2158612  0.9245478   92.45478     139.97713    2.6652732 0.9798067 2.927115
4     Atelerix_algirus             1   438917         383734  0.8742746   87.42746      76.02714    2.4077785 0.6011552 2.380663
5            Axis_axis             1     2072           1970  0.9507722   95.07722      19.40114    0.1917508 0.0000000 2.354487
6         Axis_axis_NE             0    18804          18804  1.0000000  100.00000      97.61798    2.7962866 0.3156403 2.715702

I got the recommendation of beta regression (from betareg package in R), but I have many 0's and 1's in range_prop. If I perform the suggested transformation (from an answer here Dealing with 0,1 values in a beta regression , "if y also assumes the extremes 0 and 1, a useful transformation in practice is (y * (n−1) + 0.5) / n where n is the sample size", it transforms my 1's in 0.95, and I don't know how good is that for my model, as I am very interested in outputs from observations with a range_prop value of 1).
I switched to GLM (package stats, I don't know if there are better options) thinking it would be better. I think I should use a Gamma distribution, based on the response variable (that is > 0 and is continuous). I understand that as my response variable's upper limit is 1 (or 100, if we consider range_perc), a beta regression would likely perform better compared to a Gamma distribution (that, if I am correct, assumes just values > 0, without an upper limit), but I don't know how to deal with so many 0's and 1's, and I do not understand if I should transform my data to comply with a particular modelling algorithm or if I can safely switch to more generalized techniques (such as GLMs).
I am wondering if my reasonings are correct, and also how to deal with negative values in the independent variables (such as the ones in PopgrowthAvg, not present in the sample data I show here).
Edit:
In my data, I also have the total area of interest, from which I extracted range_perc and range_prop for each species in Binomial. I added it to the sample data.
I am using R 4.0.3
Edit n.2:
After the useful answers, I tried a GLM with binomial distribution. As in Dunn & Smyth book on GLMs,

Binomial responses may be specified in the glm() formula in one of
three ways:

The response can be supplied as the observed proportions yi, when the sample sizes mi are supplied as the weights in the call to glm().
The response can be given as a two-column array, the columns giving the numbers of successes and failures respectively in each group of
size mi. The prior weights weights do not need to be supplied (r
computes the weights m as the sum of the number of successes and
failures for each row).

I tried both:

First approach

col_glm <- cbind(myData$non_null_cells, ((myData$PAR)-(myData$non_null_cells)))
#use a 2 column matrix as the response variable with the first column being the counts of 'successes' and the second column being the counts of 'failures'
#in this case, successes are the cells occupied by the species range (non_null_cells) and failures is the total area (PAR - non_null_cells)

glm2.2 <- glm(col_glm ~ PopdensityAvg + PopgrowthAvg + Railways + Roads,
              family = binomial,
              data = myData)

summary(glm2.2)

Call:
glm(formula = col_glm ~ PopdensityAvg + PopgrowthAvg + Railways +
    Roads, family = binomial, data = myData)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2612.51      2.49    129.26    610.45   1722.15

Coefficients:
                 Estimate  Std. Error z value            Pr(>|z|)
(Intercept)   -1.05252214  0.00230722  -456.2 <0.0000000000000002 ***
PopdensityAvg -0.05356983  0.00002347 -2282.4 <0.0000000000000002 ***
PopgrowthAvg   0.31591664  0.00027212  1160.9 <0.0000000000000002 ***
Railways       7.23302791  0.00304914  2372.2 <0.0000000000000002 ***
Roads          0.80775145  0.00109461   737.9 <0.0000000000000002 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 60080855  on 94  degrees of freedom
Residual deviance: 52299051  on 90  degrees of freedom
AIC: 52299902

Number of Fisher Scoring iterations: 6

Second approach

glm2.3 <- glm(range_prop ~ PopdensityAvg + PopgrowthAvg + Railways + Roads,
              weights = myData$PAR,
              family = binomial,
              data = myData)
#specify the response as a proportion between 0 and 1, then specify another column as the 'weight' that gives the total number that the proportion is from

summary(glm2.3)

Call:
glm(formula = range_prop ~ PopdensityAvg + PopgrowthAvg + Railways +
    Roads, family = binomial, data = myData, weights = myData$PAR)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2612.51      2.49    129.26    610.45   1722.15

Coefficients:
                 Estimate  Std. Error z value            Pr(>|z|)
(Intercept)   -1.05252214  0.00230722  -456.2 <0.0000000000000002 ***
PopdensityAvg -0.05356983  0.00002347 -2282.4 <0.0000000000000002 ***
PopgrowthAvg   0.31591664  0.00027212  1160.9 <0.0000000000000002 ***
Railways       7.23302791  0.00304914  2372.2 <0.0000000000000002 ***
Roads          0.80775145  0.00109461   737.9 <0.0000000000000002 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 60080855  on 94  degrees of freedom
Residual deviance: 52299051  on 90  degrees of freedom
AIC: 52299902

Number of Fisher Scoring iterations: 6

The outputs are the same. I tried, with my naive knowledge, to interpret the results.
The Deviance Residuals seem to have a high median value and 1Q and 3Q to be substantially apart, which I guess is not good.
Null deviance and Residual deviance are very high as well. Again: I guess it's not good.
Comment: A CV post about logistic regression when the outcome is a proportion, with links to more relevent posts: [Help with needed with Fractional outcomes Logit Regression?](https://stats.stackexchange.com/questions/530149/help-with-needed-with-fractional-outcomes-logit-regression)
Comment: Absolutely no logit transformation beforehand. It wouldn't work for 0 and 1 and in any case using logit link is the machinery to fit on logit scale. The excellent book of Peter Dunn and @Gordon Smyth on generalized linear models is one possibility here.
Comment: @dipetkov yes, I got a `Warning message: glm.fit: fitted probabilities numerically 0 or 1 occurred`.
I have some extreme values (both in my dependent variable `range_perc` and in my predictors, e.g., `PopdensityAvg`), skewing the data, as you can see:
`> summary(myData$PopdensityAvg)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.00   63.58   91.81  158.01  147.21 2447.92
> summary(myData$range_perc)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
  0.00922  58.32962  96.58130  79.00526  99.76029 100.00000`
. Maybe I shall try again, removing them.
Comment: I guess you're using R. Please make that explicit (or the name of your program if different). This to me is definitely not a beta regression and I am in horror at the idea of fudging 0 and 1 proportions. in Stata this could be a generalized linear model with binomial family, logit link and robust standard errors. Some software uses a quasi- jargon.  Negative values in so-called independent variables are not a problem as such Gamma distribution is not appealing for a variable that is doubly bounded and where both bounds are present in the data.
Comment: https://journals.sagepub.com/doi/pdf/10.1177/1536867X0800800212 is a good tutorial.
Comment: @Nick Cox thanks, I edited my question (I am using R). I am also in doubt about fudging the data, therefore my question. I am not totally sure I understood correctly how a Binomial distribution could fit my data (as usually it would be a proportion of successes, and I'm not sure that a % of area occupied can be interpreted as such), but based on the tutorial you posted, I guess I should apply a logit transformation before fitting the model?
Comment: Delighted to learn of _Axis axis_ or chital. How many species do you have?
Comment: In a comment to your previous [question](https://stats.stackexchange.com/questions/585063/random-effects-in-generalized-linear-mixed-models-alternative-with-generalized) you indicate that you have the total area as well (ie., the denominator in the calculation of `range_prop`). This is relevant information that you probably should be mentioned in the text of your question.
Comment: @Nick Cox thanks, I'll check it out! I have 70 species, indeed the chital is one of the nicest :)
Comment: @dipetkov you are correct. I omitted it (both from the sample data and from my question) as I thought it wasn't relevant, as I already obtained the variable I was interested in (area occupied / total area). I'll add it.
Comment: So, why not post all your data? At least for the variables already shown.
Comment: I thought it was not relevant, actually, as I still have some difficulties in interpreting this variable in the same way as I could interpret a proportion of successes over trials (but I guess it is the whole point of using a binomial distribution here, correct?). But if I understood correctly, the area occupied over the total area can be seen in the same way.  I updated my question & sample data.
Comment: Thanks @dipetkov. After your answers and those of Nick Cox, I tried a GLM with binomial distribution, and edited the question accordingly.
Comment: There might be a numerical issue? Were there any warnings/messages? It's hard to say really what's going on just from the model summaries.
Comment: Just note that we can't help you "debug by comment". If you'd like more specific help, you should consider providing the data as @NickCox pointed out.
Comment: You are right, the sample I provided is not fully representative (I am still a newbie here, sorry). I am reading how to deal with outliers; in fact, I checked some of them and they resonate (in the sense that they do not come from typos or incorrect prior analyses) , and thus will be needed. I will definitely not throw them.
Comment: You might want to look at [this page](https://stats.stackexchange.com/q/11109/28500) about your warning message and the likely "perfect separation" that you have come across. It doesn't mean that your model is incorrect per se, but you need to do some tweaking to get useful standard error estimates.
Comment: Thanks @EdM. To recap, I have i) a proportion dependent variable, with no 0's but many 1's ii) explanatory variables with negative values and outliers iii) my response variable is perfectly separated by my explanatory variables. I am looking into `glmnet` R package as suggested by the question you linked (without any real success, by far). I am also looking into robust GLM (from `robustbase` R package). I am getting a bit confused in finding the right procedure here...
Answer: The issues with deviance and potential perfect separation aren't troubling by themselves. It's not clear, however, that the analysis you describe will address your questions adequately.
You seem to have set up geographic grids, with each cell evaluated for presence or absence of a species. In a binomial model each cell would count as a trial. You have over 10 million trials (PAR) in each of your first 2 cases alone. The deviance necessarily increases with the total number of trials, so the large deviance values aren't an a priori problem.
Although your "fitted probabilities numerically 0 or 1 occurred" might be a sign of perfect separation, you don't need to worry about that, either, on its own. With your large number of trials, you don't have the usual problems of poor convergence, extreme regression coefficients and wide confidence intervals (CI). Your model converged in 6 iterations and shows narrow CI consistent with a very large number of trials.
The problem is that your trials aren't independent. The large numbers of trials within each species aren't independent of each other and can't necessarily be compared against those for the other species. Observations within a species will incorporate any species-specific effects that aren't captured in your model, effects that will differ among the species.
One species-specific characteristic is its own population density. With a random Poisson population distribution and an average population $\mu$ per cell, there is an expected fraction $\exp(-\mu)$ of empty cells. So the baseline probability of an empty cell, under a null hypothesis of a random distribution over the grid, depends on population density. That's not taken into account in your model. As it stands, your model might just be for a proxy of species' population densities.
A mixed model with random effects for species, for example via glmer() in the lme4 package, might help in this regard. Random intercepts would allow for differences among species in baseline probabilities of cell occupancy, associated with species' population densities (and other differences, like the ability to detect the species). I'm a bit hesitant, however, as a standard random effects model imposes a Gaussian distribution on those random effects, and that might not be appropriate for your data with over half of species having cell occupancies over 96.5% but a quarter below 59% and some at less than 1%.
Perhaps that skew in baseline probabilities is associated with corresponding skew in your predictors of interest and thus won't end up being a problem. Visual inspection of your data informed by your knowledge of the subject matter could help inform how to proceed.
If there are data available on the overall population density of each species, it would be best to include that in the model directly. I suspect that there are established ways to do this in the ecology literature, but that's outside my area of expertise.
Once you have a better form of model, there are a couple of other potential improvements to consider.
First, your current model assumes that the log-odds of occupancy increases linearly with each of your continuous predictors. That might not be a good assumption in general, and would seem particularly poor with a skewed predictor like your PopdensityAvg. Consider flexible modeling of the continuous predictors, with regression splines or another form of generalized additive model.
Second, your model as presented doesn't seem to address your intent:

For instance, for a species with status 0, I expect no influence of Roads, while for a species with status 1, I expect an influence of Roads.

To do that you need a model that includes status on its own and in an interaction with the other predictors whose associations with outcome you expect to differ depending on status.
Comment: @LisaTedeschi yes, that formula is what I had in mind, in a model like a mixed model that takes intra-species correlations into account. I'm not sure that you will have enough data to fit all those coefficients without overfitting, particularly if you incorporate standard regression splines. My guess is that you will want to explore generalized additive mixed models that involve penalization to avoid overfitting, which I understand can be useful in ecology (although I have no personal experience with them).
Comment: Thanks @EdM, this is a lot of material to think about. I'll start looking into that, I'd say starting from GAM and GAMM (to address also your 1st point). My predictors are very skewed as well (I also inspected them visually through violin plots): for instance, I have a species with a very small range that is located in a city, thus the associated predictor of population density has a very high value. This is quite common among my data, thus I guess it may not be a problem, as you pointed out - but I'll be careful.
Comment: As for the 2nd point, if I got what you mean by _"Including the status (Establishment) on its own and in an interaction with the other predictors whose associations with outcome you expect to differ depending on status_", my previous formula would look like `(range_prop ~ Establishment + PopdensityAvg + PopgrowthAvg + Railways + Roads +
Establishment*PopdensityAvg) + (Establishment*PopgrowthAvg) + (Establishment*Railways) + (Establishment*Roads))`, correct?
Comment: I searched a bit and started with GLMM - I added a self-answer here.
Answer: A "quick" update: I looked into GAMMs and I think they might be a good option for my data. After exploring them a bit (and understanding they are more complicated), I thought I'd first try with GLMMs, to get a better understanding of the mixed part first. Again, my response variable is:
col_glm <- cbind(myData$non_null_cells, ((myData$PAR)-(myData$non_null_cells)))

Binomial and Establishment are now factors (with, respectively, 64 and 2 levels). I first tried a model with the species (Binomial) as a random effect:
glmm_species <- glmer(col_glm ~
                        Establishment +
                PopdensityAvg +
                PopgrowthAvg +
                Railways +
                Roads +
                (1 | Binomial),
              data = myData,
              family = binomial,
              nAGQ = 0,
              control = glmerControl(optimizer="bobyqa",tolPwrss=1e-3,optCtrl=list(maxfun=2e5)))

I added control = glmerControl(optimizer="bobyqa",tolPwrss=1e-3,optCtrl=list(maxfun=2e5)) and nAGQ = 0 after receiving warning messages regarding failed convergence and large eigenvalue ratios (model nearly unidentifiable). I also tried to rescale my predictors (e.g., scale(myData$PopdensityAvg)) or center the mean (e.g., myData$PopdensityAvg - mean(myData$PopdensityAvg)) but this didn't solve the problem. So I added the control = and nAGQ = parts.
This is the summary of glmm_species:
Generalized linear mixed model fit by maximum likelihood (Adaptive Gauss-Hermite Quadrature, nAGQ = 0) ['glmerMod']
 Family: binomial  ( logit )
Formula: col_glm ~ Establishment + PopdensityAvg + PopgrowthAvg + Railways +      Roads + (1 | Binomial)
   Data: myData
Control: glmerControl(optimizer = "bobyqa", tolPwrss = 0.001, optCtrl = list(maxfun = 200000))

      AIC       BIC    logLik  deviance  df.resid
1212169.9 1212187.8 -606077.9 1212155.9        88

Scaled residuals:
     Min       1Q   Median       3Q      Max
-1006.34   -24.88     0.00    19.97   379.95

Random effects:
 Groups   Name        Variance Std.Dev.
 Binomial (Intercept) 15.79    3.974
Number of obs: 95, groups:  Binomial, 64

Fixed effects:
                  Estimate  Std. Error  z value             Pr(>|z|)
(Intercept)     2.94643168  0.49753189    5.922        0.00000000318 ***
Establishment1 -0.18042578  0.00070243 -256.860 < 0.0000000000000002 ***
PopdensityAvg  -0.00634655  0.00004349 -145.917 < 0.0000000000000002 ***
PopgrowthAvg    0.20843341  0.00111517  186.907 < 0.0000000000000002 ***
Railways       -2.42287462  0.00582613 -415.863 < 0.0000000000000002 ***
Roads           0.93458051  0.00333284  280.415 < 0.0000000000000002 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) Estbl1 PpdnsA PpgrwA Ralwys
Estblshmnt1 -0.002
PopdnstyAvg  0.006 -0.047
PopgrwthAvg -0.009  0.040 -0.680
Railways     0.001 -0.102 -0.440  0.056
Roads       -0.011  0.099 -0.639  0.495 -0.187

I imagine Establishment status cannot be both a fixed and a random effect - indeed, if I try it, I receive a message of boundary (singular) fit, and the output of isSingular is TRUE, so I didn't try the same model but with (1 | Establishment).
I then tried to add, as suggested by EdM, the interaction between the predictors and the Establishment status:
glmm_species_est_interaction <- glmer(col_glm ~
                     Establishment +
                       PopdensityAvg +
                     PopgrowthAvg +
                     Railways +
                     Roads +
                     (Establishment * PopdensityAvg) +
                     (Establishment * PopgrowthAvg) +
                     (Establishment * Railways) +
                     (Establishment * Roads) +
                       (1 | Binomial),
                   data = myData,
                   family = binomial,
                   nAGQ = 0,
                   control = glmerControl(optimizer="bobyqa",tolPwrss=1e-3,optCtrl=list(maxfun=2e5)))

Summary:
Generalized linear mixed model fit by maximum likelihood (Adaptive Gauss-Hermite Quadrature, nAGQ = 0) ['glmerMod']
 Family: binomial  ( logit )
Formula: col_glm ~ Establishment + PopdensityAvg + PopgrowthAvg + Railways +
    Roads + (Establishment * PopdensityAvg) + (Establishment *
    PopgrowthAvg) + (Establishment * Railways) + (Establishment *      Roads) + (1 | Binomial)
   Data: myData
Control: glmerControl(optimizer = "bobyqa", tolPwrss = 0.001, optCtrl = list(maxfun = 200000))

      AIC       BIC    logLik  deviance  df.resid
 662632.4  662660.5 -331305.2  662610.4        84

Scaled residuals:
     Min       1Q   Median       3Q      Max
    -778       -5        0        9 18455578

Random effects:
 Groups   Name        Variance Std.Dev.
 Binomial (Intercept) 11.65    3.413
Number of obs: 95, groups:  Binomial, 64

Fixed effects:
                               Estimate Std. Error  z value             Pr(>|z|)
(Intercept)                   1.4670433  0.4312426    3.402             0.000669 ***
Establishment1                4.8699235  0.0157346  309.504 < 0.0000000000000002 ***
PopdensityAvg                -0.0070984  0.0001197  -59.318 < 0.0000000000000002 ***
PopgrowthAvg                  0.3039196  0.0034845   87.221 < 0.0000000000000002 ***
Railways                     -1.9641992  0.0118910 -165.183 < 0.0000000000000002 ***
Roads                         2.1504846  0.0088561  242.826 < 0.0000000000000002 ***
Establishment1:PopdensityAvg -0.0464354  0.0001039 -446.874 < 0.0000000000000002 ***
Establishment1:PopgrowthAvg   0.2266168  0.0026760   84.685 < 0.0000000000000002 ***
Establishment1:Railways       6.5647116  0.0198642  330.480 < 0.0000000000000002 ***
Establishment1:Roads         -2.3143838  0.0078887 -293.378 < 0.0000000000000002 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
                 (Intr) Estbl1 PpdnsA PpgrwA Ralwys Roads  Estblshmnt1:PpdA Estblshmnt1:PpgA Estblshmnt1:Rl
Estblshmnt1      -0.025
PopdnstyAvg       0.031 -0.447
PopgrwthAvg      -0.032  0.511 -0.834
Railways         -0.002 -0.127 -0.338  0.029
Roads            -0.036  0.650 -0.807  0.750 -0.119
Estblshmnt1:PpdA  0.009 -0.032  0.238 -0.269  0.021 -0.337
Estblshmnt1:PpgA  0.026 -0.556  0.658 -0.871  0.083 -0.599 -0.057
Estblshmnt1:Rl   -0.019  0.484 -0.483  0.548 -0.326  0.671 -0.748           -0.357
Estblshmnt1:Rd    0.020 -0.936  0.347 -0.353  0.284 -0.611  0.057            0.377           -0.580

This last model seems to perform slightly better (I am using AIC and F-test to check models' performance). However, I am unsure where to go from here, and how to interpret this output.
Comment: In a logistic model, fixed-effect coefficients are in log-odds scale, with the intercept the log-odds of occupancy when all continuous predictors are at values of 0 and categorical predictors are at reference levels for an "average" species. The SD of the random effect is the SD among species around that intercept. The individual predictor coefficients are log-odds _differences_ from the intercept for a unit change in the predictor when all the other predictors are at reference/0. The interaction terms are _extra differences_ for the continuous predictors when `Establishment = 1`.
Comment: Now consider more flexible continuous-predictor modeling with a GAMM. For evaluating residuals (some are very big) consider the [`DHARMa` package](https://cran.r-project.org/package=DHARMa). Inference (p-values, etc.) isn't straightforward with mixed models; see [this page](https://stats.stackexchange.com/q/22988/28500) for discussion. The [`lmerTest` package](https://cran.r-project.org/package=lmerTest) can be used, but you should be aware of the assumptions made. The [`emmeans` package](https://cran.r-project.org/package=emmeans) helps compare scenarios.
Comment: Thanks @EdM, I will look into them.


print theme_get_setting in php-as-css file

Question: I'm trying to print out settings from my theme's theme-settings.php into a file called custom.php. Below is the code I'm using in custom.php:
<?php
    header("Content-type: text/css; charset: UTF-8");
define('DRUPAL_ROOT', '/path/to/my/drupal/installation');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

body {
    background: url(<?php print (theme_get_setting('theme_custom_background_path')) ?>);
?>;

This is what the result is when the page is rendered in the browser:
body {
    background: url();
}

I'm obviously missing something here -- theme_get_setting isn't working. I'm not sure what kind of code I need to link this file to my theme.
Does anyone know if there is a way to get custom.php to recognize the settings I've defined in my theme's theme-settings.php file with theme_get_setting? I feel like I'm so close but just missing a few lines of code.
At the end of the day if I absolutely need to, I can just print the settings out inline within the head section of html.tpl.php - but I'd much rather include them in a separate stylesheet with the .php extension.
Any suggestions?
Comment: Full bootrap Drupal just to pull a theme setting ? Trust me pal you are wasting your server resources.
Answer: Below code worked for me ! Make sure there is a value for setting "theme_custom_background_path" in your theme settings. For example i can able to get logo path of theme using below code

Created a file called get_setting.php inside my Drupal Root
Copy pasted below code
Executed in browser.

Code
define('DRUPAL_ROOT', getcwd());
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$theme_settings = theme_get_setting('logo');
print "body { background: url(" . $theme_settings . ");}";


Find integer solutions of $(1) xy=2x+2y$ and $ (2)xy=2x+y.$

Question: I've tried this for the first one:$xy=2(x+y).$
Therefore either x or y is divisible by 2.
And I'm totally stuck on the second. How to solve these?
Answer: Note that $xy=2x+y$ if and only if $xy-2x-y=0$. But
$$xy-2x-y=(x-1)(y-2)-2.$$
So we want to solve the equation
$$(x-1)(y-2)=2.$$
But it is not easy for the product of two integers to be $2$. The possibilities are:
$x-1=1$, $\quad y-2=2$;
$x-1=2$, $\quad y-2=1$;
$x-1=-1$, $\quad y-2=-2$;
$x-1=-2$, $\quad y-1=-1$.
The other problem can be solved by a very similar method.
Answer: Consider the general equation $$axy+bx+cy=d.$$ $$a^2xy+abx+acy+bc=ad+bc$$ $$(ax+c)(ay+b)=ad+bc.$$
For your first example $a=1, b=-2, c=-2, d=0.$
Now $(x-2)(y-2)=4.$
All the solutions of (1) are given by $$x-2=±1,y-2,±4$$ $$x-2=±4,y-2,±1$$  $$x-2=±2,y-2,±2$$
For your first example $a=1, b=-2, c=-1, d=0.$
Then $(x-1)(y-2)=2.$  Try to continue from here. good luck!


Does partially used object cause memory leak?

Question: I have prepared a class for storing data retrieved from db, and let's say I have 10 vars in it. What if I will reuse this class for different views and each view will use a different quantity of variables.
tableViewCell will pop-up 3 vars.
View1 will pop-up 6 vars.
View2 will pop-up 10 vars.
Will the unused data cause memory leaks?
Answer: A memory leak only happens when you delete all pointers to the memory before freeing it. If you reuse your data structure, you might have some unused memory, but it won't be a leak unless you never free it when the pointers go away (leaving you no way to free it ever again).
Comment: Ok. let's say in data structure exist int var, Nsstring *name. After the proper manipulations are both will be null while object is alive. Will this consume memory? How much does the NULL value weight in memory?
Comment: Can you give code me some example of deleting all pointers to the memory before freeing it?
Comment: I suggest reading up on objective-c memory management. http://www.raywenderlich.com/2657/memory-management-in-objective-c-tutorial
Answer: Unused variables have nothing to do with memory leaks. You want to see a memory leak?
<code>- (void)leakABunchOfMemory {
    for (int i = 0; i < 1000000000; i++) {
        NSMutableString *usedButNotUsedCorrectly = [[NSMutableString alloc] initWithFormat:@"%d", i];
    }
}
</code>
That's a memory leak. An object is created with every <code>[NSMutableString alloc]</code>, and none can never be destroyed because you lose your reference to them as soon as that iteration of the loop ends. They just go on existing and taking up space, like text-based zombies that hunger for the RAM of the living. To avoid leaks in Objective-C code, follow the memory management rules, and the equivalent rules for any other libraries you use.
Comment: Wow. It's not memory leak. That's kinda memory-issue-catrina!
Comment: Ok. What's the answer to my question? Y/N?


QT 5.2 - No 'Qt Gui application' option

Question: I'm using qt tutorial from => http://qt-project.org/doc/qt-5.1/qtdoc/gettingstartedqt.html
but I got a problem because I can't choose in QT Creator 'Qt Gui application' option.
I have already read that is due the library isn't installed but I've done it.
Comment: Have you tried the option _Qt Widgets Application_ ? It's the same as the _Qt Gui Application_ in this new version.
Comment: Thanks a lot! It was a stupid question from me. :)
Comment: @user1611534: does that mean you solved your issue? If yes, what was the solution?
Comment: 'Qt Widgets Application' is the same as 'Qt Gui application'.
Answer: I think you are trying to create either a QtQuick based application or QtWidgets. See the screenshot below what I have about it.

QT 5.2 - No 'Qt Gui application' option


unable to create log file

Question: I am using below code for creating logging in my project using PRISM ILoggrFacade.
But i am not sure is the best way and second thing how can i use CustomLogger class logging because i am unable to create logging.
public class CustomLogger : ILoggerFacade
    {

        protected static readonly ILog log = LogManager.GetLogger(typeof(CustomLogger));
        public CustomLogger()
        {
            log4net.Config.XmlConfigurator.Configure();
        }

        public void Log(string message, Category category, Priority priority)
        {
            switch (category)
            {
                case Category.Debug:
                    log.Debug(message);
                    break;
                case Category.Warn:
                    log.Warn(message);
                    break;
                case Category.Exception:
                    log.Error(message);
                    break;
                case Category.Info:
                    log.Info(message);
                    break;
            }
        }
    }

Bootstrapper
 private readonly CustomLogger _logger = new CustomLogger();
 protected override ILoggerFacade CreateLogger()
        {
            return _logger;
        }

ViewModel
            logger.Log("Logging success", Category.Info, Priority.None);

log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <log4net>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="C:\temp\log.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

Comment: First of all, don't use the `ServiceLocator` for obtaining the logger. Service locator is considered to be an anti-pattern if you're not implementing a DI container by yourself. And second: what is your **particular** question actually?
Comment: @dymanoid unable to create log file
Comment: Wha texactly goes wrong? Do you get an error? Does the code go through but the file doesn't get created? Do you get an exception somewhere?
Comment: @Metallkiller now i was able to create log file..actually i am configuring my xml in constructor...but file created once i have to specify "[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4Net.config", Watch = true)]" in assembly
Comment: @Metallkiller now i am wondering how to use logging in different modules i am using  unity .Any Idea ?
Comment: @stylishCoder No idea, I have neither worked with prism before, nor with unity :)
Answer: Problem with above code is that need to configure log4net in assembly like below:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4Net.config", Watch = true)]

Also in addition if you wan to drag log4net in ViewModels the use below code
 private readonly ILoggerFacade _loggerFacade;
 public ContentAViewViewModel(ILoggerFacade loggerFacade)
        {
          _loggerFacade = loggerFacade;
        }

Example
    private void LoadPeople()
        {
        _loggerFacade.Log("Load People", Category.Debug, Priority.High);
        }

unable to create log file


Remove element in JavaScript

Question: In the below code how to remove the hyperlink after getting the innerHTML:
function test(obj)
{
  var a=obj.innerHTML
  //remove obj element here
}

$p = $('').html( "test" );
$('#questions').append( $p );

Answer: You can remove an element using the DOM method removeChild. If you start with a reference to the child [as you seem to in your test function (the obj argument)], you can remove it like this:
obj.parentNode.removeChild(obj);

(Your question is also tagged jQuery but I see someone pointed you to jQuery's remove function and you said you didn't want to use that. In any case, for completeness I've noted it here.)
Answer: You're using jQuery, so just do:
$(obj).remove()

Remove element in JavaScript


How to override the "No web page was found for the web address" message?

Question: The "No web page was found for the web address: https://localhost/blabla" message is generated as a response to the request with an illegal path. I need to return a custom message instead of this one. Any idea how to do it?
The server is embedded Tomcat with
spring-boot-starter-tomcat-1.3.3.RELEASE.jar
spring-webmvc-4.2.5.RELEASE.jar

Answer: You can update httpd.conf and point to new page maintenance.html ( call it anything) and place it somewhere where it can be accessed.
// comment anything existing add line below
ErrorDocument 503 /maintenance.html


Causal Inference When Treatment and Outcome Are Aggregated At Different Levels

Question: Consider a scenario where a treatment is a U.S. state-level policy (some states adopted the policy while others did not) and the outcome are individual-level responses to a survey across American states. To make this scenario less abstract, let's say that the policy is gun-reform legislation and the outcome is individual perceptions of safety. As a result, treatment and outcome are aggregated at different levels.
Immediately, I can see an issue with this approach as it relates to identifying confounders to adjust for. For example, ideology seems like a clear confounder in this case, but ideology aggregated in what way? The ideological make-up of the state will impact the probability of adopting gun-reform legislation and the ideology of an individual will impact their perception of safety, but the ideology of a state and the ideology of an individual are two separate (but related) concepts. Also, if this is the case, is "ideology" even a confounder?
Naively, I can say that:
Gun Reform $\leftarrow$ Ideology $\rightarrow$ Safety Perception
But this isn't really true, is it? Because, what I'm actually assuming are two separate measures of ideology entirely:
Gun Reform $\leftarrow$ State's Ideological Makeup
Safety Perception $\leftarrow$ Individual's Ideology
How might one handle situations such as these, where problems seem to be driven solely by the different level of aggregation between treatment and outcome? One obvious course might be to average the responses of the outcome and collapse to the state-level, but this has a serious drawback of severely reducing N. Is there any way to move forward without re-aggregating?
Comment: As for the measurement levels, perhaps it helps to think of what a hypothetical experiment would look like. Would you like to randomly assign different gun laws to different individuals, or would you like to assign different gun laws to different states? That should help answer what level of aggregation you are interested in. Once you have chosen a level of aggregation, it seems to me that all variables would have to work on that level for your structural causal model to be able to generate samples.
Comment: Generally speaking the standard causal inference pipeline assumes that the variables are given, so from that perspective this could be seen as a question of domain knowledge. If we are dealing with quantities at the state level, and the state's ideological makeup is something other than the aggregate of the individuals' ideological make-up, then those should probably be two different variables - I'm not sure this is a problem of aggregation.
Comment: @Scriddie My issue with adjustment for two different variables is that only "ideology" - in this example - is a true confounder. An individual's ideology impacts their individual perception of safety but it alone does not cause a change in Pr(Gun Reform). Likewise, a state's ideological makeup impacts Pr(Gun Reform), but it does not have a direct effect (I don't think) on an individual's ideology. Conceptualized at a unit-agnostic level, ideology is a clear confounder, but, accepting the reality of the unit of analysis issue, "ideology" itself does not work... I don't think.
Answer: One of the advantages of building models in general is that it costs relatively little to test different formulations to see which one works best for your objectives. There are advantages and disadvantages to modelling each level of aggregation, and the choice must be informed by

the answers that you want your model to provide you;
the data that you have or have the resources to collect; and
domain knowledge, i.e. knowledge about the shape of the causal model

In this case, like you I (someone lacking any domain knowledge, so take this with a grain of salt) see two possibilities:

The first is similar to your first one, where the residents' "ideology" influences both gun reform legislation and perception of safety. I would argue that gun reform legislation also affects the perception of safety, like so:

The second is similar to your second one, where there is a distribution of "ideology" among the voters (not residents) of each state, which influences the "ideology" of the legislators of that state, which influences the probability that they pass gun reform legislation. Both the ideology of the voters and whether or not gun reform has been codified into law influence the perception of safety among the residents of each state:

The first model is simpler. If you have any data on each state "ideology" (be it their residents, their voters, their legislators, etc), you can plug it in the "ideology" node. However, because each "state ideology" is poorly defined (e.g. in one state you might have a phone survey of a sample of registered voters, in another you might have an internet poll of residents), there might be a lot of model uncertainty in whatever quantity you're interested in estimating.
The second model is more explicit in its description of how each variable influences the others. It also makes clear that what directly matters for gun reform legislation is the legislators' ideology; if you have data on lawmakers' opinions (e.g. a survey), it makes data on residents' preferences less influential (although not completely irrelevant, since it might reveal something about their perception of safety). Also, because it is more explicit and specific, you can focus you data collection resources on what matters (voters and lawmakers), and the model uncertainty in your estimate will probably (but not necessarily) be smaller. On the other hand, if you are limited to using existing datasets, it might be harder to find data that you can just plug into each node without further analysis and modification.


Error on update from 2.3 to 2.8 and 2.7?

Question: I'm using drupal commerce 2.3 and want to update to commerce 2.8.
I just copied the files to the new folder and get the error:
PHP Fatal error:  Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206): Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171): Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182): Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72): Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118): Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php on line 272

Fatal error: Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206): Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171): Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182): Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72): Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118): Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php on line 272
Drush command terminated abnormally due to an unrecoverable error.                                           [31;40m[1m[error][0m
Error: Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in
C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206):
Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171):
Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182):
Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72):
Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118):
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in
C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php, line 272

But when I go to :
 C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php
This file is just there.
I tried the same to goto commerce 2.7, but then same error applies.
Somebody any suggestion?
Answer:
I just copied the files to the new folder

That's not how to update a Drupal 8 project - you need to use Composer.
Run composer update in your project root, and the old version of the address library (commerceguys/addressing), which is causing your current problem, will be upgraded alongside the modules.
Comment: As Clive said. Also, we have official docs for this: https://docs.drupalcommerce.org/commerce2/developer-guide/install-update/updating


How to improve the performance of K-nn algorithm in R?

Question: I am having a digit recognizer data set which has column names as label, pixel0, pixel1...pixel783. pixel values vary from 0 to 255 indicating the lightness or darkness of that pixel, with higher numbers meaning darker. I have applied a simple k-NN algorithm on the test data which gives me 97% accuracy. What should I do to improve the performance further?
There are no other arguments in the data set but pixel0...pixel783. There are 28000 rows in the test data set and I have used k=10. Can I increase the value of k to improve the performance further?
Comment: Be wary of overfitting. This question might be better suited for CrossValidated.
Answer: There are not that many parameters available for a k-NN algorithm.  Changing k may have an improvement on the performance, but it really depends on the training cases you have for the model.  Using a larger k will use some of the lesser-related training cases for evaluation, so it is difficult without trial and error.
In my own experience, k=10 has usually been a good starting point.  Another method might be to look at your inputs and see if they could be improved, but 97% is quite a good outcome.
Hope this helps!


Bootstrap dropdown won't work In Node app because of jQuery

Question: I am currently creating a node app using handlebars. For the layout, I want a Bootstrap navbar with a dropdown inside of it. The dropdown will not work because I cannot get jquery to work.
Here is my directory structure only including relevant files:
root
  ├ models
  ├ node_modules
  | ├ jquery
  ├ public
  | ├ css
  | | ├ bootstrap.css
  | ├ fonts
  | ├ js
  | | ├ bootstrap.js
  | | ├ jquery-3.1.1.js
  ├ routes
  ├ views
  ├ app.js
  ├ package.json

As you can see, I've downloaded jquery as a module and have also added it into my public folder using the downloaded version from the website.
I've linked it on my layout.handlebars file like so:

I've also required it in my app.js file like so:
var $ = require('jQuery');

Even with two methods of implementation, jQuery is still not working and is causing my dropdown to not work.
If I inspect my page, I get this message:

If I check sources, we can see my bootstrap js file and the jquery file linked, though:

Any help is appreciated!
Comment: That errors tells you the problem. You have jquery 3.1.1 but bootstrap requires a version of jquery less than 3.
Comment: Oh my god.. thanks.. I was using an ancient version of bootstrap. I feel like quitting coding now.
Answer: After actually using my brain and reading, the error message tell me my version of Bootstrap was incompatible with my version of jQuery. See the error message in my question above for clarification.
Comment: "kiddo"? How is your answer in any way or shape a complete answer? If another user with the same question as you came in and saw that answer (which is actually pretty much what the error says), do you think they would have any idea what this means? A real answer would have at least a little more substance.
Comment: Your question on the other hand is exemplary; well formatted, had relevant code, and gave out all of the detail needed to find out what was going on. Answers should be of a similar caliber :)


How to design a closed rectangular box of minimum cost using Lagrange Multipliers

Question:
Suppose the box is to be of volume $V_0$ cubic cm; and the cost of material for the front and back sides is $b$ dollars per square cm, $c$ dollars per square cm for the left and right two sides, and $d$ dollars per square cm for the top and bottom sides.  Note that $V_0$, $b$, $c$ and $d$ are just arbitrary constants.

This is the task and so far all I've been able to get together is the following equation:
$$f(x,y,z)=2bxy+2cyz+2dxz$$
$$g(x,y,z)=xyz=V_0$$
$$\overrightarrow {\nabla}f = f_x + f_y + f_z$$
$$f_x = 2by+2dz$$
$$f_y = 2bx + 2cz$$
$$f_z = 2cy + 2dx$$
$$\overrightarrow {\nabla}g = g_x+g_y+g_z$$
$$g_x=yz = \lambda yz$$
$$g_y=xz = \lambda xz$$
$$g_z=xy = \lambda xy$$
So then I set the corresponding functions equal to each other and get:
$$2by+2dz=\lambda yz \;;\frac{2by+2dz}{\lambda} = yz$$
$$2bx+2cz=\lambda xz \;;\frac{2bx+2cz}{\lambda} = xz$$
$$2cy+2dx=\lambda xy \;;\frac{2cy+2dx}{\lambda} = xy$$
But I'm lost with where to go from here.  Any hints or tips?
Comment: use the constraint $xyz=V_0$ to simplify the algebra
Comment: I completely understand it now!  It took me a while to figure out what you were doing but its all crystal clear now.  Amazing I was hung up on the algebra all this time!  Thanks @WW1
Comment: @WW1 Sorry and I know you're probably busy, but I wonder why $V_0$ is negative?  That seems odd to me
Comment: $V_0$ isn't negative $\lambda $ is .
Answer: $$f(x,y,z)= 2bxy+2cyz+2dxz$$
is the (cost) function to be maximized
The constraint is
$$ g(x,y,z)=xyz=V_0 $$
now solve $\vec \nabla f = \lambda \vec \nabla g$
Comment: Thank you SO MUCH for this hint.  You have no idea how much this has helped me.  I just want to make sure I'm understanding, though.  So I'm going to be taking the gradient of both $f(x,y,z)$ and $g(x,y,z)$ and then multiplying $\lambda g(x,y,z)$ and setting this equal to the gradient of $f$?
Comment: yes - those 3 equations together with $xyz=V_0$ gives you 4 equations to find your 4 unknowns.
Comment: Am I crazy, or is the algebra for this problem extremely hairy
Answer: when constrained to the surface $xyz=V_0$
$f(x,y,z)= 2V_0(\frac{b}{z}+\frac{c}{x}+\frac{d}{y})$
so $\vec \nabla f(x, y, z) =-2V_0(\frac{c}{x^2}, \frac{d}{y^2},\frac{b}{z^2} ) $
$g(x, y, z) = xzy \\  \implies \vec \nabla g(x, y, z) = (yx, xz, xy)$
the gradient constrained to the surface is $\vec \nabla g(x, y, z) = V_0(\frac 1x, \frac 1y, \frac 1z)  $
So $$  \frac{-2V_0c }{x^2}=\frac{\lambda V_0}x \implies x= \frac{-2c}{\lambda}
\\y= \frac{-2d}{\lambda}
\\z=  \frac{-2b}{\lambda}
\\ \text{ and } \frac{-8bcd}{\lambda^3}=V_0 \implies \lambda = \left(   \frac{-8bcd}{V_0} \right)^\frac 13$$
Comment: I edited more of my original question, can you tell me where I'm going wrong?
Comment: Heh... it looks like you just did some fancy algebra to factor out $V_0$ to simplify solving the equations!


Unusual Confidence Interval

Question: Let $X_1 , X_2 , ... , X_n$ be a random sample from a distribution with probability density function $\frac{1}{\theta}x^{\frac{1- \theta}{\theta}}I_{[0,1]}, \theta>0$. I want to find the 100$\alpha \% $ confidence interval for $\theta$.
This is what I have done:
$F_X(x;\theta) = x^{\frac{1}{\theta}}I_{[0,1]} + I_{(1, \infty)}$
We can pick $0<q_1, q_2<1$ such that $P(q_1 < \prod_{i=1}^{n}F_{x}(X_i ; \theta) < q_2) = \alpha$
Now we have that
$P(q_1 < \prod_{i=1}^{n}F_{x}(X_i ; \theta) < q_2) = P(q_1 < \prod_{i=1}^{n}X_i^{\frac{1}{\theta}} < q_2) = P(log(q_1) < \frac{1}{\theta}log(\prod_{i=1}^{n}X_i) < log(q_2)) = P(\frac{log(\prod_{i=1}^{n}X_i)}{log(q_1)} < \theta < \frac{log(\prod_{i=1}^{n}X_i)}{log(q_2)})$
Therefore a confidence interval for $\theta$ is $[\frac{log(\prod_{i=1}^{n}X_i)}{log(q_1)},\frac{log(\prod_{i=1}^{n}X_i)}{log(q_2)}]$. I believe this is correct. What I find unusual is, the expected length of the confidence interval seems to tend to infinity as n tends to infinity, I find this very counterintuitive, can this really be correct:
The length of the interval is $log(\prod_{i=1}^{n}X_i)(\frac{1}{log(q_2)} - \frac{1}{log(q_1)})$, this has expected value $nE(log(X_1))(\frac{1}{log(q_2)} - \frac{1}{log(q_1)}) = -n\theta(\frac{1}{log(q_2)} - \frac{1}{log(q_1)})$ (because $E(log(X_1)) = \int_{0}^{1} \frac{1}{\theta}log(x)x^{\frac{1}{\theta} - 1} dx = -\theta$). We can see that as n tends to $\infty$ so does the length of the confidence interval.
Can this be correct?
Answer: Your method for finding a confidence interval is correct. But there is a small mistake:
$$q_1<\prod_{i=1}^n X_i^{1/\theta}<q_2\iff  \frac{\sum\ln X_i}{\ln \color\red{q_2}}<\theta<\frac{\sum\ln X_i}{\ln \color\red{q_1}}$$

You might also notice that $X_i\stackrel{\text{i.i.d}}\sim \text{Beta}\left(\frac{1}{\theta},1\right)$, so that $-\frac{2}{\theta}\ln X_i\stackrel{\text{i.i.d}}\sim\chi^2_2$.
Hence a pivot for $\theta$ is $$T(\mathbf X,\theta)=-\frac{2}{\theta}\sum_{i=1}^n\ln X_i\sim\chi^2_{2n}$$
So, $$P_{\theta}\left(\chi^2_{1-(1-\alpha)/2,2n}\leqslant T\leqslant \chi^2_{(1-\alpha)/2,2n}\right)=\alpha\quad\forall\,\theta$$
Equivalently, $$P_{\theta}\left(\frac{-2\sum\ln X_i}{\chi^2_{(1-\alpha)/2,2n}}\leqslant\theta\leqslant\frac{-2\sum\ln X_i}{\chi^2_{1-(1-\alpha)/2,2n}}\right)=\alpha\quad\forall\,\theta$$
So a $100\alpha\%$ C.I. for $\theta$ is
$$\left[\frac{-2\sum\limits_{i=1}^n\ln X_i}{\chi^2_{(1-\alpha)/2,2n}},\frac{-2\sum\limits_{i=1}^n\ln X_i}{\chi^2_{1-(1-\alpha)/2,2n}}\right]$$
Here, $\chi^2_{\alpha,2n}$ is of course the $(1-\alpha)$th fractile of a chi-square distribution with $2n$ degrees of freedom.
Length of this C.I is $$L=-2\sum_{i=1}^n \ln X_i\left[\frac{1}{\chi^2_{1-(1-\alpha)/2,2n}}-\frac{1}{\chi^2_{(1-\alpha)/2,2n}}\right]$$
When you take the expected length, the quantity within parenthesis is surely a constant, but it is dependent on $n$ (say, $c(n)$). That is, expected length is of the form $$E(L)=-2c(n)E\left[\sum_{i=1}^n \ln X_i\right]=2nc(n)\theta$$
I think you are ignoring the limiting behaviour of $c(n)$ (your $q_1,q_2$ also depend on $n$) when you are taking the limit $n\to\infty$.

Unusual Confidence Interval


Classification: {{ content.field_classification.value }} not displaying

Question: Hoping someone can assist me please.
I am trying to display the value of a custom field in a bootstrap sub theme
I have created my node--testtype.html.twig template and that seems to work.
I'm trying to just show the content of one field, the machine name is field_classification.
When I use
Classification: {{ content.field_classification.value }}
 the Classification displays as expected, but the value of my field_classification doesn't.
Can anyone see what I am doing wrong please as thought I d copied the correct code from what I have read?
Comment: Means you are only getting an empty ``?
Answer: {{ content }} is a render array and does not have a .value, just use {{ content.field_name }}
You only need the .value when you want to print the raw values of an entity object like node, e.g. {{ node.field_my_integer.value }}


.slideDown (jQuery) not working

Question: This is my jQuery code to add html generated by a post in a div. The slidedown() function doesn't seem to be working right. Here is my script:
$(".expand").click(function(){
      var button = $(this);
      var id = $(this).attr("eid");
      var url = "/get-complete/" + id + '/';
      $.ajax({
        type: "GET",
        url: url,
        success: function( data ) {
          var obj = $.parseJSON(data);
          var lang = '';
          $.each(obj, function() {
            lang += this['html'] + "
";
          });
          button.siblings('.comment-expand').slideDown('slow', function(){
            button.siblings('.comment-expand').html(lang);
          });
          button.attr('class', 'collapse');
          button.html('Collapse');
        },
      });
      return false;
    });

Here is the html:
Expand

This is the sample data returned by the GET request:
[{"html": "\n
\n
\n    "}]

This is the code to collapse the post, but this isn't working either:
$("body").delegate(".collapse", "click", function(){
          var button = $(this);
          button.siblings('.comment-expand').slideUp('slow');
          button.attr('class', 'expand');
          button.html('Expand');
          return false;
        });

Comment: Yes, but using `.html()` method, there is no `.innerHTML()` method. If the element is not hidden `slideDown()` doesn't do anything, hide the element using `.hide()` method before using `.slideDown()` and setting html content.
Comment: At first set the `innerHTML` then call `slideDown()` (_if the element is hidden_).
Comment: `button.next` instead of `button.siblings` ?
Comment: @BlackSheep you mean like this: button.siblings('.comment-expand').innerHTML(lang);
              button.siblings('.comment-expand').slideDown('slow');
Comment: @BlackSheep The element is empty at first and is not hidden
Answer: Try this:
$.ajax({
    type: "GET",
    url: url,
    // setting the dataType to json, jQuery itself parses the response
    dataType: 'json',
    success: function(data) {
      // Hiding the element and setting it's innerHTML
      // before calling slideDown()
      button.siblings('.comment-expand').hide().html(function() {
         // Mapping the response and concatenating `html` properties
         // If the response has only one array use:
         // return data[0].html + '
'; instead
         return $.map(data, function(v) {
             return v.html + '
';
         }).join('');
      }).slideDown();
      button.addClass('collapse')
            .removeClass('expand')
            .html('Collapse');
    },
});

Edit: Since you are adding the class dynamically you should delegate the event:
$(document).on('click', '.collapse', function() {
    // var button = $(this);
    // ...
});

Comment: i tried doing it using delegate. But, it instead is making the above GET again.
Comment: @Monique That's because events are bound to elements not to their className, when you remove the class the click handler is still bound to the element, one option is using event delegation or the `.one('click')` method.
Comment: okay i did it using one. Still not working. $( ".collapse" ).one( "click", function() {

          var button = $(this);
          button.siblings('.comment-expand').slideUp('slow');
          button.attr('class', 'expand');
          button.html('Expand');
          return false;
        });
Comment: I mean using `.one()` for the first click handler, `$('.expand').one('click')...`.
Comment: ok, so it worked. But, now there is another problem. When I click the expand again after a collapse, it doesn't work. So, should I put both in delegate?
Comment: @Monique Great, so I won't update the answer. You are welcome :)

.slideDown (jQuery) not working


sp_dboption2 error 6106

Question: I use the stored proc sp_dboption2 (http://vyaskn.tripod.com/code/sp_dboption2.txt) to close all connections to a database so I can restore it as part of refreshing our test server (SQL 2005). It has been working flawlessly for a couple of years but in the last couple of weeks it has failed both times I've used it. The output looks like this:
<code>SPID 55: transaction rollback in progress. Estimated rollback completion: 0%. Estimated time remaining: 0 seconds. [SQLSTATE 01000]
SPID 56: transaction rollback in progress. Estimated rollback completion: 0%. Estimated time remaining: 0 seconds. [SQLSTATE 01000]
SPID 55: transaction rollback in progress. Estimated rollback completion: 0%. Estimated time remaining: 0 seconds. [SQLSTATE 01000]
Msg 6106, Sev 16, State 1, Line 1 : Process ID 56 is not an active process ID. [SQLSTATE 42000]
</code>
The procedure basically loops through the spids in sysprocesses and KILLs them until there are none left. From the above it doesn't look like there's a problem KILLing the same spid twice. It looks more like spid 56 started a rollback on the first KILL, then was still in sysprocesses so a second KILL was issued but in between the rollback finished and the spid disappeared, causing the second KILL to fail. I can't think of anything that has changed recently that should have affected this - no SQL updates installed etc.
For now I'm going to try wrapping the KILL in a try...catch and ignoring error 6106. Has anyone else had this problem? Do you know what has happened to break this? How did you fix it? Is there a more modern way to kick all users out for a restore?
Answer: Try this
ALTER DATABASE [DBName]
SET RESTRICTED_USER
--SET MULTI_USER
WITH ROLLBACK IMMEDIATE
It will put the database in Restricted User mode which means only members of the db_owner, dbcreator, or sysadmin roles can use the database.
Also, the "WITH ROLLBACK IMMEDIATE" clause will cause all connections to the database to be terminated prior to putting it in restricted user mode.
This should work fine with in SQL 2005 and SQL 2008. You can then do the needful and run the command with the "MULTI_USER" clause to make it available again.
More info can be found at: http://msdn.microsoft.com/en-us/library/bb522682.aspx
Hope this helps.
Comment: Doh! Thanks, Chirag, I just hadn't put 2 and 2 together.

sp_dboption2 error 6106


My windows Task Schdulrer is raising this error "0xE0434352"

Question: I have windows server 2012 R2, and i have some tasks inside Windows Task scheduler which use to work well, but yesterday they start to return this error 0xE0434352, as follow:-

I checked the Event Viewer logs and i found this error:-
Faulting application name: RunsHourly.exe, version: 126.96.36.199, time stamp: 0xbc3caebe
Faulting module name: KERNELBASE.dll, version: 6.3.9600.19724, time stamp: 0x5ec50c3e
Exception code: 0xe0434352
Fault offset: 0x000156e8
Faulting process id: 0x9f8
Faulting application start time: 0x01d6a09f2cb0bcb1
Faulting application path: C:\batchfiles\RunHourly\RunsHourly.exe
Faulting module path: C:\Windows\SYSTEM32\KERNELBASE.dll
Report Id: 719d6328-0c92-11eb-8136-0050568b4e10
Faulting package full name:
Faulting package-relative application ID:

Log Name:      Application
Source:        Application Error
Date:          12/10/2020 14:54:28
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      *****.ad-itservices.intra
Description:
Faulting application name: RunsHourly.exe, version: 188.8.131.52, time stamp: 0xbc3caebe
Faulting module name: KERNELBASE.dll, version: 6.3.9600.19724, time stamp: 0x5ec50c3e
Exception code: 0xe0434352
Fault offset: 0x000156e8
Faulting process id: 0x9f8
Faulting application start time: 0x01d6a09f2cb0bcb1
Faulting application path: C:\batchfiles\RunHourly\RunsHourly.exe
Faulting module path: C:\Windows\SYSTEM32\KERNELBASE.dll
Report Id: 719d6328-0c92-11eb-8136-0050568b4e10
Faulting package full name:
Faulting package-relative application ID:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2020-10-12T13:54:28.000000000Z" />
    <EventRecordID>893887</EventRecordID>
    <Channel>Application</Channel>
    <Computer>******.ad-itservices.intra</Computer>
    <Security />
  </System>
  <EventData>
    <Data>RunsHourly.exe</Data>
    <Data>184.108.40.206</Data>
    <Data>bc3caebe</Data>
    <Data>KERNELBASE.dll</Data>
    <Data>6.3.9600.19724</Data>
    <Data>5ec50c3e</Data>
    <Data>e0434352</Data>
    <Data>000156e8</Data>
    <Data>9f8</Data>
    <Data>01d6a09f2cb0bcb1</Data>
    <Data>C:\batchfiles\RunHourly\RunsHourly.exe</Data>
    <Data>C:\Windows\SYSTEM32\KERNELBASE.dll</Data>
    <Data>719d6328-0c92-11eb-8136-0050568b4e10</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>

any advice please?
Also when i manually run the .exe file, i got this exception inside the CMD window:-
Unhandled Exception: System.IO.FileLoadException: Could not load file or assembl
y 'Microsoft.SharePoint.Client, Version=188.8.131.52, Culture=neutral, PublicKeyToke
n=71e9bce111e9429c' or one of its dependencies. The located assembly's manifest
definition does not match the assembly reference. (Exception from HRESULT: 0x801
31040)
   at RunsHourly.Program.Main(String[] args)

although i have the Microsoft.SharePoint.Client inside the same folder as follow:-
Answer: Do you use relative folder (reading or write files) in your program?
Then when you setup a scheduler job, you will see two fields "program/script" and "Start in(Optional)". You need also to put the program folder path in Start in(Optional). That means your program will run that folder. If you will not do that and your program start not in directory with exe, it will not find files that are located in it.screenshot


php Include function not working wamp

Question: I'm fairly new to php, and I'm sure this is something simple. I have a php file named footer.php that contains the code I want at the end of every page, so I want to use an include function to do it. The file looks like this:
   <?php
   echo "
Copyright © 1999-" . date("Y") . " W3Schools.com
";
   ?>

I then, in my main form, use an include statement like this:

     //other code//
      <?php include('footer.php');?>

The //other code// is stuff that isn't relevant and works fine.
I have my wamp server on, and both files are in the www folder in it. Any ideas why the include footer isn't showing up in my main file? I'm not getting any error messages in the log. Do I need to go into phpmyadmin or something?
Comment: Add error reporting to the top of your file(s) right after your opening `<?php` tag `error_reporting(E_ALL); ini_set('display_errors', 1);`
Comment: Try using `require('footer.php');` and see if you get an error. And if so what is the error?
Comment: can you please check you error log. I don't see anything wrong on your code.
Answer: Does your main file have a .php extension? If it is set to for instance index.html, the PHP include will not be executed and you will just see the HTML with no errors logged.
Comment: The main file is a php file, not a HTML file.
Comment: Given the information provided your include should work properly. That is assuming you have a main file with a .php extension and another file in the directory called footer.php which PHP has permissions to access. Here is an example with the setup as you describe working properly. http://goo.gl/ckS47c.
Answer: Is your main form file saved with a .php extension?
You can also try
<?php require_once "footer.php"; ?>

Comment: I used phpstorm, and created a new php file with the name footer. So, in the folder it just says footer, but it is php, not html. The same for the main form file.
Comment: PHP files created in phpstorm are displayed in the project view with their .php extension.

php Include function not working wamp


how to add conditional statement when doing double legend

Question: I try to make a plot with legend for both horizontal lines and vertical lines. Now I would like to test out whether I can add if statement base on the event status.
For the df with both Delay and Sick, my codes works. But if I want to modify the my plotting part so I can use it on a df that might only have Delay or Sick, what should I with my geom_vline and scale_linetype_manualpart? for example, if I want to use my codes on df2.

df<-structure(list(Day = c(0L, 0L, 0L, 1L, 1L, 1L, 8L, 8L, 8L, 15L,
15L, 15L, 22L, 22L, 22L, 27L, 29L, 29L, 29L, 36L, 36L, 36L, 43L,
43L, 43L, 43L, 43L, 43L), Subject = c("ELA", "Math", "Art", "Math",
"Art", "ELA", "ELA", "Math", "Art", "ELA", "Math", "Art", "ELA",
"Math", "Art", NA, "ELA", "Math", "Art", "ELA", "Math", "Art",
"Art", "Art", "Math", "Math", "ELA", "ELA"), Score = c(73L, 157L,
75L, 111L, 82L, 69L, 78L, 131L, 93L, 58L, 109L, 99L, 79L, 131L,
84L, NA, 67L, 106L, 90L, 75L, 123L, 95L, 122L, 122L, 137L, 137L,
83L, 83L), Event = c(NA, NA, NA, "Delay", "Delay", "Delay", NA,
NA, NA, NA, NA, NA, NA, NA, NA, "Sick", NA, NA, NA, NA, NA, NA,
"Sick", "Delay", "Sick", "Delay", "Sick", "Delay")), class = "data.frame", row.names = c(NA,
-28L))

ggplot(data =df)+
    geom_line(data=df[!is.na(df$Score),],aes(x = Day, y = Score, color=Subject),size=0.8)+
        scale_colour_manual(breaks = c("ELA", "Math", "Art"),
                        values=c(ELA="#cc0022",Math="#70ad47", Art="#fd9300"))+
    geom_vline(data=df[(!is.na(df$Event)&df$Event=="Delay"),], aes(xintercept=jitter(Day), linetype="Delay"), color="black", size=0.4)+
geom_vline(data=df[(!is.na(df$Event)&df$Event=="Sick"),], aes(xintercept=jitter(Day), linetype="Sick"), color="purple", size=0.4)+
scale_linetype_manual(name = 'Event',
                        values = c('Delay' = 1,
                                   'Sick' = 1),
                        guide = guide_legend(override.aes = list(colour = c("black",
                        "purple"))))

df2 <-structure(list(Day = c(0L, 0L, 0L, 1L, 1L, 1L, 8L, 8L, 8L, 15L,
15L, 15L, 22L, 22L, 22L, 27L, 29L, 29L, 29L, 36L, 36L, 36L, 43L,
43L, 43L, 43L, 43L, 43L), Subject = c("ELA", "Math", "Art", "Math",
"Art", "ELA", "ELA", "Math", "Art", "ELA", "Math", "Art", "ELA",
"Math", "Art", NA, "ELA", "Math", "Art", "ELA", "Math", "Art",
"Art", "Art", "Math", "Math", "ELA", "ELA"), Score = c(73L, 157L,
75L, 111L, 82L, 69L, 78L, 131L, 93L, 58L, 109L, 99L, 79L, 131L,
84L, NA, 67L, 106L, 90L, 75L, 123L, 95L, 122L, 122L, 137L, 137L,
83L, 83L), Event = c(NA, NA, NA, "Delay", "Delay", "Delay", NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, "Delay", NA, "Delay")), class = "data.frame", row.names = c(NA,
-28L))

I am thinking using sth like this (they don't work)
df<-df2
ggplot(data =df)+
    geom_line(data=df[!is.na(df$Score),],aes(x = Day, y = Score, color=Subject),size=0.8)+
        scale_colour_manual(breaks = c("ELA", "Math", "Art"),
                        values=c(ELA="#cc0022",Math="#70ad47", Art="#fd9300"))+
   {if (grepl("Delay", df$Event)) geom_vline(data=df[(!is.na(df$Event)&df$Event=="Delay"),], aes(xintercept=jitter(Day), linetype="Delay"), color="black", size=0.4)}+
   {if (grepl("Sick", df$Event)) geom_vline(data=df[(!is.na(df$Event)&df$Event=="Sick"),], aes(xintercept=jitter(Day), linetype="Sick"), color="purple", size=0.4)}+
scale_linetype_manual(name = 'Event',
                        values = c('Delay' = 1,
                                   'Sick' = 1),
                        guide = guide_legend(override.aes = list(colour = c("black",
                        "purple"))))

Code chunk 3:
ggplot(data =df)+
    geom_line(data=df[!is.na(df$Score),],aes(x = Day, y = Score, color=Subject),size=0.8)+
        scale_colour_manual(breaks = c("ELA", "Math", "Art"),
                        values=c(ELA="#cc0022",Math="#70ad47", Art="#fd9300"))+
 geom_vline(data=df[(!is.na(df$Event)&df$Event=="Delay"),], aes(xintercept=jitter(Day),linetype="Delay"), color="black", size=0.4)+
# geom_vline(data=df[(!is.na(df$Event)&df$Event=="Sick"),], aes(xintercept=jitter(Day) ), color="purple", size=0.4)+
scale_linetype_manual(name = 'Event',
                      values = c(
        "Delay" = 1,
        "Sick" = 1
      ),
                        guide = guide_legend(override.aes = list(colour = c("black",
                        "purple"))))

Answer: With using an if to add the layers you are on the right track. Instead of putting the conditions inside the ggplot code personally I prefer to setup the conditional layers outside of ggplot code and best to put everything inside a function.
Doing so, one option to achieve your desired result may look like so:
EDIT Additionally, instead of using the hack via the linetype aes to get a separate legend you could use the ggnewscale package to add a second color legend. One benefit is that we need no fiddling via override.aes and no additional conditioning to manage the different cases:
library(ggplot2)

plot_fun <- function(df) {
  is_delay <- !is.na(df$Event) & df$Event == "Delay"
  is_sick <- !is.na(df$Event) & df$Event == "Sick"

  layer_delay <- if (any(is_delay)) geom_vline(data = df[is_delay, ], aes(xintercept = jitter(Day), color = "Delay"), size = 0.4)
  layer_sick <- if (any(is_sick)) geom_vline(data = df[is_sick, ], aes(xintercept = jitter(Day), color = "Sick"), size = 0.4)

  ggplot(data = df) +
    geom_line(data = df[!is.na(df$Score), ], aes(x = Day, y = Score, color = Subject), size = 0.8) +
    scale_colour_manual(
      breaks = c("ELA", "Math", "Art"),
      values = c(ELA = "#cc0022", Math = "#70ad47", Art = "#fd9300"),
    ) +
    ggnewscale::new_scale_color() +
    layer_delay +
    layer_sick +
    scale_colour_manual(
      name = "Event",
      values = c(Delay = "black", Sick = "purple"),
      limits = force
    )
}

plot_fun(df2)

Comment: Haha. You were faster in accepting than me realizing that your question had a second part. I just made an edit to show you one approach to deal with the guides.
Comment: If I understand correctly what you are trying to achieve then perhaps `theme(legend.box = "vertical")` is what you are looking for.
Comment: Haha. This is the third time in 24 hours that this is asked. You could set the order of the legends via the `order` argument of `guide_xxx`, e.g. you could do `scale_xxx_yyy(..., guide = guide_legend(order = 1))` for the scale/legend to appear on top and ... = 2 for the second and so on. According to the docs if the order is not set ggplot2 will choose by "... a secret algorithm" (: (see ?guide_legend). For more on the unpredictability see https://stackoverflow.com/a/70293016/12993861.
Comment: For `scale_linetype_manual(
      name = "Event",
      values = c(
        "Delay" = 1,
        "Sick" = 1
      ),
      guide = guide_legend(override.aes = list(colour = c(
        "black",
        "purple"
      ))`, is it correct that  we can have this legend event when we only have one type of event? I tried it on sth like code chunk 3 (just added) and see no legend for vertical lines
Comment: Wonderful method! Learned a lot :D
Comment: if I used ` theme(legend.position = "bottom") `, it will put both legend in one line ,which is too crowed. Is it possible to put it as one legend at a line (one line for event, one line for subject)
Comment: when I applied the codes on different df, the legend for event sometime appear on top, sometimes at bottom. Is it possible to fix the legend appear order, such as always `Subject` first, then `Event`?


Infinite Scroll com dados JSON + Javascript

Question: Fala pessoal... Estou desenvolvendo um aplicação onde obtenho os dados via JSON e modelo eles via javascript, até aqui tudo certo...
Preciso de uma ajuda para criar um infinite scroll em javascript, mostrando 10 resultado e ao chegar no final da página ele carrega mais 10, até terminar os dados.
Qual seria a melhor forma de fazer isto?
Abaixo segue meu código:

<!doctype html>

<meta charset="utf-8">
<title>Xtart</title>

Answer: Normalmente essa técnica é usada quando não se tem todos elementos já carregados e assim vai carregando aos poucos para diminuir o tempo inicial de carregamento, mas no seu caso você já tem todos os dados carregados, se mesmo assim quiser usá-la pode fazer algo desse tipo:
/* Executar depois que os elementos da página estiverem carregados, ou seja, seu código anterior já deve ter populado o '#news'. */
var mostrados = 10; //valor inicial
var filhos = $('#news').children();
for (var i=0; i<filhos.length; i++) {
    if (i < mostrados) filhos[i].show();
    else filhos[i].hide();
}

$(window).scroll(function() { //evento de scroll na janela
    if($(window).scrollTop() == $(document).height() - $(window).height()) { //atingido o final da página
        mostrados += 10;
        var filhos = $('#news').children();
        for (var i=0; i<mostrados; i++)
            filhos[i].show();
    }
}

Obs: Você pode remover o primeiro loop se no seu código anterior adicionar style:"display:none" em todos seus divs que são inseridos ao #news exceto os 10 primeiros.
Comment: Valeu @LucasMarques me ajudou muito!
Answer: Consegui resolver o meu problema com a ajuda do @LucasMarques.
Abaixo deixo meu código funcionando, caso alguém tenha o mesmo problema que eu tive.
Valeu!

<!doctype html>

  <meta charset="utf-8">
  <title>Xtart</title>


Logarithmic axis for datetime not working

Question: I would like to plot with Python/matplotlib in such a way, that the x axis (in datetime format) is scaled logarithmically.
With the code below, I could get a logarithmic y axis, but the logarithmic x axis does not work. What do I have to do that the logarithmic x axis works, too?
import pandas as pd

my_array = ["01.01.1990 23:59:12","01.01.1992 23:59:12","01.01.1994 23:59:12","01.01.1996 23:59:12","01.01.1998 23:59:12"]
df = pd.DataFrame()
df["a"]=[1,2,3,4,5]
df["my_date"] = pd.to_datetime(my_array, format="%d.%m.%Y %H:%M:%S")
df.index = df.my_date
df.drop(["my_date"],axis=1,inplace=True)
print(df)

                      a
my_date
1990-01-01 23:59:12  1
1992-01-01 23:59:12  2
1994-01-01 23:59:12  3
1996-01-01 23:59:12  4
1998-01-01 23:59:12  5

import matplotlib.pyplot as plt
plt.semilogx(df, "-o", markersize=2)
plt.show()
plt.semilogy(df, "-o", markersize=2)
plt.show()

Comment: You want to log transform a span of 8 years?
Comment: Yes, I know, that my desire is not so usual. But indeed, this is what I want.
Answer: The Pandas syntax is just
df.plot(logy=True, logx=True)

But you'll need a little distance in your dates to get a log-transformed axis to start looking like normal "loggy" graph.  You can still transform the year integer values to their log equivalents, but they'll just be smaller numbers very close together.  The x-axis will still have more-or-less linear ticks.
You can observe this by actually taking the log of the years of my_date:
np.log(df.my_date.dt.year)

0    7.595890
1    7.596894
2    7.597898
3    7.598900
4    7.599902

Comment: Hi Andrew, thanks for your analysis. But I think that the x axis is still linear. At least the distance between 1907 and 1927 (and so on) is the same all over the axis up to 1987 (the `7x10^5` looks maybe like a bug in matplotlib... :-) ).
Comment: You're right!  I didn't look carefully enough.  I'll remove the counterexample.  But I think the point about transforming the years is still useful to call out here.  Maybe it would be helpful to know: What kind of graph are you expecting to see?


How was statistics performed before computers?

Question: What was the general approach to performing statistics before calculations were fully computerised (i.e. before both calculation and memory were managed by computer)?
I understand the question could become rather broad, so I'm mainly looking for illustrative impressions of the techniques, attitudes and approaches people employed to extract meaning out of data when all you had was a pen, paper and some other mechanical tools.

I suspect that something as simple (to modern statisticians) as linear regression with, say, 100 rows and three variables, would've been rather daunting to someone performing the matrix operations manually. But if an analysis was important, it would've been worth spending the day doing number crunching, or have a room full of human calculators do it for you. But this is still missing a lot of the pre-analysis work (stuff like visualisation, removal of extreme values, etc) that we take for granted today. How would a large regression have been approached back then? What were the shortcuts and clever labour-saving tricks?
I also suspect that many tests (t test, F test, other tests that involve taking a sample of the data) were used much more regularly back then to get a handle on the general feel of the data. Would this be correct?
Finally, were analyses by and large restricted to problems for which analytical solutions could be found?
Comment: What does "computational data processing" mean precisely? Mechanical calculators have a long history. I remember teaching their use in the early 1970s. Iterative methods for fitting logit and probit methods were routine in the 1940s and 1950s, although naturally enormously more work than now.
Comment: So, you mean "electronic computers" from say the middle 1940s on. (Computers were, seriously, the people who did the computing for some decades, usually women.)
Comment: Many historians trace the origin of modern statistics to an exchange of letters between Blaise Pascal and Pierre de Fermat in 1654.  Somewhat coincidentally, Pascal had invented (and built) a mechanical calculator 12 years earlier.  In this sense, *statistics has always existed in an era where mechanical calculation was possible.*  For a few thousand examples of real datasets that people were *expected* to analyze only with pencil and paper--using no "analytical solutions" whatsoever--please consult John Tukey's book *EDA* (1977).
Comment: Look at textbooks of the time to see what was routine. e.g. Yule and Kendall, Snedecor. Nevertheless those can be misleading. For example, I once went through some classic texts on analysis of variance (Cochran and Cox, Scheffé, etc.) and could find no examples whatsoever of graphs based on data. Does that mean that generation didn't know about plotting data? I don't think so. It's just as likely that plotting data was regarded as too obvious to deserve mention. Also, generations accustomed to hand or mechanical calculation trained themselves and students to watch out for possible outliers.
Comment: You might find [this](https://rss.onlinelibrary.wiley.com/doi/abs/10.1111/j.1740-9713.2012.00626.x) interesting.
Comment: Edited question. I mean before both computation and memory were handled by computers, so the mechanical calculator era would count for the purposes of this question.
Comment: Roughly, yes. I mean computer in the modern sense of the word. Pre-1940s is the sort of time period I'm asking about.
Comment: Looks like you know quite a bit about the topic. If you could reformulate your comments into an answer that'd be grand.
Comment: @NickCox: You should include some of the comments in a new answer.  In general, question-and-answer pages should be "self contained" in that they should not rely on reading comments for essential information.
Answer: There were rooms of people known as "computers" who would do the calculations by hand, as Nick Cox stated. Apart from analytical solutions, I imagine that they could solve problems using numerical approximations based on, e.g., a few terms of a Taylor's Series expansion. Also, they had lots of tables (logs, probabilities) they could refer to.