The gamma distribution and Poisson processes

Question: I know that the gamma distribution with parameters $k$ and $\theta$ can be used as a model for the occurrence of events. The requirement on the events would be that their occurrence is random and the mean time between them equals $\theta$ and that they belong to a Poisson process.
Now I have a question regarding the applicability of these:
I want to model a biological growth process where we think of the resulting length as random. What we do know is that the underlying processes (biochemical etc.) are Poisson processes. Is it in the context of the statement above appropriate to model the length with a gamma random variable?
Answer:
Interval between events in a Poisson process is exponentially distributed. If you skip intervals, and only count k-th event, then you get convolution of exponential r.v.'s which gives you Erlang distribution (which is a special case of Gamma distribution). Is this what you meant in the first paragraph?
If your growth process is such that it adds an iid Gamma distributed length every time, then you will get a Gamma distributed length per time (sums of Gamma r.v. with same scale is again Gamma). But this has little to do with Poisson process, I'm afraid.
Comment: Thanks, but well no, my growth process is such that a *gamma* variable is added at each time unit..
Comment: @Pegah sum of gamma r.v. is again a gamma r.v., so what is your question? You should clarify your question, I think.
Comment: The Gamma distribution is conjugate to the Poisson distribution. Perhaps this is what was meant?
Comment: So, let's say we have three interacting processes which lead together to growth. All these processes are poisson processes. I was told that in this case, I can model the growth of the length as a gamma variable since it "arises out of poisson processes", I found that a bit vague and was wondering if this modeling approach is justified..I am sorry I can not make it more precise.
Comment: @Pegah What kind of interaction are we talking here? Do you have a reference? If there's a single Poisson process that generates a unit length growth, the total growth in some time would lead to a Poisson distribution which is NOT a Gamma distribution. If there are many Poisson processes summed, it's still a Poisson distribution. It may be close to a Gamma, but then again, it is close to Gaussian as well.
Comment: Sums of gammas r.v.s are distributed gamma only if the scale parameter (equivalently, the rate parameter) are the same for all components. In that case the shape parameter of the sum random variable is the sum of the shape parameters of the components. I'm guessing everyone involved understood this already, but not everyone who reads later might have picked up on it.


When to use FLAG_ACTIVITY_RETAIN_IN_RECENTS?

Question: I am trying to familiarize myself with intent flags, and I want to understand FLAG_ACTIVITY_RETAIN_IN_RECENTS. I have read the documentation and it seems like if this flag is set when calling an Activity, if the user presses the back button or that Activity is finished(), it still remains on the stack. Is this interpretation accurate? If not, what is this flag used for?
Reference: http://developer.android.com/reference/android/content/Intent.html
Thank you in advance!
Answer:
I have read the documentation and it seems like if this flag is set
  when calling an Activity, if the user presses the back button or that
  Activity is finished(), it still remains on the stack.

No, the Activity will not remain on the stack, but its entry will be shown in the recent task list, you can click on that entry to re-launch this Activity just as you re-launch your application.
Comment: thank you for this explanation. I have a better understanding. I will experiment more with it. Cheers!
Answer: Another Usage in OverviewScreen:
If you want to retain a task in the overview screen, even if its activity has finished, pass the FLAG_ACTIVITY_RETAIN_IN_RECENTS flag in the addFlags() method of the Intent that launches the activity.
<code>private Intent newDocumentIntent() {
final Intent newDocumentIntent = new Intent(this, NewDocumentActivity.class);
newDocumentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
  android.content.Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
newDocumentIntent.putExtra(KEY_EXTRA_NEW_DOCUMENT_COUNTER, incrementAndGet());
return newDocumentIntent;
</code>
}
To achieve the same effect, set the  attribute  android:autoRemoveFromRecents to false. The default value is true for document activities, and false for regular activities. Using this attribute overrides the FLAG_ACTIVITY_RETAIN_IN_RECENTS flag


Summing infinitely many numbers: how to assign a value?

Question: If we take $S = 1-1+1-1+1-1+1-1+...$ we can show (in many different ways) that the result of the sum is $\frac{1}{2}$.

One way for example would be to add $S$ to itself but shift it along one place,
$2S =$
$1-1+1-1+1-1+...$
$0+1-1+1-1+1-...$
Clearly if we add the two 'rows' together the sum of the first 'column' is 1 and the rest if the 'columns' sum to 0 resulting in:
$2S = 1 \rightarrow S = \frac{1}{2}$
Another would be to say that the sum, $S$, results in one if you stop at an 'odd' position in the sum i.e. $S = 1-1+1$ or $S=1-1+1-1+1$ we get $S=1$ whereas if you stop at an 'even' position i.e. $S = 1-1+1-1$ we get $S= 0$.
So if we go till infinity (or arbitrarily far along the sum) the average answer will be the average of the two $S$ values, namely $\frac{1}{2}$

So now for my question(s):

How does this really work, at what point does infinity 'take over' from the normal     maths stuff.
Clearly there are no fractions on the $RHS$ of $S$ yet there is one in the answer.

I am struggling to accept the answer, because our small albeit amazing brains think on a rather small scale relative to infinity.
Thanks a lot.
Comment: But we can also show in many different ways that the result of the sum doesn't exist. For series that aren't convergent, such manipulations are dangerous, and often hard to justify (if they can be justified at all). Which method of assigning a value to that divergent series are you using?
Comment: The error in the first bullet is that you assume that the series has a value, here called $S$. The sum isn't equal to anything unless it exists.
Comment: @Surb: but if the alternate harmonic series were to be rearranged in some manner, it could attain a different value.
Comment: http://math.stackexchange.com/questions/921172/are-these-proofs-logically-equivalent/921183#921183
Comment: Or, in other words, for sums that aren't absolutely convergent, you can get any result you want.
Comment: I guess my question is, where does the disagreement between showing the sum of this series does not exist and the method shown above arise? It doesn't seem to me as if we have done something dangerous (to a large degree) in my first bullet
Comment: Your argument that you should take the average of whatever results you might get is incorrect.
Comment: @abiessu The alternate harmonic series converge to $\ln(2)$ and is not absolutely convergent.http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)
Comment: @PaulSundheim Ya I thought so... Couldn't quite remember the reasoning there, so I guess just Ignore that one.
Comment: @abiessu You're right, didn't knew that :), thanks for the info. http://en.wikipedia.org/wiki/Riemann_series_theorem Seems that a conditionally convergent series can take any real value :).
Comment: @Surb If you allow yourself to rearrange the terms, yes... I wouldn't say that's the same thing as that a conditionally convergent series can take any real value.
Comment: The sequence $(S_n)$ of partial sums is $1,0,1,0,1,0,\ldots$, which does not converge. So the series does not converge. However, there is a weaker sense in which we can assign a value to this series, namely Cesaro summation: http://en.wikipedia.org/wiki/Ces%C3%A0ro_summation Here, we form a new sequence of the *averages* of the partial sums: $T_n = (S_1 + \cdots + S_n)/n$, and $T_n$ does converge to $1/2$. One can show that any convergent series is also Cesaro summable, to the same value. But the converse is not true, as this series demonstrates.
Answer: In the usual sense, $\sum_{n=0}^\infty (-1)^n$ is defined as $\lim_{m \to \infty} \sum_{n=0}^m (-1)^n$. This limit does not exist, so the infinite sum doesn't exist.
There are a number of "regularization" techniques for divergent infinite series, which can be used to assign meaning in a certain sense to such series. They do not, however, create results which cooperate nicely with the rules of arithmetic.
Perhaps the most popular technique is analytic continuation. In this case we have a series which really does converge for certain values of a complex parameter $s$. For example, $\sum_{n=1}^\infty n^{-s}$ converges in the usual sense provided $\text{Re}(s) > 1$. It is also analytic in the parameter $s$ on the same set. This set is open, and it is a theorem of complex analysis that an analytic function on a domain $\Omega$ is determined uniquely by its values on any open subset of $\Omega$. Therefore it is natural to ask what the maximal domain of an analytic function which agrees with the sum is, and to study the extension. The extension is called the Riemann zeta function, denoted $\zeta(s)$, and it is defined for all complex numbers except $1$. In particular we have $\zeta(-1)=-1/12$, which very informally means $1+2+3+\dots=-1/12$, surprisingly.
Another popular technique which is more straightforwardly applicable to the example in the OP is Cesaro summation. This basically amounts to adding up partial averages: we replace $\sum_{n=1}^\infty a_n$ with $\lim_{n \to \infty} \frac{1}{n} \sum_{k=1}^n \sum_{j=1}^k a_j$. An equivalent expression is $\lim_{n \to \infty} \sum_{j=1}^n \frac{(n-j+1)}{n} a_j$, which may clarify what is meant by partial averages.
If the original sum converges, then the Cesaro sum will be the same, but sums like the one in the OP may fail to converge in the usual sense but still converge in the Cesaro sense. Indeed note that $\sum_{j=1}^k (-1)^{j+1} = \frac{(-1)^{k-1} + 1}{2}$. Therefore $\sum_{k=1}^n \sum_{j=1}^k (-1)^{j+1} = \lceil \frac{n}{2} \rceil$, so the relevant limit is $\lim_{n \to \infty} \frac{1}{n} \lceil \frac{n}{2} \rceil$. The partial Cesaro sums are always between $\frac{1-1/n}{2}$ and $\frac{1+1/n}{2}$ so the limit is $\frac{1}{2}$.
Answer: Remind that series like
$\displaystyle\sum_{k=0}^{\infty}t_k$
really aren't sums, but infinite sequences $(S_0,S_1,...)$, where
$S_n=\displaystyle\sum_{k=0}^{n}t_k$.
If the sequence $(S_0,S_1,...)$ is convergent, $\displaystyle\underset{n\rightarrow\infty}{lim}S_n$ exists and is denoted
$\displaystyle\underset{n\rightarrow\infty}{lim}S_n=\displaystyle\sum_{k=0}^{\infty}t_k$
The idea of limit is consistent and intuitive, but it is possible to dedicate other numbers to series (sequences) that isn't even convergent. The limit operator can be thought of as a function from convergent sequences to real numbers and in the same way one can define other functions from other classes of sequences to real numbers, as long as the functions are well defined.
Your examples has very little with sums to do, but functions like that seems to be of certain interest in science.
Answer: My answer to your questions: it doesn't work, in the conventional sense.
I am well aware that there are ways to "show" that $1-1+1-1+1-1+\dots=\frac12$. In fact, in this answer, I show that $\eta(0)=\frac12$, where $\eta$ is the alternating $\zeta$ function
$$
\eta(s)=\frac1{1^s}-\frac1{2^s}+\frac1{3^s}-\frac1{4^s}+\dots\tag{1}
$$
Plugging in $s=0$ gives the series in question.
We can also note that for $x=1$, $\frac1{1+x}=\frac12$. We can then plug $x=1$ into the Taylor series
$$
\frac1{1+x}=1-x+x^2-x^3+\dots\tag{2}
$$
and get the series in question.
However, in the conventional sense, $(1)$ does not converge when $s=0$ and $(2)$ does not converge when $x=1$ because their terms do not tend to $0$. One problem with series that don't converge in the conventional sense is that they usually fail to obey some rule of arithmetic. For example, associativity. Addition is associative, which means that we can rearrange parentheses in any way we want and still get the same answer. Consider your sum grouped as follows
$$
(1-1)+(1-1)+(1-1)+\dots\tag{3}
$$
that is
$$
0+0+0+\dots=0\tag{4}
$$
However, if we group the terms as follows
$$
1+(-1+1)+(-1+1)+(-1+1)+\dots\tag{5}
$$
that is
$$
1+0+0+0+\dots=1\tag{6}
$$
Thus, associativity fails. If you don't have associativity (and commutativity), then you can't add
$$
1-1+1-1+1-1+\dots\tag{7}
$$
and
$$
0+1-1+1-1+1-\dots\tag{8}
$$
to get
$$
1+0+0+0+0+0+\dots\tag{9}
$$


