Limit involving the norm of a Cauchy problem solution

Question: Let
$$A = \begin{bmatrix} 1 & -2009 & 0 \\
 2009 & 1 & 1492 \\
0 & -1492 & 1
 \end{bmatrix}$$
and $X_0 \in \mathbb{R}^3$, $X_0 \ne 0$. Let $X(t)$ be the solution of the Cauchy problem
$$ \begin{cases}X'(t)=AX(t), \quad \forall t \in \mathbb{R} \\
     X(0)=X_0 \, .
   \end{cases}$$
Evaluate, when $k$ varies in $\mathbb{R}$, the limit
$$ \lim_{t \to -\infty} e^{-kt} \lVert X(t) \rVert ^2 \, .$$
I don't really know where to begin. I don't think I'm supposed to solve the cauchy problem explicitly.
Comment: You don't have to provide exact solution. But since you know what form the solution has, you can compute something for matrix $A$ and from this you can deduce what this limit will be like. And of course you can compute $\exp A$ if you know some its useful properties -- it's easy to do because this matrix is a sum of two commuting matrices.
Comment: I know $X(t)=e^{At}X_0$, but how do I estimate $\lVert e^{At}X_0 \rVert^2$? I suspect it has to do something with the eigenvalues of $A$ but I don't really know.
Answer: Sort of hint
It is not the only possible way to obtain the answer for this question, but it's pretty tempting for me to follow it. Since we are dealing with linear system of equations $\dot{x} = Ax$ we know that the Cauchy problem $x(0) = x_0$ can be solved using formula $x(t) = e^{At} x_0$. The matrix $A$ in question has one remarkable property: off-diagonal elements satisfy $a_{ij} = - a_{ji}$. If it were true for diagonal elements too, we would have a skew-symmetric matrix. A skew-symmetric matrix multiplied by real scalar $t$ is still a skew-symmetric matrix and its exponent is an orthogonal matrix (useful property which is very easy to prove if we calculate $\frac{d}{dt}(x^T x)$, where $x$ satisfies $x' = Ax$, and show that in this case $e^{At} x_0$ preserves the norm of any vector $x_0$). But matrix $A$ is a sum of identity matrix $I$ and skew-symmetric matrix $B$; moreover, $I$ and $B$ commute (this is obvious), so $It$ and $Bt$ commute. In this case $$e^{At} = e^{(I+B)t} = e^{It} \cdot e^{Bt} = e^t \cdot e^{Bt},$$
where $e^t$ is an ordinary scalar function. So, it's pretty obvious that $e^{Bt}$ doesn't change the norm of vector (it's an orthogonal transformation) and only $e^t$ multiplier changes the norm.


undetected_chromedriver - is throwing TypeError: '<' not supported between instances of 'NoneType' and 'int' error

Question: I'm trying to open chrome in headless mode with undetected_chromedriver (version='3.4.6') however throwing TypeError: '<' not supported between instances of 'NoneType' and 'int' error. Any suggestions please
from undetected_chromedriver import Chrome, ChromeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

options = ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--password-store=basic")
options.add_experimental_option(
    "prefs",
    {
        "credentials_enable_service": False,
        "profile.password_manager_enabled": False,
    }, )
driver = Chrome(options=options)
driver.get('https://www.google.com/')

Answer: This appears to be a known issue with the module:

GitHub Issue Link: #1200 TypeError: '<' not supported between instances of 'NoneType' and 'int'


Fastest mobile framework for Android?

Question: I'm tasked with designing a few app style webpages for use on pretty much the cheapest Walmart Android tablet available. I started in jQuery mobile but just a listview with 4 items took 5-6 seconds to load, and it wasn't the connection. Is there a faster mobile framework for Android?
Thanks
Comment: In all seriousness, you may want to post some code that demonstrates how a listview w/ 4 items takes 5-6 seconds.  How are you getting the data?  Is it a service call to get the data?  If so, what does the service-side look like?
Answer: I have tried jQuery Mobile and finally quit because of the bad performance too.
I have learned the best is to go bare foot: jQuery (or Zepto.js, it is even faster) on top of Apache Cordova (Phonegap). For simple page transitions in the vein of jQuery mobile I use my own js stuff: https://github.com/grobmeier/Roadcrew.js
This gave me a pretty quick application, even when I have no widgets ready. For that I used Bootstrap btw. When my App grows up I will probably pay somebody to create me a more unique UX experience.

Fastest mobile framework for Android?


Check for string in "response.content" raising "TypeError: a bytes-like object is required, not 'str'"

Question: I am trying to see if a sentence is present in the response back from a request.
import requests

r = requests.get('https://www.eventbrite.co.uk/o/piers-test-16613670281')
text = 'Sorry, there are no upcoming events'

if text in r.content:
   print('No Upcoming Events')

I am getting the following error:
TypeError: a bytes-like object is required, not 'str'

I am not quite sure why this occurring and what the solution would be.
Comment: `content` attribute returns a binary representation of the response you need to use `text` attribute.
Answer: r.content is a bytes object but text is str, so you can't do the __contains__ (in) check on another directly.
You can easily (re-)define the text object to be a bytestring:
text = b'Sorry, there are no upcoming events'

Now, you can do if text in r.content:.
or you can use r.text to get the str representation directly, and use text as-is (as str).
Answer: r.content returns a bytes like object in Python 3.x. To check, do:
>>> type(r.content)
<class 'bytes'>

There are multiple ways to fix your issue. For example:

Decode r.content to string: You can decode it to string as:
>>> text in r.content.decode()
False

Convert r.content  to utf-8 string as:
>>> text in str(r.content, 'utf-8')
False

Define your text to search as a byte-string. For example:
text = b'Sorry, there are no upcoming events'
#      ^  note the `b` here

Now you may simply use it with r.content as:
>>> text in r.content
False

Use r.text instead of r.content to search for the string, which as the document suggests:

The text encoding guessed by Requests is used when you access r.text.

Hence you may just do:
>>> text in r.text
False

Answer: Try this instead:
if text in r.text:

r.text is the textual content that is returned. r.content is the binary content that is returned.
Comment: Thank you for this, unfortunately due to how the site works the r.text returns no data. This info is very useful and will keep this in mind in future! :)
Comment: @PiersThomas then you need to check again. Your url returns the same content as string with `r.text`
Answer: Requests returns a bytes object, you need to convert it to a string before performing the in
Here's a reference about built in types, one of which is bytes https://docs.python.org/3/library/stdtypes.html
the line of code you're looking for is something like,
if text in r.content.decode():
  print('No upcoming events')

by default decode assumes utf-8, you can pass in a different encoding if you need to though.


Fitting a multivariate Gaussian with extremely sparse samples

Question: We have a multi-variate Gaussian distribution. For instance with 3 variables.
The correlations between the variables are important!
We are fitting it to data, however, the samples are such that each sample only has a measurement for one of the 3 variables.
For instance:
(1, None, None)
(None, 0, None)
(2, None, None)
(None, None, -1)
This does not fit the usual situation of a "little" missing data, which algorithms such as Expectation Maximization address.
Can we still fit the Gaussian multivariate distribution with a non-diagonal co-variance?
Comment: If your data looks like that, how could you possibly have a correlation between two variables?
Answer: With the data you are describing, where at each sample point only one of the vector components is observed, there is no information (meaning no information at all) about correlations.  So there is no way you can fit a Gaussian model with non-diagonal covariance matrix.
If you tried with a bayesian model, with a (proper) prior on the covariance matrix, your posterior would be identical to the prior, confirming that there are no sample information.


The closed form of $\int_{0}^{\infty} \frac{\cos x}{\left(x^{2}+1\right)^{n}} d x$

