How to detect that a thread has started using javassist?

Question: I have to instrument any given code (without directly changing given code ) at the beginning and end of every thread. Simply speaking , how can I print something at entry and exit points of any thread.
How can I do that using javassist ?
Comment: Your question is not quite clear.... Are you asking how to detect that a new Thread object is being created (or started) in the code you are instrumenting with javassist, is that it or is something else?
I suggest you to edit the question with more detail! Also providing some code of what you are trying to do. Please check http://stackoverflow.com/help/how-to-ask to learn a bit more on how to ask questions at SO
Comment: Yes it is quite similiar to what you have understood .. I have updated the question . Please have a look .
Answer: Short Answer
You can do this by creating an ExprEditor and use it to modify MethodCalls that match with start and join of thread objects.
(very) Long answer (with code)
Before we start just let me say that you shouldn't be intimidated by the long post, most of it is just code and once you break things down it's pretty easy to understand!
Let's get busy then...
Imagine you have the following dummy code:
public class GuineaPig {

 public void test() throws InterruptedException {
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++)
                System.out.println(i);
        }
    });

    t.start();
    System.out.println("Sleeping 10 seconds");
    Thread.sleep(10 * 1000);
    System.out.println("Done joining thread");
    t.join();

 }
}

When you run this code doing
new GuineaPig().test();

You get an output like (the sleeping system.out may show up in the middle of the count since it runs in the main thread):
 Sleeping 10 seconds
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
 Done joining thread

Our objective is to create a code injector that will make the output change for the following:
 Detected thread starting with id: 10
 Sleeping 10 seconds
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
 Done joining thread
 Detected thread joining with id: 10

We are a bit limited on what we can do, but we are able to inject code and access the thread reference. Hopefully this will be enough for you, if not we can still try to discuss that a bit more.
With all this ideas in mind we create the following injector:
 ClassPool classPool = ClassPool.getDefault();
 CtClass guineaPigCtClass = classPool.get(GuineaPig.class.getName());

    guineaPigCtClass.instrument(new ExprEditor() {

        @Override
        public void edit(MethodCall m) throws CannotCompileException {
            CtMethod method = null;
            try {
                method = m.getMethod();
            } catch (NotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String classname = method.getDeclaringClass().getName();
            String methodName = method.getName();
            if (classname.equals(Thread.class.getName())
                    && methodName.equals("start")) {
                m.replace("{ System.out.println(\"Detected thread starting with id: \" + ((Thread)$0).getId()); $proceed($$); } ");
            } else if (classname.equals(Thread.class.getName())
                    && methodName.equals("join")) {
                m.replace("{ System.out.println(\"Detected thread joining with id: \" + ((Thread)$0).getId());  $proceed($$); } ");
            }

        }
    });

    guineaPigCtClass
            .writeFile("<Your root directory with the class files>");
}