Chamar um método estático pelo nome como string no JavaScript

Question: Se eu quiser chamar uma função estática pelo nome como string, como faço?
Eu fiz o que está abaixo, suponha que o nome da função é "move".
class Transformation {
    static operate(object, function_name) {
          eval(function_name)(object);
    }
    static move(object) {... some code...}
}

Mas não funcionou.
OBS: Eu estou chamando essa função de um outro arquivo no mesmo diretório.
Comment: Traduzi a pergunta para o português. Mas fica o aviso: normalmente as perguntas que são postadas em inglês neste site são rapidamente fechadas.
Answer: Não sei se entendi direito o que você quer, mas talvez seja isso:

class Transformation {
    static operate(function_name, object) {
        Transformation[function_name](object);
    }
    static move(object) { alert("oi " + object); }
}

Transformation.operate("move", "teste");


windows store api to access metro and phone apps information

Question: May I know is there any official microsoft api for metro and phone apps which we can connect and get information about apps, downloads, publishers etc.
I think live api is only for app to connect with skydrive, hotmail or skype.
I can see lots of website providing such information on their website.
Thanks in advance.
Comment: can u please give me a website names showing app information about windowsphone apps
Answer: Hello here is a blog post I created outlining the process:
http://jasonthomascarter.blogspot.com/2013/08/the-friendly-developers-guide-to.html
Here we go! First we will start with Robots.txt file for the Windows Store website. http://apps.microsoft.com/robots.txt
Websites use robots.txt to guide web crawlers on how to behave, what they want them to see, and what they don't want them to see.
http://www.robotstxt.org/
Web Robots (also known as Web Wanderers, Crawlers, or Spiders), are programs that traverse the Web automatically. Search engines such as Google use them to index the web content, spammers use them to scan for email addresses, and they have many other uses.
In this case the Sitemaps.xml index file is what we are interested in. http://apps.microsoft.com/windows/sitemap_index.xml
http://www.sitemaps.org/
Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.
The Sitemap Index file lists out each of the individual Sitemap XML files. As of this writing, the apps.microsoft.com website has 141 individual Sitemap XML files.
Inside the individual files are thousands of URL's to the web pages of Windows Store apps. Such as this URL to the PlayTo Receiver app:
http://apps.microsoft.com/windows/en-us/app/playto-receiver/72a6ba17-2d4e-4a1c-bcfb-cdc5d4b32d0e
These webpages for the apps do include a good bit of information that we could scrape from the HTML but we can do better.... The key information we are getting here is the App ID's and which geographies those App ID's are published to in the store.
For example:
72a6ba17-2d4e-4a1c-bcfb-cdc5d4b32d0e
and en-us etc...
And now to the good stuff, there a few web services we can call using our newly found App Id's and geography information.
https://services.apps.microsoft.com/browse/6.2.9200-1/615/en-US_en-US/c/US/cp/10005001/Apps/72a6ba17-2d4e-4a1c-bcfb-cdc5d4b32d0e
There is plenty of information available through this web service but it's not clearly spelled out by the element names. Here is my interpretation of many (not all) of them to start you off.
sSubCategoryName = rawXML.getElementsByTagName('Sc')[0].getElementsByTagName('N')[0].childNodes[0].nodeValue;
sSubCategoryId = rawXML.getElementsByTagName('Sc')[0].getElementsByTagName('I')[0].childNodes[0].nodeValue;
sHasTrial = rawXML.getElementsByTagName('Try')[0].childNodes[0].nodeValue;
sDescription = rawXML.getElementsByTagName('D')[0].childNodes[0].nodeValue;
sDeveloper = rawXML.getElementsByTagName('Dev')[0].childNodes[0].nodeValue;
sWebsite = rawXML.getElementsByTagName('Ws')[0].childNodes[0].nodeValue;
sSupport = rawXML.getElementsByTagName('Sws')[0].childNodes[0].nodeValue;
sPrivacy = rawXML.getElementsByTagName('Pu')[0].childNodes[0].nodeValue;
sCategoryName = rawXML.getElementsByTagName('C')[0].getElementsByTagName('N')[0].childNodes[0].nodeValue;
sCategoryId = rawXML.getElementsByTagName('C')[0].getElementsByTagName('I')[0].childNodes[0].nodeValue;
sPrice = rawXML.getElementsByTagName('P')[0].childNodes[0].nodeValue;
sForegroundColor = rawXML.getElementsByTagName('Fg')[0].childNodes[0].nodeValue;
sBackgroundColor = rawXML.getElementsByTagName('Bg')[0].childNodes[0].nodeValue;
sAppIcon = rawXML.getElementsByTagName('Ico')[0].childNodes[0].nodeValue;
sAppName = rawXML.getElementsByTagName('T')[0].childNodes[0].nodeValue;
sPackageFamilyName = rawXML.getElementsByTagName('Pfn')[0].childNodes[0].nodeValue;
sResourceId = rawXML.getElementsByTagName('R')[0].childNodes[0].nodeValue;
sId = rawXML.getElementsByTagName('I')[0].childNodes[0].nodeValue;
sCapabilities = sCapabilities + arrCapabilities[k].childNodes[0].nodeValue+",";
sUpdate = rawXML.getElementsByTagName('Ud')[0].childNodes[0].nodeValue;
sFeatures1 = rawXML.getElementsByTagName('Dbp')[0].childNodes[0].nodeValue;
sFeatures2 = rawXML.getElementsByTagName('Dbp')[1].childNodes[0].nodeValue;
sFeatures3 = rawXML.getElementsByTagName('Dbp')[2].childNodes[0].nodeValue;
sFeatures4 = rawXML.getElementsByTagName('Dbp')[3].childNodes[0].nodeValue;
sFeatures5 = rawXML.getElementsByTagName('Dbp')[4].childNodes[0].nodeValue;
sFeatures6 = rawXML.getElementsByTagName('Dbp')[5].childNodes[0].nodeValue;
sFeatures7 = rawXML.getElementsByTagName('Dbp')[6].childNodes[0].nodeValue;
sFeatures8 = rawXML.getElementsByTagName('Dbp')[7].childNodes[0].nodeValue;
sFeatures9 = rawXML.getElementsByTagName('Dbp')[8].childNodes[0].nodeValue;
sScreenshot1 = rawXML.getElementsByTagName('Ss')[0].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot2 = rawXML.getElementsByTagName('Ss')[1].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot3 = rawXML.getElementsByTagName('Ss')[2].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot4 = rawXML.getElementsByTagName('Ss')[3].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot5 = rawXML.getElementsByTagName('Ss')[4].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot6 = rawXML.getElementsByTagName('Ss')[5].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot7 = rawXML.getElementsByTagName('Ss')[6].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot8 = rawXML.getElementsByTagName('Ss')[7].getElementsByTagName('U')[0].childNodes[0].nodeValue
sScreenshot9 = rawXML.getElementsByTagName('Ss')[8].getElementsByTagName('U')[0].childNodes[0].nodeValue
sCaption1 = rawXML.getElementsByTagName('Ss')[0].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption2 = rawXML.getElementsByTagName('Ss')[1].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption3 = rawXML.getElementsByTagName('Ss')[2].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption4 = rawXML.getElementsByTagName('Ss')[3].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption5 = rawXML.getElementsByTagName('Ss')[4].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption6 = rawXML.getElementsByTagName('Ss')[5].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption7 = rawXML.getElementsByTagName('Ss')[6].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
sCaption8 = rawXML.getElementsByTagName('Ss')[7].getElementsByTagName('Cap')[0].childNodes[0].nodeValue
There is more to the Windows Store than just apps, there are also reviews, and lots of them. There are currently over 210,000 reviews for apps in the Windows Store. These reviews come from all over the world, so you'll need some country codes, your handy dandy App Id's and pay attention to the pn/1 at the end, you will find that this service only returns 10 reviews per page, just increment this value to pn/2, pn/3 etc.. until you run out of reviews.
var arrCounntryCodes = ["AE", "AR", "AT", "AU", "BE", "BG", "BH", "CA", "CH", "CL", "CN", "CO", "CR", "CY", "CZ", "DE", "DK", "DZ", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "HK", "HR", "HU", "ID", "IE", "IL", "IN", "IQ", "IT", "JO", "JP", "KW", "KZ", "LB", "LK", "LT", "LU", "LV", "LY", "MA", "MT", "MX", "MY", "NL", "NO", "NZ", "OM", "PE", "PH", "PK", "PL", "QA", "RO", "RS", "RU", "SA", "SE", "SG", "SI", "SK", "TH", "TN", "TR", "TT", "UA", "US", "UY", "VE", "VN"];
https://services.apps.microsoft.com/4R/6.2.9200-1/1/en-US/m/US/Apps/f514d64b-8705-43b7-a400-c4f4f3dedfc0/Reviews/all/s/date/1/pn/1
This one is much more descriptive with the element names, so I don't see any need for further explaination of this. You can see the full name, display name, the image the user has chosen to represent themselves with.
Next up we can do a little bit of seaching...
https://services.apps.microsoft.com/search/6.2.9200-1/615/en-US_en-US/m/US/c/US/il/en-US/cp/10005001/query/cid/0/pf/1/pc/0/pt/x64/af/0/lf/0/s/0/2/pn/0?phrase=Software Developer
Here it gets a little cryptic again, but by now you should be used to it. You can get the App ID from the I element and take it from there back to the browse service f514d64b-8705-43b7-a400-c4f4f3dedfc0
So there you have it, the basics of pulling tons of information out of the Windows Store that you can then do what you please with. If you find this useful and/or make some apps utilizing the information, have some additional information to share or otherwise please let me know in the comments
Answer: There is no such API for retrieving data. If you want to provide such information, you would have to scrape the data directly from the website and then keep it yourself. Sites that do similar things already do something like that.
Comment: it means i need to parse the html to get required data ??
Comment: Yes, you need to download all information from http://www.windowsphone.com/ yourself.
Comment: in this case we need login credentials and need to parse html page using java script
Comment: You don't need any credentials. Why do you need javascript for parsing? You can do that in C++, C# or any other language.
Comment: usually that information is visible after login only so i think like that where can i get app downloads, crash count etc can u please help me
Comment: Oh, you want to fetch developer page? There is no API for doing that. You can fake it using WebRequests, but it is going to be tough if you are not familiar with that.
Comment: hmmmmm how can i make fake WebRequest ?? am new to C#, WP7 can u please give me some points about that
Comment: Not in the small space here in comments. Google it :)
Answer: You can do as so in windows phone8 apps,
Just upgrade your app to wp8 and use this link Windows.ApplicationModel.Store namespace access app information in market place.
Hope this will help you.
Answer: Install Fiddler, configure it so the store can connect localhost (win8 config). Now trace the Windows store web traffic and you will see the URLs that the Windows store is using like:
https://services.apps.microsoft.com/4R/6.2.9200-1/615/nl-NL.nl.en-GB.en/m/NL/Apps/4bd603d9-21da-4282-a689-b2a4f384717e/Reviews/all/s/date/1/pn/2
Answer: You could consider using a free API by third parties such as http://www.appfeds.com/general/api/