Question: We are going to deal with the integral
$$
I_{n}=\int_{0}^{\infty} \frac{\cos x}{\left(x^{2}+1\right)^{n}} d x
$$
by differentiation on its related integral
$$
J(a)=\int_{0}^{\infty} \frac{\cos x}{x^{2}+a} d x,
$$
where $a>0$
Using contour integration along anti-clockwise direction of the path
$$\gamma=\gamma_{1} \cup \gamma_{2} \textrm{ where }  \gamma_{1}(t)=t+i 0(-R \leq t \leq R)  \textrm{ and } \gamma_{2}(t)=R e^{i t}  (0<t<\pi) $$
$$
\begin{aligned}
J(a) &=\frac{1}{2} \int_{-\infty}^{\infty} \frac{\cos x}{x^{2}+a} d x \\
&=\frac{1}{2} \operatorname{Re} \int_{\gamma} \frac{e^{i z}}{z^{2}+a} d z \\
&=\frac{1}{2} \operatorname{Re}\left[2 \pi i \operatorname{Res}\left(\frac{e^{i z}}{z^{2}+a}, \sqrt{a} i\right)\right] \\
&=\frac{1}{2} \operatorname{Re}\left[2 \pi i \frac{e^{i(\sqrt{a} i)}}{2 \cdot \sqrt{a} i}\right] \\
&=\frac{1}{2} \operatorname{Re}\left[\frac{\pi}{\sqrt{a}} e^{-\sqrt{a}}\right] \\
&=\frac{\pi}{2 \sqrt{a}} e^{-\sqrt{a}}
\end{aligned}
$$
Differentiating both sides w.r.t. $a$ by $(n-1)$ times yields
$$
\left.I_{n}=\frac{\pi}{(n-1)!}J^{(n-1)}(1)=\frac{(-1)^{n-1} \pi}{2(n-1) !} \frac{d^{n-1}}{d a^{n-1}}\left(\frac{e^{-\sqrt{a}}}{\sqrt{a}}\right)\right|_{a=1}
$$
Noting that
$$
\frac{d}{d a}\left(e^{-\sqrt{a}}\right)=-\frac{1}{2 \sqrt{a}} e^{-\sqrt{a}},
$$
we have $$
I_{n}=\left.\frac{(-1)^{n} \pi}{(n-1) !} \cdot \frac{d^{n}}{d a^{n}}\left(e^{-\sqrt{a}}\right)\right|_{a=1}
$$
By the formula, we can find
$$
I_{1}=\frac{\pi}{2e};I_{2}=\frac{\pi}{2 e};
I_{3}=\frac{7 \pi}{16 e} ;
I_{4}=\frac{37 \pi}{96e} ;
I_{5}=\frac{133 \pi}{384 e};\cdots\
I_{10}=\frac{12994393 \pi}{53084160 e}
$$
Suggestions on how to deal with the last derivative is highly appreciated.
Comment: For the problem of the derivatives, consider the Taylor expansion of $\frac{e^{-\sqrt{a}}}{\sqrt{a}$ around $a=1$. This is the simplest.
Comment: What is your question...?
Comment: How to find the closed form for the last derivative? Can you help?
Answer: Too long for a comment
Looking at your results and writing
$$I_n=\frac \pi {2e} a_n$$ we have the sequence
$$\left\{1,1,\frac{7}{8},\frac{37}{48},\frac{133}{192},\frac{2431}{3840},\frac{27007}{460
   80},\frac{176761}{322560},\frac{5329837}{10321920},\frac{12994393}{26542080}\right\}$$ the numerators correspond to sequence $A143991$ in $OEIS$. Taking into account what is the corresponding generating function
$$I_n=\frac{\sqrt{2\pi }}{2^n\,\Gamma (n)}\, K_{\frac{1}{2}-n}(1)$$ where appears  the modified Bessel function of the second kind.
Comment: The final result [has a name](https://dlmf.nist.gov/10.32#E11).
Comment: @metamorphy. I went to the same page. In Franch, we use to say "great minds think alike". This true excpet that I am not one of these. Cheers
Answer: From this answer of mine: $$I_{n+1}=\frac{\pi/e}{2n!}\sum_{k=0}^n\frac{2^{-n-k}(n+k)!}{k!(n-k)!}=\frac{\pi/e}{2^{2n+1}n!}\sum_{k=0}^n\frac{2^k(2n-k)!}{k!(n-k)!}.$$


Assessing loss of different parsimony levels (Cox Model)

Question: I have a Cox Proportional Hazard model with 6 covariates to determine OS. I am now trying to simplify this model by taking some of this covariates down. This is intended for a wide audience so I'm assuming not everyone will be using all 6 variables. I would want to inform the user of the cost of not entering all the variables by giving them some sort of "% of loss" or "accuracy" thing. I've did the following.
Fit the whole model and fit several 1-missing variable models. Then compute RMSE of several quantities. Thing is I don't know how much informative or "correct" this is.
I computed RMSE for:
A) Predictions of both models (so I obtain the mean error of the partial model based on the whole model)
predsfull <- predict(cph(Surv(months, cens)~rcs(var1, 4)+rcs(var2,4)+rcs(var3,4)+var4+var5+rcs(var5,4), data=df, x=T, y=T, surv=T))

predspart <- predict(cph(Surv(months, cens)~rcs(var1, 4)+rcs(var2 ,4)+rcs(var3,4)+var4+var5, data=df, x=T, y=T, surv=T)) ##Var6 is now gone

sqrt(mean((predspart-predsfull)^2))

B) The same as A, but instead of predict I did the RMSE with the survest(fullmodel)$surv and the partial model.
C) The RMSE of the bootstrap corrected C-stat given by the validate function of the rms package.
Is my approximation correct? I am kind of confused by the quantities I am obtaining, as I'm using RMSE I am getting the same units the response is giving, so, in all scenarios I am getting proabailities. Therefore I am reporting something like "you are sacrificing 0.023% of discriminative power using a partial model vs a full model".
Is any of that making sense?
PS: Code is just an example, I'm doing this for all 6 covariates and even 2 covariates at the same time. So the fact that some of them are non-linear has nothing to do with the fact I'm taking a covariate down, I just added the closest form of my model I could.
Answer: One problem with comparing full and partial models in general is the implicit assumption that the full model is better. If your full model is overfit, that won't be the case. (It seems that you are careful about such things, but answers here are ideally written for a general audience.) Another problem is just what the predict() and survest() functions are returning for making the comparisons. From the way you wrote the predict() code, for example, it looks like you would be looking at mean-square differences in linear predictor values; those aren't necessarily the easiest things for a wide audience to interpret.
What you presumably care about the most is how well each of the models (whether full or reduced) works on the data. For that, your choice of bootstrap-validated C-index makes the most sense among the comparisons you suggest. It's not clear what you gain from trying to calculate the RMSE of the C-statistic, as the C-statistic itself seems to be of most interest and is easy to interpret: it's the fraction of pairs of cases whose actual order in time of events agrees with the order predicted by the model.
That said, Harrell points out that the C-index is not a very sensitive way to compare models. Comparisons of models based on log-likelihood considerations are more sensitive. The validate() function in the rms package, with its bootstrapping, provides several such optimism-corrected indices of model quality: Nagelkerke's $R^2$, a discrimination index $D$, an unreliability index $U$, and an overall quality index $Q = D - U$, as described in Chapter 20 of Harrell's Regression Modeling Strategies, 2nd edition. You could consider choosing one of them to display differences among your full and reduced models. These indices, however, can depend on the censoring distribution of the data. Thus some question the reliability of these indices. A search on this site for Harrell and C-index provides links to extensive discussion; the discussions of comparisons among logistic regression models are generally applicable to Cox models, too.
Comparing how well calibrated the models are, with the calibrate() function in the rms package, can also be useful. That function uses flexible adaptive hazard regression, not assuming linearity or proportional hazards, to test model predictions against the data at a fixed point in time. In addition to an overall bootstrap-adjusted calibration curve, the function reports the mean absolute error and the 0.9 quantile of absolute error* in predicted survival probabilities. Those estimates of precision might be the easiest for a wide audience to understand.

*For the 0.9 quantile use the value displayed on a plot of the object returned by calibrate(); last I looked there seemed to be an error in the corresponding value returned by the print() function for those objects.
Comment: Thanks @EdM!
I think I will take your advice and go with the C-stat/Absolute error. I don't think `R^2` is that informative because of the survival nature of the data (so I'm getting as expected fairly low values which aren't very informative and can be even confused). I think I took the C-stat "prohibition" too far.
Comment: Thanks for your imput! My question comes motivated by Harrell's RMS book. As he suggests (chapter 5.5.2) "Our approach is to consider the full model fit as the "gold standard" model, especially the
model from which formal inferences are made. We then proceed to approximate
this full model to any desired degree of accuracy. For any approximate
model we calculate the accuracy with which it approximates the best model".
That is where I'm going for. Now, I'm aware of what Harrell thinks about comparing two models by its C-stat, and he suggests to use RMSE or MSE to assess that accuracy (5.7)
Comment: Also, I just checked calibration, and everything seems fine. The only thing that changes a little bit is C-stat (that we "can't" use for comparisons), so I'm stuck with this. I have a "best" model (which is the full one, not only because It's the one we use to compute predictions but also as LR tests suggest), but I can't assess by how much it's better. All models seem to be valid in terms of overfitting (which is fine as I want to adapt the model to various needs). So if I'm interpreting Harrell right, I need a way of informing from the accuracy each partial model approximates the full one
Comment: @N00b the discussion of approximating the full model in section 5.5.2 seems to be in the context of least-squares, for which MSE is appropriate. In that case, $R^2$ and MSE give equivalent assessments of model fit. For a Cox model, the analogous approach would be to use the (validated) Nagelkerke $R^2$ values. Those have potential problems with censored data, as noted, but you could present the results and discuss the potential limitations.
Comment: @N00b you aren't prohibited from using C-index, it's just not very sensitive. I suspect that the accuracy in event-time ordering provided by the C-index might be just what your "wide audience" would be interested in as they consider how many variables to include in their own related studies. You could consider presenting both the $R^2$ and C-index values. The mean and 0.9 quantiles of absolute error in predicted survival probabilities at a critical time of interest for the different models might also be helpful to that audience.


How do you back up Exchange 2007 on Windows Server 2008?

Question: There is a well known deficiency in the Windows Server 2008 backup utility that does not allow you to easily back up Exchange 2007, the way you could with NtBackup in 2k3.  The Exchange team promised a solution but never provided one.
What are some (hopefully cheap) options?
Comment: If your company has a standard 3rd party backup solution, I'd look at seeing if there are options for that product to backup Exchange.  Saves you from having to learn yet another piece of software to handle backups and recoveries (an emergency recovery is not the place to learn new tools, IMHO) :)
Answer: Exchange 2007 SP2 has now provided addon support for the Windows 2008 Server Backup tool.
Answer: Great Question Eric.  I have been looking for a solution myself.  Here is what I have found so far.  Each looks like it has its own advantages/disadvantages.  I haven't used any of the them yet..
Commercial/Paid Software:

BackupAssist - $250, adds a plug-in to Windows Server Backup
Microsoft DPM - Looks like this one is around $1010 for the Server License + Enterprise Data
Acronis Recovery For Exchange - $1219

Free Script:
 - MBS-online-backup.ps1 (GUI Version) - Uses powershell and VSS to make an online backup.  I have tested it out and it works pretty good.  There aren't any recovery instructions posted yet though but I think you can mount the backup files as a recovery storage group.  Not for the faint of heart but looks like it will get the job done.
Answer: See my answer to the related question - ntbackup.exe, Powershell, ExMerge, or offline backup.
Answer: Good news: the solution is coming in Exchange 2007 SP2, coming soon. See this article for full details. In the meantime, I'd use the MBS-online script that @TonyB mentioned. Michael B. Smith, its author, is a very knowledgeable guy, and his script does a good job.
Answer: Microsofts DPM seems to be the common choice with many.
There is also an article here that seems to indicate it is possible to backup Exchange using NTBackup on server 2008 with some hacking. Not sure how well it restores though so you would need to test that quite thoroughly.
Answer: The problem with using NTBackup is that it can corrupt the mail store if you have LCR enabled. Not sure sure what happens with SCR enabled. Without either of these enabled, NTBackup should run through fine however it will be necessary to test after major updates.


Java How to define a fundamental operation in a recursive method?

Question: In a recursive method, we will have to set up some base cases. Can we define these base cases as the fundamental operations of the method? As far as I know, fundamental operations are the core functions of the method, which means every time the method is running must pass through these functions. (Please let me know if I am wrong)
Another question is if I got a if statement in the base cases, for example,
if (a != b && b != c){}
Will it be count as 1 or 2 fundamental operations? Cause it is checking 2 part of things:  a != b and  b != c in a single if statement.
This is quite confused.
One more thing is : I am not sure will this kind of code is suitable or not:
Recursive method()
Base case:
XXXXXXX
XXXXXXX
XXXXXXX
Recursive case:
// Should I move this part to the base case?
if(conditions){

    return (Recursive method() || Recursive method());

// ********************************************************
    else if(conditions){

         do something;

    return Recursive method();

Cause I think base cases are just used to defined a exact value when meeting the conditions. Therefore I leave this part in the recursive case. I am just not so sure about this.
I am not asking for answer for coursework, just to ensure the concept is correct or not. So I didn't put my algorithm on here. Sorry if this makes you cant understand my question. I will try my best to explain.
Thanks.
Comment: Could you provide the definitions of `fundamental operation` and `base case`?
Comment: Wiki said "base case breaks the chain of recursion, it is sometimes also called the "terminating case"."
Comment: fundamental operation is the core of a function
Comment: From your definition, you have the example in the question wrong. Your example does not have a `base case` because the recursion is never stopped ;-)
Comment: jso, would you mind to explain a little bit more?
Comment: Spent some time looking for the source of your definitions but without any success.. without that, the answer is actually full of assumptions.
Answer: Based on the definitions provided, a base case or terminating case is a condition which stops the recursion calls.
The definition of a fundamental operation is a bit unclear from the question and I am honestly getting lost in here. But from my understanding it's or it should be a set of operations which are done in a function regardless the base case. Link to the definition would help!
Let's have a short example:
/**
 * Let's assume the result is not obvious here regardless it's a nth triangular number.
 * Added there a System.out though.
 */
public void calc(int i) {
    System.out.println(i);

    if (i == 0)
        return 0;
    return i + calc(i - 1);
}

The only case how to stop the recursion evaluating the first condition if (i == 0) to true. Meaning that this condition represents the base case. When i has any other value than zero, the recursion continues.
In the example, the only operation which is done regardless the outcome of the method is printing the value i. Thus that's the only fundamental operation of the method. (Based on the definition, an evaluation of a condition might and might not be considered an operation since it's not changing any value nor has any side effects, like printing.)

Can we define these base cases as the fundamental operations of the method?

Generally no, as these represent different situations. The first one defines a case when recursion is stopped and the second one what's always done. Thus if you combine them, you end up with a function which always stops the recursion.
For the following case they could be the same though.
public void calc(int i) {
    return i + 1;
}


The Domain of a Quotient with a Rational Function