So what's happening in this small nifty piece of code? We use an ExprEdit to instrument our GuineaPig class (without doing any harm to it!) and intercept all method calls.
When we intercept a method call, we first check if the declaring class of the method is a Thread class, if that's the case it means we are invoking a method in a Thread object. We then proceed to check if it's one of the two particular methods start and join.
When one of those two cases happen, we use the javassist highlevel API to do a code replacement. The replacement is easy to spot in the code, the actual code provided is where it might be a bit tricky so let's split one of those lines, let's take for example the line that will detect a Thread starting:
{ System.out.println(\"Detected thread starting with id: \" + ((Thread)$0).getId()); $proceed($$); } "

First all the code is inside curly brackets, otherwise javassist won't accept it
Then you have a System.out that references a $0. $0 is a special parameter that can be used in javassist code manipulations and represents the target object of the method call, in this case we know for sure it will be a Thread.
$proceed($$) This probably is the trickiest instruction if you're not familiar with javassist since it's all javassist special sugar and no java at all. $proceed is the way you have to reference the actual method call you are processing and $$ references to the full argument list passed to the method call. In this particular case start and join both will have this list empty, nevertheless I think it's better to keep this information.

You can read more about this special operators in Javassist tutorial, section 4.2 Altering a Method Body (search for MethodCall subsection, sorry there's no anchor for that sub-section)
Finally after all this kung fu we write the bytecode of our ctClass into the class folder (so it overwrites the existing GuinePig.class file) and when we execute it... voila, the output is now what we wanted :-)
Just a final warning, keep in mind that this injector is pretty simple and does not check if the class has already been injected so you can end up with multiple injections.


Python: regex to catch data

Question: I want to ask your help.
I have a large piece of data, which looks like this:
     a
  b : c 901
   d : e sda
 v
     w : x ads
  any
   abc : def 12132
   ghi : jkl dasf
  mno : pqr fas
   stu : vwx utu

Description: file begins with a line containing single word (it can start with whitespace and whitespaces can be also after the word), then follows line of attributes separated by colon (also can have whitespaces), then again line of attributes or line with a single word. I can't create the right regex to catch it in such form:
{
  "a": [["b": "c 901"], ["d", "e sda"]],
  "v": [["w", "x ads"]],
  "any": ["abc", "def 12132"], ["ghi", "jkl dasf"],
  # etc.
}

Here is what I've tried:
regex = str()
regex += "^(?:(?:\\s*)(.*?)(?:\\s*))$",
regex += "(?:(?:^(?:\\s*)(.*?)(?:\\s*):(?:\\s*)(.*?)(?:\\s*))$)*$"
pattern = re.compile(regex, re.S | re.M)

However, it doesn't find what I need. Could you help me? I know I could process file without regex, using line-by-line iterator and checking for ":" symbol, but file is too big to process it this way (if you know how to process it fast without regex, this also will be right answer, but first which comes in mind is too slow).
Thanks in advance!
P.S. In the canonical form of file looks like this:
a
  b : c 901
  d : e sda

Every section begins with a single word, then follow attributes line (after two whitespaces), there attributes are separated with (" : "), then agane attributes line or line with a single word. Other whitespaces are prohibited. Probably it will be easier.
Comment: +1 Super Clarity; Neatly framed question.
Answer: Are regular expressions really necessary here? Try this pseudocode:
result = {}

last = None
for _line in data:
    line = _line.strip( ).split( ":" )
    if len( line ) == 1:
        last = line[ 0 ]
        if last not in result:
            result[ last ] = []
    elif len( line ) == 2:
        obj = [ line[ 0 ].strip( ), line[ 1 ].strip( ) ]
        result[ last ].append( obj )

I hope I understand correctly your data structure.
Comment: This is the correct approach, no regex needed, I had an answer here I deleted because it is not unnecessary, this is the solution you need. (may need a little tweaking - but its what you want) +1
Answer: You can use this regex..
 (?:[\n\r]+|^)\s*(\w+)\s*[\n\r]+(\s*\w+\s*:\s*.*?)(?=[\n\r]+\s*\w+\s*[\n\r]+|$)

You need to match the above regex with singleline or dotall option
Group1 and Group2 matches what you want each time you match
check out here..use dot all option
Answer: # a more golf - like solution
from itertools import groupby

groups = groupby(map(lambda s: map(str.strip,s.split(':')), data), len)
dict((next(i[1])[0], list(next(groups)[1])) for i in groups)

out:
{'a': [['b', 'c 901'], ['d', 'e sda']],
 'any': [['abc', 'def 12132'],
  ['ghi', 'jkl dasf'],
  ['mno', 'pqr fas'],
  ['stu', 'vwx utu']],
 'v': [['w', 'x ads']]}

Python: regex to catch data


Drupal-7 - Lists and Custom Content Types

Question: I've just started with Drupal-7 coming from Drupal-5 that I last used a few years back and made a few customisations too. It seems to be Drupal-5 was much easier for modification, though Im starting to work out where all the data is saved processing through all the examples.
What isn't clear is when is a node not a node. For example, there are various support lists that I would like in my customisations, for example "salutation" (mr, mrs, miss, dr, revd etc) that should be user maintainable and stored in a database. It seems a bit overkill to create a separate content type and node just for this.
The current project Im working on is for Events, but I need to sub-categorise those Events twice by Event Type and Sub-Event-Type. Both of these should be user maintainable and therefore database driven. I can put them in a Content Type/Node but it does seem overkill.
I can't figure out if there's a programmatical way to insert, alter, delete (like the old days) into their own tables and then reference them in the Event node I will create generating a dynamic list.
There are lots of information out there about using Values, Taxonomy and Views etc. Seems everybody shys away from programming now and there's no examples anymore!
Any thoughts where to start? It seemed much easier finding the information before.
Answer: Organizing content with taxonomy (category) is a very powerful tool of Drupal.

What isn't clear is when is a node not a node. For example, there are
  various support lists that I would like in my customisations, for
  example "salutation" (mr, mrs, miss, dr, revd etc) that should be user
  maintainable and stored in a database. It seems a bit overkill to
  create a separate content type and node just for this.

According to this, you can manage "salutation" with taxonomy . The"salutation" is a vocabulary and "mr, mrs, miss, dr, revd" are terms of the vocabulary. They will be stored in the taxonomy table and the path admin/structure/taxonomy/your_vocabulary will be user maintainable list page.
You can create a custom field ( term reference ) to your vocabulary ( "salutation" in this case ) for your content type.
They can be chosen from a list when user creates a node.
Same concept for your Event Type and Sub-Event Type.
The Taxonomy Manager module may help you.
Comment: That looks absolutely perfect. Thank you. Works pretty well.


Understanding the confidence band from a polynomial regression

Question: I'm trying to understand the result I see in my graph below. Usually, I tend to use Excel and get a linear-regression line but in the case below I'm using R and I get a polynomial regression with the command:
ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + geom_smooth()

So my questions boil down to this:

What is the gray area (arrow #1) around the blue regression line? Is this the standard deviation of the polynomial regression?
Can I say that the whatever is outside the gray area (arrow #2) is an 'outlier' and whatever falls inside the gray area (arrow #3) is within the standard deviation?
Answer: The gray band is a confidence band for the regression line.  I'm not familiar enough with ggplot2 to know for sure whether it is a 1 SE confidence band or a 95% confidence band, but I believe it is the former (Edit: evidently it is a 95% CI).  A confidence band provides a representation of the uncertainty about your regression line.  In a sense, you could think that the true regression line is as high as the top of that band, as low as the bottom, or wiggling differently within the band.  (Note that this explanation is intended to be intuitive, and is not technically correct, but the fully correct explanation is hard for most people to follow.)
You should use the confidence band to help you understand / think about the regression line.  You should not use it to think about the raw data points.  Remember that the regression line represents the mean of $Y$ at each point in $X$ (if you need to understand this more fully, it may help you to read my answer here: What is the intuition behind conditional Gaussian distributions?).  On the other hand, you certainly do not expect every observed data point to be equal to the conditional mean.  In other words, you should not use the confidence band to assess whether a data point is an outlier.

(Edit: this note is peripheral to the main question, but seeks to clarify a point for the OP.)
A polynomial regression is not a non-linear regression, even though what you get doesn't look like a straight line.  The term 'linear' has a very specific meaning in a mathematical context, specifically, that the parameters you are estimating--the betas--are all coefficients.  A polynomial regression just means that your covariates are $X$, $X^2$, $X^3$, etc., that is, they have a non-linear relation to each other, but your betas are still coefficients, thus it is still a linear model.  If your betas were, say, exponents, then you would have a non-linear model.
In sum, whether or not a line looks straight has nothing to do with whether or not a model is linear.  When you fit a polynomial model (say with $X$ and $X^2$), the model doesn't 'know' that, e.g., $X_2$ is actually just the square of $X_1$.  It 'thinks' these are just two variables (although it may recognize that there is some multicollinearity).  Thus, in truth it is fitting a (straight / flat) regression plane in a three dimensional space rather than a (curved) regression line in a two dimensional space.  This is not useful for us to think about, and in fact, extremely difficult to see since $X^2$ is a perfect function of $X$.  As a result, we don't bother thinking of it in this way and our plots are really two dimensional projections onto the $(X,\ Y)$ plane.  Nonetheless, in the appropriate space, the line is actually 'straight' in some sense.
From a mathematical perspective, a model is linear if the parameters you are trying to estimate are coefficients.  To clarify further, consider the comparison between the standard (OLS) linear regression model, and a simple logistic regression model presented in two different forms:
$$
Y = \beta_0 + \beta_1X + \varepsilon
$$
$$
\ln\left(\frac{\pi(Y)}{1 - \pi(Y)}\right) = \beta_0 + \beta_1X
$$
$$
\pi(Y) = \frac{\exp(\beta_0 + \beta_1X)}{1 + \exp(\beta_0 + \beta_1X)}
$$
The top model is OLS regression, and the bottom two are logistic regression, albeit presented in different ways.  In all three cases, when you fit the model, you are estimating the $\beta$s.  The top two models are linear, because all of the $\beta$s are coefficients, but the bottom model is non-linear (in this form) because the $\beta$s are exponents.  (This may seem quite strange, but logistic regression is an instance of the generalized linear model, because it can be rewritten as a linear model.  For more information about that, it may help to read my answer here: Difference between logit and probit models.)
Comment: I think the default smoother Loess in use here, rather than polynomial regression?
Comment: +1 The examples in the documentation suggest to me the confidence is pretty high, perhaps 95%.
Comment: @gung thanks for the detailed answer (also you got a check!). I read your first statement and I'm a bit confused. Can you please elaborate more about it. If the resulted line is not straight line (y = mx+b) then what makes it linear? Thanks again for the answer.
Comment: The docs at http://docs.ggplot2.org/0.9.3.1/stat_smooth.html assert it's a 95% confidence band for the regression curve.
Comment: @adhg, I thought I had covered the linear vs. non-linear somewhere else, but I couldn't find it. So I added some extra material here. HTH
Comment: @xan, thanks for the tip. I don't really know ggplot2. I was responding to the fact that the question stated polynomial. If it's really a lowess, I think that would only impact the appropriateness the latter (peripheral) section. Moreover, I think I would categorize lowess as more *semi-parametric* rather than *non-linear*.
Comment: You seem to be making a specious distinction: if linearity is a property of a model, then how you write the model should not affect its linearity.  Thus logistic regression cannot be linear and nonlinear at the same time.
Comment: @whuber, do you mean that I should state linearity is a property of the form of the model, rather than a property of the model?
Comment: I think people could consider "linear" in either sense. The deeper sense is the one that is independent of how the model is written. In that sense, for instance, the model $Y=\beta_0+\beta_0\beta_1 X+\varepsilon$ could be considered linear because it is linear in $\alpha_0=\beta_0$ and $\alpha_1=\beta_0\beta_1$. In some cases, though, this change would not be allowable because interest might focus on confidence intervals for the $\beta_i$. I think, though, that we may only be muddying the waters here and we should stick with the simplest, clearest examples of linear models as illustrations.
Comment: @xan You are correct: the curve clearly is not a polynomial fit. That misperception was introduced at the beginning of the question, not by gung or ladislav (whose answer begins with an appropriate correction), but fortunately it is not really germane to the answers, which apply regardless of the nature of the fit.
Answer: To add to the already existing answers, the band represents a confidence interval of the mean, but from your question you clearly are looking for a prediction interval. Prediction intervals are a range that if you drew one new point that point would theoretically be contained in the range X% of the time (where you can set the level of X).
library(ggplot2)
set.seed(5)
x <- rnorm(100)
y <- 0.5*x + rt(100,1)
MyD <- data.frame(cbind(x,y))

We can generate the same type of plot you've shown in your initial question with a confidence interval around the mean of the smoothed loess regression line (the default is a 95% confidence interval).
ConfiMean <- ggplot(data = MyD, aes(x,y)) + geom_point() + geom_smooth()
ConfiMean

For a quick and dirty example of prediction intervals, here I generate a prediction interval using linear regression with smoothing splines (so it is not necessarily a straight line). With the sample data it does pretty well, for the 100 points only 4 are outside the range (and I specified a 90% interval on the predict function).
#Now getting prediction intervals from lm using smoothing splines
library(splines)
MyMod <- lm(y ~ ns(x,4), MyD)
MyPreds <- data.frame(predict(MyMod, interval="predict", level = 0.90))
PredInt <- ggplot(data = MyD, aes(x,y)) + geom_point() +
           geom_ribbon(data=MyPreds, aes(x=x,ymin=lwr, ymax=upr), alpha=0.5)
PredInt

(note: actual confidence intervals are smoother, as there was a code typo in the original answer)
Now a few more notes. I agree with Ladislav that you should consider time series forecasting methods since you have a regular series since sometime in 2007 and it is clear from your plot if you look hard there is seasonality (connecting the points would make it much clearer). For this I would suggest checking out the forecast.stl function in the forecast package where you can choose a seasonal window and it provides a robust decomposition of the seasonality and trend using Loess. I mention robust methods because your data have a few noticeable spikes.
More generally for non-time series data I would consider other robust methods if you have data with occasional outliers. I do not know how to generate prediction intervals using Loess directly, but you may consider quantile regression (depending on how extreme the prediction intervals need to be). Otherwise if you just want to fit to be potentially non-linear you can consider splines to allow the function to vary over x.
Answer: Well, the blue line is a smooth local regression. You may control the wiggliness of the line by the span parameter (from 0 to 1). But your example is a "time-series" so try to look for some more proper methods of analysis than only fit a smooth curve (which should serve only to reveal possible trend).
According to documentation to ggplot2(and book in comment below): stat_smooth is a confidence interval of the smooth shown in grey. If you want to turn the confidence interval off, use se = FALSE.
Comment: (1) I do not see in your reference where it claims the gray area is the pointwise confidence interval.  It seems pretty clear from the examples that the gray area is instead a confidence interval for the *curve*.  (2) Nobody would reasonably declare the large proportion of points beyond the gray area as "outliers"; there are just too many of them.
Comment: (1) my mistake, here I add a book which refers to "point-wise confidence interval": Wickham H (2009) ggplot2 Elegant Graphics for Data Analysis. Media 212. (page 14). (2) I agree.
Comment: Do any of your references state what the default confidence level is set at?
Comment: No, I can't find any reference about default setting.
Comment: I found the default on the first page of your reference: "(0.95 by default)." That means that either this smoother has serious bugs or else your interpretation of the reference is wrong: because such a large proportion of the data points typically lie beyond the gray area and assuming the code is correct, the gray area *has* to be a confidence region for the prediction (fitted curve) and not a confidence region for the points.
Comment: I'm not as experienced as you. If you consider my answer wrong, feel free to delete it completely. I do not want to earn my reputation by creating non-useful answers.
Comment: The issue here is that two conflicting but reasonable answers have been posted.  People should decide between them based on the arguments adduced in their support, not on the experience or reputation of those making the arguments.  That is why I have posted comments explaining the evidence that suggests to me why @gung's answer is the right one and this one may be in error--but it's always possible I am making a mistake somewhere, too.


Is this proof of convergence right?

Question: I was curious to analyze the convergence of the series $$\sum_{n=1}^{\infty} \frac{1}{n^{(2+\frac{1}{n})}}$$ Because I would be able to evaluate it via integral $$\int_{1}^{\infty} \frac{1}{x^2}\cdot\frac{1}{x^{\frac{1}{x}}} \ dx$$
$$= \int_{1}^{\infty} \frac{1}{x^2} \cdot \left( \frac{1}{x} \right)^\frac{1}{x} \ dx $$ if I replace by $u=\frac{1}{x}$ I get
$$\int_{0}^{1} u^u \ du$$
Which means that the integral has a finite value and hence the series converges.
But I am not sure if I failed somewhere during this reasoning and would like to know if there is any error.
Comment: You could also do comparison to $\sum n^{-2}$.
Answer: Your proof is correct, it is great way to prove it actually.
I will just organize it slightly:
We know: $$\sum_{n=1}^\infty \frac{1}{n^{(2+\frac{1}{n})}} \le \int_{0}^{\infty}\frac{1}{x^2}*\frac{1}{x^{\frac{1}{n}}} dx$$
$$\sum_{n=1}^\infty \frac{1}{n^{(2+\frac{1}{n})}} \le \int_{0}^{\infty}\frac{1}{x^2}*(\frac{1}{x})^\frac{1}{n} dx $$
Using the substitution $u=\frac{1}{x}$ yields:
$$\sum_{n=1}^\infty \frac{1}{n^{(2+\frac{1}{n})}} \le \int_{0}^{1}u^u du$$
And since $$ \int_{0}^{1}u^u du = C $$ where $C$ is a finite constant.
Therefore, $$\sum_{n=1}^\infty \frac{1}{n^2{(2+\frac{1}{n})}} \le C  $$
Meaning, the sum has a value less than or equal to C $\implies$ Converges.
Also, if this helps, we can simplify the integral to another sum: $$\int_{0}^{1}u^udu$$ as follows:
$$\int_{0}^{1}u^u du = \int_{0}^{1}e^{u\ln(u)} du $$
Recall, $$e^z=\sum_{n=0}^{\infty}\frac{z^n}{n!}$$ valid for all $z$.
$$\implies \int_{0}^{1}e^{u\ln(u)} du = \int_{0}^{1} \sum_{n=0}^{\infty} \frac{(u\ln(u))^n}{n!}du $$
$$\implies \int_{0}^{1}e^{u\ln(u)} du =  \sum_{n=0}^{\infty}\frac{1}{n!} \int_{0}^{1}u^n*(\ln(u))^n du \space\space\space\space (*)$$
Let $$ J = \int_{0}^{1}u^n*(\ln(u))^n du $$
Make the change of variables $u=-\ln(x)$ to get:
$$J = \lim_{\alpha-->\infty} (-1)^n\int_{0}^{\alpha}e^{-(n+1)u}u^n du$$
Let $t=(n+1)u$
Hence, $$J = (-1)^n \lim_{\alpha-->\infty} \int_{0}^{\alpha} \frac{t^n*e^{-t}}{(n+1)^{(n+1)}} dt \iff J = \frac{(-1)^n}{(n+1)^{n+1}} \lim_{\alpha-->\infty} \int_{0}^{\alpha} t^n*e^{-t} dt $$
The RHS looks similar to $\Gamma(z)=\lim_{\alpha -->\infty} \int_{0}^{\alpha}e^{-t}t^{z-1} dt$
So, $$J = \frac{(-1)^n}{(n+1)^{n+1}} \Gamma(n+1) = \frac{(-1)^n}{(n+1)^{n+1}}*n! $$
Substituting in (*) yields:
$$\int_{0}^{1}e^{u\ln(u)} du = \sum_{n=0}^{\infty}\frac{(-1)^n}{(n+1)^{n+1}}=\sum_{n=1}^{\infty}\frac{(-1)^{n-1}}{n^n} $$
Which is our original integral. It is known that this alternating series converges to ~0.7834. The proof however, I do not know of.
(Note I got this integral simplification idea from Dr. Peyam on YouTube.)
Comment: The OP uses the Integral test which requires the function to be monotone decreasing. See the other answer.
Comment: That was brilliant, I really appreciate your contribution, sir.
Comment: @bob, Oh yes, I forgot to use it at the start, but it came out to be monotone decreasing either way.
Answer: You are missing something: you need to show that your integrand $\frac{1}{x^{2 + 1/x}}$ is monotone decreasing for sufficiently large $x$. This is a requirement of the integral test.
Let $f(x) = \frac{1}{x^{2 + 1/x}}$. Then, using logarithmic differentiation,
\begin{align*}
\log f(x) &= -\left(2 + \frac{1}{x}\right)\log x \\
f'(x) &= f(x) \cdot \left(\frac{1}{x^2}\log x - \frac{2}{x} - \frac{2}{x^2}\right) \\
&= \frac{f(x)}{x^2} \cdot (\log x - 2x - 2).
\end{align*}
For large $x$, the $-2x - 2$ will dominate the logarithm, and $\frac{f(x)}{x^2} > 0$ for any $x$, so for large $x$, $f'(x) \le 0$, and so the integrand is monotone decreasing. Thus, the integral test holds, and your (augmented) solution shows convergence.
Comment: @excitedGoose No, the monotonicity requirement is necessary. Remember, you are essentially just sampling a whole continuous function at integer points. Without monotonicity, you could have your function drop to $0$ at integer points, but have infinite area under the function. Or, you could create sharp, large peaks at integer points, but still have a finite area. Monotonicity is necessary for the usual argument, involving forming the series as right/left Riemann sums, and either fitting this in the region under the graph, or vice-versa.
Comment: I thought this condition was valid to just establish a relation between a series and an integral (even if the integral yields infinity, for example). But, if an integral, in an interval of positive terms (from a point to infinity), shares the same expression of a series and yields a finit value, doesn't it automatically mean that the function is decreasing and tending to zero at it's "end". Otherwise, it would diverge, would not?
Comment: As a concrete example, consider $f(x) = \inf_{n \in \Bbb{Z}} |x - n|$. This is a continuous (indeed, non-expansive) function that produces essentially a sawtooth wave; $0$ at integer points, $1/2$ at the midpoints of successive integers, and straight lines connecting them. Then $\sum_{n=1}^\infty f(n) = \sum_{n=1}^\infty 0 = 0$, but $\int_0^n f(x) \, \mathrm{d}x = \frac{n}{4} \to \infty$ as $n \to \infty$.

Is this proof of convergence right?


MediaPlayer error(1,-1010) MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED

Question: Im implemented my music player function and sometimes the ogg files throws the (1,-1010) thats means

MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED

error. There is nothing wrong with file format because sometimes the file loading correcly (lets say 70% correcly 30% got that error).
private void loadAudio(){
        if(!readyToPlay){
            elapsedTimeStart.setText("");
            elapsedTimeEnd.setText(context.getString(R.string.loading));
            mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaplayer.setDataSource(audioURL);
            mediaplayer.prepareAsync();
            mediaplayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    double ratio = percent / 1000.0;
                    bufferingLevel = (int)(mp.getDuration() * ratio);
                    seekBar.setSecondaryProgress(bufferingLevel/SECOND);
                }
            });
            mediaplayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.i("lang","on error " +what +" extra "+ extra);
                    switch (what) {
                        case MEDIA_ERROR_UNKNOWN:
                            Log.i(TAG, "MEDIA_ERROR_UNKNOWN");
                            break;
                        case MEDIA_ERROR_SERVER_DIED:
                            Log.i(TAG, "MEDIA_ERROR_SERVER_DIED");
                            Toast.makeText(context, context.getString(R.string.problems_connecting_try_again), Toast.LENGTH_SHORT).show();
                            break;
                    }
                    switch (extra) {
                        case MEDIA_ERROR_IO:
                            Log.i(TAG, "MEDIA_ERROR_IO");
                            break;
                        case MEDIA_ERROR_MALFORMED:
                            Log.i(TAG, "MEDIA_ERROR_MALFORMED");
                            break;
                        case MEDIA_ERROR_UNSUPPORTED:
                             Log.i(TAG, "MEDIA_ERROR_UNSUPPORTED");
                            break;
                        case MEDIA_ERROR_TIMED_OUT:
                            Log.i(TAG, "MEDIA_ERROR_TIMED_OUT");
                            Toast.makeText(context, context.getString(R.string.problems_connecting_try_again), Toast.LENGTH_SHORT).show();
                            break;
                    }
                    return false;
                }
            });

            mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.i("lang", " SUCCEFULLY PREPARED");
                    readyToPlay = true;
                    durationTime = mp.getDuration();
                    durationHour = durationTime /HOUR;
                    durationMint = (durationTime %HOUR)/MINUTE;
                    durationSec = (durationTime %MINUTE)/SECOND;
                    elapsedTimeStart.setText(String.format("%02d:%02d:%02d",currentHour,currentMin,currentSec));
                    elapsedTimeEnd.setText(String.format("%02d:%02d:%02d", durationHour, durationMint, durationSec));
                    seekBar.setMax(durationTime /SECOND);
                    play();
                }
            });
        } catch (IllegalArgumentException|SecurityException|IllegalStateException|IOException e) {
            Log.i("lang","Exception!");
            e.printStackTrace();

        }
        catch (Exception e){
            Log.i("lang", "Exception!! smthing goes wrong ");
            e.printStackTrace();

        }

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mediaplayer != null && fromUser) {
                    timeElapsed = durationTime * progress / 100;
                    mediaplayer.seekTo(timeElapsed);
                    if (durationTime / SECOND == timeElapsed / SECOND)
                        stop();
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }}