Sum and average length of constrained chords

Question: This question:
Sum and average length of chords (1)
has already been sufficiently well answered, and What is the average length of 2 points on a circle, with generalizations (2) seems to be the same question, but malformed, although the responses seem to indicate the same results as (1).
However, if the end points of the chord are constrained, for example, if all the chords are constrained to be vertical, and no other chords are allowed, then how does one estimate the average length of chords constrained in such a manner using geometric probability? Are there any textbooks or references for this?
Answer: So, I finally got around to doing this.
One has to use the formula for length of a chord given its distance to the center. The average length of a constrained chord (l) of a circle of radius (r), given its distance from center (h) varying from 0 to r is:
$$\ l = {\int_0^r 2{\sqrt{r^2-h^2}}dh\over{r}}$$
Averaged over r, the integral is:
$$ l = {\biggl[h\sqrt{h^2-r^2}+r^2tan^{-1}\Bigl(\frac{h}{\sqrt{h^2-r^2}}\Bigr)\biggr]_0^r\over{r}} $$
After applying the limits, and since, $tan^{-1}$ of large numbers is $\pi/2$,  the average length of a vertical (or horizontal chord) would be:
$$\ l = {\pi\over2}r$$
For a unit circle this would be: 1.57. I used a CAD software and very painstakingly verified this as well.
Answer: Consider the unit circle $\rho=r$ in polar coordinates.
the generic vertical chord is $AB=2r \sin\theta$
The average chord is
$$x=\frac{1}{\pi}\int_0^{\pi } 2 r \sin \theta \, d\theta=\frac{4r}{\pi}$$
In the unit circle the average vertical chord is $1.27324$
Looks weird :)
Comment: The formula for a chord is the same whether it is vertical or not, result proposed is same as ref (1). Here, once the 1st point is selected, the other point is constrained to be at a particular location only (since the chord has to be vertical). So average chord should be larger than 1.27324 for a unit circle. I get 4, dividing by pi may not be required, but that cant possibly be correct? I'll try to do this problem "numerically", i.e. draw vertical chords with uniform spacing, measure the lengths and converge on a result. This is an application related to tribology (chords are lines of wear).
Comment: I've come up with an answer that seems to work, your inputs would be appreciated.


VS2008 Team Edition Code Metrics - Skip Generated Code?

Question: According to this blog the build in code metrics feature in VS2008 Team Edition is suppose to be smart enough to skip generated code.  It's not.  Is there an option somewhere that I need to set?
Comment: **MUST NOT RANT ABOUT HOW MEANINGLESS CODE METRICS ARE**

Gahhh
Comment: Agree.  What I really want is a line count so instead of saying "project x is big", I can say "project X is 50,000 lines of custom code". Helps people visualize it better.
Comment: ...the metrics include line counts. Which is what I'm looking for.
Answer: There are a few tags that affect this, depending on the source (MSDN/blogs/...)

CompilerGenerated
ToolGenerated
GeneratedCode
DebuggerNonUserCode

I'm not sure which of these works best in your case, but iirc I was able to get the metrics working right using one of these. Let me know how it worked out in your case.
Answer: The real answer to this question is I gave up. :-) After messing with it a bit I got the distinct impression that the code metric feature was mostly a marketing stunt for Team System and nobody really invested in making it work well. I hope that changes in 2010--while metrics can be misused they can provide valuable insights as well.
Comment: P.s. Thanks for taking the time to comment on such an old question.  +1 vote!


Solve PDE subject to two conditions

Question: Consider the following PDE for $u(x, y)$
$u_x + 2√yu_y = 0$
which is defined for $y>0$
Solve the PDE in the domain $Ω$ = {$(x, y) : x > 0, y > 0$} subject to the condition $u(x, 0) = f(x)$ and  $u(0, y) = g(y)$ for
some given functions $f$ and $g$
Ok, so I have found the characteristic curves to be described by
$x −√y = c_1$
I have asked a previous question which was similar, but had only one condition and managed to find the correct answer. I am having problems now that there are 2 conditions and could use some guidance on how to tackle this.
Answer: The method of characteristics leads to the general solution of the PDE, with any differentiable function $F$ :
$$u(x,y)=F(x-\sqrt{y})$$
First condition, in $x>0$ :
$u(x,0)=f(x)=F(x-0) \quad\to\quad F(X)=f(X) \quad\text{in domain }\quad X>0$
Hence with $X=x-\sqrt{y}$ , the solution of the PDE according to the first condition is :
$$u(x,y)=f(x-\sqrt{y})\quad\text{in domain }\quad x-\sqrt{y}>0$$
Second condition, in $y>0$ :
$u(0,y)=g(y)=F(0-\sqrt{y}) \quad\to\quad F(-\sqrt{y})=g(y)\quad\text{in domain  }y>0 $
With $X=-\sqrt{y}\quad$ :   $\quad F(X)=g(X^2)\quad\text{in domain  }X<0$
Hence with $X=x-\sqrt{y}$ , the solution of the PDE according to the second condition is :
$$u(x,y)=g\left((x-\sqrt{y})^2\right)\quad\text{in domain }\quad x-\sqrt{y}<0$$
The solution of the PDE in domain $(x>0\:,\:y>0)$according to the tw0 conditions is :
$$u(x,y)=\begin{cases}
f(x-\sqrt{y}) &\text{if}&  x>\sqrt{y}\\
g\left((x-\sqrt{y})^2\right) &\text{if}&   x<\sqrt{y}
\end{cases}$$
Comment: Thanks for the clear solution. I managed to get most of the way but I wasn't confident enough to commit that I had it correct. Thank you!

Solve PDE subject to two conditions


null reference with and if statement c#

Question: I am just want to check for empty text boxes and change the text the boxes if they are null in RowEditing event. I just can't figure this out. Of course the some of the boxes will be empty when the Grid is populated. The other question is am I placing this in the right event?
Here is the row editing event :
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    fill_grid();

    //Set the edit index.
    GridView1.EditIndex = e.NewEditIndex;
    //Bind data to the GridView control.
    check_grid_boxes();
    GridView1.DataBind();
}

Here is the check_grid_boxes Method :
protected void check_grid_boxes()
{
    if (gtxtLane.Text == "")
    {
        gtxtLane.Text = "0";
    }
    else if (gtxtCarriers.Text == "")
    {
        gtxtCarriers.Text = "0";
    }
    else if (gtxtREV.Text == "")
    {
        gtxtREV.Text = "0";
    }
    return;
}

Before you mention Java Script or Jquery. This is a web control and my attempts at using java has not worked.
I changed my code to this :
  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            fill_grid();
            GridView1.EditIndex = e.NewEditIndex;

            var lane = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtLane");
            var car = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtCarriers");
            var badcar = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtBadCarriers");

            if (String.IsNullOrEmpty(lane.Text))
            {
                lane.Text = "0";
            }
            else if (String.IsNullOrEmpty(badcar.Text))
            {
                badcar.Text = "0";
            }
            else if (String.IsNullOrEmpty(car.Text))
            {
                car.Text = "0";
            }
               GridView1.DataBind();
         }

Comment: What line is raising the exception?
Comment: Looks like those input elements are in a row in a GridView, correct?  If so, you can't access them via their ID like you are trying, since _each_ row has those elements.
Comment: You don't need to `return` anything in a `void` method.
Comment: I know this will sound pedantic, but I think you mean JavaScript not Java. Similar names, two vastly different things.
Comment: Is `.Text` null or are things like `gtxtLane` null? If it's the first, you're looking for `String.IsNullOrEmpty(gtxtLane.Text)`... (presuming that the empty fields might not be empty strings, but are actually null values...)
Comment: The check_grid_boxes method is throwing the exception. I was thinking the way I close the If statements is is wrong with just using return?
Comment: But in that case, `gtxtLane` shouldn't be predeclared. @briskovich, did you add fields for `gtxtLane` and others yourself?
Comment: There is a difference between an `Empty` string and a `Null` string. Your code is only checking to see if the string is empty. Your question and the problem you are trying to solve is not clear.  It sounds like you need to debug this problem a great deal more.
Comment: @hvd - these are item template fields in a gridview that I programmed by hand. I think the problem is calling them by name as Gromer suggested.
Answer: You must get a reference to the TextBoxes that are inside that row being edited like this:
GridView1.EditIndex = e.NewEditIndex;

TextBox gtxtLane = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtLane");

Comment: I still get the null reference error. Object not referenced to an instance of an object.
Comment: Do this: `if(lane != null && String.IsNullOrEmpty(lane.Text))`. Your problem is that it's not finding the control in the grid row. See if the name of the textbox inside the grid is correct...
Comment: Did you try what Max answered here http://stackoverflow.com/a/12959735/114029? Add this to your HTML markup in each textbox: `nulldisplaytext="0"`
Comment: Yep I tried that but it did not work. This was a real head scratcher. So I just decided to change my select query and the problem was solved. I also tried the find control method with and if statement but the statement but that would not work either. So the isnull was the way to go and everything is working and off my desk.
Answer: DUH!!!! how bout --> select isnull(lane,'0') as Lane <---. I can't believe I didn't think of that!! 6 hours wasted!!
Answer: You could use the nulldisplaytext property of the gridview
<asp:boundfield datafield="discounttype"
            nulldisplaytext="0"
            headertext="Discount Type"/>

Answer: I'm guessing you're getting a reference problem, because the compiler doesn't know where to get gtxtLane and the rest from. Remember that each row in the grid has its own version of these controls, so you will need to reference them directly. You can use FindControl on the row object. You can get a reference for the row object from GridViewEditEventArgs. Your code will look something like this (e refers to GridViewEditEventArgs)
var gtxtLane = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtLane");
if (gtxtLane.Text == "")
{
    gtxtLane.Text = "0";
}

e.NewEditIndex gets you the index of the row being edited, we use that to get the row object from the gridview, then we find the wanted control, and cast it to TextBox, then use it. Rinse and repeat.
Comment: I thought about this very thing but was trying this. I didn't think about how the controls are rendered by the compliler. This makes a lot of sense. I was having the same problem with the update statement and had to use FindControl to add the boxes as parameters.
Comment: @briskovich - You'll run into this sort of thing with all repeater style controls. So it's a good trick to know.
Comment: I made the changes but still get the null reference. Check the edit.
Comment: @briskovich - Which part is giving you the null reference? gtxtLane?
Comment: @briskovich - Yeah I saw that, but I still don't know which statement threw the exception.