Question: The function is $f(x)=\frac{x+1}{1+\frac1{x+1}}$. It's natural to say the domain is $\Bbb R\setminus\{-2,-1\}$.
However:
In this case, $f(-1)=\frac0{1\pm\infty}$ (throw in a limit if it makes you feel better) would unambiguously be 0, so this looks like a nice continuous function at $x=-1$ to me.
What is the domain of this function? (and why?)
Answer: The domain of $f$ is still $\Bbb R\setminus\{-1,-2\}$. However, if both halves of the fraction were multiplied by $x+1$, $-1$ would no longer be outside the domain:
$$\frac{x+1}{1+1/(x+1)}=\frac{(x+1)^2}{x+2}$$
This shows that $-1$ is a removable singularity; $f$ may be assigned its limit there (zero) and it will remain regular around $-1$.
Comment: You're absolutely correct. I'm just an idiot.
Comment: The continuity comment I made was misleading. I know it can be a removable singularity. I guess I was thinking in the context of the one-point compactification of the real line, where division by 0 is defined because it's unambiguous (like it isn't here). I'll think about it more, but you're almost certainly correct. I'm just getting tired.


Residually finite nilpotent group

Question: It is known that every finitely generated nilpotent group is residually finite. Why finitely generated hypothesis is essential?
Answer: It is essential in the proof, that the group is finitely generated. A finitely generated nilpotent group is supersolvable, and every supersolvable group is residually finite( a result of K.A. Hirsch). For the first part, the proof uses that the $k$-th group $G_k$ in the lower central series of the group $G$ is finitely generated for each $k$, so that each $G_k/G_{k+1}$ is finitely generated Abelian, i.e., a direct product of finitely many cyclic groups.
This is not true for nilpotent groups which are not finitely-generated.
Edit: A possible counterexample is the additive group of $\mathbb{Q}$. It is abelian, hence nilpotent, but not residually finite.
Comment: The question is not about the demonstration. It needed a counter-example?
Comment: I added a counterexample. The proof, however, gives more insight (and shows why finitely-generated is essential).
Answer: Consider the additive group of rational numbers. It is abelian, but has no nontrivial finite quotients since it is divisible and every quotient of a divisible group is again divisible. Hence, this group is not residually finite.

Residually finite nilpotent group


Adding translation files to install profile?

Question: I am building a Drupal installation profile to make deployment of my site easier, ideally I would like to include the translation files to the install profile as well. But apart from adding the core translation files download to the makefile, is there a way to somehow add the translation files for the modules that are in use and for the custom fields as well?
Ideally I would like to add the needed .po files to the makefile or the profile's .install-file. Any ideas on how to do it?
Answer: Have you seen http://zgadzaj.com/drupal-installation-profile-with-multiple-languages ?
Also you can try to export it with Features

Features
The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

And for more especific export data

UUID Features Integration
The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.
  What's that you say? You thought features was only for configuration?
  This module is meant to be used in the cases where certain pieces of
  content straddle the line between pure content and configuration.
  You've to configure the entity types / bundles to be exportable. Read
  the Documentation for further information.


Updating a graph through C++ and GLUT