EDIT: I debug my program and the first callback which trigger after mediaplayer.prepareAsync()  is onPrepared method. Is there a way to check when the (MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED) occurs on this state and recall loadAudio() function to get correct track?
Comment: In my case, I had Gzip Compression on the web address where the url info is. Compressed media files may not be decoded on android.
Answer: There is problem with URL, the URL is incorrect or the server not sending proper response by this URL.
Thats why this URL give this Error  MEDIA_ERROR_MALFORMED
EDIT
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {

                LogUtils.e(TAG, "onError() called : what=="+what);
                LogUtils.e(TAG, "onError() called : extra=="+extra);

                return false;
            }
        });

Comment: but this problem do not occur every time when Ive been testing with the same url
Comment: did you try this URL working on browser.
if not, hit this URL to browser direct. If it plays there then it should be over code.
Comment: hmmm The url that I testing works every time in browser, but when Ive tested another url form sample mp3 page, it works on every time in my app. So I assumed that its the server fault. Is there any way to increase the response time or handle it?
Comment: The response is depend on Server,

But you can handle your response by setting `onErrorListener` on `MediaPlayer`. this will give you error code and that code will help you to handle your App.

See My Edit


Redirect Module doesn't redirect from node/{nid} to alias

Question: I installed the redirect Module in Drupal 8 but sorrily can't get it to work properly. I enabled all checkboxes in the settings, also the "Enforce clean and canonical URLs" option.
In my page source, the canonical is printed in a meta tag. But if I browse my page and enter a system URL like www.domain/node/5, no redirect to the autopath alias / canonical happens.