null reference with and if statement c#


Is it bad practice to look at hands when practicing piano? How to break the habit?

Question: I've been playing piano for over 13 years and mostly did this by learning the pieces by heart when studying, because when I play, I usually look at where my hands are going (especially for left handed jumps or strides). Never had any remarks about this.
I do realise now, that for sightreading and learning new pieces, this becomes an issue as you can't both look up at the sheet music while looking at the keys.
How should I practice breaking this habit? I could just force myself not to look at the keys when practicing, but I'd mostly be butchering the piece and the actual practice.
Do professional pianists not need to look at keys when doing jumps and strides?
Comment: Lots of practice helps develop muscle memory. After a while, even octave plus movements become second nature. No need to look at the gearstick when changing? Same idea.
Comment: I sometimes practise in the dark.
Comment: It's as bad as looking at a computer keyboard when you type.
Comment: Can you clarify? Are you wanting to not look ever, or not look when making jumps/strides... or both? If you play music that doesn't have large leaps, do you still look at your hands all the time?
Comment: Related question: [Is there any evidence that suggest not looking at your hands increases ability to sight read on the piano?](/q/63252/1941)
Comment: learn to play something slowly and correctly and not look. If you make a mistake go back to the beginning. Speed will come. I do not look at my bass neck, except when learning something,
Answer: I've been playing professionally for many years and have always had to look at my hands for stride piano, though that wasn't my specialty. Nevertheless, I have a hard time believing that all but the very best stride pianists must look at their left hands pretty regularly.
That being said, when an accomplished jazz pianist I was taking lessons from several years ago challenged me to play my scales without looking, I was shocked that I kept missing my thumb tuck, no matter the scale. Turns out I had never gained a feeling in my hands for the tuck of a close note (i.e. F# -> G in G maj in RH) as opposed to that of a note away (Bb -> C in F maj RH). I was subconsciously relying on my sight to play it correctly. A few weeks of dedicated practicing resolved the problem and changed my habit, but it was unnerving nevertheless.
In your case, and for players in general, my rule-of-thumb advice is that you should be able to play without looking as long as your hands aren't changing positions drastically. I think it's always normal to look down quickly if you're moving a 5th or so without anything between.
If you are butchering your pieces, as you say, when attempting to play without looking at your hands then you need to slow it down in to the zone where you are playing correctly. (You'll probably clean up a few other things in the side!) Although this is excruciating at first, make yourself stay slow and only speed up only once you're satisfied with how you're doing. It will go by quickly in the end, and your skills and performance will improve.
Comment: Even Mrs Mills, who specialises in stride, looks at her left had from time to time, though clearly she doesn't need to. https://youtu.be/MSf5uMB0eL0?t=126
Answer: Get 1st- or 2nd-level piano music, especially stuff that doesn't require you to move your hands, and start there. If you find that you have trouble not looking down at your hands, lay a blanket over your hands when you play.
Gradually work your way up to harder and harder music with the understanding that once you get to music where your hands are moving a lot, you're going to need to glance down unless you become an expert piano player, and even then, not necessarily.
Answer: I'd love to find something that wraps around your hand and blocks view of your fingers, for kids' practice. You know, those simple songs where your hand never moves. It builds trust that your hands are in the right place so you can actually concentrate on the written music.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://music.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://music.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/75659)
Answer: If the piece is slow enough, you can get corroboration about your hands' location from feeling the black keys versus white keys... Even in faster tempos, feeling the adjacent keys when your hands "land" after a jump can be a reassurance.


Returning generic type from cypher query

Question: I'm creating an asp.net web api.  Many of the routes all do the same thing, just with different node objects.  I'd like to create a base model from a BaseRepository class and simply have the child class cast and return the object(s).
For example.  GET api/{controller}
The only thing that changes in this cypher query is the Label of the node which is easily provided as a parameter.
I've tried many, many ways to do this such as.
var query = client
            .Cypher
            .Match(string.Format("(node:{0})", label))
            .Return(node => node.As<Node<object.GetType()>>())
            .Limit(10)
            .Results;

But the lambda will not accept that.  I've tried
.Return(node => node.As<Node<string>>())

and converting it to the object type and dynamic but it says I can't do that either.
Is there anyway to do what I'm trying here or maybe another avenue could be suggested so that I don't have to write dozens of GET api/{controller} methods exactly the same way?
Thanks!
Answer: I have taken a similar approach in some solutions by using generics. Do your types match your labels? If so I wonder if this approach can go some way to solving your issue?
public T GetNode<T>(Guid nodeId)
{
    // derive the label from the type name
    var label = typeof(T).Name;
    // now build the query
    var query = client.Cypher
        .Match(string.Concat("(node:", label, " { nodeid : {nodeid} })"))
        .WithParams(new { nodeid = nodeId })
        .Return(node => node.As<T>())
        .Limit(10)
        .Results;

    // now do something with the results
}

Obviously this is using a schema index to search for a specific node but you could omit that part, e.g.
    // derive the label from the type name
    var label = typeof(T).Name;
    // now build the query
    var query = client.Cypher
        .Match(string.Concat("(node:", label, ")"))
        .Return(node => node.As<T>())
        .Limit(10)
        .Results;

    // now do something with the results

Any mileage in this?
Comment: You are spot on man(or woman), that worked perfectly!  I can't thank you enough!


Univariate clustering of time series

Question: I just want to know if its possible to cluster an univariate time series, in order , say, to detect anomalies?
and do you have any online version for denstream code, in Matlab?

here is the time series

+0003;+0004;+0004;+0005;+0004;+0004;+0004;+0003;+0003;+0004;+0003;+0002;+0004;+0002;+0002;+0002;+0002;+0002;+0002;+0005;+0004;+0004;+0004;+0004;+0004;+0004;+0004;+0004;+0004;+0004;+0004;+0005;+0004;+0004;+0004;+0004;+0003;+0003;+0000;+0002;+0004;+0002;+0004;+0004;+0004;+0004;+0003;+0003;+0004;+0003;+0002;+0000;+0003;+0002;+0003;+0002;+0002;+0002;+0002;+0002;+0003;+0002;+0002;+0003;+0000;+0003;+0003;+0002;+0003;+0002;+0003;+0002;+0004;+0004;+0004;+0003;+0004;+0004;+0004;+0004;+0004;+0005;+0004;+0002;+0003;+0002;+0005;+0004;+0003;+0003;+0001;+0005;+0003;+0003;+0005;+0005;+0004;+0005;+0002;+0005;+0005;+0006;+0005;+0005;+0004;+0003;+0003;+0005;+0002;+0002;+0001;+0003;+0004;+0002;+0002;+0002;+0001;+0001;+0003;+0004;+0004;+0004;+0005;+0004;+0005;+0002;+0002;+0005;+0003;+0002;+0003;+0002;+0001;+0002;+0003;+0005;+0004;+0005;+0004;+0004;+0003;+0003;+0004;+0005;+0003;+0004;+0005;+0004;+0005;+0003;+0003;+0005;+0005;+0005;+0003;+0002;+0004;+0004;+0004;+0005;+0005;+0004;+0005;+0005;+0004;+0004;+0003;+0003;+0005;+0005;+0005;+0005;+0004

First you should now @IrishStat, that i should use a datamining technique for clustering,
an exemple of times serie dataset is presented in this :
What i'm using now , is a density base clustering,
let's said that I have adapte the Dbscan for streaming Time series points, and its Should detect anomalies, and changes eacht time,
after your introdudction , i'll trying to explain to u by pictures what i'm doing,
thanks u ,
time data series sample :
<code>     [,1]
V1    3.0
V2    4.0
V3    4.5
V4    5.0
V5    4.0
V6    4.0
V7    4.4
V8    3.0
V9    3.0
V10   4.0
V11   3.0
V12   2.0
V13   4.0
V14   2.0
V15   2.0
V16   2.0
V17   2.0
V18   2.0
V19   2.0
..... so on
</code>
Answer: I would approach this problem from a robust filtering point of view, as is done for real time curve monitoring. There is a German team that has worked extensively on this and related problems such as filtering, shift detection etc. --see these papers here, here and here for example--
They also have an R package were most of these algorithm are implemented in C++ and in their "on-line" versions. Check the codes in the robfilter package.
Fried R., Bernholt, T. Gather, U. (2006), Repeated median and hybrid filters, Computational Statistics & Data Analysis 50(9), 2313-2338
Fried, R., Gather, U. (2007), On Rank Tests for Shift Detection in Time Series, Computational Statistics and Data Analysis, Special Issue on Machine Learning and Robust Data Mining 52, 221-233.
Gather, U., Schettlinger, K., Fried, R. (2006), Online signal extraction by robust linear regression. Computational Statistics 21, 33-51.
Schettlinger, K., Fried, R., Gather, U. (2006), Robust Filters for Intensive Care Monitoring: Beyond the Running Median, Biomedizinische Technik 51(2), 49-56.
Comment: Thank you so much for this information,
recently , i've tried to use , DBSCAN clustering algorithmg (with some modification in code)  for detection anomalies in Times series signal, FYI : the anomalies in this signal is a jum from a normal stat to abnormal )
anyway! i WILL read this articals now, hoping, find what i'm looking for,
Answer: Univariate clustering is another way of looking at Intervention Detection. Unusual values (anomalies) can arise as Pulses , Seasonal Pulses or Level Shifts ( a contiguous sequence of anomalies having the same same sign and magnitude ). Consider the airline series where the anomalies are not visually obvious. A histogram of the original series  and the histogram of the anomalie-cleansed series is informative. . In order to detect the statistically significant anomalies  it was necessary to have a model (Note: There is no need for a logarithmic transformation as the variance of these errors is homogenous ) which yielded the following ACF for the error term . In many cases there are level shifts ( distinctly different means ) waiting to be discovered. For example the Nile Series (annual data for 100 years) is a series that illustrates this  and . The histogram of the original series is  naively suggests just two pulses (low values) while a model containing the empirically identified level (mean) shift generates the following analysis with model  detailing the step (level ) shift and the one-time pulses . Bacon summarized this, writing in Novum Organum about 400 years ago said:
"Errors of Nature, Sports and Monsters correct the
understanding in regard to ordinary things, and
reveal general forms. For whoever knows the ways
of Nature will more easily notice her deviations; and,
on the other hand, whoever knows her deviations
will more accurately describe her ways." which I have paraphrased . In summary detecting anomalies require a model which describes "typical behavior". Segmenting data into "typical and "atypical" is what Intervention Detection is all about http://www.unc.edu/~jbhill/tsay.pdf and elsewhere.
ADDITIONAL ANSWER TO ACTUAL 173 VALUES
Anomalies can be both one-time events (pulses) or they can be a contiguous sequence od pulses having the same sign and similar magnitude (Level/Step Shifts). You data has been identified as having an ARIMA structure ( simple AR(1) ; value .568 ) and  with 12 pulses and 1 level/step shift at period 136. The identified pulses in chronological order; 1 time anomalies) . The actual step-by-step analysis started with the ACF of the original series  which led to an automatically identified ARIMA model  which upon estimation was reduced to  . Using procedures called Intervention Detection detailed by Tsay and others http://www.unc.edu/~jbhill/tsay.pdf and a number of my previous posts here at SE led to   . Now the final ACF of the errors suggesting sufficiency is . The histogram of the original 173 values is of little help in detailing the anomalies and the level/step shift DUE to the auto-correlative structure in the 173 values.  .The Histogram of the final model residuals ( original series adjusted for memory, 1 level shift and the one-time pulses ) is shown . The plot of actual and cleansed provides another view . Summary: to find the exception , one needs to have an expectation.
Answer: I would suggest you PWCTools for MatLab from here:

Implementations of algorithms for noise removal from 1D piecewise constant signals, such as total variation and robust total variation denoising, bilateral filtering, K-means, mean shift and soft versions of the same, jump penalization, and iterated medians. It uses a range of solvers including interior-point optimization, adaptive step-size Euler integration and greedy knot placement.

It is simple to use and produces fast and robust results. In your case k-means clusterring would be the best choice although you can try other techniques depending on your needs.
Comment: @mcdani To detect an anomaly, one needs a model. If you post your time series or send it to me I will illustrate this.
Comment: @IrishStat, can you explain to me , what u mean by a model ?
Up, you'll find the data series that u asked,
regards
Comment: @mcdani In this case  the model is an ARIMA model of order AR(2) which simply means that the data requires a two period adjustment i.e there is auto-correlation suggesting that before you can detect unusual values are have to adjust the observed values by using values 1 period and two periods ago. See the analysis below.
Comment: Kmeans wont be effecient for the a time series clustering, because what i'm looking for is not clustering times serieS, but in one TS i should be able to detect an anomaly using a data mining or data driven approach, so, the number of clusters is undifined withing a TS, a,
Comment: The toolbox provides functions for automatic estimation for number of clusters. K-means is just the simplest and strightforward approach.

Univariate clustering of time series


Um background é carregado mesmo quando uma regra não é aplicada sobre um elemento?

Question: Não sei se o título da pergunta é clara, vou tentar explicar o mais claramente possível. Eu estou estudando sobre sites responsivos e tento ao máximo não usar imagens grandes para o site não ficar lento. Vi que posso criar versões de tamanhos diferentes de uma imagem e dependendo do tamanho do dispositivo, colocá-las em um objeto.
Assim, ao invés de carregar uma imagem com 5000px de largura e fazer ela se redimensionar de acordo com o tamanho do elemento dessa forma:
#elemento {
  background-image:url('imagem.png'); /* Imagem com 5000px de largura */
  background-size:100%;
  width:100%;
}