Question: I have written a c++ program in Xcode to implement Symbolic Regression & Genetic Programming. I'd like to create a window to visualize the reference data (an array of 2d points) and the best function that the program generates each generation.
To put it simply, I'd like the window to show 2 graphs, and have it be updated with a for loop. From what I understand, GLUT seems like a good framework, and I've written a function to display the reference data (std::vector is how I'm storing the "referenceDataSet" variable):
void renderScene(){
    // The min/max variables are just for scaling & centering the graph
    double minX, maxX, minY, maxY;
    minX = referenceDataSet[0].first;
    maxX = referenceDataSet[0].first;
    minY = referenceDataSet[0].second;
    maxY = referenceDataSet[0].second;
    for (int i = 0; i < referenceDataSet.size(); i++) {
        minX = min(minX, referenceDataSet[i].first);
        maxX = max(maxX, referenceDataSet[i].first);
        minY = min(minY, referenceDataSet[i].second);
        maxY = max(maxY, referenceDataSet[i].second);
    }
    glLoadIdentity ();
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin( GL_LINE_STRIP );
    glColor4f( 1.0, 0.0, 0.0, 1.0);
    for (int i = 0; i < referenceDataSet.size(); i++) {
        glVertex2f((referenceDataSet[i].first-minX)/(maxX-minX)-0.5, (referenceDataSet[i].second-minY)/(maxY-minY)-0.5);
    }
    glEnd();
    glFlush();
}

void renderInit(int argc, char **argv){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutInitWindowSize(600, 600);
    glutCreateWindow("");
    glutDisplayFunc(renderScene);
    glutCheckLoop();
}

The problem with this is that I'm not sure how I should go about updating the window, or drawing a second graph that constantly changes.
Also, this is my first question on Stack Overflow, so I apologize if I'm not doing something correctly here, or if any of this is difficult to understand. I searched as best I could for the answer, but couldn't really find anything relevant.
Answer: In glut or OpenGL, glutIdleFunc(void (*func)(void)) is used to update the scene.
The idle func will call the glutDisplayFunc every time the scene refreshes.
Reference is here http://www.opengl.org/resources/libraries/glut/spec3/node63.html
I guess renderScene() is your glutDisplayFunc. And you need to register an idle function using glutIdleFunc. In the idle function, you can change the parameters for the second graph that constantly changes, and renderScene() will be called again after changes in the idle function are done.

Updating a graph through C++ and GLUT


$r$-dimensional Meshes of Trees

Question: So i am reading up on some interesting network topologies for a CS course and what i am reading is $r$-dimensional meshes of tree's.
An $r$-dimensional mesh of trees is formed by adding complete binary tree's to an $N$-sided $r$-dimensional grid where the grid vertices act as the leafs of each binary tree.
Something like this:

This book says this about the graph $G = (V, E)$
$|V| = (r+1)N^r - rN^{r-1}$
$|E| = 2rN^r - 2rN^{r-1}$
And the diameter of this graph (the longest path) is $2rlogN$
How did they come about getting this result? The book does not explain it at all and i do not see how they calculated it.
The book i am reading is: Introduction to Parallel Algorithms and Architectures: Arrays, Trees, Hypercubes is any of you are interested.
EDIT:
I have tried to derive this myself by first finding $|V|$ when $r=2$ which would make it a 2-dimensional mesh of trees.
For this i know there are $2n$ complete binary tree's. Each binary tree have $2^{n-1}-1$ vertices. So this means $2n * 2 ^{n-1} -1$ vetices but we are double counting some because there is a binary tree for every row and column. Therefore we can minus out all the leaves of the column binary trees and they will be accounted in the row binary tree's. So that gives us $n * 2^{n-2}$ vertices to minus from the original.
$2n * (2^{n-1} - 1) - n2^{n-2}$
From this can i just times it by $n$ for 3 dimensions and $n^2$ for 4 dimensions? Then up to $n^{r-2}$ to find the total in $r$-dimensions? Was i calculating this correct for $r=2$? I read somewhere else that when $r=2$ $|V| = 3n^2 - 2n$
Second Edit
Maybe i should use the fact that i know the leafs of each complete binary tree have $n$ vertices which means each binary tree is made out of $n + (n-1)$ vertices.
There are $2n$ complete binary tree's which gives me: $2n(n + (n - 1))$ total vertices which contains a few we counted twice. A total of $n^2$ we counted twice. So
$2n(n + (n-1)) - n^2 = 2n^2 + 2n^2 - 2n - n^2 = 3n^2 - 2n$
That looks right, doesn't it?
So now how would I apply this for 3 dimensions, 4, 5 ect.. all the way to $r$-dimensions?
Comment: Have you tried deriving it yourself and seeing if you get the same result? What have you got so far?
Comment: yes, i edited my post to show you how i started to derive a solution but got lost...
Comment: Your question is not clear. How exactly do you add binary trees so that the grid vertices are the leaves? For instance what leaves are part of the same tree?
Comment: Check out this picture http://users.atw.hu/parallelcomp/files/02fig48.gif which shows a 2-dimensional mesh of trees
Answer: You seem to have mixed up two different formulas for the number of nodes in a complete binary tree. If the height of the tree is $h$, it has $2^h-1$ nodes. But in this case, $N$ is not the height but the number of leaves, so the tree has $N-1$ internal nodes, and the total number of nodes is $2n-1$.
From here you get, for $r = 2$, a total of $2N\cdot(2N-1)$ vertices in each tree, less the overcounting of shared leaves, $N\cdot N$, equalling $|V| = 2N(2N-1) - N^2 = 3N^2 - 2N$, which also agrees with the formula $|V| = (r+1)N^r - rN^{r-1}$.
A better way to do it would be to notice that the shared nodes are simply the nodes in the grid, and count them once: $N^r$. The internal nodes of the trees are not shared, there are $N-1$ of them for each tree, and there are $rN^{r-1}$ trees (see below). Add this up and you'll get your solution without worrying about overcounting.
The number of trees is $rN^{r-1}$ because along any direction, a tree connects $N$ nodes, so you need $N^{r-1}$ of them to cover the grid. And the graph contains $r$ copies of this arrangement, one each for the $r$ directions along the grid.
A similar approach should work for counting the number of edges in the graph -- count the edges in the trees and the edges in the grid separately.
For the diameter, first think about what the shortest path between two nodes is in a traditional mesh (without trees), then consider how the additional tree structure shortens this path. Then it should be clear which pair of nodes remains the farthest apart; their distance is the diameter of the graph.

$r$-dimensional Meshes of Trees


Configuring Cruise Control with NUnit and SVN

Question: I am trying to configure Cruise Control with Nunit for reporting purpose. But I am unable to do this task. Any one can please help me how to configure the ccnet.config file for its configuration and also some easy and step by step tutorial for its explanation.
Answer: Do you use a build script for MSBuild or NAnt ?
I do it like this:

I have a build script (msbuild), in where I have a task which runs my NUnit-unit tests
This task looks like this in my buildscript (simplyfied):

<Target Name="rununittests">
    <NUnit Assemblies="$(outputdir)\MyTests.dll"
           OutputXmlFile = "$(artifactdir)\MyTests.Results.xml"/>
</Target>

In my cruise-control project, I call this task:

 <msbuild>
      <executable>c:\....\msbuild.exe</executable>
      <projectFile>c:\...\mybuildscript</projectFile>
      <targets>rununittests</targets>
      <logger>c:\...\rodemeyer.msbuildtoccnet.dll</logger>
 </msbuild>

The RodeMeyer logger is a logger that I've found somewhere on the CC.NET webpage.

At the end of my CC.NET project configuration, I make sure that the output XML is merged :
<publishers>
<merge>
   <files>
     <file>...\*.results.xml</file>
   </files>
</merge>

<xmllogger/>
</publishers>


Get Nodes from xml by specifying limit

Question: Here is the xml ,
<Faculty>
    <facultyMember>
        <FirstName>A</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>B</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>G</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>H</FirstName>
    </facultyMember>

</Faculty>

I want to get nodes from this xml by providing index ,
For e.g. If i provide 3 to 6 the output should be like ,
    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>

How to do this using etree python ?
Answer: The idea is to find all facultyMember items and use python's list slicing:
from xml.etree import ElementTree as ET

data = """<Faculty>
    <facultyMember>
        <FirstName>A</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>B</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>G</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>H</FirstName>
    </facultyMember>

</Faculty>"""

tree = ET.fromstring(data)
begin, end = 3, 6

for element in tree.findall('.//facultyMember')[begin - 1: end]:
    print ET.tostring(element).strip()

prints:
<facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
<facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
<facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
<facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>

Comment: Thanks , But what if i want to in the format like `OrderedDict` in `list` ?
Comment: Ok, could you provide the desired output? Thanks.

Get Nodes from xml by specifying limit


why its fail at n = $1$ and $2$?

Question: i have some  confusion in this  answer
Why is $\mathbb{Z}[\sqrt{-n}], n\ge 3$ not a UFD?
My  confusion is

My attempt :  we know that  $1$ is odd and $2$ is  even  . So  if $n$ is even then $n=2$ , then obviously  $2$ divides $\sqrt{-2}^2=-2$ but does not divide $\sqrt{-2}$, so $2$ is a nonprime irreducible
Again  similarly take $n =1$ when $n$ is odd ,$2$ divides $(1+\sqrt{-1})(1-\sqrt{-1})=1+1=2$ without dividing either of the factors, so again $2$ is a nonprime irreducible.
But the user chris eagle  said that  it fail for $n= 1, 2$
why  is fail for $n =1 , 2 $??
Comment: I meant $\Bbb Z[\sqrt{-1}]$ and $\Bbb Z[\sqrt{-2}]$, respectively?
Comment: Doesn't $2=(1+\sqrt{-1})(1-\sqrt{-1}) =-\sqrt{-2}^2$ show $2$ is reducible in $\Bbb Z[\sqrt{-1}$ and
Comment: @J.W.Tanner $ 2 $ does not  divide $ ( 1+ \sqrt {-1})$
Answer: The problem with your argument is that $2$ is actually reducible in $\mathbb{Z}[\sqrt{-2}]$, as $2=(-\sqrt{-2})\sqrt{-2}$. So there is no problem with it being not prime.
Similarly, in $\mathbb{Z}[i]$ we have $2=(1+i)(1-i)$, so again it is reducible.
Comment: $1+i$ is irreducible, but why is that important? I'm saying $2$ is reducible as it is a product of two non-invertible elements.
Comment: ....@Mark   But $1+ i $ is  an irreducible  element of $\mathbb{Z}[i]$  How  it is reducible ?
Comment: oh soorry @Mark u

why its fail at n = $1$ and $2$?


How do I backup a MySQL database?

Question:
Possible Duplicate:
Optimal way to make MySQL backups for fairly large databases (MyISAM / InnoDB)

What is the best way to backup a MySQL database?  Is there a way to automate that process?
Comment: Please give some more information. How is anybody supposed to answer this like that. What operating system? Is it a remote or local server? Where do you want to do the backup to?
Answer: mysqldump --opt --all-databases | gzip > /path/to/backup/mysql.$(date -Ihour).sql
To automate it just add it to your crontab. But the comments are right, if you give us some more info, we can give a better answer.
Answer: MySQL Administrator provides easy backup and restore capabilities, and it's free.
Answer: http://www.phpmyadmin.net/home_page/index.php will perform an export of your databases.

How do I backup a MySQL database?


How to read data result from light sensor using interrupts

Question: I'm using Arduino mega 2560 and light sensor BH1750FVI. to show result i'm using minicom, work on Ubuntu 16.04 LTS
I write code and it's work and send me data result reading from light sensor, i can read info only once. I don't understand how i make it work through interrupts (TWI_vect) and display the results every time using my uart.
#include "my_header.h"

#define I2C_STATUS_MASK                 0xF8
#define START_COND_TRANSMITTED          0x08
#define REPEATED_START_COND_TRANSMITTED 0x10
#define SLA_W_TRANSMITTED_ACK_RECEIVED  0x18
#define DATA_TRANSMITTED_ACK_RECEIVED   0x28
#define SLA_R_TRANSMITTED_ACK_RECEIVED  0x40
#define DATA_RECEIVED_ACK_RETURNED      0x50
#define DATA_RECEIVED_NACK_RETURNED     0x58
volatile int light_intensity = 0; // var for read data from sensor

ISR(USART0_UDRE_vect) {
  if (!bufferIsEmpty(&buffer)) //if we have something to read do it
    UDR0 = popFromBuff(&buffer);
  else
    UCSR0B &= ~_BV(UDRIE0); //disallow interrupts
}

int     main(void) {
  cli();
  init_port(); //initialize my port
  init_buffer(&buffer, BUFF_SIZE); //init ring_buffer for uart
  init_uart();
  TWI_init();
  sei();

  TWI_start(); //send start
  TWI_send_SLA(WRITE); //send SLA+W to light sensor
  TWI_sendData(0b00010000); //opecode for Measurement
  TWI_stop(); //stop

  TWI_start(); //send start
  TWI_send_SLA(READ); // send SLA+R to sensor
  TWI_readData(); // read data from it light_intensity = TWDR
  TWI_stop(); // stop
  u_printnumbers(light_intensity); /*my func that send data to ring_buffer and later
                      *using interrupts send it form buffer to UDR
                      */
  u_print("\n");

  while (1) {
    if (!bufferIsEmpty(&buffer)) /*if buffer is not empty allow interrupts for uart*/
      UCSR0B |= _BV(UDRIE0);
  }
}

So this code work and i receive data from sensor and all fine. But i want using it with interrupts (TWI_vect) and receive data all the time from sensor like in while(). i read a lot of info but don't understand how it should look.
Can you show me the right way using my code with interrupts (TWI_vect) some little example. Thx for help!
Comment: We are not a tutoring service.
Answer: To use the Two-Wirte interface (I²C; TWI) interrupt-driven, you will have to implement some sort of state machine inside the TWI ISR.
Atmel Application Note AVR135 give a slight idea how this can be done. You will have to have buffers ready and abstract transactions into a struct of some sort. For example, you can have a
struct i2c_transfer {
    uint8_t        i2c_sla; /* slave address */
    const uint8_t *txbuf;
    size_t         txbytes;
    uint8_t       *rxbuf;
    size_t         rxbytes;
}

That you set up, then have a function start transmitting I2C and check if you're done via checking if txbytes == 0 && rxbytes == 0 or an error occurred. Your ISR would then need to check its state and act appropriately depending on the number of bytes it's supposed to write and read.


Depurar aplicações em NodeJS

Question: Quais a melhores ferramentas para serem utilizadas na depuração de aplicações node na opinião de vocês?
Comment: Apesar de ter respondido, estou dando um voto negativo à pergunta por ser uma informação facilmente encontrada na documentação do node. Se você tiver uma pergunta mais específica sobre o uso do debugger do node, por favor edite a pergunta.
Comment: Considero a pergunta válida, entretanto não acho interessante usar expressões como "na opinião de vocês" já que isso tira a objetividade da resposta. Mesmo assim, acho que deve ser reaberta.
Comment: @DanielT.Sobrosa O problema dessa pergunta é ser abrangente demais. Talvez uma pergunta melhor seria: "Como usar o node debugger para depurar aplicações Node no console?" e as outras versões equivalentes. Note que a sua resposta ficou grande e ainda precisa pular detalhes -- por exemplo, você precisou assumir que o OP sabe depurar uma aplicação utilizando um depurador.
Comment: Acho a questão pertinente. Horas, se o mesmo autor **realizou uma pesquisa sobre** e não encontrou uma resposta satisfatória, por que não perguntar aqui? Mais pessoas que estejam iniciando no NodeJS podem chegar até esse site através da pergunta dele.
Comment: Eu acho a pergunta muito pertinente, pois depurar no console muitas vezes quebra o galho, mas ter uma ferramenta profissional para isso é essencial quando se desenvolve aplicações robustas.
Comment: Apesar da pergunta ter sido muito bem respondida, gostaria apenas de acrecentar: Eu gosto muito de usar o https://codenvy.com/ para desenvolver em node. A IDE é na nuvem e já possui tudo que preciso para trabalhar. No meu caso atende bem pois não desenvolvo profissionalmente em Node.
Comment: É verdade. Mas eu tive o mesmo problema quando comecei no node, não sabia que ferramenta a comunidade estava usando. E continuo sem saber, mas eu achei uma que caiu como uma luva no meu modo de trabalhar. Por isso achei válida a pergunta.
Comment: Agradeço as respostas e concordo que eu poderia ter sido mais específico, porem ao realizar pesquisas rápidas não tinha encontrado nada que me parecesse "o mais usado". A pergunta foi mais para saber opiniões.
Answer: O próprio node já possui uma ferramenta de debug, basta executar o seu módulo node da seguinte maneira:
node debug nome_do_seu_modulo

Segue a documentação para ver como funciona:
http://nodejs.org/api/debugger.html
Porém existe o node-inspector que permite utilizar o browser para depurar. Basta startar o debugger e acessar a url no browser. Segue documentação:
https://github.com/node-inspector/node-inspector

Usando o Node Inspector
Instale via npm:
$ npm install -g node-inspector

Inicie o debugger:
node-inspector

Inicie seu app em modo debug:
$ node --debug your/short/node/script.js

Ou inicie dizendo para pausar na primeira linha:
$ node --debug-brk your/short/node/script.js

Acesse a url:
http://127.0.0.1:8080/debug?port=5858

Pronto, é só depurar no browser!

Usando o debugger do node
Inicie seu app em modo debug:
node debug meu_app

Nesse momento o debugger vai parar na primeira linha, daí em diante é só depurar. Segue alguns comandos:
cont, c - Continue execution
next, n - Step next
step, s - Step in
out, o - Step out
pause - Pause running code (like pause button in Developer Tools)

É possível também monitorar o valor de variáveis:
watch( "nome_da_variavel")

Desta forma, a cada passo que for dado, ele vai imprimir no console o valor das variáveis observadas.
É possível também escrever expressões, basta usar o comando repl e digitar as expressões. Para voltar digite Ctrl + C.
Consulte a documentação para ter mais detalhes sobre os comandos.
Comment: É realmente simples de fazer e dá um ganho imenso na produtividade ao depurar uma aplicação node.
Answer: Além do próprio debugger do node recentemente lançaram o Node.js Tools for Visual Studio.
o add-on parece promissor e, na minha opnião, o Visual Studio é uma das melhores IDE para debugar que existem... recomendo dar uma olhada.
Answer: O Node tem um debugger, que você roda assim:
node debug myscript.js

Answer: Eu uso as IDE's da JetBrains para Java, Ruby e Node.js (utilizo o plugin do Node no RubyMine). Então costumo utilizar o debugger na própria IDE. http://www.jetbrains.com/webstorm/webhelp/running-and-debugging-node-js.html

Depurar aplicações em NodeJS


Compose Preview Broken in Android Studio Bumble Bee

Question: I have the latest 2021.1.1 Patch 2 and latest Compose libraries, have been trying many things but keep getting an exception in the Compose Preview Window.
I'm getting The red "The project needs to be compiled successfully " message
and when clicking on Info I get the below exception.
I've tried downgrading ui-tooling dependency but nothing seems to work.
What is strange is that JetSnack project Preview is working, I've spent a day copying all the versions to my project but nothing seems to work, any ideas?
java.lang.ClassNotFoundException: android.view.OnBackInvokedCallback
at com.android.tools.idea.rendering.classloading.loaders.DelegatingClassLoader.findClass(DelegatingClassLoader.kt:81)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:589)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at com.android.tools.idea.rendering.classloading.loaders.DelegatingClassLoader.loadClass(DelegatingClassLoader.kt:65)
at androidx.compose.ui.tooling.ComposeViewAdapter$FakeOnBackPressedDispatcherOwner$1.<init>(ComposeViewAdapter.kt:738)
at androidx.compose.ui.tooling.ComposeViewAdapter.<init>(ComposeViewAdapter.kt:737)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:352)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:189)
at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:149)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:301)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:417)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:428)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:332)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
at android.view.LayoutInflater.inflate(LayoutInflater.java:663)
at android.view.LayoutInflater.inflate(LayoutInflater.java:505)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:361)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:436)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:121)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:736)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$7(RenderTask.java:892)
at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:187)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)