Does anyone have any suggestions? I also reinstalled it twice already. Nothing helped.
Comment: Have you tried completly wiping cache? I had the same problem until I did a `drush cr` on command line
Comment: I just cleared the cache in the Backend UI, as this Drupal site sorrily doesnt have drush installed. Is there any possibility to wipe the cache completely without drush?
Comment: Clearing cache via Development > Performance is the same as full wipe via `drush cr`. If that didn't help it is a different problem.
Comment: Perhaps this needs to be implemented to get the features you need working: [Merge global redirect functions into Redirect module](https://www.drupal.org/project/redirect/issues/905914).
Comment: Thanks @prkos, but this was only neccessary, before global redirects was merged with redirect module. The Drupal 8 version is a combination of those two modules. Anyways thanks - I already found out why it didn't work.
Answer: LEL - it's so stupid, I have to clarify this. The redirect module works without any problem. Everything's just like I wanted it. Maybe it's pointed out anywhere, but I didn't read it.
When the page is set to maintenance mode, it doesn't work. I have some dummy-users that can bypass the "maintenance-page" and use the site. While the site is in maintenance mode, the node/IDs are accessible. When I turned off maintenance mode, the module was redirecting...


Why would someone use a DI box if they're recording directly into the external sound card

Question: It has been recommended to me to connect my bass directly to a DI box and then into my external sound card.
The sound card is MOTU 896.
I don't understand why this is the case and the person who suggested it is no longer around for me to ask.
I was under the impression from other posts like What does a DI box do? that you'd use a DI Box for live performance, where the signal was going into a console, but in this case, it's going directly into the sound card, over a short distance (no more than 3 metres).
I understand a DI box may add some character/flavour, but, is there any real need to use a DI Box when recording bass guitar (dry) and the intention is to use an bass amp simulation (VST).
Answer: The job of a DI box is not to colour the sound at all. Some may, but that is not the original purpose. The original purpose is impedance matching.
You only need a DI box when you are going into what would otherwise be a mis-matched input, for instance a mic or line input. Most computer interfaces these days have a third option - instrument -  which would be suited to plugging a bass or guitar straight into.
Sometimes there is a hardware or even software switch on a dual-purpose line/instrument jack, sometimes it just has broad enough characteristics that it can accept both.
There are secondary/tertiary purposes, but not really relevant to this particular application - that of balancing a signal so it can be pushed a long way; to a studio patch-board or over long distances for live work.
There's also the potential for a ground-lift to isolate earthing/grounding issues. In a home studio, you may run into grounding issues, but any hum in a home environment is most likely to be induction from nearby computer monitors, lighting etc. It's always worth testing to see if a ground-lift DI may fix it, but it won't fix induction, only true ground issues.
Comment: For the OP: guitars and *some* bass, the jargon term to look for is "hi-Z" which is shorthand for high impedance. The manual for the 896 mk 3 hybrid specifically mentions "HI-Z" rear inputs when identifying the input gain knobs on the front panel. It also states "All eight inputs have preamps, so you can plug just about anything into them: a microphone, a guitar, or a synth. If you plug in a +4 or -10 line level signal, use the quarter-inch jack and be sure to enable the -20 dB pad." So for instrument direct in, do not enable the -20 pad.
Comment: @Yorik - yup, I did read that, but just decided to leave my answer more generic, for future googlers.
Answer: No reason for that. A DI box will change the impedence of the signal, and also convert it to a balanced output; if you need to be over 20ft or so from the mixing console, a DI box is essential.
Some DI boxes also model the sound for you - e.g SansAmp, Tonehammer etc - but as you already know, that's not essential.
In short - plug into the sound card, and enjoy playing the bass. Worry about a DI box once you get to playing out live.
Comment: It's worth noting that sound cards can have relatively low-impedance "Hi-Z" inputs.
Answer: When recording to a sound card, a reason to use a DI box is input impedance. (DI boxes have many other uses in live sound)
EDIT: Looking at the manual of the MOTU 896 interface, I'm not sure if it is an issue. The manual says the quarter-inch jacks will "accept" a guitar, and that the inputs are "high impedance", but I couldn't find numerical figures about what that actually means. As a warning example, the Echo product demonstrated below was advertised as "high impedance", but the numbers were like 1/10 of a normal guitar amplifier and the sound was bad. It might be an issue for you. Owning a good-quality DI box never hurt anyone.
Some sound cards may be relatively bad in this regard, despite the manufacturer's claims. The lower the input impedance (i.e. alternate-current resistance) is, the more work the guitar's pickups have to do in order to create a voltage between the poles of the input. (Mainly talking about passive electronics, with no battery power on the guitar or anything.) If there's very little resistance, it's easy for the electrons i.e. electric current to start moving through the wire. But moving electrons is not what you want to do, you want to move the signal and that's done by creating a voltage i.e. electrical pressure or tension in the wire. Through the magnetic pickups, the motion energy of the strings pulls an electronic "signal rope" (for the lack of a better analogy), and you don't really want the pull to succeed, you just want there to be lots of tension. The receiving end (input) detects the tension, and so signal is transmitted. But the rope shouldn't move. The more it moves, the more you have to pull it in order to keep the level of tension, and that means work, which eats energy. You want the vibration of the strings to generate a voltage (tension), not work as an electric power supply. If the energy is transformed into electrical current, high frequencies are attenuated and the notes lose sustain, because the energy is "leaked" to unnecessary things.
Check out this comparison between an old Echo AudioFire 8 audio interface's "guitar/bass" input called "Hi-Z", which the manual says is 102 kOhm, and the same single-coil Squier strat played through a Countryman Type 85 DI box that's 10 MOhm according to the manufacturer. The standard for guitar amps is said to be 1 MOhm.

I think that's like two completely different instruments. The 102 kOhm value is not very good for a "guitar" input, when the standard for guitar amps is 10 times higher, 1 MOhm. But hey, just call it "Hi-Z" and "guitar/bass" and everyone is happy? ;)
A similar phenomenon or rule applies to amplifiers and speakers. The lower the impedance of the speakers is, the more "watts" you have to have on the amp side, because the amp will have to do more work to create the electric tension i.e. voltage. The ultimate low-impedance load would be a short-circuit, which will (if it's not protected) cause the amp to overload and burn a fuse or itself. This is why amps have a specified minimum speaker Ohm value, so you shouldn't use anything below 4 Ohms, for example.
Comment: 100 kΩ should certainly not be called "hi-Z". Pretty sure most interfaces have better values, at least 500 kΩ. Meanwhile, most DIs that aren't specifically intended to double as acoustic guitar preamps only have something like 200 kΩ, and many passive DIs much lower than that, so just saying "use _a_ DI" isn't really helpful at all.
Comment: Also worth noting that many guitar amps and effects pedals also only have an impedance in the 200 kΩ range. And that _after_ any effects pedal / buffer or with an active bass, the impedance of the input becomes almost completely irrelevant.
Answer: Theoretically, there is no need to run into a DI and then into an external soundcard. In practice... maybe.
The job of a direct input box is to convert a guitar's or bass's high-impedance signal circuit to a low-impedance mic/line circuit to send "directly" to the mixer, instead of capturing the instrument's sound by putting a mic in front of the speaker cabinets. In live sound, a direct box gives the sound engineer a cleaner bass sound with less fiddling to mix in to the PA mains; a cabinet mic will pick up other sound including the crowd, and mic positioning has an important effect on tone so sound checks will take longer as a stage hand futzes with the cab mic to give the sound engy what he wants. A DI also reduces the required size and power of a bassist's "stage rig", often to just the DI itself, as the DI pumping his sound into the PA should give the band all the bass they need through the system's mains and monitors.
While designed for these stage uses, they're also useful for recording, as they allow inputting instrument signals directly into studio equipment like multitrack recorders, with no microphone needed. This again gives you a cleaner input without, say, the sounds of your three elementary-age daughters banging around upstairs doing God knows what (just a hypothetical, in absolutely no way whatsoever related to my personal experience laying down tracks). It also allows you to lay down guitar riffs or bass lines into your DAW at any time of the day or night, without needing a mic'ed amp blaring your bass tone at performance levels into your SM-57 (and the rest of the house).
Now, your average external soundcard (aka "audio interface", to further differentiate from the internal soundcard hardware of your PC) will commonly support "Hi-Z" inputs by incorporating a DI transformer circuit into the interface design. That increases the value of this piece of gear, and reduces your initial investment, by reducing the need for additional equipment in your home studio to make the interface useful. Almost all the major brands and models of USB audio interface allow plugging in at least one instrument. So, you don't need to have a separate DI in the signal chain.
Now, here's where theory meets practice. These audio interfaces are built on a budget, to meet a pricepoint that's attractive to the average music hobbyist. As such, they usually cut a corner somewhere, and one option is that DI circuit. To avoid making the interface too large (and heavy and expenive), a much smaller transformer coil is typically used for each input, and that has an effect on sound quality. A dedicated DI box will usually have a more substantial transformer, that more faithfully reproduces the upstream signal. That signal, now balanced and running into the interface via an XLR or TRS cable, will bypass the DI circuit in the soundcard, giving you cleaner tone and less noise in the DAW tracks.
Dedicated DIs can also have other circuitry, ranging from a simple gain boost ("Active" DIs boost the gain and reduce transformer impedance to reduce signal attenuation over a long run through the snake to the sound desk) to a full tone-shaping preamp (the LR Baggs Paracoustic DI is a combination DI/preamp designed for acoustic guitars; the Tech21 SansAmp is a more well-known general-purpose preamp for electric guitar and bass). If you get your live performance tone through one of these devices, there's a lot to recommend keeping it in the signal chain in your home studio at least as a starting point, and very few reasons to skip it.


Forward mDns from one subnet to another?

Question: Is there an ipfw rule that can easily forward mDns packets from one subnet to another?  I have a Snow Leopard Server machine serving as the gateway between the two subnets and would like for machines in each subnet to see the services available in the other subnet.  The gateway machine is already confirmed as configured correctly such that packets route correctly between the two subnets (ping works, traceroute shows the subnet hop, etc).  My problem in designing a ipfw rule is that I don't know how to instruct that I would like multicast packets addressed to 188.8.131.52:5353 on en0 to be addressed to the same ip/port but on fw0 (the other interface).  I attempted a rule such as
fwd 192.168.10.1 log udp from 192.168.1.0/24 to 18.104.22.168 recv en1
to force the packet to hop over to the other interface (from en1 to fw0), but no dice.  The ipfw log shows that the rule is being triggered by packets, but tcpdump isn't showing any packets on the other interface.  Also, the only other firewall rules in place are the divert port 8668 and rule #65535 "allow any to any".
Any suggestions?  Thanks.
Answer: I've tried to have this work as expected for a long time.
All I found is that these multicast packets will not cross subnets.
However, the only real solution I have found is to use an mDNS Reflector daemon such as avahi-daemon on a system which spans across subnets.
It also sounds like you could benefit from Wide Area Bonjour which is designed for large corporations to broadcast Bonjour / mDNS traffic across subnets.
See http://discussions.apple.com/thread.jspa?threadID=1251044
Comment: I think that it is also worth mentioning what needs to be done to get it working:
1. set `enable-reflector=yes` in /etc/avahi/avahi-daemon.conf;
2. restart avahi-daemon: `sudo service avahi-daemon restart` (or equivalent for your OS).

Didn't even need to install anything, as on Raspberry Pi OS avahi comes pre-installed and activated by default.
Comment: I've been trying the same problem for a few days now, and indeed, the only working solution (and unexpectedly simple one) was to use avahi.
Answer: In short, no. As per RFC2365 and IANA's multicast assignments, 188.8.131.52/24 is reserved for link-local multicast. This means that a multicast packet address to anything in the range 188.8.131.52 - 18.104.22.168 should never cross between IP subnets.
I've not looked in to wide area Bonjour, which is mentioned in another answer, however if this is to work, it must use multicast addresses that do not come from 126.96.36.199/24
Comment: There is some talk about mDNS Gateways here:
http://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst3850/software/release/3se/multicast/configuration_guide/b_mc_3se_3850_cg/b_mc_3se_3850_cg_chapter_010100.html
Answer: occur to same problem, i wrote a simple mdns forward proxy. forward mdns to dns service. https://github.com/naughtyGitCat/mdns-proxy
assuming we have a net area A(192.168.1.0/24), have machines run mdns compatible daemon, (linux avahi-daemon, windows wins, macos bonjor)
and another net area B(192.168.2.0/24), can't access area A machines by .local
run ./mdns-proxy --debug on oneof area A machine which run avahi-daemon. add this machine ip to area B machine dns server lis


How can I tell the raw size of a MySQL DB snapshots in Amazon RDS?

Question: When I launch an Amazon MySQL database instance in RDS, I choose the amount of Allocated Storage for it.
When I create a snapshot (either manually or with the automatic backup), it says under "Storage" the same size as the size allocated for the instance, even though my database did not reach that size.
Since the pricing (or the free tier) in Amazon is dependent on the amount of storage used, I would like to know the real storage size I'm using, rather than the size allocated by the original database.
From looking at the Account Activity, and from knowing how mysqldump works, I would guess the snapshot does not really include the empty space allocated.
Answer: I was interested in the answer to this question and a google search brought me here.  I was surprised to see that although there is an accepted, upvoted answer, it does not actually answer the question that was asked.
The question asked is:

How can I tell the raw size of a MySQL DB snapshots in Amazon RDS?

However, the accepted answer is actually the answer to this question:

Am I charged for the allocated size of the source database when I take an RDS snapshot from it.

As to the the original question, AFAICT, there is no API or console function to determine the storage used by an RDS snapshot.  The DBSnapshot resource has allocated_storage (ruby, java), but this returns the storage maximum size requested when the database was created.  This mirrors the AWS RDS console:

One might have thought this would be broken out on the AWS bill, but it provides very little details.  For RDS:

The S3 part of the bill is even less helpful:

Conclusion, there is no way to tell the raw size of a MySQL DB snapshot in Amazon RDS.
Comment: I like this, but the accepted answer is shorter, to the point, and more importantly actionable. While "you can't" is a more precise answer it helps me less. I hope this answer rises to the top by popular because it is also useful.
Answer: RDS is being stored through EBS according to FAQ:

Amazon RDS uses EBS volumes for database and log storage.

EBS doesn't store empty blocks, according to its pricing page:

Because data is compressed before being saved to Amazon S3, and Amazon EBS does not save empty blocks, it is likely that the snapshot size will be considerably less than your volume size.

And takes space only for changed blocks after initial snapshot was made, according to details page:

If you have a device with 100 GB of data but only 5 GB has changed after your last snapshot, a subsequent snapshot consumes only 5 additional GB and you are billed only for the additional 5 GB of snapshot storage, even though both the earlier and later snapshots appear complete.
Comment: You are now the accepted answer, which somewhat makes your answer a paradox!
Comment: After reviewing the improved documentation that AWS provides nowadays about the internal workflows of EBS and RDS snapshots pricing, I must accept the fact that you are 100% right. My answer was "the best" aproximation in those days, when the AWS insights where much more dark than what is today.
Answer: RDS backups are block level full virtual machine snapshots; no mysqldump at all is involved. Given this fact, each of your snapshots will use exactly the same ammount of storage as your production instance at the moment the backup took place.
Comment: Can anyone confirm this is correct? My understanding is that AWS snapshot backups are incremental. For example, the snapshot is 100G. The underlying storage for 10 snapshots should be much less than 10x100G.
Comment: @XinChen, I am 100% sure this is incorrect, see my answer.
Comment: Maybe I didn't explain myself correctly. I meant the snapshot uses the instance USED storage. To be more precise, the provisioned storage minus the Cloudwatch metric Free Storage Space.


Erro na interface da listagem

Question: Estou fazendo um exercicio da faculdade, e quando vou aciono o click do botão resposavel por fazer a listagem, a minha tabela é refeita inteira, assim perco os nomes que deveriam ser fico na primeira linha, que são:
-Codigo
-Limite do Prazo
-Nome do Usuario
-Categoria
-Comentarios
Porem, a primeira linha já é logo substituida pelas informações do banco

Listagem

        <button id="btListar" class="btn btn-info">Listar Atendimentos</button>

                  Codigo
                  Limite do Prazo
                  Nome do Usuario
                  Categoria
                  Comentarios

 var auxHTML = '';
 listaObjetos = JSON.parse(resposta);
 var total = listaObjetos.length;
 for (var i = 0; i < total; i++) {
    auxHTML += '
' +
            '' + listaObjetos[i].code + '	' +
            '' + listaObjetos[i].deadline + '	' +
            '' + listaObjetos[i].userName + '	' +
            '' + listaObjetos[i].category + '	' +
            '' + listaObjetos[i].comments + '	' +
            '
';
              }
  $('#tabelaLista').html(auxHTML);

Comment: @user140828 Funcionou perfeitamente! Gostaria de adicionar a correção para eu poder marca-la?
Answer: O método .html(meuHTML) do jQuery sobrescreve todo o HTML do objeto encontrado, para concatenar mais HTML com o já existente, você pode utilizar .append(meuHTML) para adicionar esse HTML no final do já existente, ou .prepend(meuHTML) para adicionar o HTML no início do já existente.
Comment: Obrigado! Com a explicação ficou perfeito!

Erro na interface da listagem


Simplify SQL where exists in clause

Question: I want to simplify the below given procedure especially I want to remove most of the where clause filters such as IN and exists clauses.
For that, I have used a CTE and also declare a temp table and used it to get the select query that was talking long time since it was in where in clause. I would appreciate if you could show me some tricks in order to simplify this query.
ALTER PROCEDURE dbo.GetMappingBranchScenarios
    @Mapping INT
    @UserId INT= NULL
    @BranchId INT = NULL

SELECT
    BS.BranchId,
    NULLIF( CC.Code, '' ) AS Code,
    BS.BranchName,
    BS.Active
FROM
    Branch BS
LEFT OUTER JOIN
    Code CC ON CC.BranchId = BS.BranchId
LEFT OUTER JOIN
    BranchRule BRE ON BRE.MappingId = @Mapping
                   AND BRE.BranchId = BS.BranchId
WHERE
    (BS.Active = 1
        OR EXISTS (SELECT * FROM BranchRule BRE
                   WHERE BRE.BranchId = BS.BranchId
                     AND BRE.BranchId > 0
                     AND BRE.MappingId = @MappingId))
     AND (@UserId IS NULL
             OR BS.BranchId IN (SELECT BranchId
                                FROM branch2mapping.dbo.ListBranch(@UserId))
             OR EXISTS (SELECT 1 FROM dbo.SecondaryMapping
                        WHERE Id = @UserId AND Admin = 1))
    AND BS.BranchId = (CASE WHEN BranchId is NULL THEN BS.BranchID ELSE @BranchId END)
    AND CC.Code =  (CASE WHEN @Code IS NULL THEN CC.Code ELSE @Code END)
ORDER BY
    CC.Code ASC

What I have done so far :
IF OBJECT_ID('tempdb..#Temp', 'U') IS NOT NULL
    DROP TABLE #Temp

CREATE TABLE #Temp (BranchId INT)

SELECT BranchId
FROM branch2mapping.dbo.ListBranch(@UserId)

;WITH CTE AS
(
    SELECT
        BS.BranchId,
        NULLIF(CC.Code, '' ) AS Code,
        BS.BranchName, BS.Active
    FROM
        Branch BS
    LEFT OUTER JOIN
        Code CC ON CC.BranchId = BS.BranchId
    LEFT OUTER JOIN
        BranchRule BRE ON BRE.MappingId = @Mapping
                       AND BRE.BranchId = BS.BranchId
)
SELECT *
FROM CTE
WHERE
    (CTE.Active = 1
     OR EXISTS (SELECT * FROM BranchRule BRE
                WHERE BRE.BranchId = CTE.BranchId
                  AND BRE.BranchId > 0
                  AND BRE.MappingId = @MappingId))
     AND (@UserId IS NULL
             OR BS.BranchId IN (SELECT * FROM #Temp)
             OR EXISTS (SELECT 1 FROM dbo.SecondaryMapping
                        WHERE Id = @UserId AND Admin = 1)
         )
     AND BS.BranchId = (CASE WHEN BranchId is NULL THEN CTE.BranchID ELSE @BranchId END)
     AND CTE.Code = (CASE WHEN @Code IS NULL THEN CTE.Code ELSE @Code END)
 ORDER BY
     CTE.Code ASC

Thank you for all your help.
Answer: Could you try if this is faster and still returning the same values with different filtering criteria?
ALTER PROCEDURE dbo.GetMappingBranchScenarios
    @Mapping INT
    @UserId INT= NULL
    @BranchId INT = NULL

DECLARE @IsRuleExists BIT;
DECLARE @IsUrerADmin BIT;

IF EXISTS
(
    SELECT 1
    FROM Branch BS
    INNER JOIN BranchRule BRE
        ON BRE.BranchId = BS.BranchId
        AND BRE.BranchId > 0
        AND BRE.MappingId = @MappingId
)
BEGIN;
    SET @IsRuleExists = 1;
END;

IF EXISTS
(
    SELECT 1
    FROM dbo.SecondaryMapping
    WHERE Id = @UserId AND Admin = 1
) OR @UserId IS NULL
BEGIN;
    SET @IsUrerADmin = 1;
END;

CREATE TABLE #Branches
(
    [BranchId] INT
);

INSERT INTO #Branches ([BranchId])
SELECT BranchId
FROM branch2mapping.dbo.ListBranch(@UserId);

SELECT
    BS.BranchId,
    NULLIF( CC.Code, '' ) AS Code,
    BS.BranchName,
    BS.Active
FROM Branch BS
LEFT OUTER JOIN Code CC
    ON CC.BranchId = BS.BranchId
WHERE
(
    BS.Active = 1 OR @IsRuleExists = 1
)
AND
(
    @IsUrerADmin = 1
    OR
    BS.BranchId IN (SELECT BranchId FROM #Branches)
)
AND BS.BranchId = (CASE WHEN BranchId is NULL THEN BS.BranchID ELSE @BranchId END)
AND CC.Code =  (CASE WHEN @Code IS NULL THEN CC.Code ELSE @Code END)
ORDER BY CC.Code ASC;

Comment: Sorry for the late response. It takes a sec to retrieve the value. Previously it took 9 sec. Thank you one again.

Simplify SQL where exists in clause


Creating and accessing Cookies in ASP.NET MVC3

Question: How can I create cookies in the controller and access it in any view just like for example
User.Identity.Name

I can use that code anywhere since the user has logged in and it's also removed when the user log out based on the default code of
FormsAuthentication.SetAuthCookie

Also I want to know how to delete or clear that cookie.
Answer: ....
//create cookie
var cookie = new HttpCookie("cookieName");

cookie.Value = "value";
Response.Cookies.Add(cookie);

//remove cookie
var cookie = new HttpCookie("cookieName");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);

//To Request the cookies value
var val = Request.Cookies["cookieName"].Value;
....

Comment: how to add multiple values in cookie? Like I referred this example to save user data like email id, user id and some other info in cookie.


Not getting "Add unimplemented methods" error in eclipse

Question: I am working on Selenium with Java and using Listeners.
I created the class, imported the TestNG, and then added method as;
Public class Listener implements ITestListener{
}

I got an error at "ITestListner" and then imported "ITestListner(org.testng). After this it was expected that I will get an error for "Listener" but I didn't get any error.
I tried creating with abstract class but still didn't get the error.
package com.testng;

import org.testng.ITestListener;

public class Listeners implements ITestListener{

}

The expectation is when I move the cursor over "Listeners" I should get "Add unimplemented methods" option.
Comment: Is ITestListener.java file available in the defined package ?
Comment: No, my class name is Listeners, I used ITestListener to implement the Listener methods.
Comment: What are the methods available inside ITestListener class. I assume ITestListener is an interface.
Comment: Yes, its an interface. If I get the "Add unimplemented methods" option, below code will be exposed.
Comment: Post the code for ITestListener.java
Comment: `@Override
 public void onTestStart(ITestResult result) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onTestSuccess(ITestResult result) {
  // TODO Auto-generated method stub

 // System.out.println("I successfully executed Listeners Pass code");
 }

 @Override
 public void onTestFailure(ITestResult result) {
  // TODO Auto-generated method stub
  //screenshot code
  //response if API is failed

  System.out.println("I failed executed Listeners Pass code" +result.getName());

 }`
Comment: This is the code for method, edit your question and add the complete code for ITestListener.java.
Answer: Right click(on the Listeners class ) -> go to source-> click on overide/implement methods -> select the check boxes for the ITest listener (make sure all check box inside it should be checked )->click on oK. That's it !!!
Answer: As i got to know from the below link - TestNG 7.0.0 uses JDK8 and with it default methods within interfaces. What this means is that every listener would now have a default implementation (which doesn't do anything ) for all methods defined within the interface.
So now you won't see those indications from the IDE. The biggest benefit of default methods in interfaces is that let's say you are implementing an interface that has 10 methods defined in it, you can just implement whatever you need and the rest of the behavior comes via the default methods in the interface.
Reference-
https://github.com/cbeust/testng/issues/1964
Comment: I see, by [adding empty default implementations](https://github.com/cbeust/testng/commit/3006219166232fc643bee513c84bb6772277a0d6#diff-8853c664e8e938b88ec7cb0677afac15), the [listener interface became an adapter](https://blogs.oracle.com/corejavatechtips/listeners-vs-adapters). Probably the name was not changed due to compatibility reasons.
Answer: Right click on the class --> select source --> choose override/implement methods --> then pick the methods you'd like to implement.
Answer: All methods in ITestListener interface changed to default from 7 version onwards. You can call them with class object where you implemented interface.
Answer: Try downgrading the TestNg version to 6.14.3.
It worked for me.
Answer: The Best solution is go to the source tab besides the File-Edit options and click the Overide/implement methods and you are set
Answer: It seems like Eclipse might not be displaying the "Add unimplemented methods" error on hovering over the class name. However, you can still generate the unimplemented methods by following these steps:

Right-click on the class name in the editor.
Navigate to "Generate" in the context menu.
Select "Override Methods" from the submenu.
A dialog will appear listing the methods that can be overridden. Choose the methods you want to override.
Click "OK" to generate the selected overridden methods.

This way, you can manually generate the unimplemented methods even if the IDE is not showing the error on hovering over the class name.
Answer: Right click(on the Listeners class ) -> go to source-> click on overide/implement methods -> select the check boxes for the ITest listener (make sure all check box inside it should be checked )->click on oK.


Dovecot, maildir on Windows 2008r2 NFS share

Question: I'm really banging my head on this one.  I have a CentOS 6.1 running postfix/dovecot accessing a Windows 2008R2sp1 NFS share.  In a test where the Windows server is a stand-alone file server, I can process email no problem.  Once I try to do the same in a CLUSTERED 2008r2sp1 file server all that dovecot seems to be able to do is create the domain folder and account folder beneath that - not the cur, new, or tmp folders. Dovecot gives this error:
<code>Error: chdir(/var/vmail/xxx.com/xxx/) failed: Permission denied (euid=5000(vmail) egid=5000(vmail) missing +w perm: /var/vmail/xxx.com/xxx/, euid is not dir owner)
</code>
And in the shared folder I see the xxx.com directory and xxx subdirectory, but nothing inside the xxx subdirectory
The Windows NFS share has the following checked
NFS ADVANCED SHARING
 - No Server Authentication
 - Enable unmapped user access
 - Allow anonymous access UID 5000 GID 5000 (mapped to an AD domain user)
NFS SHARE PERMISSIONS
 - All Machines
 - Read-write
 - Root access allowed
 - ANSI
This share was set up the same on the standalone development server as it is in the server cluster.  All file server systems are 2008r2sp1.
Any help or insightful questions would be greatly appreciated.
Answer: Read the error message again. It says "euid is not dir owner" which means "the user with the id 5000 is not the owner of the directory".
Correct that. Authentication is not the problem here. Authorization is.
On the other hand: Don't do NFS that way with Dovecot! See http://wiki2.dovecot.org/NFS for details. And then NFS is no native service on Windows, which means another pitfall. I - personally - would never ever trust this kind of setup.


Branch points of an equation

Question: I was reading the Mathematica Guidebook to Symbolics by Michael Trott, and saw the following expression to evaluate the branch points of a Riemann surface given by $f(x,a)=x^3+x^2+ax-1/2$.
<code>Eliminate[{#==0},D[#,x]==0},x]&[eq=x^3+x^2+ax-1/2]
</code>
This gives the result $36a-4a^2+16a^3+19=0$. The roots of this equation are the branch points of $f(x,a)$.
My question is: Why is this so? How does eliminating $x$ from $f(x,a)=0$ and $\dfrac{df(x,a)}{dx}=0$ lead us to the solution?
NOTE: I'm not asking for an explanation of the Mathematica command... I don't get the math behind it.
Answer: Imagine the plane $(x,a)$ where the equation $f(x,a)=0$ gives a curve $C$. We project the curve onto the $a$-axis. Branch points are the points on the $a$ axis over which the projection "is not so nice". You can imagine e.g. the points over which the projection "folds", e.g. if $f(x,a)=x^2-a$ then $a=0$ is such a point.
Now you have to imagine, though, that $a$ and $x$ are complex numbers (and hence $a$ is a point in a plane, and $C$ is 2-dimensional). Over a general point $a$ the equation $f(x,a)=0$ has $n$ different solutions (for $x$), where $n$ is the degree of $f$ as a polynomial in $x$ (in your case $n=3$). We have $n$ different solutions iff $f(x,a)=0$ and $df(x,a)/dx=0$ (for this given $a$) don't have a common root. Over such points $C$ covers the plane of $a$'s in $n$ sheets. When, however, $f(x,a)=0$ and $df(x,a)/dx=0$ do have a common root, the number of roots of $f(x,a)=0$ is less than $n$, so over these points $a$ some of the sheets meet. These are the branch points. In fact, what happens, if you go around such a point then you would see that you get from one sheet (also called one "branch") to another. That's why these points are called branching.
(I skipped some unimportant technical details)
Comment: But number of roots less than $n$ could happen even in the case of a double root, right? Needn't necessarily be a branch point. How does eliminating $x$ in this case help?
Comment: The common roots of $f(x,a)=0$ and of $df(x,a)/dx=0$ (for a fixed $a$) are precisely the multiple roots of $f(x,a)=0$. (In those skipped technical details I assumed e.g. that $f$ is irreducible as a polynomial in 2 variables - that implies that a multiple root happens only for finitely many $a$'s). In principle the fact that $f(x,a)$ has a multiple root (equivalently, has less than $n$ roots) is only a necessary condition for  $a$ being a branch point. (again a technical detail) It means that the algorithm you described is not quite right - it might some false positives.
Comment: The point I don't understand is how does eliminating $x$ from $f(x,a)$ and its derivative help? What does the resulting function $g(a)$ mean w.r.t. the original function?
Comment: The question is: for which values of $a$ does the polynomial $f(x,a)$ (as a polynomial in $x$) have multiple roots (ie. less than $n$ roots)? A root is multiple iff it's also a root of $df(x,a)/dx$. Hence you want to know whether $f(x,a)=0$ and $df(x,a)/dx=0$ have a common solution (for a fixed $a$). That's what "elimination of $x$" does: it gives an equation for $a$ s.t. you have a common root of $f$ and $df/dx$ exactly for the solutions of that equation
Answer: Branch points will occur at values of $x$ which are double or higher roots of $f(x,a)=0$, that is, where $f(x,a)$ and $f_x(x,a)$ have common zeros. "Elimination of x from $f(x,a)$ and $f_x(x,a)$" amounts to running the Euclidean algorithm on $f$ and $f'$, where the field of coefficients is rational functions of $a$ with complex coefficients. The expression the algorithm produces is the (non-zero, constant) GCD, unless $f(x,a)$ and $f_x(x,a)$ have a common factor for every $a$, as in $f(x,a)=(x-a)^2$. Avoiding that kind of degeneracy, for only finitely-many values of $a$ that GCD vanishes, which shows a non-trivial GCD.

Branch points of an equation


Apache httpd mod-auth-form giving error 405

Question: I have been trying to setup a new website, and I have now ran into a major problem. When I log in to the page it simply gives me the following error when I enter the correct credentials:
Method Not Allowed The requested method GET is not allowed for the URL /RestrictedPages/index.html.
When I enter the wrong credentials it works just as I want it to.
Here is my httpd.conf (The parts that I changed):
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_form_module modules/mod_auth_form.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule allowmethods_module modules/mod_allowmethods.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule cache_socache_module modules/mod_cache_socache.so
#LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule macro_module modules/mod_macro.so
#LoadModule dbd_module modules/mod_dbd.so
#LoadModule dumpio_module modules/mod_dumpio.so
#LoadModule buffer_module modules/mod_buffer.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule request_module modules/mod_request.so
#LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule deflate_module modules/mod_deflate.so
LoadModule mime_module modules/mod_mime.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
#LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
#LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
#LoadModule remoteip_module modules/mod_remoteip.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so
LoadModule session_module modules/mod_session.so
LoadModule session_cookie_module modules/mod_session_cookie.so
#LoadModule session_dbd_module modules/mod_session_dbd.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule unixd_module modules/mod_unixd.so
#LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule info_module modules/mod_info.so
#LoadModule cgid_module modules/mod_cgid.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
#LoadModule actions_module modules/mod_actions.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
#LoadModule rewrite_module modules/mod_rewrite.so

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

<Directory "/etc/apacheHttpd/htdocs/RestrictedPages">
SetHandler form-login-handler
AuthFormLoginRequiredLocation /loginPage.html
AuthFormLoginSuccessLocation /RestrictedPages/index.html
AuthFormProvider file
AuthType form
AuthName "Reserved Area"
Session On
SessionCookieName session path=/
Require valid-user

# This is the login page
ErrorDocument 401 /loginPage.html

# This is the file containing users login data
AuthUserFile /etc/apacheHttpd/auth/.htpasswd

</Directory>

#<Location /auth/logout.html>
#    SetHandler form-logout-handler
#    AuthType form
#    AuthName "Reserved Area"
#    Session On
#    SessionCookieName session path=/
#</Location>

Here is the login form:
<form method="POST" action="/RestrictedPages/index.html">

Användarnamn:<input type="text" name="httpd_username" value="" />

Lösenord:<input type="password" name="httpd_password" value="" />

 <input type="submit" name="login" value="Login" />

    </form>

Could anyone of you tell me what I am doing wrong?
Best Regards
Oskar
PS. If you are missing something from my files, just ask me. This is my first time asking for help here.
Answer: I think that I solved it now...
I figure that the problem was in the form-login-handler, I did the following changes:
<Location "/RestrictedPages">
    AuthFormProvider file
    ErrorDocument 401 "/loginPage.html"
    AuthUserFile "/etc/apacheHttpd/auth/.htpasswd"
    AuthType form
    AuthName realm
    AuthFormLoginRequiredLocation "/loginPage.html"
    AuthFormLoginSuccessLocation "/RestrictedPages/index.html"
    Session On
    SessionCookieName session path=/
    Require valid-user
</Location>

The changes I made were all according to this document under the headline "basic configuration".
Thanks anyways,
Oskar


Do powers of 256 all end by 6 and if so, how to prove it?

Question: I computed the 10 first powers of 256 and I noticed that they all end by 6.
<code>256^1 = 256
256^2 = 65536
256^3 = 16777216
256^4 = 4294967296
256^5 = 1099511627776
256^6 = 281474976710656
256^7 = 72057594037927936
256^8 = 18446744073709551616
256^9 = 4722366482869645213696
256^10 = 1208925819614629174706176
</code>
My intuition is that it is the same for all powers of 256 but I can't figure out how to prove it, any suggestion?
My attempt was to show that $\forall n$ there is a $k$ such that $2^{8n} = k*10 + 6$, $k$ and $n$ being non null integers. I tried to decompose the right member in powers of $2$ but that leaves me stuck.
Comment: not only 256 but the products of any values that end with 6. The same with numbers that end with 0, 1 or 5
Comment: Arithmetic modulo 10, plus induction?
Answer: $$(10x+6)(10y+6)=100xy+60 (x+y)+3\color {red}6. $$
Comment: i.e. RHS $= 10(10xy\!+\!6(x\!+\!y)\!+\!3) + 6 = 10n+6\,$ so it has units digit $= 6.\ $ By induction it follows that the product of any number of naturals all ending with $6$ also ends with $6\ \ $
Comment: @BillDubuque The [other question](https://math.stackexchange.com/questions/528191/product-of-two-numbers-ending-in-6-also-ends-with-6) doesn't have an "answer", it has a "question". I'd say so.
Answer: In $\mathbb{Z}_{10}$ (the integers moduo $10$) we have that $6^2 = 6$, an idempotent, so all its positive powers are $6$ too. And $256 \equiv 6 \pmod{10}$.
Comment: that is fascinating... can it be explained for people like me with a bit less experience with modular arithmetic?
Comment: @donbright the last digit of a number $n$ is just its class modulo $10$. And if you want to answer questions about arithmetic modulo $10$ it makes sense to work in the ring (structure having $+,0,1,-,\times$ with the usual rules) of all integers modulo $10$. You'll need a little bit of elementary algebra.
Answer: Let $P(n)$ be the statement that $6^n$ ends on $6$.
Then evidently $P(1)$ is true.
If $P(n)$ is true then it is not difficult to prove that also $P(n+1)$ is true (try it yourself).
According to the principle of induction on natural numbers we are allowed to conclude that $P(n)$ is true for every positive integer.
Comment: Thank you, my maths are rusty I did not thought about induction, I managed to solve this using it ! I am still marking user's answer as accepted since it provides a quick explanation to this phenomenon. (And my upvotes are not displayed yet since I am new here)
Comment: You are welcome.
Answer: Using the binomial theorem
$$256^n{\pmod {10}}=(250+6)^n{\pmod {10}}=6^n{\pmod {10}}.$$
Now note that $$6^2{\pmod {10}}=36{\pmod {10}}=6{\pmod {10}}$$ and thus $6^n{\pmod {10}}=6{\pmod {10}}$, completing the proof.
Answer: We can prove this by complete induction:
For $n = 1$, we have $256^n = 256^1 = 256$, which ends with a $6$.
Now, let $256^n$ end with a $6$, so there is an integer $k \ge 0$ such that $256^n = 10k+6$ and we have
$$256^{n+1} = 256(10k+6) = 2560k+1536 = 10(256k+153)+6$$
Therefore, $256^{n+1} = 10k'+6$ with $k'=256k+153$, and so also $256^{n+1}$ ends with a $6$.


Are $\mathbb S$ and $\mathbb T$ subspaces of the vector space $\mathbb V$?

Question: $\mathbb{V}$ is the set of all real-valued random variables on a fixed sample space forms a vector space over $\mathbb{R}$ under the usual binary operation (Addition and Scalar Multiplication).
$\mathbb{S}$ is the set of all discrete random variables belonging to $\mathbb{V}$.
$\mathbb{T}$ is the set of all continuous random variables belonging to $\mathbb{V}$.
Answer: Linear combinations of discrete random variables assume only countably many values so the first set is  subspace.
The second set is not a subspace: If $X \sim N(0,1)$ and $Y=-X$ then $X,Y \in \mathbb T$ but $X+Y \notin \mathbb T$


The musical scale E-sharp major is fake?

Question: WikiPedia has an article about E-sharp minor scale (that is a scale relative to G-sharp major) there is no article of E-sharp major, instead it redirects to F major that is a scale using flats instead of sharps. I want to know if the E-sharp major scale is fake? PS. I am asking specifficaly this scale.
Comment: Having just read the article, it specifically says "Its parallel major, E-sharp major, is usually replaced by F major, due to the presence of 4 double-sharps in the E-sharp major scale causing it to be one of the more impractical key signatures in music to use."
Comment: 'Fake' is a poorly chosen term. 'Redundant' would be more like it.
Comment: There is enough scope in keys by purely using # or b in the key sig. There's little point taking things further so one needs to use x or bb. Technically it exists, but mostly in the minds of masochists. Why stop there? Let's play the scale of key Ex - or start being sensible and realistic!
Comment: I think you're confusing notation and tone. E# major *sounds* just like F major, but the notes of the scale are different, being E#-F doublesharp-G doublesharp-A#-B#-C doublesharp-D doublesharp-E#. Why in the world anyone would want to write something in E# major escapes me, but that's not to say that you can't do it! :-)
Answer: Let's see:

Doesn't look fake to me.  But sort of cumbersome to read.  E major has 4 sharps, so it's not surprising E sharp major has 4 double sharps and the other notes sharped.
In general, going to the enharmonically equivalent key implies a jump by net 12 sharps/flats (2 for each whole step in the scale, 1 for each half step).  F major has -1 sharps (well, 1 flat), so E sharp major has a net of 11, namely 3 single and 4 double ones.
Comment: @awelotta: For the record, this answer has Lilypond's default order for rendering the sharps in a key signature.  However, on the very few occasions where I've actually seen an engraved key signature with a double sharp, I'm pretty sure I've always seen the double-sharp(s) listed first, so that the sharps follow the typical ordering/placement, just with double-sharps replacing single ones as needed.
Comment: The rightmost sharp in sharp signatures is _always_ the leading tone, so why not here?  If you wanted to retain F♯ as first accidental, you'd have both F♯ and F in your accidental row, making for a confusing total (basically, you'd have to count double accidentals only once and would have to disregard the first one when playing).
Comment: @awelotta: Okay, I take that back.  Now I've found an actual engraved example showing the manner of this answer too.  Seems both are possible.
Comment: https://music.stackexchange.com/questions/65936/where-do-the-double-accidentals-go-in-theoretical-key-signatures
Comment: If I had to read the above example, I'd mentally put one flat, and transcribe everything up one step - that bottom line note then becomes a bottom space note.
Comment: Why is it starting from A#? Is it to show that the double sharps are the "newest notes"? I would think that the right-most double sharp is the most useful for determining the leading tone (Dx) and thus the key center (E#), so your notation is a little confusing. On the other hand, I don't think there exists "real" notation for this, so if there's some logic behind flipping the key signature as you did, I would like to know about them.
Comment: Sorry, I didn't read carefully. It still bugs me that the ordering is different, but I realize the accidentals "loop" around the circle of fifths so that's why the order of the accidentals looks the same despite starting on a different sharp.
Comment: @awe lotta: "Why is it starting from A#?"  The key signature starts with the three "lesser" accidentals.  If the "higher" accidentals would be naturals (and thus "invisible"), you'd have A♭, E♭, B♭ for the three lower ones.  As the higher ones are double sharps, the three lower ones are A♯, E♯, and B♯.
Answer: It's not fake, it's theoretical.
https://en.wikipedia.org/wiki/Theoretical_key
There is a theoretical difference between E sharp major and F major because they are spelled differently and reside in different places on the circle (spiral?) of fifths. In practical terms, they are identical because they are enharmonically equivalent, thanks to equal temperament.
Comment: @BobJarvis-ReinstateMonica I assume you were being humorous, but I have edited my answer slightly to hopefully avoid any such genuine confusion along those lines.
Comment: No, they're not. Every note in E# major is different than the notes in F major. The notes of the F major scale are F-G-A-B flat-C-D-E-F. The notes of the E# major scale are E#-F doublesharp-G doublesharp-A#-B#-C doublesharp-D doublesharp-E#. Don't confuse tone with notation, or vice versa, for this way lies madness! Hurry, before it's gone!!! :-)
Answer: It exists but probably isn't included as an article because, whereas a scale like Db minor is a flat note with no "simpler" spelling*, E# is enharmonic to F which is a white key and arguably simpler / more common to read. Db minor also has double accidentals.
Basically, E# refers to the same pitch as F, and there's not much reason to use E# as the root of your scale in the first place, so there's no article for E# minor.
As a sidenote, E# and F don't necessarily refer to the same pitch. For example, in the tuning system 19TET, E# is enharmonic to Fb instead, which then lies halfway between E and F.
*typically Db minor is replaced with C# minor because C# minor, being the relative minor of E major, has a much simpler key signature without any double accidentals. But if a piece is in Db major and borrows chords / notes from the parallel minor, then Db minor would theoretically be used.
Answer: As other answers point out, E# minor exists in theory, but is in used vanishingly rarely (if ever) in practice.  But this provokes the followup question: if E# minor so rare as to be "purely theoretical", why is G# major (with the same key signature) less rare in practice?
In isolation, G# major is just as impractical: for the primary key of a work, one would almost always write it as Ab major instead.  But G# major is closely related to several minor keys which have fewer sharps in their key signature — most closely, C# minor and G# minor.  These keys do appear often in practice (since their enharmonic equivalents, Db minor and Ab minor, have more flats than these have sharps).  So if a piece is primarily in C# minor and modulates to its dominant major, it's often more readable to write the section in G# major than to switch between sharp spellings and flat spellings within the piece.
Generally, major keys have closely related minor keys with more flats/fewer sharps, while minor keys have closely related major keys with more sharps/fewer flats, so extremely sharp key spellings occur more often as major keys, while extremely flat key spellings occur more often as minor keys.  On the sharp end, E# minor and A# minor are rarer than G# major and C# major respectively, as mentioned in the question.  On the flat end, Fb major and Cb major are rarer than Db minor and Ab minor, because (for instance) these minors can appear secondarily in a piece with primary key Ab major.
Comment: Modulation doesn't typically involve a change of key signature.  And switching between flats and sharps for different movements is certainly common (moonlight sonata, for example).  Do you have an example of a piece that uses G# major for this reason?
Answer: Yes, an e-sharp minor scale exists, but you're not gonna find many examples of one in music. If you do, we can go yell at the editor.
Comment: @phoog yes, though it's actually not unlikely for a guitarist to describe a piece in G♯ major or even D♯ major. But A♯ or E♯, probably not.
Comment: The same is true of G# major, frankly. Welcome.
Comment: @phoog: see my answer for why G# major isn't quite as rare.


Given three non-isomorphic spanning trees of the complete graph K5, how many trees in each class?

Question: The graph, K5 has 125 different spanning trees, which I beleive fit into three different non-isomorphic classes of spanning trees. However, I'm at odds as to how to figure out how many are in each class.
The trees I've found are, according to vertex degree:
(4, 1, 1, 1, 1)
(3, 2, 1, 1, 1)
(2, 1, 2, 1, 2)
How do I found out how many there are in each, to add up to 125?
Answer: The first one you have listed is by far the easiest, we just pick the vertex we wish to be of degree 4 (out of the 5 choices) and everything else is determined. So there are 5 of the first type.
The next easiest class for me is the second, we can first choose the vertex we wish to be of degree 3 (of 5 choices) then of the remaining 4 vertices we pick the one we wish to be of degree 2. Finally we have to decide which of the last 3 vertices is connected to the degree 2 one (equivalently which two are connected to the degree 4 one) there are 3 choices and hence $5\cdot 4 \cdot 3 = 60$ isomorphic trees.
I'll leave the derivation of the last class up to you, it does require maybe a little more care to ensure you do not over count.


Musica no slide jquery

Question: Tenho um slideshow, estou tentando que a cada div de id Content seja tocado a musica em questão dentro da div content.
Estava pensando em usar um if ($("#Content1").is(":visible") {$('#1.mp3').play();}  Porém procurei na net como fazer isso más não encontrei nada parecido :(
Muito obrigado pessoal. Stackoverflow SHOOWWW! :)
OBS: Codigo abaixo esta tocando as 2 musicas juntas.

                    <audio id="playTune" autoplay>
                        <source src="2.mp3">
                    </audio>

                    <audio id="playTune" autoplay>
                        <source src="1.mp3">
                    </audio>

Answer: Algo assim resolve seu problema?

$(window).load(function() {
  $("#showContent1").click(function() {
    showContent("Content1")
  })

  function showContent(id) {
    if (!$("#" + id).is(':visible')) {
      $("#Content1").show()
      $("#" + id + " audio")[0].play()
    } else {
      $("#" + id).hide()

    }
  }

})

<button id="showContent1">show content1</button>

                                    <audio controls="">
  <source src="http://www.w3schools.com/html/horse.ogg" type="audio/ogg">
  <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

                  <audio controls="">
  <source src="http://www.w3schools.com/html/horse.ogg" type="audio/ogg">
  <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

Comment: Esse trecho de codigo salvou o final de semana que tive de dor de cabeça tentando achar uma solução. Obrigado amigo Marco. :)

Musica no slide jquery


.net mvc application load wrong language resource file

Question: Hello everyone I'm writing a small asp.net mvc application and i want to make it localized and support more than one language I've found many useful articles
I added routing for languages
I used a custom actionfilter attribute to choose current culture of current thread depending on the language code in url like "site.com/en/controller/action" for english or "site.com/ar/controller/action" for arabic.
i created "Resources\Views\Shared\Layout.resex" for english language and "Resources\Views\Shared\Layout.ar.resex" for arabic language.
the problem that it is stuck with arabic localization only and i set the current thread culture manually to english and removed actionfilter attribute but it still display arabic content!! what is the problem this is crazr
Answer: It's hard to tell without more detail or code, but one easy thing to miss is your web.config file's configuration. If you have something like <globalization uiCulture="auto" culture="auto" /> in <system.web> (with "auto" instead of culture identifiers) then ASP.NET will use the accept-language header, which is determined by your browser's language settings, to automatically choose your thread's cultures. So what you are seeing could be partially explained by having this configuration and having Arabic ahead of English in your browser's language list.
Edit: The issue was that the code needs to use of Thread.CurrentThread.CurrentUICulture to control what localized resources are used (Thread.CurrentThread.CurrentCulture is a different thing, doesn't affect localization but locale-dependent formatting/parsing such as dates).
Comment: Note that enableClientBasedCulture doesn't do anything, have a look at this post: http://stackoverflow.com/questions/8536715/enableclientbasedculture-vs-culture-in-web-config
But I think I know what your issue is: for localization it is not Thread.CurrentThread.CurrentCulture that you need to set but Thread.CurrentThread.CurrentUICulture.
Comment: that didn't solve the problem i used  now it is stuck to english in other words this line Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");  has no effect when i use ar-EG or en-US the default file is the only one used
Comment: yes man when i saw the example i thought it was a duplicated line then didn't write it. when i realized i wrote it every thing was okay and i wanted to share the solution and you mentioned the problem thanks a lot for trying to help please edit your answer to include your last comment about adding CurrentCulture.


Describe the following spaces $L^1$ & $L^2$

Question: I'm trying to practice my understanding of $L^1$ and $L^2$ spaces with the problem below.

Given $\Omega = \{\omega_1,...,\omega_7 \} $ let's consider the probability space $(\Omega, \mathcal{F},P)$ where $\mathcal{F} = \mathcal{P}(\Omega)$ the power set of $\Omega$, and also $P(\omega_5) = 1/3$ and $P(\omega_i)= 1/9$ for $i \neq 5$. Let $X \in L^1(\Omega, \mathcal{F}, P)$ be a function defined as $X = (2,4,2,1,3,1,4)$ and let $\mathcal{G}$ be the $\sigma$-algebra generated by the sets
$$
B_1 = \{\omega_1, \omega_3\} \ \ B_2 = \{\omega_2,\omega_4\} \ \ B_3 = \{\omega_5, \omega_6, \omega_7\}
$$
Describe  $L^1(\Omega, \mathcal{F}, P); L^1(\Omega, \mathcal{G}, P);L^2(\Omega, \mathcal{F}, P);L^2(\Omega, \mathcal{G}, P)$

I've done the following but I feel like I'm mixing some stuff:
$L^2(\Omega, \mathcal{G}, P) = \{ X \ \text{r.v.} | \int_{G}|X|^2dP < +\infty\ \forall G \in \mathcal{G}\} $
which translates on the integral being finite in each of $B_1,B_2,B_3$, but my question here is, it's a discrete r.v. right? So shouldn't it be a sum?, and in the end it would translate to $\sum_{i=1}^7 X^2(w_i) < + \infty $ since the probabilities are finite right?
Same for $L^1(\Omega, \mathcal{G}, P)$ but $\sum_{i=1}^7 X(\omega_i) < + \infty $ instead of the squared.
And I don't know the differences for $L^1(\Omega, \mathcal{F}, P)$ and $L^2(\Omega, \mathcal{F}, P)$
Answer: For any random variable $Z$ on $\Omega =\{\omega_1,\omega_2,...,\omega_7\}$ we have $\int Z dP=\sum\limits_{k=1}^{7} Z(\omega_k) P(\omega_k)$. Also all random variables belong to $L^{p}(\Omega,\mathcal F,P)$  for every $p$ since finite sums  real numbers are always finite.
$L^{p}(\Omega,\mathcal G,P)$ consists of all real functions measurable w.r.t $\mathcal G$ and these are real functions $Z$ such that $Z(\omega_1)=Z(\omega_3), Z(\omega_2)=Z(\omega_4)$ and $Z(\omega_5)=Z(\omega_6)=Z(\omega_7)$.
Comment: So should I see $L^p(\Omega, \mathcal{G},P)$ as some sort of "quotient" space where if $X \in L^p(\Omega, \mathcal{G},P)$ then $X$ is constant restricted to the sets that generate the $\sigma$-algebra $\mathcal{G}$?
Comment: That is correct. @M. Navarro
Comment: Thanks! So it should look like $L^p(\Omega, \mathcal{G}, P) = \{ X r.v. | X(\omega_1) = X(\omega_3); X(\omega_2) = X(\omega_4); X(\omega_5) = X(\omega_6) = X(\omega_7); \sum_{i=1}^7|X(\omega_i)|^pP(\omega_i) < \infty$
Comment: @M.Navarro No point in writing the last condition.  A finite sum of real numbers is always finite, so simply drop that condition.


Monotonic functions have only jump discontinuities proof (stuck on the last step)

Question: I want to show, that monotonic functions only have jump discontinuities.
By the definition of discontinuity, this assumption must fail:
$$\lim_{x\to x_0}f(x)\ne f(x_0)\;.$$
where $f(x)$ is our monotonic decreasing function and is discontinuous at $x_0\in[a,b]$.
Right and left limits exist (because of completeness of $R$) and are equal to:
 $$\lim_{x \to p^+}f(x)=\inf\{f(x) \mid x \gt p\}\quad \mbox{and} \quad \lim_{x \to p^-}f(p)=\sup \{f(x) \mid x \lt p\}$$
and I know how to prove it.
The only thing, that I don't know how to show is why $\lim\limits_{x\to x_0}f(x)$ fails. I am sure it's connected with definitions of supremum and infimum, but i cannot come to the right conclusions.
Can you give me a hint?
Comment: It seems you took an arbitrary $p \in \mathbb{R}$ such that $f$ is discontinuous at $p$ and showed that left and right limits exist. This is enough to state that it is a jump discontinuity. Why would you need anything else?
Comment: @Adayah I want to show, that left and right limits are not equal (definition of jump discontinuity). I don't know how to prove it
Comment: Ah, you're right.
Answer: Disambiguation: it seems that you're using $x_0, p, c$ for the same point. I will just use $p$. ;-)
Note that by monotonicity
$$\lim_{x \to p^-} f(x) = \sup \{ f(x) : x < p \} \leqslant f(p) \leqslant \inf \{ f(x) : x > p \} = \lim_{x \to p^+} f(x)$$
so if the one-sided limits were equal, then they would equal $f(p)$, so $f$ would be continuous at $p$, which by assumption it does not.


Largest cricket ground by length of boundary

Question: Which is the largest cricket ground by length of boundary in the world?
Answer: Melbourne Cricket Ground is the largest cricket ground by area. The playing area in the  MCG is 172.9m x 147.8m. If we consider the boundary length of the cricket ground, ICC stated about this in the playing conditions that,

In all cases the aim shall be to provide the largest playing area,
  subject to no boundary exceeding 90 yards (82.29 meters) from the
  centre of the pitch to be used.

So, the largest boundary length a cricket ground can have is 82.29 meters. The boundary line should be located according to that.