Eu posso fazer isso:
@media screen and (max-width: 600px) {
  #elemento {
    background-image:url('imagem600.png'); /* Imagem com 600px de largura */
  }
}

@media screen and (max-width: 900px) {
  #elemento {
    background-image:url('imagem900.png'); /* Imagem com 900px de largura */
  }
}

@media screen and (max-width: 1300px) {
  #elemento {
    background-image:url('imagem1300.png'); /* Imagem com 1300px de largura */
  }
}

A pergunta
Ao ter um dispositivo com 900px de largura, somente a imagem correspondente irá carregar ou todas irão ser baixadas? Se todas forem baixadas, tem alguma forma para o usuário que tenha um dispositivo pequeno não tenha que baixar uma imagem muito gigante desnecessariamente?
Comment: Só é "baixada" a imagem indicada na `@media` que corresponde ao ecrã do visitante porque só o conteúdo dessa `@media` é que vai ser lido!
Comment: Vou responder, estou a elaborar o assunto em maior detalhe para clarificar algumas coisas associadas a este tema. Entretanto também outras respostas poderão surgir para melhor clarificar a duvida :)
Comment: Então a imagem só irá ser baixada caso um usuário que esteja usando um computador redimensionar a janela? Logo, não existe a possibilidade de por exemplo, alguém que esteja acessando o site por um celular baixar 5mb em imagens, certo?
Comment: ..... Certo! .....
Comment: Os pontinhos no comentário anterior é só porque o sistemas não deixa comentar com tão poucos caracteres. Este comentário é só para chatear até alguém apagar!
Comment: Muito obrigado, pelo menos com isso não devo me preocupar mais. Coloque como resposta para eu marcá-la!
Answer: O comportamento varia de navegador para navegador, embora seja algo em constante melhoria.
Um artigo muito interessante:
Media Query & Asset Downloading Results
Em Inglês, publicado em 10-04-2012
e com testes relativamente exaustivos permite-nos apurar que para evitar o download de múltiplas imagens quando só vamos apresentar uma, a técnica ideal é definir a imagem nas diversas declarações @media:

Da forma que tens as tuas declarações de CSS, só uma imagem é descarregada porque a declarada na @media em uso subscreve a necessidade das outras.


24TB RAID 6 configuration