these are related dependencies from gradle, I'll be happy to provide more info if required:
implementation "androidx.core:core-ktx:1.7.0"

//current compose_version is 1.1.1
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation "androidx.compose.ui:ui-tooling-data:$compose_version"
implementation "androidx.compose.runtime:runtime:$compose_version"

implementation "androidx.activity:activity-compose:1.6.0-alpha01"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.0-alpha05"
implementation "androidx.navigation:navigation-compose:2.5.0-alpha03"
implementation 'io.coil-kt:coil-compose:2.0.0-rc02'

Answer: Had the same issue and I changed this dependency:
implementation "androidx.activity:activity-compose:1.3.1"

Found here:
https://stackoverflow.com/a/68499790/3465420


Change subnet with bash script

Question: I'm looking to change every instance of 192.168.XXX in a file to 192.168.yyy. in a network config file using a bash script. The thing hanging me up is that I don't know for sure what xxx is going to be. For example it could be 192.168.122.1 or 192.168.123.1.  Also it could be 192.168.122.2 or 192.168.122, etc. I think this can be done with one command.
Here is the default network file:
    <network>
      <name>default</name>
      <bridge name="virbr0" />
      <forward/>
      <ip address="192.168.122.1" netmask="255.255.255.0">
        <dhcp>
          <range start="192.168.122.2" end="192.168.122.254" />
        </dhcp>
      </ip>
    </network>

Comment: The accepted answer (from sudo_o) doesn't quite work.  For example, with `fip 192.168.247 192.168.73.1 192.168.188.13 192.168.123` in file t1, command `sed 's/192.168.[0-9]*\.\([0-9]*\)/192.168.15.\1/' t1` produces `fip 192.168.247 192.168.15.1 192.168.188.13 192.168.123` while my answer produces `fip 192.168.15 192.168.15.1 192.168.15.13 192.168.15`
Comment: @jwpat7 you are mistaken. The op asks to change only the 3 portion of IP address and provides an example of the files he needs to change. You have misunderstood, you can't have an IP address in format aaa.bbb.ccc so your point is moot.
Comment: @sudo_o, question says: "Also it could be 192.168.122.2 or 192.168.122".  Re 3-group form see link at end of my answer
Answer: The following sed one liner will change the 3rd portion of an IP (to 15 in this example) and leave the other 2 or 3 portions unchanged.
sed -r 's/192\.168(\.??[0-9]*){2}/192.168.15\1/g'
Output:
192.168.0.12
192.168.15.12

192.168.25.34
192.168.15.34

192.168.0
192.168.15

So to change all the IP's from 192.168.XXX.YYY to 192.168.15.YYY or 192.168.XXX to 192.168.YYY  in network.conf run
sed -r 's/192\.168(\.??[0-9]*){2}/192.168.15\1/g' network.conf
This will display the file to stdout with the changes, if you are happy with the changes use the -i option to save the changes to the file.
sed -r -i 's/192\.168(\.??[0-9]*){2}/192.168.15\1/g' network.conf
Just remember to change 192.168.15.\1 to 192.168.XXX.\1 where XXX is the actual number you need (not 15) and change the filename also (from network.conf).
Comment: FYI double quotes:     sed -e "s/192.168.[0-9]*\.\([0-9]*\)/192.168.${NEW_RAND_SUBNET}.\1/" ${FIREWRULE}
  cat ${FIREWRULE} | sed -e "s/192.168.[0-9]*\.\([0-9]*\)/192.168.${NEW_RAND_SUBNET}.\1/"
Comment: Just realized it's not changing the second one "192.168.122.254"... Any ideas?
Comment: Yes sed only replaces the first match on each line, to replace all matches on a line we need to use `/g`. This is how you need your command `sed -e "s/192.168.[0-9]*\.([0-9]*)/192.168.${NEW_RAND_SUBNET}.\1/g" ${FIREWRULE} cat ${FIREWRULE} | sed -e "s/192.168.[0-9]*\.([0-9]*)/192.168.${NEW_RAND_SUBNET}.\1/g"`
Comment: Made match lazy to fit both 3 portion and 4 portions IP, still a one liner and doesn't replace `192.168.0junk` with `192.168.15junk` like jwpat7 answer does.
Answer: The sed command
NEWIP=YYY
sed "s/192\.168\.[0-9]*/192.168.$NEWIP/g" filename

(with some number in place of YYY) will change 192.168.XXX to 192.168.YYY, and by doing that will change forms 192.168.XXX.ZZZ to 192.168.YYY.ZZZ as well.  The g in s/.../.../g says to change all of the matches on a line, instead of just the first.   As shown, it will output the result on stdout.  If you want to edit a file in place, use the -i switch:
sed -i "s/192\.168\.[0-9]*/192.168.$NEWIP/g" filename

If you want to edit a file in place after making a backup of the original with extension ~, you can say:
sed -i~ "s/192\.168\.[0-9]*/192.168.$NEWIP/g" filename

Note, changing entries of form 192.168.122 (ie entries which have three parts instead of four) was done as requested in question; however, a change like that does not necessarily make sense.  As noted in LarsH's answer to  Why does pinging 192.168.072 (only 2 dots) return a response from 192.168.0.58? the IP dotted form A.B.C is equivalent to A.B.0.C, and if that convention is followed it does not make sense to change 192.168.122 (with value 192.168.0.122) to say 192.168.15 (with value 192.168.0.15).
Comment: The use of the `NEWIP` variable is very clunky, plus the OP asked for a one liner which this is not. You should learn about using capture groups `s/\(^capture this line.$\)/\1/` where `\1` referred to the matched line starting with `capture this line`. I did forget the `/g` for global matching however, thanks.
Comment: who do I award, technically the previous one was correct but yours is correcter ..lol
Comment: Both can be consider *equally correct* but you should accept the first correct answer.. mine :)
Comment: @MikeQ, *upvote* any answer that you find useful.  *Select* whichever answer helps you more or has the clearer explanation.

Change subnet with bash script


Understanding this differential equation $y' = |y|^{\alpha}$

Question: I'm studying Numerical Analysis and the first example given in Suli and Mayers book on the section on initial value problems is the following -

Consider the differential equation $y' =  |y|^{\alpha}$, subject to
  the initial condition $y(0) = 0$, where $\alpha$ is a fixed real
  number, $\alpha \in (0,1)$.
It is a simple matter to verify that, for any nonnegative real number
  $c$,
$y_c(x) = (1 - \alpha)^{\frac{1}{1 - \alpha}}(x - c)^{\frac{1}{1 -
> \alpha}}$ when $c<=x< \infty$
$y_c(x) = 0$ when $0<=x< c$
is a solution to the initial value problem on the interval $[0, \infty)$.

I have not studied differential equations before so it is not a 'simple matter' for me to verify the solution to this equation. Can someone explain to me what is going on and how that $y_c(x)$ is a solution to the initial value problem? I don't see where the $x$ is 'coming from' for example...I see no $x$ in $y' = |y|^{\alpha}$.
Comment: You plug it into the equation.......
Answer: The solution to a differential equation is a function - in this case, you want to find the function $y(x)$ such that
$$\frac{dy}{dx}=|y(x)|^{\alpha}, \ \text{and} \ y(0)=0$$
Even when a function $y$ is written without explicit reference to the variable it is acting on, there's still such a variable. It's just often omitted to make the notation simpler, and shouldn't cause any problems once you're used to seeing ODEs (as you probably should be if you're doing numerical analysis).
The nice thing about differential equations (both ordinary and partial) is that, while finding a solution is in general extremely difficult, once you think have a solution, it's extremely easy to check that it is indeed a solution: just calculate as many derivatives as the equation requires, and see if they satisfy the equation.
In this case, $y(x)=(1-\alpha)^{\frac{1}{1-\alpha}}(x-c)^{\frac{1}{1-\alpha}}$ (and by using $y(0)=0$, you could find what $c$ is). Then you get
$$\frac{dy}{dx}=(1-\alpha)^{\frac{1}{1-\alpha}}\cdot\frac{1}{1-\alpha}(x-c)^{\frac{1}{1-\alpha}-1}=(1-\alpha)^{\frac{1}{1-\alpha}-1}(x-c)^{\frac{1}{1-\alpha}-1}\\=(1-\alpha)^{\frac{\alpha}{1-\alpha}}(x-c)^{\frac{\alpha}{1-\alpha}}.$$
We just have to check that this is equal to $|y(x)|^{\alpha}$, which is obvious.
Answer: There is a technique to solve first order differential equations called separation of variables. For example, if one has the differential equation $ y'(x)=y(x)^2 $, then the solution is
$$ y'(x)=y(x)^2 \implies  \frac{y'(x)}{y(x)^2} = 1 \implies \int y(x)^{-2}y'(x)\,dx = \int 1\,dx $$
$$ \implies -y(x)^{-1} = x + c \implies \frac{1}{y(x)} = c-x \implies y(x) = \frac{1}{c-x}\,.$$
$c$ is a constant which can be determined exploiting the initial condition.


How to redirect to a different URL based on node content while loading a node

Question: I have a site that uses the webforms module to gather user information. On the front page there is a list of previous submissions. Each of which has a link to view the submission (generated by Views module)
Link is like thingie.com/node/115/submission/1763
However, some users are saving the form as draft and coming back at a later date. When they get to the view page they aren't noticing they can click on the edit tab and are filling in a second submission. So we're getting 'weird' duplicates and they're wasting time.
As the submission view node is loading I'd like to check if it is a webform; which is in draft; and they are the submitting user. If so I'd like to redirect them to
thingie.com/node/115/submission/1763/edit
I think know how to do the redirect and the test but I'm being slow and am not sure what hook to catch.
I'm about to investigate the node load hook but wondered if there was a better way.
Answer: Ah ha... and I just learnt about row and field level templating in Views... isn't views incredible?!
I followed the instructions here http://drupal.org/node/352970 and can alter the link and it's text based on the context of each row.
Super!
Answer: You should take a look at hook_init, it's the best option to make a redirect. But it's not the best option.
You should try to have 1 views with a attachment.
I de user save the webform the main view should show it. If it's a draw the attachment view should show it. And in the main views show a text like "Please finish your lead" or something similar.
Oskar


Statistical evidence that the AUC was not overfitted to the model. With N=119, C-stat = 0.81 seems optimistic. Optimism-adjusted?

Question: My data have 119 cases and we did ROC for x (continuous variable) to predict postoperative y (categorical variable) available here, we got a comment from a reviewer asking:

Please provide statistical evidence that the AUC was not overfitted to the model. With N=119, C-stat = 0.81 seems optimistic. Optimism-adjusted?

I found some answers: basically I split my cohort into train set (n=107) and test set (n=12), did 2 ROC curves and compared AUC for both using this command:
testobj <- roc.test(rocobj0, rocobj1);testobj

and this was the output
DeLong's test for two ROC curves

data: rocobj0 and rocobj1
D = 0.44822, df = 12.488, p-value = 0.6617
alternative hypothesis: true difference in AUC is not equal to 0
sample estimates:
AUC of roc1 AUC of roc2
80.26961 72.22222

Regarding the optimism adjustment, I did it using the following code copied from a blog post on cainarchaeology.
library (pROC);library (kimisc)
  auc.adjust <- function(data, fit, B){
  fit.model <- fit
  data$pred.prob <- fitted(fit.model)
  auc.app <- roc(data\[,1\], data$pred.prob, data=data)$auc # require 'pROC'
  auc.boot <- vector (mode = "numeric", length = B)
  auc.orig <- vector (mode = "numeric", length = B)
  o <- vector (mode = "numeric", length = B)
  for(i in 1:B){
    boot.sample <- sample.rows(data, nrow(data), replace=TRUE) # require 'kimisc'
    fit.boot <- glm(formula(fit.model), data = boot.sample, family = "binomial")
    boot.sample$pred.prob <- fitted(fit.boot)
    auc.boot\[i\] <- roc(boot.sample\[,1\], boot.sample$pred.prob, data=boot.sample)$auc
    data$pred.prob.back <- predict.glm(fit.boot, newdata=data, type="response")
    auc.orig\[i\] <- roc(data\[,1\], data$pred.prob.back, data=data)$auc
    o\[i\] <- auc.boot\[i\] - auc.orig\[i\]
  }
  auc.adj <- auc.app - (sum(o)/B)
  boxplot(auc.boot, auc.orig, names=c("auc.boot", "auc.orig"))
  title(main=paste("Optimism-adjusted AUC", "\nn of bootstrap resamples:", B), sub=paste("auc.app (blue line)=", round(auc.app, digits=4),"\nadj.auc (red line)=", round(auc.adj, digits=4)), cex.sub=0.8)
  abline(h=auc.app, col="blue", lty=2)
  abline(h=auc.adj, col="red", lty=3)
}

model <- glm(data$y ~  data$x, data = data, family = "binomial")
auc.adjust(data, model, B=200)

But it gave me this weird figure below in which AUC is > 1:

I should conclude that AUC was not overfitted based on the splitting of the data that I did and P value of 0.66 from DeLong's test for two ROC curves, Right?
How to fix the optimism adjusted AUC figure to get it <=1?
Answer: A single test/train breakdown, your first suggestion, is not going to work well for evaluating overfitting in your situation with only 119 cases. Separating out one test and one training set doesn't usually work well unless there are thousands of cases, as otherwise the results depend too heavily on the vagaries both of the sample from the population and the particular choice of test set out of your sample.
The second approach, based on bootstrapping, is well accepted and works well with limited data sets like yours. For each bootstrap sample you develop a model and compare the AUC on the bootstrap sample against the AUC from applying that model to the original data set. The difference is a measure of the optimism of the model that was developed on the bootstrap sample. The idea is that bootstrap sampling from your data set is like taking the original data set from the full population, so this optimism (averaged over multiple bootstrap samples) estimates the optimism in your original model.
It's not clear why your code produced such strange looking results, and coding questions per se are not on topic here. (I do note that in one place you call your data set data and in other places df.) You can avoid coding problems by using well documented statistical functions. The rms package in R, for example, provides an lrm() function to do logistic regression and a validate() function that evaluates optimism (of several measures) directly on lrm output and provides optimism-adjusted values. It might not show AUC directly, but you can get that from the $D_{xy}$ value it reports: AUC = $0.5 + (D_{xy}/2)$. The rms package is from Frank Harrell, acknowledged in the blog post you cite as the originator of this approach to evaluating and correcting for optimism.
Comment: Thanks for your invaluable input. I edited previously provided code here but it was OK in my lab computer. I followed your advice and here is the used code and output
Comment: @MohamedRahouma coding-specific questions and troubleshooting of code aren't on topic on this site. From the statistics perspective of this site, you should go with the bootstrapping-based estimate of optimism rather than the train/test approach. You can get your optimism estimate with established tools, in the `rms` package for example, and avoid the risks of such coding errors.
Comment: Thanks a lot for your invaluable help.
Answer: Cross-validation is another approach to avoid over-optimism. I ran a logistic model with your data, using 4-fold cross-validation (i.e. fit the model on 75% of the cases, and then measure the error on the remaining 25% -- then do this 3 more times).
I get a cross-validated ROC area of .788, so your .81 looks pretty accurate.  I think EdM's suggestion of using Frank Harrell's work is going to work better with the reviewers, though.
Comment: Thanks for adding in about cross validation as an extension of the single test/train breakdown approach. The `rms` `validate()` function does provide a cross-validation option to the default bootstrap. The cross validation should be extensive, though, to pass muster. Harrell notes [100 repeats of 10-fold cross-validation](https://stats.stackexchange.com/a/23045/28500) as an alternative to bootstrapping.
Comment: **Thanks a lot** I used validate ( ) and it gives the same AUC value obtained in pRROC.


Extending $\frac{f(z)}{z}$ for holomorphic f to be continuous.

Question: Define $f: D(0,1)-> C$ to be holomorphic such that$ f(0)=0$. I want to extend  $\frac{f(z)}{z}$ to be continuous on $\overline D(0,r)$ for arbitrary $0<r<1$.
My initial guess was to define:
$g(z)= \frac{f(z)}{z}$ for non-zero $z$ but extend $g(z)$ to be $0$ for $z=0$.
But if I take $\lim_{z \to 0} \frac{f(z)}{z} = f'(0)$ using L'Hopital's rule. So I think this should be the expression for $g(0)$? I wonder if:
i) L'hopital's rule is applicable to complex functions, and,
ii)Am I taking the limit incorrectly? I also do not see a use for $f(0)=0$ in my deduction so I'm rather perplexed.
Any help would be appreciated!
Answer: If $f(0)\ne0$, then the limit $\lim_{z\to0}\frac{f(z)}z$ does not exist (in $\Bbb C$). On the other hand, if $f(0)=0$, then $\lim_{z\to0}\frac{f(z)}z=f'(0)$ byt the definition of $f'$. So, extend $f$ to$$\begin{array}{rccc}F\colon&D(0,1)&\longrightarrow&\Bbb C\\&z&\mapsto&\begin{cases}\frac{f(z)}z&\text{ if }z\ne0\\f'(0)&\text{ if }z=0,\end{cases}\end{array}$$and then $F$ is continuous. In particular, if $r\in(0,1)$, the restriction of $F$ to $\overline{D(0,r)}$ is continuous.
Comment: @OP In fact, more is true. This extension is holomorphic


Vantagens e desvantagens de usar arquivos INI

Question: Poderiam me dizer as possíveis vantagens e desvantagens em usar um arquivo <code>.INI</code> para fazer a configuração de uma aplicação? Preferencialmente, aplicações PHP.
Comment: A principal vantagem é a simplicidade pois é uma operação simples em um arquivo texto , a desvantagem é que uma configuração errada podecser feita , basta ter acesso ao arquivo texto.
Comment: Sua pergunta tem 2 votos para fechar como "principalmente baseada em opiniões" (e terá 3 contando com o meu), afinal de contas o que João acha importante para usar INI no PHP pode ser algo que o Pedro não aprecie. Ou algo que a Maria considere um motivo forte para não usar os arquivos INI, a Paula pode achar que não há nada de errado. No final, tudo depende de circunstâncias específicas da sua aplicação e os requisitos envolvidos, circunstâncias e requisitos tais que você não descreveu.
Comment: Geralmente é bastante utilizado para não precisar criar mais um executável com uma configuração diferente diretamente na aplicação, assim na aplicação é apenas apontado o caminho do arquivo .INI e as mudanças podem ser feitas diretamente neste arquivo, principalmente se tratando de banco de dados, configuração específica para uma determinada empresa, ou outro parâmetro qualquer que precisa fazer uma operação diferente em um executável ou outro.
Comment: É uma aplicação php, é mais recomendável fazer em INI ou PHP (Esse arquivo ficaria com as config da database)
Comment: Relacionado: http://pt.stackoverflow.com/questions/50275/qual-a-vantagem-de-utilizar-include-de-array-vs-arquivo-de-configura%C3%A7%C3%A3o
Answer: Arquivos INI são considerados um standard. Um "padrão informal" para arquivos de configuração para software. Arquivos INI são arquivos de texto simples, com uma estrutura básica composta por secções, propriedades e valores.
Só vejo vantagens na sua utilização, mas irá sempre depender das necessidades de um projeto.
Não acho muito relevante em pequenos projetos. Mas quando trabalhamos projetos em equipe ou se existir a necessidade de outros poderem parametrizar é importante ter um standard pois simplifica e muito.
Destacaria que é totalmente independente do software, legível e simples de analisar, por isso é um formato utilizável para arquivos de configuração até com algum grau de complexidade.


background-size: cover on smaller DIVs

Question: As we all know, using background-size: cover makes the background-image automatically scale perfectly on the browser's viewport.
Although, if we apply it on a DIV that has a smaller size, say for example 100x100px, the image will still scale, not based on the container DIV but on the total browser's viewport, resulting in showing only part of the image.
Is there any workaround for this, without considering background-size: 100% 100%, which doesn't really scale it by maintaining the proportions?
The background-size: cover is very useful to have a simple resize on the fly without using JS or either server side modifications.
Thanks in advance.
Comment: Got an example? I'm pretty sure I used cover on smaller divs without any issues before. And background size can also be: 100% auto or auto 100%
Comment: I don't know why it's not working properly on JSfiddle, have a look at this: http://pastie.org/4615936
Comment: Try not using fixed :) http://jsfiddle.net/vnMeK/ btw, do you know the actual difference between cover and contain?
Comment: seems good, give a second to test it with my environment. I'll let you know so you can post it as and answer and I can mark it as accepted
Comment: GREAT! It's working! post it as answer so I can mark it :)
Answer: I'm pretty sure what you want is background-size: contain.
Comment: not working, it's almost the same as "cover", but it doesn't really fix it. Please check the pastie link on my comment above.
Answer: Copy of comment so poster can accept:
Try not using fixed :) jsfiddle.net/vnMeK
Note that not all browser support this, there is a semi working filter for IE.
Comment: Although I personally don't really care for older browsers, they should update :D

background-size: cover on smaller DIVs


Probability density of transformation of 2D normally distributed vector

Question: let (X,Y) be a 2 dimensional normally distributed vector, with X,Y~N[0,1] independently.
Let U=X$^2$+Y$^2$. find the density function f$_u$(u) for u$>$0.
Answer by book: U~exp(0.5)
I tried creating a second transformation V(X,Y) and finding f$_u,_v$ using the density transformation formula,and than getting rid of v using integral.
 All the different transformations I tried led me to the same integral, that seems to lead me closer to the answer but I can't get rid of v (integral d0esn't converge)
Thanks in advance
Answer: Hint: Find the CDF of $U$ by computing
$$P(U \leq u) = P(X^2+Y^2 \leq u) = \iint _{\{(x,y) : x^2+y^2 \leq u\}} f_{X,Y}(x,y) \ dy \ dx$$
and convert this to an integral in polar coordinates. Everything will work out to be the CDF of the exponential distribution with $\lambda = 1/2$.


If F is a functor from $C_{1} \times C_{2}$ does this equlity hold: $F(f, h \circ g) =F(f,h) \circ F(f,g)$?