Question: I am in charge of a new website in a niche industry that stores lots of data (10+ TB per client, growing to 2 or 3 clients soon). We are considering ordering about $5000 worth of 3TB drives (10 in a RAID 6 configuration and 10 for backup), which will give us approximately 24 TB of production storage. The data will be written once and remain unmodified for the lifetime of the website, so we only need to do a backup one time.
I understand basic RAID theory, however I am not experienced with it. My question is, does this sound like a good configuration? What potential problems could this setup cause?
Also, what is the best way to do a one-time backup? Have two RAID 6 arrays, one for offsite backup and one for production? Or should I backup the RAID 6 production array to a JBOD?
EDIT:
The data server is running Windows 2008 Server x64.
EDIT 2:
To reduce rebuild time, what would you think about using two RAID 5's instead of one RAID 6?
Comment: Holy crap the rebuild on that would take a long time.
Comment: i would not trust all of my eggs to be in two raid6 sata arrays.  i would suggest tape as a better choice for longer term archive.
Comment: What are your [MTTR](http://en.wikipedia.org/wiki/Mean_time_to_recovery) requirements? 24TB of LTO4 tape would work out a lot less than $2500 if you can afford to recover over a day or two.
Comment: @Phil, anything you read about tape backups being unreliable is either completely (like a decade or so) out of date or is utter nonsense. This isn't the place to go into it but put simply, modern tape technology has error detection and recovery at a level never seen in hard drive. Then you also have to consider that hard drives are by far the single most unreliable computer component ever created. Drives that have been used and then placed in storage doubly so.
Comment: Is the data going to be read extensively?
Comment: @Bittrance Yes, it will be read extensively
Comment: @MarkM How long is a long time? Days?
Comment: @Phil - that really depends on how much data is on there, what the load is on it during the rebuild, and also the controller, but it's not unreasonable to think that a 24TB R6 could rebuild for days if your app is read-heavy.
Comment: If the "backup" is just a copy of the data, might consider RAID60 than two separate RAID6 (though RAID60 doesn't protect against accidental deletion). As for rebuild time, it's dependent on the individual disk size and usage patterns, doesn't matter how you arrange the disks in the array (within certain limits).
Comment: @Jack Douglas From what I read, tape backups can be pretty unreliable. Do you have experience that says otherwise? http://www.mainframezone.com/storage/backup-recovery-business-continuity/tape-a-collapsing-star
Comment: @John Thanks, good to know. I'll be looking into that as well.
Answer: I currently support 220 servers up to 96 TB (totalling 2 PB or so), some in clusters of up to 240 TB, that my team built. Here are my advices :

use a good, reliable hardware RAID controller : possible choices are 3Ware 96xx or 97xx, LSI 92xx, Areca 16xx, Adaptec 5xx5... Of course, with a Battery Backup Unit because power failures occur sometimes.
use only professional grade drives,coming with 24/24 and 7/7 operation support; don't use cheap desktop drives. You don't want to lose 100,000$ worth of data because you chose to save 20 bucks per drive.
The biggest the drives, the longer the rebuild. 3 TB will need at least 12 hours in the best case. Use RAID-6 for reliable protection.
drives do fail. Up to 5% per year; don't even dream of using JBOD, even for backup. This is plain bad advice. Use RAID-6.
RAID-5 is obsolete, we simply don't use it anymore with drives bigger than 300GB.
See this expert post for instance. Did I mentioned you should use RAID-6?
For only 24 TB, I'd stick to 2 TB drives; there is a 10-15% premium on 3 TB; more spindles will provide better performance, shorter rebuild, and better safety because the drives have been available for quite a long time and are really very reliable.
You could buy an excellent 3U Supermicro, AIC or equivalent chassis with 16 drives slots, filled with 2TB drives (RAID-6 + hot spare) that would provide exactly 24 TiB of available space and redundant power supplies.
Comment: Extremely useful answer. Where do I find these professional grade drives? Everything I see on the web refers to just plain hard drives. Are you just suggesting getting drives with a high non-recoverable error rate?
Comment: @phil: professional drives are labelled as such: Hitachi calls them Ultrastar (vs Deskstar), Seagate calls them Constellation ES, etc.
Comment: +1 for build your own box
Comment: nonsense at a 5% failure rate a year - JBOD is jsut fine for backups for static data.  It seems silly to spend as much on data as you would on backup.  drives do fail but not nearly as often as one might get the impression from this lot.  see http://www.storagereview.com/guide/specMTBF.html for a discussion of MBTF and hardrives.  You would have drives piled high with such failure rates.  Most importantly you shoud not be buying your own drives.  By a san - you simply cannot get the drives san manufacturers use (or rather you cannot do the testing on drives like they do)
Comment: @wazoox - why did you claim a failure rate of 5% then say "and better safety because the drives have been available for quite a long time and are really very reliable."
Comment: @JimB: 5% failure rate is about what I currently get from a "sample" of several thousand drives in production. Newer drives ("advanced format", 4KB blocks) apparently fare much better but we can't be sure yet; so better safe than sorry.
Comment: JBOD : given the current bit error rate, at 24 TB you're guaranteed to have about 2 errors, that is, corruption. Is it a chance you'll take? I wouldn't. This isn't a question of MTBF, but a question of irrecoverable bit error rate. Learn the difference.
Answer: Honestly, I think $5k for the drives is a bit steep... but that's a whole other subject.  The setup sounds sound-enough, but in the event of a drive-failure... having a single-volume that is 24tb will take FOREVER to rebuild.  (ever tried to read 3tb of data split across 9 other disks?)  It would be better to have smaller raid-sets and join them together to form a bigger volume.  If a drive fails, it doesn't kill the performance of the entire volume while the whole thing rebuilds... but rather only the performance of the one raid-set.
Also, depending on what your website is run on... (Linux/Windows/OSX/Solaris/???) can also dictate what tools you use and the configuration you use.
What do you mean by a "one-time backup?"  If you meant a "one-way archive"... (i.e. new files are written to the backup-server.. but nothing is ever read from it), I highly recommend using rsync in *nix flavored environments (linux/unix/etc...) or if it's IIS (windows) based use something like synctoy or xxcopy.  If you need a LIVE copy (0 delay between when a file is written to when it appears on other server) you'll need to provide more information about your environment.  Linux & Windows work completely different, and the tools are 100% different.  For stuff like that, you'll probably want to look into clustered-file-systems and probably should look more towards a SAN rather than host-based storage.
Comment: By one-time backup, I mean once data is written to the array, it will not be changed. The write should only happen once - during the initial copy from the client's disks to our disks.
Comment: Linux (rsync) or Windows (xxcopy/synctoy)?
Answer: We generally use RAID5 or 6 for backup disks as it gives the best bang-for-buck once you ignore RAID 0 :-) so I'd go for that rather than JBODs
One thing you might consider is buying your disks in separate batches rather than all 20 at once as if there is a manufacturing defect in a batch, they may fail at similar times.
You also may wish to consider using mirroring rather than conventional backups if the data is only being written once - there are quite a few software and hardware storage systems that allow that to be set up and you may also get the benefit of failover in the event of your primary storage failing.
Comment: +1 for separate batches!
Comment: mirror is not a backup.  it protects against hardware failure, but if you mistakenly delete something, it's gone from both copies
Answer: One option that would fit well with your use-case, especially if your requirements keep growing, is an HSM (Hierarchical Storage Manager). I've installed several HSMs ranging up to 150TB of disk and 4PB of tape.
The idea is that an HSM manages the lifecycle of data to reduce the overall cost of storage. Data is initially stored on disk but almost immediately archived to tape (which is much cheaper per byte). Archive policies can be configured to store multiple copies on tape for extra safety, and most people take a second copy offsite. The migration to and from tape is transparent to the end user - the files still appear in the filesystem.
When the end user requests the file in future, the data is automatically staged back from tape and served to the user. With a tape library, the staging process only adds about a minute to the retrieval time.
One huge benefit of an HSM is the recovery time if your disks fail or if you have filesystem corruption. If you ever have a catastrophic disk or filesystem failure, you can just find some more disk and restore a recent backup of the filesystem metadata (a tiny fraction of the total data volume). At that point, all of the data is available on-demand as per usual.
Answer: when determing the raid configuration for a san you have to worry about performance and the amount of reliability, and recovery time you require. Because you double the number of parity writes (depending your particualr flavor of raid six) it's usually best in a san with custom ASICs to do the calculations.  Since your data is static your real concern is how long you can afford to be in a degraded state should 1 drive fail. Also of note is that drives tend to fail multiples so it's best to install drives with some time between sets.
As far as backups go, I see no need for redundancy in the backup set so JBOD is fine
Comment: JBOD would be a very bad idea. Given general drives bit error rate, that's a recipe for silent corruption. Spend a little more and buy the 2 additional parity drives for RAID-6 and excellent protection.
Comment: parity for what?  hopefully the backup solution already has error checking and recovery built in.  If not uses rar format and add a recovery record.
Comment: So for backups you'd spend just as much money as you would on production?  That's fairly ludicrous
Comment: To connect 16 or 24 drives you'll need a RAID controller anyway. Not using parity will save you 200$; using parity will buy you reliability, data integrity, and no hassle in case of disk failure; and you could even use your backup system for failover if necessary.
Answer: I currently have filesystems on that scale range, currently totaling 58TB onsite, plus a separate copy offsite.
I've had a few drive failures and yes, the bigger the drives, the longer the rebuild.  To alleviate it somewhat, I split the storage in several RAIDs, each one 5-7 drives.  It's currently RAID5, but when I get 3TB drives I plan to start using RAID6.
It's all joined and resplit with LVM, so i don't have to think about what goes where, simply add extra boxes when needed and remove old drives when they're too small to justify the slots they occupy.
The Hardware is mostly Coraid AoE boxes (but some iSCSI targets will join soon), managed with LVM, the filesystems are Ext3/4 if under 4-6 TB, or XFS if over that (up to 34TB, currently).  All backup is handled with rsync and DVD for offline archive.
Besides some monitoring software (mostly Zabbix), it's a nearly maintenance-free setup.
Comment: How long of a rebuild am I looking at? Hours? Days?
Answer: Another point to add to what everyone is saying here.  With Windows and huge file systems, if you do decide to break a filesystem up, but want to retain the same file structure as you would have had, look at mounting these drives to folder paths.
http://technet.microsoft.com/en-us/library/cc753321.aspx
Answer: I'm surprised nobody has suggested using MogileFS (github).
MogileFS will mirror data on different servers automatically and each disk is just a "JBOD" dumb disk.  There are many production installations with many TBs (100+) of data.
For the server hardware there are many options for "lots of disks in an enclosure". For example a Backblaze Pod (a bit of do-it-yourself/unsupported, relatively) or a Super Micro server (we use Silicon Mechanics.  I believe at wordpress.com they use regular 2U Dell servers with MD1000 enclosures for the disks.

24TB RAID 6 configuration


San lun wwid number 3 in front

Question: I have a san lun in a linux server, using this following command I saw this:
<code> scsi_id -g -u -s /block/sda
 38001438005dea3760000700002660000     #3 number in front of wwid
 sg_inq -p 0x83 /dev/sda | grep "\["
 [8001438005dea3760000700002660000]
</code>
From san of view the wwid is 8001438005dea3760000700002660000, but the os add a 3 number in front.
What means the number 3 in the front of the wwid?
Answer: http://linux.die.net/man/8/scsi_id

Identifiers based on page 0x83 are prefixed by the identifier type followed by the page 0x83 identifier. For example, a device with a NAA (Name Address Authority) type of 3 (also in this case the page 0x83 identifier starts with the NAA value of 6):

<code># /lib/udev/scsi_id --page=0x83 --whitelisted --device=/dev/sda
3600a0b80000b174b000000d63efc5c8c
</code>

San lun wwid number 3 in front


Recording technique: not letting the crash cymbals ring out

Question: I listened to the following song this morning on the way into work.  I heard something I hadn't heard before.
Each of the crash cymbals were very minimal, almost gated, or maybe miked from a distance.
What is the recording technique to get the cymbals to only let out quickly like this?
Comment: Different cymbals absolutely behave differently. So thinner, smaller cymbals is one way this is done in studios. Also, riding the overhead fader is done during mixing - either to extend or reduce cymbal decay. You could put an expander on them to make it less work but the overall quality of the drum sound might suffer.
Comment: Around 1:10, the drummer chokes a cymbal. Sounds like tat's what may happen.
Comment: I know some drummers that put a few pieces of gaff tape on the underside of cymbals to reduce the sustain.
Comment: @MichaelCurtis The question came about after hearing the song, and wondering how I would reproduce these results on a recording.  Playing drums live, I am not interested in reducing the crash cymbals' presence.
Comment: I'm no expert, but I would guess it's just not heavy compressed. So the initial attack will bleed thourgh the mix and than the tail of the sound will fall down very fast. Maybe there is some gate to fade out the long tail.
Comment: @JasonPSallinger After careful listening, I'm convinced Alen has the answer: The overheads were mixed very low. This is not a recording technique, it's a mixing decision. There aren't really *recording* techniques shorten cymbal sustain. There are different cymbal setups and different cymbals and different playing techniques that can do that. They could be gated during recording but gating overheads is tricky because they pick up the whole kit, not just the cymbals. And the context of the mix really creates the *apparent* sustain of the pieces of the drum kit.
Comment: Some more things that come to my mind is that different cymbals might behave differently. So maybe here they used some cymbals which dont ring out to long, or at least don't have a loud and long tail. The mic itself and its position will also make a difference how the tail of the crash will be recorded. Just a guess
Comment: https://music.stackexchange.com/questions/39750/what-is-the-technique-called-where-you-hold-a-crash-cymbal-while-hitting-it?rq=1 This might help for clarification on "choking a cymbal"
Comment: Thanks.  I am a drummer and aware of cymbal choking.  He doesn't use this technique the whole way through.  Good tips, @Olli, thanks.
Comment: @ToddWilcox  I am wondering if it might be as simple as tightening the felts on the crash.  Wouldn't it effectively muffle the decay?
Comment: The crash at 2:37 kinda rings. It never gets quiet enough to really tell. A lot of it is just closing the HH (squashing the HH after a crash will mimic the effect to some extent).... *getting* it to ring and not clip on the attack is the hard part. That's why we trade cars for microphones.
Comment: If you tighten the felts they don't fly right and you break cymbals.
Comment: Just curious, are you interested in getting a similar cymbal sound acoustically? Or is it just about the sound engineering part?
Answer: Disclaimer: I'm in no way an expert in cymbals or recording (yay! guess that makes me fully qualified to provide answers on the Internet) but here's $0.02 from my experience.
This cymbal is not only short but also fairly quiet. I'd assume the drummer plays the kit more-or-less in the same way he does in the video. The assumption is that the song has been practiced thoroughly and there's not much point playing it differently on a video vs playing live or recording. The cymbals seem to be hit pretty hard so they most-likely do ring if you're around them. This means that the cymbals are set to a fairly low value in the mix, and only the attack is audible. Sounds almost as if the cymbals are picked by a mic that's a bit remote or even used for another drum. It could be an overhead mic on top of which the rest of the drums (using separate mics) are added with more volume. You might notice that all the cymbals in the mix are rather low - there's no hi-hat or ride at all, for example. The overall drum sound is pretty dry and there's just strumming of the guitars instead of the hi-hat beat.
There are other techniques if you want to get the similar sound live, though. People mostly tape the cymbals at the bottom or at the top. There are also magnets that can be attached. This dampens the cymbals somewhat and shortens the sustain. One can also adjust the technique and play with stick tips only, etc. But that will never give this much force with such a low volume unless the cymbal is wrapped in tape like a suitcase at an airport.
And the third option, naturally, is the characteristics of the cymbal itself. As suggested in other answers, splash cymbals will be high-pitched and have a short sustain simply due to their size. The cymbals in the video, i.e. at 1.14", seem rather small to me, apart from the ride. Definitely not 18"(!) but more like 16" or even smaller. Just compare them to the size of the snare. Meaning that they ring out decently in live mode but are only adjusted in the mix.
Comment: The hats and ride are actually there, just as you said the acoustic guitar strums over it in pretty much the same frequency range.
Comment: I'm sure this is the closest to the answer. The drums themselves have very little of the sound of the overheads in them - it's almost entirely close mikes. And the cymbals are very quiet in the mix. So the overheads have been pulled way down, which means the cymbal sustain becomes lost in the mix much faster. If you listen closely, you can actually hear the overhead fader(s) were ridden up and down in the mix. To me it sounds like the overheads were pulled way down to make sure the distinctive sound of the unique acoustic guitar tuning stand out.
Comment: We seem to want this to be about recording technique.   I suspect it's more about using a cymbal that just sounds like that!
Answer: It's hard to give a definitive answer for a particular song, because there are many ways to skin a cat and we don't have the raw recording on hand.
I suspect it's not a single thing resulting in this sound.
Some suggested causes:

The drummer sounds like they are striking the drums with some force. Listen to the attack in the other parts of the drum kit. This means it was probably recorded fairly loudly, and ring-out of a cymbal can quickly be masked by volume of the hats and snare. That said, at about 3:21 the cymbals are allowed to ring and do die quite quickly.
It's easy to use non-linear amplification in production which can give a similar effect. Most compression is applied with some kind of a soft cut-off (or you'd end up with a square wave rather than sound per se).
MP3-style compression (used in youtube videos) exaggerates this effect by hiding sounds that are "less important" to your ear. Find a higher bit-rate recording and you'll hear the cymbals and hats ringing slightly longer than in the link
We don't have any guarantee the kit in the video is the same as in the recording. However, if it is at least similar, you can note that crash cymbal has a small diameter. So long as it's relatively thin or has a meaningful curvature, this literally can result in the sound you're talking about. China cymbals, for example, ring only for a fraction of a second
Cymbals can be dampened by adjusting the size, diameter, and presence of the felt washers. A wide moderately tight washer one or both sides can help produce the sound you're talking about. I've used a large felt washer below the cymbal to get a similar sound on a smaller crash for live performance.
There are some suggestions in comments this could also be the drummer choking the cymbal. This is possible for the few moments the rest of the playing stops - an experienced drummer can choke with their hand more dynamically than simply grabbing the thing. I don't think it could apply while striking the cymbal and returning the right hand to the hats, though.
Answer: You asked about recording techniques, so this isn't really answering that question, but regarding the actual cymbal, it may be a Zildjian A 18" medium thin crash.
This is what I pieced together:
https://i.ebayimg.com/images/g/xG0AAOSwdHteYAH3/s-l1600.jpg

If that is the right cymbal, the live video sounds really different than the test lab video. Although, that final hard hit in the test lab video seems like it starts to get that splashy sound. Maybe that particular tone isn't achieved until it's hit very hard.
Don't know if this page... https://www.prosoundweb.com/on-stage-whats-in-the-mic-box-for-the-current-tour-by-the-goo-goo-dolls/ ...is accurate for mic info, but it a 2010 interview with Paul David Hager who mixed the band. It lists this detail about cymbals...

hi-hat and ride cymbals employ Neumann KM 184 condensers

The short, splashy sound of the recording does seem similar to the live shows. Maybe the mics are part of that sound.
Comment: 17" A Custom crash. 18" medium thin crash. 21" rock ride. 14" quick beat hi-hats. https://www.musicfanclubs.org/googoodolls/misc/gear.htm
Answer: Some ideas: the cymbals themselves could be splash or China cymbals, which are designed to make shorter sounds than normal crash cymbals.
They may be (as well) choked by the drummer (or another) grabbing them as or just after they're hit.
That's probably the solution, rather than some tweaking at the desk. Although careful mic placing could easily catch the hit, and eliminate the longer ringing after.
Comment: I would exclude choking the cymbals because it would be extremely difficult to play this tune relaxed in such a manner.
Comment: I agree that it isn't choking.  I also am fairly certain these are crash hits, and not splashes or chinas - they sound like crashes, but they sound low in the mix and decay really fast.
Comment: @AlenSiljak - that's why I said (or another). Often pieces in the recording studio don't consider live rendititions of the piece.


Break out line items in one cell and separate

Question: I have data that has multiple entries in one cell and I needed the individual entries broken on into multiple cells.
For example:
in Cell A1 I have this data:
Corporate
Dr. 1392.9999 Accounts Receivable Reconciled
 Cr. 1092.5921 Other Revenues

Back Office
Dr. 9821.0000 Accounts Payable
 Cr. 4322.9820 Redemptions Payable

Note: These accounts are related to the payments received and sold.

I needed all of the Dr. and Cr. line items separated into separate cells.
For example, in Cell A2 I need
Dr. 1392.9999 Accounts Receivable Reconciled

And cell A3 to be
Cr. 1092.5921 Other Revenues

And cell A4 to be
Dr. 9821.0000 Accounts Payable

And Cell A5 to be
Cr. 4322.9820 Redemptions Payable

I tried using text to columns and using line breaks but it breaks out all of the data in the cell but I just need the Dr. and Cr. line items.
Thanks
Comment: On the third screen of the text to columns wizard, there is an option to skip any or all result columns.
Answer: Use one of the 2 versions bellow

Option Explicit

Public Sub ExtractDrCrV1()
    Dim txt As String, arr As Variant, drcr As Variant, itm As Variant, r As Long

    txt = Sheet1.Range("A1").Value2
    arr = Split(txt, Chr(10))
    ReDim drcr(1 To UBound(arr), 1 To 1)
    For Each itm In arr
        If InStr(1, itm, "Dr.") > 0 Or InStr(1, itm, "Cr.") > 0 Then
            r = r + 1
            drcr(r, 1) = Trim$(itm)
        End If
    Next
    Sheet1.Range("A2:A" & r + 1) = drcr
End Sub

Public Sub ExtractDrCrV2()

    Const R1 = "A1"
    Const R2 = "A2"

    Application.ScreenUpdating = False
    With Sheet1
        .Range(R1).TextToColumns Destination:=.Range(R2), DataType:=xlDelimited, _
                                 Other:=True, OtherChar:=Chr(10)
        .UsedRange.Rows(2).Copy
        .Range(R2).Offset(1).PasteSpecial Transpose:=True: .Range(R1).Select
        With .UsedRange.Columns(1)
         .AutoFilter Field:=1, Criteria1:="<>*Dr.*", Operator:=xlAnd, Criteria2:="<>*Cr.*"
          Sheet1.UsedRange.Offset(1).EntireRow.Delete
         .AutoFilter
        End With
        .UsedRange.Offset(1).Columns(1).Replace " Cr.", "Cr."
    End With
    Application.ScreenUpdating = True
End Sub


Redirect from subfolder to subdomain

Question: This should be simple right? I've tried a few solutions with no results...
How do I redirect:

http://www.domainname.com/subdomain   and    http://www.domainname.com/subdomain/

to:

htt://subdomain/domainname.com   and   htt://subdomain/domainname.com/

~
What code should I use, and do I place it in .htaccess of the domainname.com root folder?
or in the subdomain folder?
Thanks so much!
JD
Answer: I'm presumming a typo in your request and that you wish to redirect:
http://www.domainname.com/subdomain ---->   http://subdomain.domainname.com
If you are using apache, I'd use the following directive in the httpd.conf file:
Redirect /subdomain http://subdomain.domainname.com

Comment: I'm using Apache. what is the httpd.conf file? Wouldn't I be adding that code to my .htaccess file? Would this go in the subdomain folder then or the domainname.com root folder? Thanks!
Comment: I placed your code in the .htaccess file in the subdomain folder and got the following error:

Common reasons for this error are:

    * Incorrect file/directory permissions: Above 755.

      In order files to be processed by the webserver, their permissions have to be equal or below 755. You can update file permissions with a FTP client or through cPanel's File Manager.
    * Incorrect Apache directives inside .htaccess file.

      Make sure you have not specified unsupported directives inside the local .htaccess file. Such include PHP settings and Apache module settings.
Comment: I checked my error log ---- Invalid command 're', perhaps mis-spelled or defined by a module not included in the server configuration ---
Comment: Here is the URI that describes the directive:

    http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect
Answer: And if you're using IIS, set up redirects in the site properties in the IIS management snapin.

Redirect from subfolder to subdomain


What are the problems if you estimate a linear regression model using OLS, when the dependent is a dummy ? What Models are used to overcome it

Question: What are the problems if you estimate a linear regression model using OLS, when the dependent is a dummy ? What Models are used to overcome it
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: This is called a linear probability model. Despite people liking it, there are issues.

It can predict illegal probabilities outside of $[0,1]$.

When we have a binary $y$, we are in the lucky situation of knowing the conditional distribution, and we can model that conditional distribution. Unfortunately, OLS is equivalent to maximum likelihood estimation with Gaussian conditional distributions, not binomial, and the OLS solution is not the minimum-variance solution among consistent estimators.

A solution that remedies both of these is to use maximum likelihood estimation of a binomial conditional distribution while applying a link function that compresses predicted values to $(0,1)$. The most common example of this is logistic regression.


Group homomorphism from $S_3$ to $A_3$

Question: How many number of group homomorphisms are there from $S_3$ to $A_3$ ??
In case of $Z_m$ to $Z_n$,  I can map 1 to an element whose order divides order of both $Z_m$ and $Z_n$ (m and n).
What method should be applied to non abelian groups??
$S_3$ is of order 6 , $A_3$ is of order 3
Identity should be mapped to identity. And how can we conclude about mapping of other elements in $S_3$ to $A_3$..
Answer: Note that if $\phi : G \to H$ is a homomorphism, then $|\phi (a)|$ divides $|a|$ for all $a \in G$.
Now, let $\phi : S_3 \to A_3$ be a homomorphism.
What does this imply on the order of the image of $2$-cycles under $\phi$? (What are the possible orders in $A_3$?)
Then, recall that the $2$-cycles generate $S_3$, and conclude that the only homomorphism $S_3 \to A_3$ is trivial.
Comment: Possible orders in A3 are 1 and 3 .. As 3 doesn't divide 2 , All 2 cycles should be mapped to identity and therefore, 3 cycle elements should also be mapped to identity to preserve homomorphism
Comment: @BharadwajRcr exactly.
Answer: $S_3$ is generated by ??
It does not help to consider generating set as full $S_3$. What is the smallest generating set can you think of for $S_3$?
Any morphism is determined by generators of its domain. Once you know generators you will know possible images in $A_3$  depending on order.
Comment: Elements (123) and (132) generates A3 Elements (12) ,(13), (23) generates respective subgroups..
Comment: It was not clear what respective groups you are talking about. I was asking for generators of $S_3$ and not of $A_3$.. Suppose you know $a$ is a generator of $S_3$ and is of order $3$, any homomorphism $\phi:S_3\rightarrow A_3$ should be such that $\phi(a)^3=1$. So, you have to check what are elements of $A_3$ that satisfy the property that its cube is identity. Does this help?
Comment: I meant subgroups generated by (12),(13) and (23) . That is {(12),e} , {(13),e}{(23),e} S3 doesn't have any generators, otherwise it would become cyclic
Comment: I think you misunderstood the word generators.... I did not mean single generator. If a group has a generating set with single element, you call it cyclic group. I can write down the definition but I want you to read some book and see what does it mean to say generators of a group. you can google what is it mean by generating set of a group.

Group homomorphism from $S_3$ to $A_3$


How can a module in node.js maintain state?

Question: I have two different js files that use the same module.
file1.js:
var mod1 = require('commonmodule.js');
mod1.init('one');

file2.js:
var mod2 = require('commonmodule.js');
mod2.init('two');

(both these files file1.js, file2.js are loaded inside my server.js file, they themselves are modules)
now in commonmodule.js:
var savedName;
exports.init = function(name)
{
    savedName = name;
}
exports.getName = function()
{
    return savedName;
}

I noticed that this savedName is always overridden dependent on who set it last.So it doesn't seem to work. How would I get a module to maintain state?
Note: I also tried to set savedName as exports.savedName in the commonmodule.js but it doesn't work either
Comment: This is how state is `maintained`. Perhaps you wanted to ask how to get isolated state for each module?
Comment: No, because modules are cached so any changes will be effective everywhere. What is your question then? How to solve that? Just why?
Comment: yes, I want to know HOW I can maintain state inside a module
Comment: Modules are effectively IIFEs and the variable as you have defined it is part of the IIFE's closure. @miguel-mota's solution works for your scenario because the variable has been defined within the `CommonModule` function and is thus part of that function's closure.
Answer: You can just create a new instance every time the module is required:
commonmodule.js
function CommonModule() {
    var savedName;
    return {
        init: function(name) {
            savedName = name;
        },
        getName: function() {
            return savedName;
        }
    };
}

module.exports = CommonModule;

file1.js
var mod1 = new require('./commonmodule')();
mod1.init('one');
console.log(mod1.getName()); // one

file2.js
var mod2 = new require('./commonmodule')()
mod2.init('two');
console.log(mod2.getName()); // two

Comment: Why is the "new" keyword needed? Correct me if i'm wrong but functions doesn't store state but direct object does. so each time the function is ran then a fresh object will be returned from it.
Comment: @CarlosMiguelColanta you're correct the `new` keyword is not required in this example. If you use `this` or ES6 classes to maintain state then it would be required
Answer: modules in and of themselves are  simple object instances. A single instance will be shared by all other modules (with the caveat that it is loaded via the same path). If you want state, use a class and export a constructor function.
example:
//Person.js
function Person(name) {
    this.name = name;
}

module.exports = Person;

To use it:
var Person = require("./Person");
var bob = new Person("Bob");

Answer: Modules are not like classes/class functions; by default, mod1 and mod2 will refer to the same module due to caching. To keep track of per-instance state, you'll need a constructor function or something similar inside your module, e.g.
var mod = require('commonmodule.js');
var state = new mod.init('one');

Where init defines the stateful object. You could also have it return an object literal, in which case you wouldn't have to use new (e.g. var state = require('commonmodule.js').init('one');)
(This is assuming you want the module to have other, shared state in addition to the per-instance state; if that is not the case, Peter Lyons' method would be simpler.)
Comment: so I would have to pass this 'state' into every function I use in this module right? (as the module depends on state)
Answer: You could perhaps remove from cache your module. Like that:
file1.js:
var mod1 = require('commonmodule.js');
mod1.init('one');

file2.js:
delete require.cache[require.resolve(modulename)];

var mod2 = require('commonmodule.js');
mod2.init('two');

But I don't find it very convenient and clean.
But you could also clone it or make a small proxy.
Also you could create classes:
var savedName;
exports.obj = {}
exports.obj.prototype.init = function(name)
{
    savedName = name;
}
exports.obj.prototype.getName = function()
{
    return savedName;
}

Then :
var mod2 = new (require('commonmodule.js'))();
mod2.init('two');


Requiring two-factor ssh authentication only from certain clients

Question: I am about to make two-factor authentication mandatory for ssh logins using libpam_google_authenticator.  I'd like to be able to waive this requirement when users log in from certain IP addresses.
I have this in /etc/pam.d/sshd:

auth       required     pam_google_authenticator.so

and this in /etc/ssh/sshd_config:

ChallengeResponseAuthentication yes

I thought about using the Match directive in sshd_config, but the manpage suggests that ChallengeResponseAuthentication can't be used in that way.  In any event, I'm not sure that would get around the pam requirement.
Is there a way of waiving the challenge-response for clients with certain IP addresses?
Answer: I've not done this specifically with google auth, but I'm doing something similar with pam_access and a substack.  The way I do it to create a file in /etc/pam.d named yubi-auth.  It contains:
auth sufficient pam_yubico.so
auth required pam_combo.so

Then in password-auth, I use auth substack yubi-auth.  The result is that if a user is coming from an approved ip address in acceess.conf they don't have to use the yubikey, otherwise they have to use it.  (and they CAN always use it if they wish).
I've not tested this method with google auth, but I think the same logic should work.
Comment: (sorry for the long time in reply, I missed the question about pam_combo).  Pam_combo is a combination of pam_access and pam_time.  So can say things like "allow this ip address only during these hours."  I assume there is some way to do that without writing your own pam module, but I once drove myself crazy trying to figure it out and decided it was easier to write my own pam module.  On suppressing the google auth prompt, I'm not sure on that one -- you don't get any extra prompt with yubi, which is all I've done.
Comment: Thanks! -- but what is `pam_combo.so`?
Comment: Ah, maybe you meant `pam_access.so` -- I tried it with that, and it works, sort of.  Clients connecting from an address listed in access.conf still get prompted for the verification code, but it is ignored.  Is there any way to suppress the prompt?
Answer: You can run two instances of sshd with different configurations. In an extreme case: Use one patched version (as this is probably not possible via the config file) which uses a different PAM string than ssh so that you can create different PAM configurations for both instances. Or you start one instance in chroot / lxc so that it sees a different PAM configuration. That might be easier (to maintain).
The client selection can be done by iptables (DNAT) then. Just send the respective clients to the port of the second instance (or to the lxc IP).


Search from Solr 4.4 to include Alfresco Solr 1.4

Question: I have an application which is using Solr 4.4 for search,  Solr 4.4, has a core pointing to database [db1] and I am using JSon at the UI.
Now, in addition, I would like my application to search against Alfresco, which is Internally using Solr 1.4.
What is the preferred approach in getting this done.
Answer: You shouldn't access Alfresco's Solr directly, why?:
- Alfresco uses some specific query parameters (fq's) to respect permissions
- Alfresco has his one Query Syntax & Query Handler to handle their dynamic data model
So the way to go is to use the existing REST or CMIS APIs or to write your own Alfresco WebScript to execute the search & just consume this REST API in your search app.
more on Alfresco's search syntax:

http://docs.alfresco.com/4.2/topic/com.alfresco.enterprise.doc/concepts/rm-searchsyntax-intro.html


EOFError while trying to run rmate algorithm on Linux

Question: I have been trying to setup Sublime Text 3 on my local Windows 10 machine to work remotely on files on my Ubuntu 16.04 LTE server (google cloud compute engine instance). I followed these instructions: https://github.com/henrikpersson/rsub and https://github.com/textmate/rmate
I have decided to use a standalone bash version (though I apparently still needed to install ruby environment).
I have setup my rmate script in /bin/ catalogue, but when I try to run the command rmate on my remote Ubuntu server through ssh, I get the following end of a line error:
<code>/bin/rmate:145:in `readline': end of file reached (EOFError)
    from /bin/rmate:145:in `handle_cmd'
    from /bin/rmate:180:in `connect_and_handle_cmds'
    from /bin/rmate:223:in `block in <main>'
    from /bin/rmate:222:in `fork'
    from /bin/rmate:222:in `<main>'
</code>
I have tried simply reinstalling the script from the link provided, but it didn't help. I also made sure that the rest of my installation: config file on my local machine and my firewall rules and sshd config files are correct.
I would be grateful if you pointed me in the direction of what I am missing.
Answer: I am also facing same error when I connecting raspberry PI and doing remote coding from Visual Studio Code.
I try to reconnect SSH with IP address 127.0.0.1 instead of host name localhost.
After that try to open rmate again.
Comment: did that solve your problem?


Inverse of a ring isomorphism is also an isomorphism?

Question: Let $f:R \rightarrow S$ be an isomorphism of rings.
Let $g:S \rightarrow R$ be the inverse function of $f$.
Show that $g$ is also an isomorphism.
I know I can show and isomorphism by first showing $g$ is injective, surjective, and operation preserving. I am unclear on how to do that exactly. Any help would be greatly appreciated.
Comment: The only problem here, assuming you already know the basic set theory stuff for inverse functions, is to show the inverse preserves the operations. So suppose $\;s,s'\in S\;$ . You must prove $\;g(ss')=g(s)g(s')\;,\;\;g(s+s')=g(s)+g(s')\;$ ...Use bijectivity of $\;f\;$ for this
Comment: Related: https://math.stackexchange.com/questions/2039702/what-is-an-homomorphism-isomorphism-saying/2039715#2039715
Answer: because $f$ is a bijection, there are $r,r' \in R$ such that $f(r)=s$ and $f(r')=s'$.
So now ,
$g(ss')=g(f(r)f(r'))=g(f(rr'))=rr'=g(s)g(s')$
also
$g(s+s')=g(f(r)+f(r'))=g(f(r+r'))=r+r'=g(s)+g(s')$.
finally,
$g(1)=g(f(1))=1$
Hence, $g$ is a homomorphism and since inverse of a bijective function $f$ is bijective, $g$ is also a bijective hence an isomorphism.


Can another process signal systemd to restart a service?

Question: We have a service which is managed by systemd. I'm looking for a way to programatically restart that service on demand - for instance, by sending a signal, writing to a file, or messaging over a socket.
Context: the systemd managed service maintains a pool of headless chrome instances. But it manages them somewhat poorly, and over time they increase in number and memory usage. A systemctl restart fixes that.
I could set RuntimeMaxSec and Restart=always to restart the proxy periodically, but it might be doing work at the moment the restart occurs.
Another service on that machine is the only consumer of the chrome proxy, and knows when it's not using it. So periodically when it's not using the chrome proxy (so that no requests will be dropped), it could restart it.
How could I do that?
Comment: for what do you need chrome? curl and wget can do almost sone parts easily
Comment: Headless Chrome can execute JavaScript, render the page and take screenshots, and more. Different tools for different purposes.
Answer: One solution is to have the other service actually run systemctl restart some_service. That requires sudo, but it's possible to use the sudoers file (visudo) to give a user permission to run one specific command: some-user ALL=NOPASSWD: /some/command some args
Answer: If you want to avoid sudo, you can set your user's linger flag and create a user service instead of a system service. This might not work on centos 7 or below.
Another solution is to ask systemctl what the PID is
systemctl --user status your_scraper

then send a SIGHUP to that process id
os.kill(main_pid_of_your_scraper, signals.SIGHUP)

which you need to catch inside of your application and reset your browser.
signal.signal(signal.SIGHUP, restart_myself)

This also plays nicely with systemcl, since systemctl reload sends a SIGHUP signal to the process as well.


convert categorical data into numerical data?

Question: I am doing project for post graduation....project is document clustering.in the project raise the problem is the text data convert into the numerical data?
Answer: You can try to build the classical Bag of Words features by counting words (and normalizing using eg TF-IDF). Another approach would be using word hashing, perhaps here you would like to use ngrams as more powerful features as well. Some data cleaning might be needed before (do not neglect this step).
When features are extracted, you can try Latent Dirichlet Allocation (see Vowpal Wabbit package for implementation). The LDA algorithm will transform your word documents into topic documents. These new representations are arguably better when trying to cluster the documents (eg using k-means). Here are two important parameters to tune - number of topics and number of clusters.
Comment: TF-IDF use after removing stop words and stemming ...otherwise no need of those..
Comment: i have 20 text documents ...how to cluster those documents?