Question: Lets say we have a functor $F:C_{1} \times C_{2} \rightarrow D$, where $C_{1},C_{2},D$ are catagories.
Does this equation hold for funtors: $F(f, h \circ  g) =F(f,h) \circ F(f,g)$, where $f,h,g$ are morpshism?
Comment: No. If $F$ is really a functor, then $F( (f, h) ) \circ F(f, g) ) = F( (f, h) \circ (f, g) ) = F( f \circ f, h \circ g)$. But you probably are assuming $h, g$ are composable while $f$ is not with itself. So no.
Answer: I don't think this makes sense. If you have $F(f,h\circ g)$ you need to have an
arrow $f:A_0\to A_1$ in the category $C_1$ and arrows $g:B_0\to B_1$ and $h:B_1\to B_2$ in the category $C_2$.
Then $F(f,g)$ is an arrow from $F(A_0,B_0)$ to $F(A_1,B_1)$ in $D$
and $F(f,h)$ is an arrow from $F(A_0,B_1)$ to $F(A_1,B_2)$ in $D$.
In general $F(A_1,B_1)\ne F(A_0,B_1)$ so you can't compose these arrows.
But you do have
$$F(f,h\circ g)=F(f,h)\circ F(\text{id}_{A_0},g)$$
and
$$F(f,h\circ g)=F(\text{id}_{A_1},h)\circ F(f,g).$$
Comment: Yes @espasios that is correct
Comment: So if I say $f=id_{C_{1}}$ then it would be true?


Como verificar se as propriedades do objeto window são nativas?

Question: Estou utilizando shim que modifica vários das propriedades no objeto window dos browsers.
Neste momento preciso validar se uma das propriedades especificas é nativa ou um shim. Pois os shim podem modificar a propriedade nativa.
Por exemplo:
(function () {
  var native = window.alert;
  window.alert = function (): {
    /* faz alguma coisa */
    console.log(arguments);
    return native.apply(this, arguments);
  };
})();

No exemplo podemos ver que ele não muda a funcionalidade do alert aplicando o original ao final, porém esse alert não é mais o original em outro trecho de código eu gostaria de saber se esse método é o original ou um modificado.
O alert foi usado só como fins de exemplo do problema.
Sem modificar o "shim" que não expõe mais o alert nativo, como acessar o alert nativo para comparar com o modificado e saber que a função no window não é a nativa?
Comment: Caso não esteja implementado, ele retorna false quando usando em um if().
Comment: @2madera não foi isso que eu perguntei, `alert` vai retornar verdadeiro sendo ele modificado ou nativo. Quero saber se ele é nativo ou não. Se ele existe no objeto `window` é outra coisa bem simples de resolver.
Answer: Não sei o quanto isto seria compatível com todos os browsers, mas se você converter a função para string, verá o código-fonte no caso das funções não-nativas, e uma string contendo [native code] nas nativas. Por exemplo, no caso da sua variável native (testado no console do Chrome):
native.toString(); // function alert() { [native code] }

Com base nisso, pode-se criar uma função para verificar isso:
function nativa(fn) {
    return typeof fn == 'function' && fn.toString().indexOf('[native code]') > -1;
}

Comment: Eu foquei na pergunta do título e deixei passar o mais importante, a última frase. A solução é o que o Gustavo Rodrigues postou.
Comment: +1 Cara eu posso usar essa solução no meu caso muito exclusivamente por causa de uma falha de implementação do shim que to tentando detectar, mas no IE não vai funcionar e se resolverem a dependência corretamente em uma futura versão vai acabar quebrando. O ideal era conseguir acessar o método original mesmo.
Answer: Uma função nativa irá retornar function () { [native code] } ao ser convertida para string.
var nativa = typeof funcao === 'function ' && funcao.toString().indexOf('[native code]') !== -1

Por outro lado isso não funciona caso a função Function.prototype.toString tenha sido modificada.
Você pode ter acesso a funções do javascript nativas usando outra janela (um iframe ou um popup) e ainda compará-las:
function retrieveNative(native) {
  var iframe = document.createElement('iframe');
  document.head.appendChild(iframe);
  var retrieved = iframe.contentWindow[native];
  document.head.removeChild(iframe);
  return retrieved;
}
var alertNativo = retrieveNative('alert');

Observação:
O correto é colocar no body o iframe, porém se o mesmo não foi carregado ainda, vai gerar uma exceção, colocando no head não vai carregar o iframe porém ele vai fornecer acesso ao window que é o objetivo neste caso.
Créditos ao @bfavaretto pela alteração nos comentários.
Comment: @Gabriel Você pode tentar um appendChild no head. Seria html inválido, mas se funcionar...
Comment: Não se preocupe, @GabrielGartz. Aceita a solução do Gustavo, é mais completa (Gustavo: se quiser adicionar minha sugestão no corpo da resposta, fique à vontade).
Comment: Achei a fonte, não pensei que seria tão fácil: http://stackoverflow.com/a/3108140/1850091
Comment: +1, esse hack do iframe é a única solução em certos casos.
Comment: +1 eu usei esse hack do `iframe` também, mas agora... estou tendo problema pois preciso fazer essa validação antes dele carregar do DOM, então não da pra fazer `appendChild` no `body`.
Comment: Uma observação importante sobre esse método: tudo o que vem do outro frame é completamente independente do que está no frame pai. Portanto se você pegar um construtor, como em `var obj = retrieveNative('Object')`, e comparar com o nativo, verá que são diferentes (`obj.prototype != Object.prototype`)
Comment: @bfavaretto muito boa cara funcionou e resolveu cara!!! Tenho vontade de dar accept pros dois, pois foi esforço em comum, mas como faze-lo? hehe Tem como dar accept nessa questão e mesmo assim te gratificar cara?
Comment: Fica expressa minha gratidão pela sua ideia de usar o `head` pois funcionou e resolveu o caso para todos os browsers agora, uma vez que posso comparar por string se é nativo e no iframe se ele existe no `window` padrão.
Comment: Essa função eu peguei dos meus favoritos, que tinha pego uma questão do SOEN. Podem editar a questão, ainda mais se encontrarem a fonte da função.
Comment: Já tem muitos comentários, vamos deixar como está: se formos preocupar muito com isso teremos que fazer igual o Google Analytics, pois o `document.head` pode não funcionar caso seja `<=IE8`.
Answer: Para restaurar uma função nativa, podemos usar o delete. Exemplo:
delete window.alert;

Então, aplicando isso numa função que deleta e restaura o valor inicial, podemos verificar se a função é nativa sem o hack do iframe:
function isNative(object, name) {
    var aux = object[name]; //salva o valor
    delete object[name]; //apaga a função
    var result = object[name] == aux; //se continuar a mesma é porque é nativa
    object[name] = aux; //restaura a anterior, caso não seja a nativa
    return result;
}

Teste:
console.log(window.alert, isNative(window, 'alert'));
window.alert = function() { }
console.log(window.alert, isNative(window, 'alert'));
delete window.alert;
console.log(window.alert, isNative(window, 'alert'));

Saída:

True
False
True

Jsfiddle
Nota: está técnica não funciona em alguns navegadores caso a função tenha sido definida  com a função Object.defineProperty e o parâmetro writable : false. Veja o fiddle de teste. No Chrome não houve problemas, mas no Firefox a função retornou true quando deveria ser false.
Nota 2: também não funciona se a definição da função for feito diretamente no escopo global, por exemplo:
function alert() { ... }

Comment: Boa mesmo. Só deve falhar se o shim tiver sido FDP o suficiente para sobrescrever a função com [[Configurable]]  `false`. Isso acontece se ele declarar `function alert(){}` em vez de `window.alert = ...`, ou usando `Object.defineProperty` para setar o atributo explicitamente.
Comment: Cara, maneira essa ideia, vou testar, mas acho que até o momento de fato é a melhor de todas.
Comment: @GabrielGartz Certo, faça o teste. Não sei se pode ter algum efeito colateral ou algum caso em que não funcione. Se alguém souber me informe!
Comment: @bfavaretto No Chrome [funcionou](http://jsfiddle.net/utluiz/A48x6/1/), pois ele deve ter ignorado o `writable`. No firefox não. :(
Comment: Você precisa definir o `configurable` para impedir o `delete`.
Comment: @bfavaretto Acabei de ver!
Comment: Tipo pro meu caso os shim do Polymer não usam `defineProperty` então funcionou, no Webkit, Mozilla e Opera, definitivamente é usa solução mais leve que as anteriores, porém a do @GustavoRodrigues não da pra ser enganada eu acredito...
Comment: @GabrielGartz Não é só defineProperty, `function alert(){}` já impede um delete (a propriedade é criada como não-configurável).
Comment: É que a função do @utluiz não prevê mas eu testo 2 coisas, se após o delete elas são iguais e se após o delete ela ainda existe no `window`. No caso de `alert` são diferentes mas existe nativa, no caso de `HTMLTemplateElement` não existe nativa após o delete no Opera.
Answer: Uma possibilidade é fazer um "backup" da janela antes de rodar o seu shim. Depois disso você pode comparar os valores das funções com o valor antigo do backup pra ver se houve uma alteração.
//Coloque esse código em uma tag


Proving Conditional Probability of the intersection and union

Question: I want to prove that:
$$P(A \cap B|A \cup B)\le P ((A \cap B)|A)$$
I know that
$$P(A \cap B|A \cup B) = \frac{P(A \cap B)}{P(A \cup B)}$$
I have tried using formula that consider them as subsets but seem to be going around in circles. Can anyone give me a few pointers to the theorems that would be useful?
Comment: Once again, [as in your previous question](https://stats.stackexchange.com/questions/447238), this is easy to do by drawing a Venn diagram because it clearly shows the denominator in the left fraction is no less than that in the right fraction whereas they share the same numerator.
Answer: Using the second equation that you wrote, you want to prove that
$$\frac{P(A \cap B)}{P(A \cup B)} \le \frac{P(A \cap B)}{P(A)}$$
If $P(A \cap B)=0$, then we are done. Suppose not, then this is equivalent to
$$P(A) \le P(A \cup B).$$
Try to prove this last inequality by showing that a set is another set's subset.


How to run JavaExec with out compile

Question: I run a gradle javaexec in build.gradle
task main(type: JavaExec) {
  main = 'com.gtan.Application'
  classpath = sourceSets.main.runtimeClasspath
}

this is the output result:
:compileJava UP-TO-DATE
:compileScala UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:main

i want run this javaexec without compile tasks. like:
:main

what should i do ?
Comment: Seems like [XY](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) problem.
Comment: @HardikModha thank you,this is my first question.sorry
Comment: The tasks before `main` are not executed in your example, because they are up-to-date. If this is not the case, it is only logical to execute them, otherwise you could not use **source** files as **class**path.
Answer: When you set up the classpath as the runtime classpath from the main sourceSet, you're telling Gradle that your task depends on the output from the main sourceSet. So, it will compile the main source set first, in order to ensure that the classpath is correctly set up for your JavaExec task.
The answer to your question depends on where the com.gtan.Application class is, and what classpath the application is expecting. If this class resides in the local project, under src/main/java, you won't be able to get rid of compilation, because Gradle must compile this class in order to execute it.
If the class lives in a JAR that your build depends on, for example:
dependencies {
    runtime 'com.gtan:this-example-has-what-to-run:1.0.0'
}

Then, you can change your task definition to:
task main(type: JavaExec) {
    main = 'com.gtan.Application'
    classpath = configurations.runtime
}

By setting the classpath to a configuration, Gradle does not need to perform any compilation, and you get:
$ ./gradlew main
:main

Comment: I started a service on the server through Gradle main, and the CPU was overused when the compileScala & compileJava was started. Is there any good advice?
Comment: You might want to try running with the [Gradle daemon](https://docs.gradle.org/current/userguide/gradle_daemon.html).

How to run JavaExec with out compile


Is it reasonable to calculate $P(X_1 = X_2)$ given that $X_1$ and $X_2$ are continuous random variables?

Question: To be specific, suppose $X_1$ and $X_2$ are independent exponential random variables with parameters $\lambda_1$ and $\lambda_2$; what is $P(X_1 = X_2)$?
According to section 5.2.3 of the book "Introduction to Probability Models" by Sheldon M.Ross (the 10th edition), $P(X_1 < X_2) = \frac{\lambda_1}{\lambda_1 + \lambda_2}$. Symmetrically, $P(X_1 > X_2) = \frac{\lambda_2}{\lambda_1 + \lambda_2}$.
$$P(X_1 < X_2) = \int_{0}^{\infty} P(X_1 < X_2 \mid X_1 = x) \lambda_1 e^{-\lambda_1 x}dx \\ = \int_{0}^{\infty} P(x < X_2) \lambda_1 e^{-\lambda_1 x}dx \\ = \int_{0}^{\infty} e^{-\lambda_2 x} \lambda_1 e^{-\lambda_1 x}dx \\ = \int_{0}^{\infty} \lambda_1 e^{-(\lambda_1  + \lambda_2) x}dx = \frac{\lambda_1}{\lambda_1 + \lambda_2}.$$
My Problems:

Can I now conclude that $P(X_1 = X_2) = 1 - P(X_1 < X_2) - P(X_1 > X_2) = 0$?
I am confused about the argument because of the fact that the probability that a continuous random variable will take on any particular value is zero. Is it reasonable to calculate the probability that the two variables simultaneously take on the same particular value?
If so, how to calculate $P(X_1 = X_2)$ directly, in the same way used in the calculation of $P(X_1 < X_2)$? Furthermore, can this calculation be applied to all continuous random variables?
Comment: Your confusion is more basic: given any continous random variable (say, $X$ exponential) is $P(X=x)=0$?
Comment: @leonbloy Isn't it? As I understand it, the claim that `the probability that a continuous random variable will take on any particular value is zero` is exactly about this. Do I miss or misunderstand something?
Answer:
Yes.
Yes.
Your confusion appears to be the following.  If $X_1,X_2$ are continuously distributed random variables then $X_1-X_2$ may or may not be continuously distributed.  If $X_1-X_2$ is continuously distributed then $\Pr(X_1=X_2)=0$.  If it is not continuously distributed then it can be anything.  For instance, suppose that $X_1$ has a $N(0,1)$ distribution, $Z$ has a Bernoulli (0/1) distribution with $p=0.5$ and $X_2=X_1+Z$.  Then $X_1,X_2$ have continuous distributions but $\Pr(X_1=X_2)=0.5$.
Comment: The natural thing to do would be to derive the distribution function of $Z=X_1-X_2$, i.e. $$\Pr(Z\leq z)=\int_0^z \Pr(X_1\leq z-x) f_{X_2}(x) dx$$ and then check if there is a jump at $z=0$.  In your case there isn't.
Comment: Interesting points and nice example! Never thought that the difference of two continuous random variables could be discrete; it is quite clear after your explanation. If I want to calculate $P(X_1 = X_2)$ directly, how should I go further with $P(X_1 = X_2) = \int_{0}^{\infty} P(X_1 = X_2 \mid X_1 = x) \lambda_1 e^{-\lambda_1 x}dx = \int_{0}^{\infty} P(X_2 = x) \lambda_1 e^{-\lambda_1 x}dx$?
Could I substitute in $P(X_2 = x) = 0$ directly? Is this mathematically rigorous?
Comment: What would a jump at $z = 0$ imply?
Comment: That there is a mass point at zero.  The jump is $\Pr(Z=0)$.
Answer: It can be confusing to think of an event such as $\{X_1=X_2\}$, since both sides are random; perhaps it will be easier to think about it a little differently.
Instead of considering the event that $X_1=X_2$, let's consider the (clearly equivalent) event that $X_1-X_2=0$.  Note that $X_1-X_2$ is just another random variable -- and, in particular, since $X_1$ and $X_2$ both have densities, and are independent, it is not hard to show that $X_1-X_2$ also has a density.
We can compute that density, $f_{X_1-X_2}$, explicitly by considering cases:
If $x\geq0$, then
$$
f_{X_1-X_2}(x)=\int_x^{\infty}f_{X_1}(t)\cdot f_{X_2}(t-x)\,dt=\frac{\lambda_1\lambda_2e^{-\lambda_1x}}{\lambda_1+\lambda_2},
$$
while for $x<0$ we have
$$
f_{X_1-X_2}(x)=\int_{-\infty}^{x}f_{X_1}(x-t)\cdot f_{X_2}(-t)\,dt=\frac{\lambda_1\lambda_2e^{\lambda_2x}}{\lambda_1+\lambda_2}.
$$
where $f_{X_1}$ and $f_{X_2}$ are the densities for $X_1$ and $X_2$, respectively.
But, since $X_1-X_2$ has a density, it is a continuous random variable -- and so the probability that it takes any particular value is $0$.
Comment: If you want to do that, it can be done by considering CDF's; you can show that if $A$ and $B$ are independent random variables (think $X_1$ and $-X_2$) then $C=A+B$ has CDF $F_C(z)=\mathbb{E}[F_A(z-B)]$. (The thought process is that $A+B\leq z$ if and only if $A\leq z-B$.) You could compute this, then show that it is nicely differentiable... and voila.
Comment: I notice that before computing the density $f_{X_1 - X_2}$, you first claim that it *exists*. Could you please give some explanations? As a non-mathematical student, I often tend to forget and misunderstand such rigorous things.


H264 Decoding with Apple Video Toolkit

Question: I am trying to get an H264 streaming app working on various platforms using a combination of Apple Video Toolbox and OpenH264. There is one use-case that doesn't work and I can't find any solution. When the source uses video Toolbox on a 2011 iMac running MacOS High Sierra and the receiver is a MacBook pro running Big Sur.
On the receiver the decoded image is about 3/4 green. If I scale the image down to about 1/8 of original before encoding then it works fine. If I capture the frames on the MacBook and then run exactly the same decoding software in a test program on the iMac then it decodes fine. Doing the same on the Macbook (same image of test program) give 3/4 green again. I have a similar problem when receiving from an OpenH264 encoder on a slower Windows machine. I suspect that this has something to do with temporal processing, but really don't understand H264 well enough to work it out. One thing that I did notice is that the decode call returns with no error code but a NULL pixel buffer about 70% of the time.
The "guts" of the decoding part looks like this (modified from a demo on GitHub)
<code>void didDecompress(void *decompressionOutputRefCon, void *sourceFrameRefCon, OSStatus status, VTDecodeInfoFlags infoFlags, CVImageBufferRef pixelBuffer, CMTime presentationTimeStamp, CMTime presentationDuration )
{
    CVPixelBufferRef *outputPixelBuffer = (CVPixelBufferRef *)sourceFrameRefCon;
    *outputPixelBuffer = CVPixelBufferRetain(pixelBuffer);
}

 void initVideoDecodeToolBox ()
    {
        if (!decodeSession)
        {
            const uint8_t* parameterSetPointers[2] = { mSPS, mPPS };
            const size_t parameterSetSizes[2] = { mSPSSize, mPPSSize };
            OSStatus status = CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault,2, //param count
                                                                                parameterSetPointers,
                                                                                parameterSetSizes,
                                                                                4, //nal start code size
                                                                                &formatDescription);
            if(status == noErr)
            {
                CFDictionaryRef attrs = NULL;
                const void *keys[] = { kCVPixelBufferPixelFormatTypeKey, kVTDecompressionPropertyKey_RealTime };
                uint32_t v = kCVPixelFormatType_32BGRA;
                const void *values[] = { CFNumberCreate(NULL, kCFNumberSInt32Type, &v), kCFBooleanTrue };
                attrs = CFDictionaryCreate(NULL, keys, values, 2, NULL, NULL);
                VTDecompressionOutputCallbackRecord callBackRecord;
                callBackRecord.decompressionOutputCallback = didDecompress;
                callBackRecord.decompressionOutputRefCon = NULL;
                status = VTDecompressionSessionCreate(kCFAllocatorDefault, formatDescription, NULL, attrs, &callBackRecord, &decodeSession);
                CFRelease(attrs);
            }
            else
            {
                NSLog(@"IOS8VT: reset decoder session failed status=%d", status);
            }
        }
    }

CVPixelBufferRef decode ( const char *NALBuffer, size_t NALSize )
    {
        CVPixelBufferRef outputPixelBuffer = NULL;
        if (decodeSession && formatDescription )
        {
            // The NAL buffer has been stripped of the NAL length data, so this has to be put back in
            MemoryBlock buf ( NALSize + 4);
            memcpy ( (char*)buf.getData()+4, NALBuffer, NALSize );
            *((uint32*)buf.getData()) = CFSwapInt32HostToBig ((uint32)NALSize);

            CMBlockBufferRef blockBuffer = NULL;
            OSStatus status  = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, buf.getData(), NALSize+4,kCFAllocatorNull,NULL, 0, NALSize+4, 0, &blockBuffer);

            if(status == kCMBlockBufferNoErr)
            {
                CMSampleBufferRef sampleBuffer = NULL;
                const size_t sampleSizeArray[] = {NALSize + 4};
                status = CMSampleBufferCreateReady(kCFAllocatorDefault,blockBuffer,formatDescription,1, 0, NULL, 1, sampleSizeArray,&sampleBuffer);

                if (status == kCMBlockBufferNoErr && sampleBuffer)
                {
                    VTDecodeFrameFlags flags = 0;VTDecodeInfoFlags flagOut = 0;

                    // The default is synchronous operation.
                    // Call didDecompress and call back after returning.
                    OSStatus decodeStatus = VTDecompressionSessionDecodeFrame ( decodeSession, sampleBuffer, flags, &outputPixelBuffer, &flagOut );

                    if(decodeStatus != noErr)
                    {
                        DBG ( "decode failed status=" + String ( decodeStatus) );
                    }
                    CFRelease(sampleBuffer);
                }
                CFRelease(blockBuffer);
            }
        }
        return outputPixelBuffer;
    }

</code>
Note: the NAL blocks don't have a 00 00 00 01 separator because they are streamed in blocks with explicit length field.
Decoding works fine on all platforms, and the encoded stream decodes fine with OpenH264.
Answer: Well, I finally found the answer so I'm going to leave it here for posterity. It turns out that the Video Toolkit decode function expects the NAL blocks that all belong to the same frame to be copied into a single SampleBuffer. The older Mac is providing the app with single keyframes that are split into separate NAL blocks which the app then sends individually across the network. Unfortunately this means that the first NAL block will be processed, in may case less than a quarter of the picture, and the rest will be discarded. What you need to do is work out which NALs are part of the same frame, and bundle them together. Unfortunately this requires you to partially parse the PPS and the frames themselves, which is not trivial.  Many thanks to the post here at the Apple site  which put me on the right track.
Comment: Yeah, the dreaded green slime.  It's due to missing chroma data.

H264 Decoding with Apple Video Toolkit