Likert scale questionnaires with ANOVA and Kruskal-Wallis test

Question: Could someone recommend me sources where I could find illustrated examples, solved by hand and/or using software, on how a Likert scale questionnaire (with more than 1 question, say 10, 20, etc. questions; where each question has items to rate, say 3,4, etc; where (0) means disagree and (1) agree or (1) disagree and (5) agree (I think this is a matter of taste?)) "interacts" with ANOVA and Kruskal-Wallis test.
I've seen many examples and plenty of exercises on books but they are always like

Provides context and some numerical data sets.
Use of ANOVA (one or two way or repeated) or Kruskal-Wallis.
and Results.

So far I've never encountered one that in the context considers a Likert-scale questionnaire, data, ANOVA or Kruskal-Wallis and results.
Answer: EDIT: Based on a critical edit to your question: Yeah, sums of Likert items do not have a Likert distribution. Thanks to the Central Limit Theorem they have an approximately normal distribution. Approximately normal data are pretty soundly in ANOVA's bailiwick, (the more items contributing to your outcome variable, the more comfortable with ANOVA you should be), though you will still need to make appropriate corrections for unequal variances between groups.
If the number of Likert-scale items contributing to your variable is small, you might want to use the Kruskal-Wallis test instead. There will be a small hit to statistical power (as compared with ANOVA) using Kruskal-Wallis with approximately normal data, but you should be able to use either.

The Kruskal-Wallis test assumes the outcome data measured across $C$ groups are measured continuously. I.e., from their original paper "If the samples come from identical continuous populations, and the $n_{i}$ are not too small, $H$ is distributed as $\chi^{2}(C-1)$…" ($H$ is the Kruskal-Wallis test statistic, and the $n_{i}$s are the sample sizes in each group.)
The same is true of the Mann-Whitney(-Wilcoxon) rank sum test between two samples—which the Kruskal-Wallis test is effectively a $C$ sample extension of—where Mann & Whitney's first sentence is "Let $x$ and $y$ be two random variables with continuous cumulative distribution functions $f$ and $g$."
Unfortunately, this means that the inferential properties based on the distribution of the $H$ test statistic may be invalid if applied to, for example, ordinal data of only a few values. While Kruskal & Wallis do give corrections for ties, which may arise in any continuous variable where $n>10^p$ where $p$ is the precision in number of significant digits, I suspect the test is unreliable for cases where all values are tied many times, as would be the case for Likert scale data with 5-ish or 7-ish values.
At the very least you may expect to find few illustrated examples published which violate an assumption of the test.

References
Kruskal, W. H., & Wallis, W. A. (1952). Use of ranks in one-criterion variance analysis. Journal of the American Statistical Association, 47(260), 583–621.
Mann, H. B., & Whitney, D. R. (1947). On A Test Of Whether One Of Two Random Variables Is Stochastically Larger Than The Other. Annals of Mathematical Statistics, 18, 50–60.
Comment: @America ANOVA also has assumptions about continuous variables—in fact more stringent, since ANOVA assumes continuous *normally distributed* variables. I think for Likert outcomes/dependent variable, I might go to something like [ordered logit regression](https://en.wikipedia.org/wiki/Ordered_logit), with group as a predicting factor variable.
Comment: 4) when averaging between all items in the same batch of questions (for the same participant), you get a more continuous variable, and this helps for testing, both parametric and not. for instance, if someone puts 5, 5 and 4 to three items of some questionnaire, about the same issue, it results to be more convinced than someone else that puts three 5s as answers. 5) one can argue that the resulting average, coming from variables that are independent at least for some of their parts, is gaussian, and then t-test is appropriate. this is disputable, but t-tests are disputable almost always.
Comment: @carlo Ah! I see I see... I misunderstood your initial comment about means. Yes: *sums* of Likert items are going to be approximately normal, so game on. (My assumption was that America was considering a *single* Likert scale outcome.)
Comment: I don't know about America, but I hope that when someone is doing t-tests on likert surveys, they have used multiple items averages.
Comment: about that answer by BruceET, you got it wrong: those are the frequencies of results, for two groups of 200 and 250 participants each, of a single survey question with 5 choices
Comment: Also, thank you @carlo, if you hadn't commented, then I would have gone with the idea that neither ANOVA nor KW is correct for a Likert scale questionnaire.
Comment: @America That is what I am saying, yes. Sorry if that wasn't clear. :) (Also: welcome to CV!)
Comment: while KW test was created for continuous distributions without possible ties, adjustments for discrete variables including possible ties have been proposed. also, likert good practice includes averaging many similar 5-scale answers the same survey, to get a more continuous and also gaussian-ish variable. this justifies ANOVA: even if gaussianity is not really respected (when it is, after all?), the collected p-values are still useful, if rough, and biased, indicators of the significance of the result.
Comment: "People make all sorts of mistakes. Some mistakes even become standard practice". all models are wrong, but some are useful. standard practice makes mistakes comparable and thus useful.
Comment: @carlo Could you explain more this part "likert good practice includes averaging many similar 5-scale answers the same survey, to get a more continuous and also gaussian-ish variable."?
Comment: "the collected p-values are still useful" Hahaha! *Nope!*
Comment: @America when planning a quantitative analysis, it is a good thing to put into surveys many questions that basically ask the same thing. This of course has to be made before data collection. Questions opposites to each other are a particular recommendation. This has many advantages: 1) you can check that answers are coherent, and that the participant was paying attention to the questionnaire; 2) the result is more robust to ambiguity or bad formulation of any singular question; 3) you can make questions that about behaviors that are complex to put in one simple sentence...
Comment: @carlo I see. That's what I also had thought. I asked something similar  [here](https://stats.stackexchange.com/questions/465852/why-the-variable-type-is-discrete-ordinal-and-not-interval). Assuming there're 10 or 20 questions, there're will be an average at some point, for example in BruceET's answer we see `[1] 46 62 60 16 16  # Likert scores 1,2,3,4,5, resp
[1] 62 51 85 35 17` . And yes, this scores came from  a Likert scale questionnaire. But we still can use ANOVA or KW (assuming we have more than 2 groups to compare). Am I missing something?
Comment: @Alexis oh I see. What I had in mind, was a typical Likert scale questionnaire, which usually has more than 1 question, say 10-20-etc. Sorry for the confusion, I'm going to edit my question.
Comment: @carlo Sorry, that's exactly what I was thinking some minutes ago. So here again, I'm imagining something like this `[20.9 ... 30.2] %group 1` `[40.7 ... 10.8] %group 2` `and so on` and basically done. ANOVA (assuming all the other assumptions hold) would do the rest. Having in mind that those numbers (29.9 ... 30.2) are the average score from a Likert scale from each individual, respectively. In other words, in case I didn't explain myself clearly, it would be something like  this [One-way ANOVA and Post Hoc Test Using SPSS](https://www.youtube.com/watch?v=ehOWuOcyejI). Am I correct?
Comment: @America Yeah, *sums* of Likert items do not have a Likert distribution. Thanks to the Central Limit Theorem they have an approximately normal distribution.
Comment: @Alexis ahh:) I see then, got it now. Thank you.
Comment: Thanks Alexis for your answer. I'm not sure that I understand your answer, are you saying that one should not use the Kruskal-Wallis test when one have ordinal data from a Likert scale?
Comment: Oh ok, got it. Thank you:) although I've been a member since some time ago, not very active tho.
Comment: What about ANOVA?
Comment: The closest that I have come as an 'illustrated example' are papers, where they use one-way ANOVA, but as you can imagine, they only present the results. I've tried to find examples, like the ones that are in books, but as I said in my post, I've found none, which is kinda strange or I don't know what I could be missing here.
Comment: Ahh. So is a _no_ for ANOVA too. But then I don't understand why do people use ANOVA when using Likert scale questionnaires?
Comment: I've read the Wikipedia link about ordered logic regression. "...the purpose of the analysis is to see how well that response can be predicted by the responses to other questions, some of which may be quantitative,..." I don't understand how is this related to ANOVA or Kruskal-Wallis purposes. Aren't they designed for different purposes, the ANOVA or Kruskal-Wallis _and_ ordered logit regression?
Comment: @America People make all sorts of mistakes. Some mistakes even become *standard practice*. From the first sentence from Wikipedia: "the ordered logit model (also ordered logistic regression or proportional odds model) is an ordinal regression model—that is, a regression model for ordinal dependent variables." This is ***precisely*** what Likert outcomes are: *ordinal data*. Presumably you want to look for evidence that, say, some group variable (but really, whatever kind of varible) predicts the value of your Likert variable.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/108102/discussion-between-america-and-alexis).


Render View in twig template

Question: I'm pretty new to Drupal, and very new to Drupal 8.  I've created a view, and have set up it up with a display block.  I'm trying to render this on a specific page.  So, I created a page template and a preprocess hook, created the following function.
function MYTHEMENAME_preprocess_node__13(&$variables) {
 $block = \Drupal\block\Entity\Block::load('views_block__downloads_block_2');
 $block_content = \Drupal::entityManager()->getViewBuilder('block')->view($block);
 $variables['downloads'] = $block_content;
}

When I place {{ downloads }} in my page template (page--node--13.html.twig) nothing happens.
Any ideas what I might be doing incorrectly?
Comment: Use this function  function mytheme_preprocess_page(&$variables) {....your code ....} ,if you are creating a page template
Answer: When you configure the visibility of the block in UI you can use a standard region and the standard page template.
If you want to do this with a specific page template similar to the question, add a region download to the theme, place the view block in this region and render the region in the page template specific to the node page--node--13.html.twig:
{{ page.download }}

Render View in twig template


Create DB by taking DBName from C# application

Question: I've a requirement to create DB by taking the DB name from the C# application. Basically, avoiding hard-coding of DBname in the sql script. ex: "create Database abc". In this "abc" must be passed as parameter.
Once i read the DBName from the application, can anyone please suggest how to pass DBName to the script file?  The Script file will be read by the C# application again and executes it.
-Prashanth
Answer: You can do two things:

Use a dynamic statement, and use it to create the database:
SET @sqlText = 'create database ? ...';
PREPARE stmt FROM @sqlText;
EXECUTE stmt using @name;
DEALLOCATE PREPARE stmt;

Pass in the name as parameter.
Create the statement in .NET:
string statement = string.Format("create database {0} ...", databaseName);

Comment: @user3744269: Was this post helpful to you?


best introductory simple readable undergraduate book for algebraic geometry

Question: I like to study algebraic geometry and what is the best introductory simple readable undergraduate book for it?
Comment: http://mathoverflow.net/questions/35288/undergraduate-roadmap-to-algebraic-geometry
Answer: Reid's undergraduate algebraic geometry is a great book.


Approximating cos using the Taylor series

Question: I'm using the Taylors series to calculate the cos of a number, with small numbers the function returns accurate results for example cos(5) gives 0.28366218546322663. But with larger numbers it returns inaccurate results such as cos(1000) gives 1.2194074101485173e+225
def factorial(n):
    c = n
    for i in range(n-1, 0, -1):
        c *= i
    return c

def cos(x, i=100):
    c = 2
    n = 0
    for i in range(i):
        if i % 2 == 0:
            n += ((x**c) / factorial(c))
        else:
            n -= ((x**c) / factorial(c))
        c += 2
    return 1 - n

I tried using round(cos(1000), 8) put it still returns a number written in scientific notation 1.2194074101485173e+225 with the e+ part. math.cos(1000) gives 0.5623790762907029, how can I round my numbers so they are the same as the math.cos method?
Comment: You're worried about scientific notation, but entirely missing the fact that you have a number that's something times 10^255
Comment: "`round(cos(1000), 8)` put it still returns a number written in scientific notation `1.2194074101485173e+225`" It doesn't, actually. Scientific notation is just that... a notation. The result of `round` is a float, with a magnitude which is not decimal notation, or scientific notation, or any other. That comes as a result of how you *print* the value.
Comment: Look at the polynomial expansions of cosine. 1000/6.2... > 100, so your polynomial *can't* converge to the answer that far from zero. You need to take the argument modulo 2pi
Comment: @Jared. I've updated my answer some more.
Answer: A McLaurin series uses Euler's ideas to approximate the value of a function using appropriate polynomials. The polynomials obviously diverge from a function like cos(x) because they all go towards infinity at some point, while cos doesn't. An order 100 polynomial can approximate at most 50 periods of the function on each side of zero. Since 50 * 2pi << 1000, your polynomial can't approximate cos(1000).
To get even close to a reasonable solution, the order of your polynomial must be at least x / pi. You can try to compute a polynomial of order 300+, but you're very likely to run into some major numerical issues because of the finite precision of floats and the enormity of factorials.
Instead, use the periodicity of cos(x) and add the following as the first line of your function:
x %= 2.0 * math.pi

You'll also want to limit the order of your polynomial to avoid problems with factorials that are too large to fit in a float. Furthermore, you can, and should compute your factorials by incrementing prior results instead of starting from scratch at every iteration. Here is a concrete example:
import math

def cos(x, i=30):
    x %= 2 * math.pi
    c = 2
    n = 0
    f = 2
    for i in range(i):
        if i % 2 == 0:
            n += x**c / f
        else:
            n -= x**c / f
        c += 2
        f *= c * (c - 1)
    return 1 - n

>>> print(cos(5), math.cos(5))
0.28366218546322663 0.28366218546322625

>>> print(cos(1000), math.cos(1000))
0.5623790762906707 0.5623790762907029

>>> print(cos(1000, i=86))
...
OverflowError: int too large to convert to float

You can further get away from numerical bottlenecks by noticing that the incremental product is x**2 / (c * (c - 1)). This is something that will remain well bounded for much larger i than you can support with a direct factorial:
import math

def cos(x, i=30):
    x %= 2 * math.pi
    n = 0
    dn = x**2 / 2
    for c in range(2, 2 * i + 2, 2):
        n += dn
        dn *= -x**2 / ((c + 1) * (c + 2))
    return 1 - n

>>> print(cos(5), math.cos(5))
0.28366218546322675 0.28366218546322625
>>> print(cos(1000), math.cos(1000))
0.5623790762906709 0.5623790762907029
>>> print(cos(1000, i=86), math.cos(1000))
0.5623790762906709 0.5623790762907029
>>> print(cos(1000, i=1000), math.cos(1000))
0.5623790762906709 0.5623790762907029

Notice that past a certain point, no matter how many loops you do, the result doesn't change. This is because now dn converges to zero, as Euler intended.
You can use this information to improve your loop even further. Since floats have finite precision (53 bits in the mantissa, to be specific), you can stop iteration when |dn / n| < 2**-53:
import math

def cos(x, conv=2**-53):
    x %= 2 * math.pi
    c = 2
    n = 1.0
    dn = -x**2 / 2.0
    while abs(n / dn) > conv:
        n += dn
        c += 2
        dn *= -x**2 / (c * (c - 1))
    return n

>>> print(cos2(5), math.cos(5))
0.28366218546322675 0.28366218546322625
>>> print(cos(1000), math.cos(1000))
0.5623790762906709 0.5623790762907029
>>> print(cos(1000, 1e-6), math.cos(1000))
0.5623792855306163 0.5623790762907029
>>> print(cos2(1000, 1e-100), math.cos(1000))
0.5623790762906709 0.5623790762907029

The parameter conv is not just the bound on |dn/n|. Since the following terms switch sign, it is also an upper bound on the overall precision of the result.
Comment: @Ironstone1_: you are taking way too many terms. factorial(172) is already larger than the largest float value.
Comment: When I add `x %= 2.0 * math.pi` to the beginning of function I get `n -= ((x**c) / factorial(c)) OverflowError: int too large to convert to float`
Comment: Maybe Taylors series isn't the best method for calculating cos, I'll look for another.
Comment: @Ironstone1_. Most fast implementations use a bunch of hacks and something called Chebyshev Polynomials
Comment: @Ironstone1_. That being said, I've added a concrete implementation that's probably good enough for your immediate needs
Comment: Actually this happens with your original code when n > 85 also.
Comment: @YuriGinsburg. Well, (85*2))! ~= 7.26e306, while DBL_MAX ~= 1.80e308, so that's not surprising. Also, if you type "172 factorial" into Google, the result is "undefined". Heh.
Comment: @MadPhysicist Not sure what Google uses for computing factorial, but using Python I can easily get  100000! with no overflow.
Comment: @YuriGinsburg Google most likely uses IEEE754 double precision floats, while python supports infinite precision integers. The issue here isn't computing the factorial: it's computing 1/factorial as a float.
Comment: @YuriGinsburg. I've added a couple of examples to bypass the issue
Comment: @MadPhysicist This is good, the third function with the while loop, does appear to throw an error through if you enter cos(0) `while abs(n / dn) > conv: ZeroDivisionError: float division by zero`.
Comment: @MadPhysicist I understand the issue here ). But why Google uses double precision for factorial is still a mystery for me.
Comment: @YuriGinsburg. Because it was faster and easier to use floats for everything. Let's say that most people that are worried about factorials 86+ are not going to rely primarily on Google for that.
Answer: The number returned is simply a number; it has no sense of notation until you print it. If you're looking to control how the value is printed, let's suppose you're printing like so
print(cos(1000))

Then we can use format strings to control output
print("{:f}".format(cos(1000)))

If you're on Python 3.6 or newer, we can even interpolate it directly into the string literal.
print(f"{cos(1000):f}")

You can read the above links to see more details about the format mini-language (the language is the same between the two features). For instance, if you want to print a specific number of decimal places, you can request that too. We can print exactly three decimal places as follows
print("{:.3f}".format(cos(1000)))
print(f"{cos(1000):.3f}")

However, as Mad Physicist pointed out, there are some more mathematical problems with your code as well, so I strongly urge you to read his answer as well.
Comment: The function is not fine, and you can't magically turn 1.2*10^255 into a number between negative one and one.
Comment: Oops! I thought that read `e-255` (hence, was a number quite close to zero). My mistake.
Comment: Your answer makes a lot more sense now!
Comment: I'll leave my answer here, since I think the formatting information is still helpful, but yours is definitely the right answer to the question.
Comment: I'll remove my downvote because I agree that the info is useful and I understand why you thought it was relevant now.


Div showing before slidedown when using javascript

Question: I have an issue with a Div that is temporarily shown before, sliding into view.
The Div should be visible if no javascript is available and start hidden if javascript is available. I use css and javascript.
.no-js .show {
    display:block
}

$('body').removeClass('no-js').addClass('js-ok');

However, I want to slide the div in rather than just show it. Here's the code:
$('#site-cookie-notice').slideDown();

The result is that the div temporarily shows (via the css), before being hidden, then re-displayed with javascript.
Any ideas as to how this could be worked around?
Answer: I guess you're using doc.ready? You need to use blocking JS like Modernizr does to replace your no-js class in the head. That way it'll be hidden when it's first rendered. Modernizr does it in the head thus:
var docElement = document.documentElement;
docElement.className = docElement.className.replace('no-js', 'js-ok');

Comment: Modernizr doesn't specifically use "blocking JS" - it just is required to be a script tag in the head in order to work. All script tags are blocking (regardless of position), and if they are in the head then the rest of the page won't get rendered until the script is downloaded and executed.
Comment: The term blocking js makes total sense here, you could still asynchronously include a script in the head, or defer part of it's execution until later. The fact that we swap the class name, then proceed loading means the page will render in full correctly.
Answer: Yes.

Put the code that adds/removes the js class in the head
DO NOT put it inside a $(document).ready() like so many people do.
Put the classes of no-js and js-ok on your HTML, instead of your body (your body element won't be available when your code gets executed)

If you do it like this, then the classes will get applied to the HTML element before the rest of the page is rendered (meaning your .no-js .show CSS rule will never get applied).
Like this:
<!doctype html>

   ...


Cut Off My Own Google Cloud Engine SSH Nose

Question: A bit of stupidity. On my Google Compute Engine (GCE) instance, I went in and changed the sshd_config to listen another port (something I do routinely)...but I didn't test before logging off.  And there's a typo. So now I can't log in via ssh because the config is screwed up and sshd won't even start. (I can launch sshd with a different config file, as a non-root user, but it gives me a "Could not load host key", as expected, probably doesn't have the permissions.)
Use the GCE serial console you say? Ah... but none of the users I can login with are sudoers. (I have two others with sudo'er, but the passwords aren't working, don't know why. I wrote them down wrong?)
So I have user (non-root) access with password, and have keys for root (sudo'er) users, I just don't have a way to log in with those thru the serial console?  (Is there a way to have the console recognize my keys instead of a password?)
It's good for security that I can't just fix this in 5 minutes with my limited knownledge, but can I leverage what I have to get back in with root? I have the access to the project in the Google Compute Engine Console and the users, etc., I just have cut myself off from command line on this instance.
If it were a physical machine, I'd stick in bootable usb distro and simply edit config file and restart.
Any suggestions?
Thanks.
Comment: If you have console access, you should be able to boot the system into single user mode and correct the ssh configuration.
Comment: Great suggestion larsks, thank you.  I know how to do this on a physical machine. As noted, this is about a Google Cloud Engine instance, so where/how do you do that for an instance in GCE? I've Googled, but I can't find that anywhere.
Comment: I'm not actually certain (I'm not a GCE user), but you said that you had access to a serial console, in which case the process should be the same as for a physical machine: while connected to the console, reboot the machine, and then see if it's possible to interrupt the bootloader.
Comment: There is some documentation [here](https://cloud.google.com/compute/docs/instances/interacting-with-serial-console)
Answer: To edit or examine configuration files in the root disk of a VM that you do not have access, follow the steps in the section ¨Inspect an instance without shutting it down¨ of this document.
A summary of the steps:
1) Create a temporal VM you can SSH into.
2) Create a copy of the root disk that is failing (this would have to be from a snapshot). You can actually delete the original VM and keep the disks (-keep-disks=all) but I would rather work with a copy.
3) Attach the copy of the disk to the temporal VM and mount the disk you wish to examine.
4) Modify the config files. Detach the modified disk and spin a new VM using this disk.
Comment: Thanks Carlos.  Seemed like a lot of work when I thought about it, and wasn't sure it would work. With your guidance and knowledge that it would work in the end, was not so hard. I guess if there were a way to change the file directly, that would represent a security issue.
Comment: I am glad it worked. I believe the serial console approach would have worked if you had been able to log with a sudoer.


Analysis: Prove that this function is not uniformly continuous on the interval $(0,1)$

Question: Prove that the function defined by
$$f(x)=\sin\left(\frac{1}{x}\right)$$
is not uniformly continuous on the interval $(0,1)$.
Comment: Perhaps they wanted you to show your work.  Perhaps someone didn't know what uniformly continuous means.
Comment: The information about Quora is superfluous. As to this site, it would be better next time if you showed what you tried, where you're stuck and such details, which helps people answer your question better.
Answer: We need to show:
$$(\exists \epsilon >0) \space \space (\forall \delta >0) \space \space (\exists \space x, y \in \mathbb{R})$$ with $$\left |\space x-y\space \right|<\delta,\space\space\space\space \left|\space f(x)-f(y) \space\right|\geq\epsilon$$
Let $\epsilon=1$. Let $\delta>0$ be arbitrary. By the corollary of the Archimedean property $\exists n_0 \in \mathbb{N}$ such that $\frac{1}{n_0}<2\pi\delta$. Let $x_n = \frac{1}{2n\pi}$ and $y_n = \frac{1}{(2n+1/2)\pi}$.$\space$Then for every $n \in \mathbb{N}, n>n_0$ we have
$$\left|\space x_n-y_n\space \right|=\left|\space \frac{1}{2n\pi}-\frac{2}{(4n+1)\pi}\space \right|= \frac{1}{2n\pi(4n+1)}<\frac{1}{2n\pi}<\frac{1}{2n_0\pi}<\delta$$
but
$$\left|\space f(x_n)-f(y_n)\space \right|=\left| \space sin(2n\pi)-sin((2n+\frac{1}{2})\pi) \space \right|=1\geq\epsilon.$$
$$\space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \space \blacksquare$$
Answer: A uniformly continuous function sends cofinal sequences to cofinal sequences, that is, if $|x_n-y_n|\to 0$ and $f$ is uniformly continuous, then $|f(x_n)-f(y_n)|\to 0$. You should be able to prove this using the definition of uniformly continuous function. This doesn't happen with $\sin(x^{-1})$ over $(0,1)$, for the sequences defined by $1/x_n=2\pi n$ and $1/y_n = 2\pi n +1/2$ are cofinal in $(0,1)$ yet their image sequences are not.


Finding path for maximum value of line integral

Question: I need help in the following question:
I have a field: $$F=\left(y^3-3y+xy^2,3x-x^3+x^2y\right)$$
bounded in region $D$ defined by $x^2+y^2\leq 2.$
I need to find a path $C$ that goes from $(1,1)$ to $(-1,-1)$ inside $D$ such that the value of the line integral/work of $F$ on the path $C$ is maximum.

I have thought about the edge of the circle as a possible path because the magnitude of $F$ seems to grow with the distance from $(0,0),$ but the field is not tangential so I don't know how to prove it's actually the maximum. So I am out of ideas; thanks in  advance.
Comment: You might be able to adapt this idea (https://mathhelpboards.com/potw-university-students-34/problem-week-153-march-2-2015-a-14514.html?highlight=line+integral) for your problem. The issue, of course, is that the problem to which I linked had a closed curve, whereas yours is not. Green's Theorem only applies for a simple closed curve. Working on it...
Comment: Hello sir, if it helps, in the previous section they asked to explain intuitively why for every path C1 that isn't the edge of the circle there is a path C2 such that the value of the line integral for C1 is smaller than C2. This pretty much screams that the edge of the circle is the maximum work path. I thought I'd start with this, but now it seems like the given order is the natural one..
Answer: Let's examine a related problem first: finding a simple, closed curve $C$ from $(1,1)$ to $(-1,-1)$ and back again that maximizes $\displaystyle\oint_C\mathbf{F}\cdot d\mathbf{r}.$ Let $G$ be the region enclosed by $C.$ Using the notation $\mathbf{F}=(F_x, F_y),$ not to be confused with taking the partial derivatives, which I will make explicit, we have by Green's Theorem that
\begin{align*}
\oint_C \mathbf{F}\cdot d\mathbf{r}&=\iint_G\left(\frac{\partial F_y}{\partial x}-\frac{\partial F_x}{\partial y}\right)dA \\
&=\iint_G\left[\left(3-3x^2+2xy\right)-\left(3y^2-3+2xy\right)\right]dx\,dy \\
&=\iint_G\left[6-3x^2-3y^2\right]dx\,dy.
\end{align*}
To maximize this integral, we want to pick up all the region where the integrand is positive. But this is all of $D,$ since
\begin{align*}
6-3x^2-3y^2&\ge 0 \\
6 &\ge 3\left(x^2+y^2\right)\\
2&\ge x^2+y^2.
\end{align*}
This exactly describes $D.$ To pick up all of $D,$ we will just do the circle of radius $\sqrt{2},$ which is the boundary of $D.$ The integral will become
\begin{align*}
\iint_D\left[6-3x^2-3y^2\right]dx\,dy&=\int_0^{2\pi}\int_0^{\sqrt{2}}\left(6-3r^2\right)r\,dr\,d\theta \\
&=6\pi.
\end{align*}
But notice that the final integrand we had was $\theta$-independent. So from the area integral perspective, we wanted to pick up as much of $D$ as possible, and we needed to skirt around it on its boundary. Moreover, it didn't matter which direction we chose: we could have gone clockwise or counter-clockwise.
Now, to solve the original problem, we can see by angle symmetry that we just want to chop the region in half diagonally from $(1,1)$ to $(-1,-1),$ and go around the circle's edge. The maximum value will just be half of what we computed before, or $3\pi.$
This is not a rigorous proof, but I think it could be made into one fairly easily.
Comment: All you have to do is constrain the "back again" to be the line segment from $(-1,-1)$ to $(1,1)$, so that the region has that as its lower boundary. Note that the work along that line segment is $0$ anyhow.
Comment: @TedShifrin Nice, thanks!
Comment: @AdrianKeister thanks alot !!
Comment: I think the bit about the direction needs to be clarified. The direction does matter because the contour in Green's theorem is assumed to be positively oriented. There is only one choice for $C$: the semicirle above the line $y = x$. Rephrasing your argument, the scalar curl is positive, therefore the integral over this $C$ minus the integral over any other path from $(1, 1)$ to $(-1, -1)$ is positive, because we get a closed contour traversed in the positive direction.


What is the beginner's explanation on how accessing a domain name resolves to the web server IP?

Question: I have an Apache web server hosting a few Django sites using the same domain name but different sub-domains:
proj1.example.com
proj2.example.com
proj3.example.com

The apache configuration file of each of the above begins like the following:
<VirtualHost *:80>
    ServerName proj1.example.com

Assuming the external IP of the server is 200.x.x.x and its internal IP is 10.x.x.x  Which of those two IP should I use if I want to add a new sub-domain name(proj4.example.com) to the server? I usually do the web dev and basic apache configuration, I'm still fuzzy on what's happening beyond that. Can someone give me a thorough explanation on what need to be setup and what is going on once I have setup the apache configuration file for a new site?
Answer: To quickly answer your question, , you don't need to worry about the IP address for your configuration, the domain name/alias is all you have to worry about, as apache will use the HTTP_HOST header passed by the browser.
<VirtualHost *:80>
    ServerName proj1.example.com
    DocumentRoot /path/to/proj1
</VirtualHost>
<VirtualHost *:80>
    ServerName proj2.example.com
    DocumentRoot /path/to/proj2
</VirtualHost>
<VirtualHost *:80>
    ServerName proj3.example.com
    DocumentRoot /path/to/proj3
</VirtualHost>

Long winded explanation.
In lamen terms, there are 2 seperate things going on here.

resolving a domain name to an IP
sending a web request to a server with virtual hosts set up

Resolving a domain name to an IP
when a browser is told to pull up a page, the first thing it does is do a DNS lookup for proj1.example.com.  The DNS requests first it goes to the ROOT servers, and says "who controls example.com", then the root servers point to the DNS server that controls .com domains, and says to that DNS Server and says "who controls example.com", then it goes to your DNS server, and goes "What's the IP address for proj1.example.com".   Your DNS Server says, "oh that's IP x.x.x.x", which is the external IP address.   The browser will send the request to your IP, at which point, your router forwards it to the your server (with the internal IP address).    The IP address of the web server is not part of the HTTP request/response, so it's not needed.
Requesting content from the web server
Your browser now knows that IP address, and sends a request to your iP.
The request looks like:
GET http://proj1.example.com/path/being/requested HTTP/1.0
Host: proj1.example.com
User-Agent: [blah blah blah]
Cookie: [cookie info]

The response will look like
HTTP/1.0 200 OK
(new line)

...

Apache knows which host the request is for by domain name in the host/url, and pulls the content accordingly.
More documentation is available here:
http://httpd.apache.org/docs/2.1/vhosts/name-based.html
Note: The older version of the HTTP protocol didn't support the Host header, so back then, if u wanted to set up virtual hosts on the same machine, it had to use multiple ip address and tie each ip address to a unique site.   Some documentation out on the web may still reflect this.  In general, tho, you don't have to worry about this as all browsers now support using the Host header
Comment: In "oh that's IP x.x.x.x", is that IP external or internal?
Comment: updated my answer to answer your question
Comment: Explanation of the DNS request is wrong: the query to the root name servers (actually, all the queries) includes the full domain name.


negative one times positive one is negative one

Question: This is a question I was surprised that no one on this forum has asked(as far as my search went).
I gave a proof that negative times negative = positive.
But it relied on the assumption negative times positive = negative.
SO now I am asking myself how does one show this fact:

negative times positive = negative

I am guessing that maybe the axioms of the real numbers maybe able to help.
I am wondering if anyone has pondered this question.
A lot of people pondered the -1 x -1, but not this one.
Regards,
P
Comment: What is "negative", an integer, a symbol, a mouse? What is "positive"?
Comment: Harder is to prove that 1 > 0.
Answer: It's a standard proposition of the field axioms.
If $x> 0, y>0$ then $xy > 0$ is a field axiom.
If $x < y$ then $x + z < y + z$ is a field axiom.
For every $x$ there exists a unique $-x$ such that $x + (-x) = 0$.  Field definition.
Prop: If $x > 0$ the $-x < 0$ and vice versa.
Proof: $x > 0 \implies x + (-x) > 0 + (-x) \implies 0 > -x$.
Prop: $(-x)y = y(-x) = -(xy)$ (and $-(-x) = x$).
Proof $(-x)y + xy  = (-x + x)y = 0*y = 0$.  And $x(-y) + xy = x(-y + y) = x0 = 0$.  So $(-x)y = -(xy) = x(-y)$.
($ x + -x  = 0$ so $-(-x) = x$.)
Prop: if $x > 0$ and $y < 0$ then $xy < 0$.
Proof: $ (-y) > 0$  so $x(-y) = -xy > 0$.  $So -(-xy) = xy < 0$.
Answer: $ (-1)1 = -1 $ because 1 is the multiplicative identity.
$$ x * -1 = x * ( 0 - 1) = (0x) - (1x) = \\ 0 - x = -x $$ by the distributive law.
Then you can generalize to $ x * -y $
$ x * -y = x * ( y * -1 ) = (x * y) * -1 = -(x * y) $
Comment: And what about $x * y$; $y < 0; y \ne -1$?
Comment: Edited to cover that case.
Answer: For the equation $1\times-1$, we can use the following fact:
$$1\times A=A\quad\text{ for every }A$$
Substituting in $A=-1$, we get $1\times-1=-1$.
For the general case, consider $a\times-b$, where $a$ and $b$ are positive. We have:
\begin{align}
0&=a\times 0\\
&=a\times(b+-b)\\
&=(a\times b)+(a\times-b)
\end{align}
We know $a\times b$ is positive. Thus, $a\times-b$ must be negative, because otherwise, if it were positive, we would have $0={\rm positive}+\rm positive$, which is impossible.
Comment: How do you know 1 > 0? and how do you know that if b is positive that -b is therefore negative?  Okay, I'm being picky but if we are doing axioms....
Comment: Hi  Akiva, yes I like your proof. Using the multiplicative Identity of 1. And your general case if very good too! This proof of yours using the axioms seems to be the easiest of all. Thanks so much for this simple to understand proof!


Memory warning and crashing app - can't find source of issue

Question: My app is constantly crashing after receiving many memory warnings. It is almost thirty thousand lines of code long so it is not easy to track the problem. I have run it through instruments and there are up to 30MB of live bytes at some stages, which should not be too much of an issue as far as I am aware. The memory leaks are extremely minimal, so they can not be the problem. The app tends to crash after playing it for long periods of time. Nothing in instruments has helped me to track the source of the memory warnings I am constantly receiving. Is there any other possible way to do this? It is very important that this doesn't happen for obvious reasons. Any help is greatly appreciated.
Comment: Use the VM Tracking tool to see how much dirty memory is associated with your app. It's almost certainly leaks that appear very small because the tracking structures in your app's memory space are small, but they're associated with media objects in another memory space (e.g., pictures being backed by large render buffers in the render server, audio/video files being backed by buffers in mediaserverd and launchpad, etc). The VM Tracker tool will show you the real picture of your app's memory usage. Those "tiny" leaks may not be tiny at all.
Comment: Have you tried Analyze Build Product -> Analyze ? surely show some lines with memory leakage...
Comment: @JasonCoco apparently 76% of the resident memory is dirty. I am not very familiar with VM Tracker, but I assume this means I have alot of leaks and unused memory. The next step would be to figure out exactly what id causing this, and this is where I am now stuck.
Comment: @Keithbunts Analysis did not reveal anything significant
Comment: About dirty memory: http://stackoverflow.com/questions/5176074/what-do-dirty-and-resident-mean-in-relation-to-virtual-memory
Comment: You should also take some time and watch the latest WWDC videos about instruments. They spend some time explaining the VM tracker and how to find the causes of the dirty memory. In my experience, it's often leaked or abandoned references to media that is the biggest offender.
Answer: Actually, 30MB of live bytes are not that little memory, in my experience. IMO, it is ok to consume up to large amounts of memory but only for a very short time, then go back to safer levels of memory occupation (which if you want to address iPad1 should be between 10 and 15/20 MB).
I think this is the case for "abandoned memory", i.e., memory which is allocated and, although it could be freed, is never (or too late).
Have a look at this post to learn about snapshot memory analysis, which could help in your case.
Of course there is also a chance that your app does need that much memory (e.g., because of some large resources it handles), and in this case the path forward would be trying to reduce required memory (and this highly depends on the kind of data your app manages. If it is a game, e.g., you could use an RGB565 format instead of RGBA8888 for your artworks).
Besides, if Instruments allows you to pin down a certain number of cases where the memory consumption goes up, you could work on those to remove all leaks you have, or remove abandoned memory, or optimize your app memory consumption requirements.
Comment: Thanks alot, this has helped me greatly. It seems that I have alot of unused memory, now the only issue I have is that I don't know exactly WHAT is causing this to happen. I will first try to reduce memory consumption by changing artwork and the likes, and then use instruments to track the exact issues if it is needed.


Room Acoustics for Singing

Question: I'm working to improve my singing ability at a very basic level.
During the week I have access to three different rooms 1) with a lot of echo (bare walls, ceiling and floor) 2) One that has a little bit of echo(specifically a music room with acoustic tiles etc) 3) a room with no detectable echo (by me, it's not an anechoic chamber)
I intend on practising in each room, but I'd like your opinions on what I should be checking for in each room.
At a guess, I tihnk I should use the echoing room to check if I'm hitting the right notes, and the echoless room to work on building volume and power in my singing.
How would you best use each of these rooms?
Comment: I suggest paying extra close attention to intonation in the echoless room!  It is much more difficult to be in tune without strong monitors or feedback, and doing that is a useful skill in performance.
Answer: My suggestion would be to practice in all three rooms and learn to optimize your voice in each situation. It's a sure bet that when you begin performing in public, you'll need to be able to adapt to the current acoustics at hand, and there seems to be no standardized acoustics for performance venues in the real world. It seems like previous experience dealing with associated acoustical problems might prove to be of value. Using your ears should help you determine what you'll need to focus on in each situation.
Answer: Try recording in the echoless room with a microphone and closed-back headphones to isolate whatever sound is resonating in the room. This way you can get the pure sound from your voice without reverberation interfering with the acoustics of your voice.
If you don't have fancy headphones, you can probably get away with regular ones since the reflections off of the surrounding walls isn't a huge issue.

Room Acoustics for Singing


In Python, what's the point of 'x or False' and 'False and x?

Question: I'm working with web2py and I've been looking through the source code to get
some better understanding. Multiple times I've seen assignments like
# in file appadmin.py
is_gae = request.env.web2py_runtime_gae or False

If request.env.web2py_runtime_gae is true, then False does not matter. Either way the expression becomes false, if request.env.web2py_runtime_gae is false.
And also:
# in file appadmin.py
if False and request.tickets_db:
  from gluon.restricted import TicketStorage

The second part of the and clause is never evaluated, because False and x always returns false.
So why would one do something like that?
Answer: Not quite like what you are assuming.  Python evaluates conditions lazily, so if the value is known to satisfy the condition then the evaluation quits.  See this example:
>>> None or False
False
>>> True or False
True
>>> 0 or False
False
>>> 'Value' or False
'Value'

The second one, as per lazy evaluation, will simply return False on that statement and the rest of the statements will not be evaluated.  This can be a way to unconditionally disable that if statement.
Comment: It's a feature called [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) and is present in many languages, such as JavaScript.
Comment: Python is a fascinating and bizarre language.
Answer: val = x or False

Ensures that val is actually 'False' (type 'bool') instead of Falsey values like 0 or "".
The second might be just a temporary disable for that condition?
The best place to investigate might be source control history?


Isomorphisms and Order of Elements

Question:
I don't fully understand the solution to the following problem. The way that isomorphisms were defined in my abstract algebra class was the following (I'm paraphrasing) :
A function, $\phi$, establishes an isomorphism between two groups if $\phi$ is bijective and establishes a homomorphism between the two groups. I can't seem how this relates to the order of elements in the groups other than perhaps $f(a*b) = f(a)f(b)$ failing to be true when $a=b=-1$.
Comment: If $\phi $ is an iso it will take an element x of order n to an element $\phi(x)$ of order n.
Answer: Let $G$ and $H$ be groups, and suppose $\varphi: G \to H$ is an isomorphism. Then it is easy to show that for all $g \in G$, if the order of $g$ is $m$, then the order of $\varphi(g)$ must also be $m$.
The proof in the book may be rephrased as a proof by contradiction. Suppose for a contradiction that $\psi: \mathbb{R} \to \mathbb{R}^*$ is an isomorphism. Since $\psi$ is surjective, there exists $x \in \mathbb{R}$ such that $\psi(x)=-1$.
But $x$ has infinite order in $\mathbb{R}$ and hence $-1$ has infinite order in $\mathbb{R}^*$. But $(-1)^2=1$, a contradiction since $1$ is the identity in $\mathbb{R}^*$. Therefore the two groups are not isomorphic.

Isomorphisms and Order of Elements


Derivation of the relationship between prevalence, incidence and duration of a disease p/(1-p)=id

Question:
(Sourced from a paper)
I don't understand why 'the inverse of the mortality m1 is the mean duration d of the disease'.
Answer: This relation comes from the assumption, not explicitly stated in this excerpt but clear from the rest of the paper, that there is no path back from the diseased state to the normal state. That is, once an individual gets the disease the disease persists until death. Thus the sooner one dies after contracting the disease (higher mortality), the shorter the disease duration.
The author's simple first-order model is equivalent to a Poisson process with a constant risk of death for a diseased individual and with deaths independent among individuals. For this type of model, the mortality rate (say, deaths per year) is the inverse of the expected time to death (years per death) and thus of the expected disease duration if there is no "cure" for the disease except for death. That, unfortunately, is a reasonable assumption in the cited paper's application to dementia.
Comment: Ah! So, if the mortality rate was say, 2 deaths per 10 years, than the mean disease duration would be the inverse (10 years per 2 deaths, or 5 years per death). I see.


Swipe usando a ferramenta Appium

Question: Estou aprendendo sobre uma nova ferramenta de testes automatizados mobile chamada Appium, e um dos testes que criei foi:
<code>@Test
      public void Swipe () throws InterruptedException{
        Thread.sleep(4000);
        System.out.println("Vamos fazer swipe no tutorial");
        driver.swipe(75, 0, 500, 0, 10);
       }
</code>
ao executar o teste, ele passa. Porém, eu não consigo ver ele fazendo a função do swipe, não entendo como ele consegue passar. Porque será que ele passa?
O que eu queria obter com meu teste: fazer um swipe horizontal, da direita para a esquerda.
Answer: Se você não inseriu nenhum assert no seu teste, e nenhuma linha de código disparou uma exceção, seu teste passará mesmo (porque não houve nenhum erro).
Você deve conferir o estado do seu app após o executar o "swipe" usando algum Assert ou mesmo disparando uma exceção.
<code>// assert com testng
Assert.assertEquals(<valor atual>, <valor esperado>);
// disparando exceção
throw new RuntimeException("Erro no app");
</code>
Veja um exemplo de como utilizar o método swipe (extraído de https://discuss.appium.io/t/screen-orientation-and-element-relative-swiping-tutorial/52)
<code>public void swipeElementExample(WebElement el) {
  String orientation = driver.getOrientation().value();

  // pega a coordenada X do canto superior esquerdo do elemento, e adiciona a largura do elemento pra pegar o valor X da extrema direita do elemento
  int leftX = el.getLocation().getX();
  int rightX = leftX + el.getSize().getWidth();

  // pega a coordenada Y do canto superior esquedo do elemento e subtrai a altura pra pegar o menor valor Y do elemento
  int upperY = el.getLocation().getY();
  int lowerY = upperY - el.getSize().getHeight();
  int middleY = (upperY - lowerY) / 2;

  if (orientation.equals("portrait")) {
    // Swipe do centro-esquerdo para o centro-direito do elemento, em 500 ms
      driver.swipe(leftX + 5, middleY, rightX - 5, middleY, 500);
  }
  else if (orientation.equals("landscape")) {
    // Swipe do centro-direito para o centro-esquerdo do elemento, em 500ms
    driver.swipe(rightX - 5, middleY, leftX + 5, middleY, 500);
  }
}
</code>

Swipe usando a ferramenta Appium


.mount a folder from the salt:// share onto a minion?

Question: I'm trying to write a state that will mount the folder currently in the "salt://" directory with the sophos installer, run the installer.sh, then unmount it. I'm hoping to avoid copying the whole folder or setting up a file share just for this purpose, but i'm not sure if that's possible. Any guidance?
Answer: salt:// is not really share (at least not normally), it's part salt's internal file system. I would not recommend mounting parts of the real file system mapped from salt. You are better off having a repository system (which could include a shared ro filesystem), separate from salt, to hold your distribution files if they're too big to serve via salt directly.


Is there a resource/site that I can use to practice harmonization?

Question: As above. With my theory exam in the distance, I want to brush up on harmonizing a given melody. Are there any sites/resources I could use to do this?
Comment: [Related](http://music.stackexchange.com/questions/17641/how-can-i-practice-harmony)
Answer: there´s a software that can be useful:
http://harmonypractice.altervista.org/index.html
Hope this helps, good luck in your exams!
Answer: Here is a free online class I am following on that very topic. I do not know if you have time to follow the entire class though.


Dynamic links block

Question: I want to make a block with dynamic links. An example path would be http://example/node/7/addreview
The number 7 will change depending on what node it's viewing. So if it's viewing node 14 then it should be http://example/node/14/addreview. How can i do this?
Answer: Enable module PHP Filter it is part of drupal core and disabled by default
Add a new (custom) block (/admin/build/block/add)
Add following code in the body
<?php
    if(arg(0) == 'node' && is_numeric(arg(1)){
        print l('Add review', 'node/'. arg(1) . '/addreview');
    }
?>

Set Input Format type to PHP Code
Save your block with appropriate visibility conditions
Associate your block to some region beside main content area.

Dynamic links block


A Combinatorics question whose solution I can't understand.

Question: The question is
"For a natural number $n$, let $T(n)$ denote the number of ways we can place $n$ objects of weights $1,2,...,n$ on a balance such that the sum of the weights in each pan is the same. Prove that $T(100) > T(99)$."
Now while I have (one of the many possible) solutions thanks to the fact that the people conducting this test released it, though I do not understand one bit of it.
Could someone explain me how to do this question? It's very difficult (for students) as it's part of the Stage I of selection of students from India for the International Mathematics Olympiad.
I am so confused even looking at the question!!!
The solution which was posted was: (scroll down to the last question) http://olympiads.hbcse.tifr.res.in/uploads/crmo-2013-solutions-2
I apologize in advance if this is too simple to search on the Internet.
Answer: One way would be to find a $1$ to $1$ injection from balanced partitions with $99$ items to balanced partitions with $100$ items.
For example, replace item $50$ with item $100$ and put item $50$ in the other part: both parts have increased by $50$ so are still balanced
Then to show a strict inequality, find another balanced partition  with $100$ items not already seen, i.e. with items $50$ and $100$ on the same side.
Answer: The first sentence is

Let $\mathcal S(n)$ denote the collection of subsets $A$ of $X(n) = \{1, 2, \ldots n\}$ such that the sum of the elements of $A$ equals $n(n+1)/4$.

This means that $X(n)$ is the set that contains the numbers from 1 up to $n$, which you are trying to divide into two parts, so that the sum of the numbers in one part is equal to the sum of the numbers in the other part.
Since the sum of all the numbers $1+2+\cdots n$ is equal to $ \frac12n(n+1)$, when the numbers are divided into two parts with equal sums, the two parts each have a sum of $\frac14n(n+1)$.
$S(n)$ is a family sets, each of which contains some of the numbers from $1$ to $n$. A set, say $A$, is a member of the family $S(n)$, if the sum of its elements is $\frac14n(n+1)$.
Do you understand the first sentence now? If not, what part don't you understand?
Comment: So $S(n)$ is basically a power set of $X(n)$ including only those sets whose elements add up to $n(n+1)/4$?
Comment: Yes, except that $\mathcal S(n)$ is a *subset* of the power set of $X(n)$. It doesn't contain *every* subset of $X(n)$; it contains only the subsets whose elements add up to $\frac14n(n+1)$.
Comment: OK, got it. Thanks for the really quick replies. I don't understand the rest of the solution as well.
Comment: Now you should re-read the second sentence and see if you understand it better.
Comment: I don't understand what is giving a map $f : S(99) \to S(100)$ (a function? If yes, why do we do it, what does it really mean?)
Comment: That's the third sentence. Do you understand the second sentence?
Comment: The second one is obvious(once someone gets the first one). I understand it. I am having  a doubt in 3rd one.
Answer: You said you now understand the first two sentences.
The third sentence is

We shall give a map $f : \mathcal S(99) \to \mathcal S(100)$ that is one-to one but not onto.

A map is a function.  A function $f : A \to B$ takes an element from set $A$ and gives you back an element of set $B$.  There is a theorem that says that if there is a function $f : A\to B$ that is one-to-one but not onto, then set $A$ has fewer elements than set $B$.
To see this, consider the range $f[A]$ of the function.  This is a subset of $B$. Because $f[A]$ is in one-to-one correspondence with $A$, it is the same size as $A$.  But because $f$ is not onto $B$ (that is, there are elements of $B$ that are not in the range of $f$) then $f[A]$ is a proper subset of $B$.  So $A$ is the same size as a proper subset of $B$, so must have fewer elements than $B$.
If we could construct a function $f : \mathcal S(99) \to \mathcal S(100)$ that was one-to-one but not onto, we would have shown that $\mathcal S(99)$ was smaller than $\mathcal S(100)$, which , according to sentence 2  (which you say you understand) would solve the problem.
Comment: In particular, if you want $f$ to be a function from $\mathcal S(99)$ to $\mathcal S(100)$, it must take a set $x$ whose sum is 2475 and return a set whose sum is 2525. If the set doesn't already contain $50$, you can do that by returning $x\cup\{50\}$, and if $x$ already contains $50$, you can do that by returning $x\setminus\{50\}\cup\{100\}$.
Comment: GREAT! I understood this and why we did this. Now how to prove that $f : S(99) \to S(100)$ is one-to-one and not onto (I don't understand the steps given in the solution). Thanks a lot.
Comment: The next three sentences ("Suppose that $A$ is … $f(A) = A\cup\{50\}$. ) define the function $f$ that the solution uses. Do you understand how the function $f$ works?
Comment: Use `A\setminus\{50\}` to write $A\setminus\{50\}$.  $A\setminus \{50\}$ is a set that has everything that $A$ has, except $50$.
Comment: $A\setminus \{50\}$ is a set that has everything that $A$ has, except $50$.
Comment: OK, so why do we define it this way? Especially the union with 100?
Comment: Because it works.  We want that if $a\in \mathcal S(99)$ (that is, if $a$'s elements add up to 2475), then $f(a)\in \mathcal S(100)$ (that is, $f(a)$'s elements should add up to 2525). We want $f$ to be one-to-one, and we want $f$ to be not onto. If we can do that, we win.  This definition of $f$ does those things.
Comment: OK, your second comment made it MUCH clearer. So, as I see it, we choose the condition of $50 \in A$ (when $A \in S(99)$) because the sums required (2475 and 2525) differ by 50, making it easier when $50 \not \in S(99)$. When 50 is there, we can avoid 50, but then we need 100 and fortunately 100 won't be in any set in $S(99)$. So we can just unite the $A\setminus\{50\}
$ with {100}. Am I correct?
Comment: I would be thankful if you could explain a bit more of the solution and tell me if my above comment is true.
Comment: You are correct.  Now your job is to show that this function from $\mathcal S(99)$ to $\mathcal S(100)$ is one-to-one but not onto. If you can do that, then the problem is solved.
Comment: Now I am sorry, but despite everything, I don't understand the NEXT two sentences where they prove that the function is one-to-one. Could you please explain that. I also do not understand the "not onto" proof. Thanks for all the help.
Comment: If you don't understand their proof, perhaps you can write your own proof?
Comment: Since I don't have enough knowledge to write a proof on my own, I carefully looked at their proof. So, they say that if A and B are two sets belonging to S(99), and $f(A)=f(B)$, then 50 belongs to both of them or neither of them, because our function is defined that way. Now if 50 belongs to both of them, $f(A) = A\setminus\{50\}\cup\{100\} = f(B) = B\setminus\{50\}\cup\{100\}$. Is it correct that this can be the case ONLY IF $A = B$, I got the one-to-one proof. Is it correct?
Comment: Could you explain the not onto proof if my assumption in my above comment is valid?
Comment: I think we have taken this as far as it can go in the comments.  Perhaps we could continue the discussion in email.  My address is on my profile page.
Comment: Can I move this discussion to chat? Also, I don't think email addresses are visible to others.
Answer: We can show that we always need an even number of odd primes to satisfy this condition.So the number N has to be of the form 4k+3 for some positive integer k or 4q for some positive integer q.Now if we check for T(99) and t(100).99 falls into the category of 4k+3 and 100 of 4q.Now as we know that they are consecutive integers try to show that whenever 4k+3 and 4q are consecutive integers such that 4q-1=4k+3.Then the number of ways of arranging 4q are more.First you can take examples like t(7) and t(8). and when you solve you will find that the number of arrangements of subsets are more in t(8).and then by induction you can show this is true for all t(n).so we get t(99)
Comment: Please edit and use [MathJax](https://math.meta.stackexchange.com/questions/5020) to properly format math expressions.


How to define (overload) symmetrical binary operator between two classes in C++, taking r-values into account?

Question: What I want to have: R = V + R = R + V.
How I do it:
R operator+(const R &r, const V &v) { return R(r) += v; }
R operator+(R &&r, const V &v) { return R(r) += v; }
R operator+(const R &r, V &&v) { return R(r) += v; }
R operator+(R &&r, V &&v) { return R(r) += v; }

R operator+(const V &v, const R &r) { return r + v; }
R operator+(V &&v, const R &r) { return r + v; }
R operator+(const V &v, R &&r) { return r + v; }
R operator+(V &&v, R &&r) { return r + v; }

Is there a shorter way?
Comment: related: http://stackoverflow.com/questions/13166079/move-semantics-and-pass-by-rvalue-reference-in-overloaded-arithmetic and https://stackoverflow.com/questions/2696156/how-to-reduce-redundant-code-when-adding-new-c0x-rvalue-reference-operator-ove
Comment: to clarify, is `V` such that doing `r + v` is faster if `v` can be moved out of?
Comment: I assume that not-copying v or r is faster than copying it. (So if I don't have to copy it, I shouldn't). Here, I also assumed that I have copy and move constructors, so when I write R(r), it either copies it or moves it, depending on whether r is an rvalue - at least that was my intent.
Answer: Because you will create an instance of r from either const R& or R&& anyway, this will shorten by 4 lines:
R operator+(R r, const V& v) { return std::move(r += v); }
R operator+(R r, V&& v) { return std::move(r += std::move(v)); }

R operator+(const V& v, R r) { return std::move(r += v); }
R operator+(V&& v, R r) { return std::move(r += std::move(v)); }

However, I think this is enough for you in all cases unless your R::operator+=(V&&) have difference implementation from R::operator+=(const V&):
R operator+(R r, const V& v) { return std::move(r += v); }

R operator+(const V& v, R r) { return std::move(r += v); }

My answer was written when I didn't aware of this implementation:
R operator+=(R&& r, const V& v)
R operator+=(R&& r, V&& v)

The answer of Yakk is better when take those functions into account.
Comment: Unless `+=` can take a `V` by `&&`.  Also note you should `move` into the `+=` above for `r`, otherwise `+=` has no way to know it can reuse the storage or return an rvalue.
Comment: @Yakk I added that note.
Comment: How do you know that I will always create a copy of `r`? If I had `R r = some_function_returning_R() + v`, then wouldn't the `some_function_returning_R()` be an rvalue, and then, couldn't I add `v` to it and then return it as a result of `operator+(R &&r, const V &v)` without having to create any copy of `r`?
Comment: @Jecke My wording is not quite good. But at the end of the day, you will always create an instance of `R` from either `const R&` or `R&&`.
Comment: @Danh - but why? If I get an R&& in an argument, wouldn't I be able to reuse it and not have to create another instance of R? Something like this: `R operator+(R &&r, const V &v) { return std::move(r += v); }?
Comment: @Jecke And you will end up moving it, which in turn call its move constructor, my implementation call move constructor first, then add `v` to it and return it.
Comment: @Dahn sorry for a noob question, but where does your implementation call move constructor for R?
Comment: @Jecke when you call `std::move(r)+v`, the argument is `R&&`, that function is passed-by-value, hence a move constructor is called overthere. Note: in some case, it's optimized out as copy elision
Comment: I don't understand. I asked why don't you define a function `R operator+(R &&r, const V &v)` and `R operator+(R &&r, V &&v)`. You said that your implementation calls move constructor for R, but I don't see any place where it does. You mentioned `std::move(r)+v`, but there is no such instruction in your code.
Comment: I hope [this example](http://coliru.stacked-crooked.com/a/0bebcaa67c65a5b8) will help you understand it.
Comment: The `main` function in line 41 want to call `operator+` for `R&&` and `V`. It found `R operator+(R r, const V& v)` then it need an implicit conversion from `R&&` to `R`, which ended up by calling move constructor of R
Comment: @Dahn I see, thanks :) But still, the R(const &R) constructor (line 10) is called at the end. If I understand correctly, that's because the return statement creates a copy? Is it possible to avoid it?
Comment: @Danh I've changed `R operator+(R r, const V& v) { return r += v; }` to `R operator+(R r, const V& v) { return std::move(r += v); }` and now it says "13 26 13" instead of "13 26 10", so, if I understand correctly, `r` is moved twice, instead of being copied. That's better, right?
Comment: @Jecke Yes, that's better if move is cheap (it's correct is most case)
Answer: Assuming:
R& operator+=( R& r, const V& v );
R& operator+=( R& r, V&& v );
R operator+=( R&& r, const V& v ) { r += v; return std::move(r); }
R operator+=( R&& r, V&& v ) { r += std::move(v); return std::move(r); }

we should have:
R operator+( R r, V const& v ) { return std::move(r)+=v; }
R operator+( R r, V && v ) { return std::move(r)+=std::move(v); }
R operator+( V const& v, R r ) { return std::move(r)+=v; }
R operator+( V && v, R r ) { return std::move(r)+=std::move(v); }

where I assume R is cheap-to-move, while += with a V&& is only marginally more efficient than a V const&.
Note that the return value of R operator+=( R&& r, ? ) should be a value.  I implement it in terms of +=(const&,?), then just move into the return value.
This means you have to implement two += operators beyond the above boilerplate.
If there is no gain from a moved-from V we get:
R& operator+=( R& r, const V& v );
R operator+=( R&& r, const V& v ) { r += v; return std::move(r); }
R operator+( R r, V const& v ) { return std::move(r)+=v; }
R operator+( V const& v, R r ) { return std::move(r)+=v; }

3 boilerplate, one actually implemented function.
If you dislike R operator+=( R&& r, const V& v) we can rewrite this as:
R& operator+=( R& r, const V& v );
R operator+( R r, V const& v ) { return std::move(r+=v); }
R operator+( V const& v, R r ) { return std::move(r+=v); }

and similarly for the V&& cases if needed:
R& operator+=( R& r, V&& v );
R operator+( R r, V&& v ) { return std::move(r+=std::move(v)); }
R operator+( V&& v, R r ) { return std::move(r+=std::move(v)); }

We make a copy of the R in the signature of operator+ rather than internally; if we are going to copy it anyhow, may as well do it in the signature.
Want speed?  Pass by value. is the technique used to remove the R const& and R&& overloads as redundant.
Comment: Hmm, 1. is `return std::move(r)+=v;` different from `return std::move(r+=v)`? If so, how? 2. Shouldn't I consider a possibility of `R operator+(R &&r, ?)`?
Comment: I do not see the reason to implement `R operator+=( R&& r, const V& v )` or `R operator+=( R&& r, V&& v )`. Operator `+=` implies, that you modify the left operand. Otherwise you would use `+`. Why should you use `+=` to overwrite the left operand if you remove the content from it afterwards?
Comment: Isn't it ended up calling `R& operator+=( R& r, const V& v );` in `R operator+( R r, V const& v ) { return std::move(r)+=v; } `? Is there any benefit?
Comment: @Danh The state is moved from `+` into `+=(&&)`, then `+=(&)` is called on the state, then the state is moved out (twice, but elision-capable) and returned.
Comment: @JojOatXGME If I did not implement `+=(&&)`, I'd have to make other changes to remain as efficient.  Are you saking why I don't just make those other changes?
Comment: @Jecke Slightly different, in that `std::move(x)+=v` returns a value, while `std::move(x+=v)` returns an rvalue reference.  Not a large difference.  You can do away with `+=(&&)` if you prefer, but then `+` must use `std::move(x+=y)` in those cases.  You do not need `R operator+(R&&, ?)` because `R operator+(R, ?)` works, and if we assume move is cheap it will be good enough.  Within `+` we are making a copy of the `R`, so why not make it in the signature?
Comment: @Yakk I thought that I could avoid making a copy of R if I defined `R operator+(R &&r, const V &v)`. I thought defining it as something like `{return std::move(r+=v);}` then it wouldn't make any copy of r.
Comment: @Yakk I'm not sure if I understand everything. Right now, my implementation looks like this:

`R operator+(R r, const V &v) { return std::move(r += v); }  `,

`R operator+(R r, V &&v) { return std::move(r += std::move(v)); }    `,

`R operator+(const V &v, R r) { return r + v; }      `,

`R operator+(V &&v, R r) { return r + v; }`

Does that solve all possible combinations? (r + v, move(r) + v, move(r) + move(v), r + move(v), v + r, v + move(r), move(v) + move(r), move(v) + r)?
Comment: @Jecke Always `std::move( r += v )` or `std::move( r += std::move(v) )`.
Comment: You mean that I shouldn't write `return r + v`? I thought that this would call one of the first two functions (depending on whether v is an rvalue), so it will be `return std::move(...)` in the end...
Comment: @jerke Yes, I mean that.  Instrument the copies and moves, yours does needless copies.
Comment: @Yakk Hmm... Here http://stackoverflow.com/questions/11817873/using-stdmove-when-returning-a-value-from-a-function-to-avoid-to-copy it says that one shouldn't use `move` if there are temporary objects created in-function (which may or may not be the case, because we don't know if `r` is an rvalue... that could be solved if we had two functions: `operator+(R &&r, ?)` and `operator+(const R &r, ?)`)
Comment: @jecke at this point I have given you about a half dozen variously optimal solutions, and described them, and explained roughly how they differ.  If you have further questions ask them in a new SO question.  If you see an alternative, consider making a noisy type that prints when copied/moved, and test and watch why your alternative is or is not worse.


Log in to SSH without home directory Synology

Question: I need a knight in shining armour.. go internet!
I have a failed volume on my Synology NAS. In DSM6 they have 'removed' the root user. - the only user which doesn't have a home dir.
To recover, we need to log into ssh. When we log in as admin, it disconnects immediately because the home dir doesn't exist which is obvious since the volume is unmounted.
Once we are in, Synology support seems to be somewhat confident that he can restore the volume.
Sure, I have backups - of the important stuff, but the thing about the unimportant stuff is, I don't know what is there.
Any way I can bypass the home dir not valid which closes the SSH connection?
Thank you.
Comment: Is it possible to execute a remote command? ssh user@server 'ls -l /tmp' May be helpful to recover.
Comment: Is it possible to connect a keyboard and a monitor?
Comment: It doesn't have any video outputs, there is a service serial (inside) the NAS unit. But I have managed to get on now by attempting to install a fake .pat firmware file. The nas goes into telnet mode.
Answer: All of the SSH implementations I've tried will let you log in if your home directory has been deleted, so I'm thinking maybe it's the ash shell (I don't have access to it to test).
Try connecting with sftp. That might get around the shell and let you re-create a home directory. I can sftp to my server as a test user whose home directory has been deleted; it just puts me in /. Escalating your privileges without sudo might be an issue, but it might work. Or it might not. Good luck!
Answer: It sounds like the failed volume has the Synology system partition on it. If so, any attempt to recover it by connecting to Synology may cause more to be overwritten.
The filesystem isn't anything proprietary, it's most likely ext4. You can mount it as read-only on any computer and recover what you need.
Comment: It's raid 5 :-/
Comment: Shouldn't RAID5 handle this automatically when replacing the failed drive with an empty one? That's what it is supposed to do!
Comment: You would have thought ay. It has done in the past with no downtime. This time the system ground to a halt, I could barely connect to it over MySQL, but not the web interface, so I booted it and it refused to boot. It's a bit difficult to diagnose when there is no console. Took all disks out, put an empty disk in and installed DSM, took that out put the old disks back in and it boots this time with no volume. Can't say I've been impressed by Synology support, 3 days of chasing and they now escalate to Taiwan and we hit the weekend.
Comment: Ouch! A RAID is (and backups are) only useful if it can recover.
Comment: 10TB is a little difficult to back up, so I only back up the most important stuff. I felt that in the ultimate disaster, I weighed up my risk and could live with only my photos and my websites. I have a successful photos backup less than a week ago. But it's more of the stuff I collected that I don't know really what I've lost that bothers me.
Comment: Can't get it back on at all now. Have all my drives connected into a new Linux machine. Two of the drives show up as 16T the other two at 3.6T each. Going to try RAIDfinder ISO.
Answer: Synology does have a root user.
It is hard coded to change every day and Synology have the generator.
Someone has also reverse engineered the generator which you can find online. That may be why root is disabled in DSM6+
There is a method to boot the NAS into telnet mode by creating and attempting to install a fake .pat file causing the installation to fail (without disks) I obtained this file via a private synology ftp, but most of the text is commented out apart from a few lines:
pollinterval = 5

[ups]
    driver = usbhid-ups
    port = auto
    #community =
    #snmp_version = v2c

Tom


How to count columns from multiple rows

Question: How can I count number of columns in different rows of a column family?
I am a Cassandra newbie. I do not know a starting point. The only option I have is to make the application fetch data for each row at a time. It does not sound right to me. I am using Hector to connect to Cassandra.
Answer: this is how you will get total column count in particular rowkey
sliceQuery.setColumnFamily("**your column family**");
sliceQuery.setKey("**your row key**");
sliceQuery.setRange(null, null, false, Integer.MAX_VALUE);

QueryResult<ColumnSlice<String, String>> result = sliceQuery.execute();
ColumnSlice<String, String> cs = result.get();

long noOfColumnInRowKey=result.get().getColumns().size();

Answer: Assume that you have wide row (Lets create it using CLI)
create column family cf3
 with column_type = 'Standard' and
 comparator = 'TimeUUIDType' and
 key_validation_class = 'UTF8Type' and
 default_validation_class = 'UTF8Type';

This is what I see in CQL3:
cqlsh:ks> desc table cf3;

CREATE TABLE cf3 (
  key text,
  column1 timeuuid,
  value text,
  PRIMARY KEY (key, column1)
) WITH COMPACT STORAGE AND
  bloom_filter_fp_chance=0.010000 AND
  caching='KEYS_ONLY' AND
  comment='' AND
  dclocal_read_repair_chance=0.000000 AND
  gc_grace_seconds=864000 AND
  read_repair_chance=0.100000 AND
  replicate_on_write='true' AND
  populate_io_cache_on_flush='false' AND
  compaction={'class': 'SizeTieredCompactionStrategy'} AND
  compression={'sstable_compression': 'SnappyCompressor'};

I inserted some values from CQL3, which makes you feel like good ol' MySQL
cqlsh:ks> insert into cf3 (key, column1, value) values ('user1', now(), 'time5');
cqlsh:ks> select * from cf3;

 key   | column1                              | value
-------+--------------------------------------+-------
 user1 | f0c687b0-d114-11e2-8002-2f4261da0d90 | time1
 user1 | fb9fa130-d114-11e2-8002-2f4261da0d90 | time2
 user1 | 09512f10-d115-11e2-8002-2f4261da0d90 | time3
 user1 | 0f5c93e0-d115-11e2-8002-2f4261da0d90 | time4
 user1 | 21155220-d115-11e2-8002-2f4261da0d90 | time5

But it's your wide-row (as seen from CLI)
[default@ks] list cf3;
Using default limit of 100
Using default column limit of 100
-------------------
RowKey: user1
=> (column=f0c687b0-d114-11e2-8002-2f4261da0d90, value=time1, timestamp=1370789864363000)
=> (column=fb9fa130-d114-11e2-8002-2f4261da0d90, value=time2, timestamp=1370789882563000)
=> (column=09512f10-d115-11e2-8002-2f4261da0d90, value=time3, timestamp=1370789905537000)
=> (column=0f5c93e0-d115-11e2-8002-2f4261da0d90, value=time4, timestamp=1370789915678000)
=> (column=21155220-d115-11e2-8002-2f4261da0d90, value=time5, timestamp=1370789945410000)

1 Row Returned.
Elapsed time: 105 msec(s).

Now, you wanted to count number of columns starting from a given time onwards. Right? Here is CQL3 for that.
cqlsh:ks> select count(*) from cf3 where key = 'user1' and column1 >= 09512f10-d115-11e2-8002-2f4261da0d90 ;

 count
-------
     3

Now, I am somewhat doubtful what goes beneath. But, my intuition says that actually all the columns gets fetched at coordinator node and counted in memory. Which is probably somewhat similar to what you were planning to manually on client machine.
Also, I am unaware if cassandra-cli provides such functionality, but you mentioned you are using Hector. So, you can leverage get_count or CountQuery like mentioned here except have null as range finish and large count value. Like this:
CountQuery<String, String> cq = HFactory.createCountQuery(keyspace, StringSerializer.get(), TimeUUIDSerializer.get());
cq.setColumnFamily(cf).setKey("user1");
cq.setRange(timestamp, null, Integer.MAX_VALUE);
QueryResult<Integer> r = cq.execute();

(uncompiled code above)
HTH

Old answer:
See Hector documentation:
CQL:
CqlQuery<String,String,Long> cqlQuery = new CqlQuery<String,String,Long>(keyspace, se, se, le);
cqlQuery.setQuery("SELECT COUNT(*) FROM StandardLong1 WHERE KEY = 'cqlQueryTest_key1'");
QueryResult<CqlRows<String,String,Long>> result = cqlQuery.execute();
assertEquals(2, result.get().getAsCount());

You may just miss the WHERE condition and use LIMIT to get your purpose solved.
Comment: This works for a single row. what I need is to count columns starting from a given column name for each row with a single query. eg if row key is a username and column names are timestamps, given 100 usernames and 100 timestamps each corresponding to a username, how do I get count of columns for each row beginning at the given timestamp?
Comment: Do you want a count per row or a single count for all rows?
Comment: @Richard I wanted to do exactly what Nishant has done above but for multiple rows. Something like a 'multigetcountslicequery' if there was anything like that. But it doesn't matter now because I have found out that these count queries are slow so I opted to use a counter column which I reset  to start counting from a given time.

How to count columns from multiple rows


How to generalize $\sigma_\alpha$ (Dirichlet convolution)

Question: I'm having some trouble deriving a generalization for $\sigma_\alpha(n)$ from this:
$$\sigma_1(n)=\sum_{d \mid n} \varphi(d)\sigma_0 \left( \frac{n}{d} \right).$$
My proof of the above is
$$\sigma_1=N \ast u = (\varphi \ast u) \ast u = \varphi \ast (u \ast u) = \varphi \ast \sigma_0,$$
and by experimentation I found
$$\sigma_\alpha(n)=\sum_{d \mid n} \varphi(d^\alpha)\sigma_{\alpha-1} \left( \frac{n}{d} \right),$$
but I don't see how I can derive this from $\sigma_\alpha=N^\alpha \ast u$. I don't even know how to write the $\varphi(d^\alpha)$-part... Am I doing this all wrong or is it just some detail I'm missing?
Comment: To put anon's comment another way: what exactly were you Dirichlet-convolving?
Comment: @anon: Oh, ok, I'm using the notation as it is presented in Apostol. $N=\text{Id}$ and $u=1$, using the notation from [link](http://en.wikipedia.org/wiki/Multiplicative_function)
Answer: Alternatively, a purely functional approach might go like
$$\rm\sigma_\alpha=(\color{Blue}{Id}\cdot Id^{\alpha-1})*1 \tag{1}$$
$$\rm= (\color{Blue}{(\varphi*1)}\cdot\color{Red}{Id^{\alpha-1}})*1 \tag{2}$$
$$\rm=(\color{Orange}(\color{Red}{Id^{\alpha-1}}\cdot\color{Blue}{\varphi}\color{Orange})*\color{Red}{Id^{\alpha-1}})*1 \tag{3}$$
$$\rm =\color{Orange}(\color{Green}{Id^{\alpha-1}\cdot\varphi}\color{Orange})*(\color{Purple}{Id^{\alpha-1}*1}) \tag{4}$$
$$\rm=(\color{Green}{\varphi\circ Id^\alpha})*\color{Purple}{\sigma_{\alpha-1}}. \tag{5}$$
In the above we used

$\rm\color{Purple}{\sigma_\alpha}=\color{Purple}{Id^\alpha*1}$ in $\rm(1),\;(4)\to(5)$ by definition.
$\rm \color{Blue}{Id}=\color{Blue}{\varphi*1}$ from $\rm(1)\to(2)$.
$\rm Id^\rho$ is completely multiplicative for any $\rho$, in $\rm(2)$.
$(\color{Blue}{g*h})\cdot\color{Red}f=(\color{Blue}g\cdot \color{Red}f)*(\color{Blue}h\cdot\color{Red}f)$ when $f$ is completely multiplicative, from $\rm(2)\to(3)$.
Associativity, $(\color{Orange}a*b)*c=\color{Orange}a*(b*c) $, from $\rm(3)\to(4)$.
$\rm \color{Green}{Id^{\rho-1}\cdot\varphi}=\color{Green}{\varphi\circ Id^{\rho}}$ from $\rm(4)\to(5)$.
Comment: I believe this is precisely what I was looking for!
Comment: Very well explained! Thanks again!
Answer: We define $$\sigma_{x}(n)=\sum_{d|n} d^x,$$ so that $\sigma_x = 1*N^x.$  This means that it has the Dirichlet series $\zeta(s-x)\zeta(s)$.  Your identity is correct, the simplest way to prove it is perhaps with Dirichlet series.  Notice that $\phi(d^\alpha)=d^{\alpha-1}\phi(d)$ so that $\sum_{d|n}\phi(d^\alpha)\sigma_{\alpha-1}\left(\frac{n}{d}\right)$ are the Dirichlet coefficients of the series $$\left(\sum_{n=1}^\infty \frac{\phi(n)}{n^{s-\alpha+1}}\right)\left(\sum_{m=1}^\infty \frac{\sigma_{\alpha-1}}{n^s}\right)$$  As the series for the Totient function is $\frac{\zeta(s-1)}{\zeta(s)}$ this becomes $$= \frac{\zeta(s-\alpha)}{\zeta(s-\alpha-1)}\cdot \zeta(s-\alpha-1)\zeta(s)=\zeta(s-\alpha)\zeta(s). $$
Now this is the dirichlet series for $\sigma_a(n)$, so we have proven the identity.
Comment: @Carolus: if you're familiar with combinatorics, what Eric did here is more or less taking the *generating function* approach to proving identities.
Comment: Thanks, but I'm sorry to say I've never seen Dirichlet series before. Is it possible to do this using the same (or a similar) method as the one I used to prove $\sigma_1$?
Comment: @J.M.: sorry, I've just started looking at combinatorics, I haven't seen generating functions yet :/ Thanks though, since I'm self studying mathematics, comments like this can be very helpful!
Answer: Also you can use Exercise 2.17 on p48 (Apostol) where the Jordan totient $J_k(n)$ is defined.
Then $J_{\alpha}=\mu*N^\alpha$ so $\sigma_{\alpha}=J_{\alpha}*\sigma_{0}$ - perhaps a more pleasing generalisation.


Reinstalling Plesk via SSH

Question: I deleted PHP via SSH using yum as an update would not work, but it seems to have also removed Plesk - I presume because it is dependent upon PHP?
Is it possible to restore or reinstall Plesk via SSH?
Thanks!
Comment: have you tried `yum install plesk` ?
Comment: This question appears to be off-topic because it is about [`working with a service provider's management interface, such as cPanel`](http://serverfault.com/help/on-topic).
Answer: If you new to Linux and Plesk, I would rather not recommend you installing Plesk by yum. Plesk autoinstaller does several extra configuration steps which yum will not perform, so even if installed, you won't be able to access Plesk until you do all these configurations.
I can suggest two options

Download Plesk autoinstaller, run it in SSH and do installation through it. It has sufficiently simple interactive interface. Unfortunately it may not work if you already have the product half-installed by yum manually.
if #1 won't help, run so called bootstrapper which does a lot of essential configuration for Plesk. i.e. if you are on the latest Plesk it will be something like
/usr/local/psa/bootstrapper/pp10.13.4-bootstrapper/bootstrapper.sh repair
If you don't have this file, run whatever the latest one you have in /usr/local/psa/bootstrapper/ folder

Hope something of that can repair your installation.
Answer: Sure, I mean you can do almost anything via SSH. For your needs, just do
ssh <user>@<something> "yum install plesk -y"

Although I think it would ultimately be better to shell into the OS and do the Yum install.
Comment: Hi, Thanks for your help... I'm new to Linux I'm afraid!
Comment: This is what I get...  I presume I need to direct it to the Plesk repository?
Comment: [root@ntdd3027-g14ec ~]# yum install plesk -y
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * atomic: www7.atomicorp.com
 * base: mirror01.th.ifl.net
 * extras: mirror01.th.ifl.net
 * updates: mirror01.th.ifl.net
Excluding Packages in global exclude list
Finished
Setting up Install Process
No package plesk available.
Nothing to do
Comment: Oh, looks like you have the the Atomicorp repo, but it might not be enabled. Append a `--enablerepo=atomic` to the yum install and that should fix it
Comment: That didn't work so I tried 'yum -y install psa psa-autoinstaller' and got this below - does that mean that Plesk is still installed? Yet if I navigate to where the login should be at https://188.8.131.52:8443/ I just get a 404 error? Is there anyway of checking through SSH that Plesk is installed and actually running? Thanks!
Comment: [root@ntdd3027-g14ec ~]# yum -y install psa psa-autoinstaller
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * atomic: www7.atomicorp.com
 * base: mirror01.th.ifl.net
 * extras: mirror01.th.ifl.net
 * updates: mirror01.th.ifl.net
Excluding Packages in global exclude list
Finished
Excluding Packages from Plesk Server Administrator
Finished
Setting up Install Process
Package matching psa-autoinstaller-3.10.1-110812.13.i386 already installed. Checking for update.
Resolving Dependencies
Comment: There is then a long list of errors - mainly 'command not found' - too long to post on here!

Reinstalling Plesk via SSH


Como verificar se é Internet Explorer menor que versão 10?

Question: Preciso fazer uma verificação do browser para saber se é Internet Explorer e se é  menor do que a versão 10.
Como fazer?
PS: Minha idéia é dizer pro usuário se estiver usando uma versão inferior ao 10 que baixe um navegador mais atual.
Comment: Geralmente isso não é uma boa ideia, é melhor verificar se uma funcionalidade específica está disponível do que checar qual é o browser. Claro que sempre existem exceções, mas não sei qual seria o caso aqui.
Comment: Se realmente quer chegar verifique se na string user agent o ultimo numero e' menor que 6.0 `Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)`
Answer: O Internet Explorer tem uma propriedade do document que dá isso. É o documentMode.
Teste este código:
alert(document.documentMode); // dá o numero da versão do IE

http://jsfiddle.net/t5Lup/
Porem, e como o bfavaretto referiu o melhor é confiar no "feature detection", detectar funcionalidades, pois isso é mais fiável.
Um exemplo bom foi quando a versão 11 do IE saiu eles decidiram mudar a UA string e toda a gente teve problemas com isso.
Aqui fica um link interessante com mais alternativas: http://tanalin.com/en/articles/ie-version-js/

Se quiser detectar dentro do HTML (sem JavaScript necessáriamente)  pode usar comentários de código que só o IE detecta. Por exemplo:

lte quer dizer IE<=7, somente lt quer dizer IE<7
Answer: Uma outra forma é, verificar a existência de alguns objetos e combinar algumas verificações.
A tabela a seguir contém as condições prontas para uso.
Versões do IE   Verificar condição
10+             document.all
9+              document.all &&! Window.atob
8+              document.all &&! Document.addEventListener
7+              document.all &&! Document.querySelector
6+              document.all &&! Window.XMLHttpRequest
5.x             document.all &&! Document.compatMode

No exemplo a seguir a condição é verdadeira se o navegador é IE11+ ou não.
if (!document.all) {
    alert('Voce utiliza o IE11+ ou um outro navegador');
}

Fonte
Comment: Isso dá certo com o IE de aparelhos móveis/Windows RT também?


How can I override with my module the existing commerce_file_field_access function?

Question: I am trying to alter the way commerce_file module shows the product file in the Product display. Actually it is shown to all users owning sort of administrative permissions (such as administer commerce_file or administer commerce_field type).
Its format is:
label: file.pdf
This code is driven by the
commerce_file_field_access($op, $field, $entity_type, $entity = NULL, $account = NULL)

function in commerce_file module itself, it seems.
I would like with my_module to override this behavior to make the file visible to users that doesn't own those permissions but that have already bought the digital product and had license granted for that, but really don't know how to. (I already succeeded in disabling the add to chart button)
I am able to define if the user/buyer already bought it, but just cannot override the module access conditions to apply my rules.
I already tried defining another function like my_module_field_access(), but it doesn't seem to work...
How is it possible to override the hook_field_access() function already defined in commerce_file module?
As an alternative I was minding to replicate/copy that field and render it again without that access control, just in the defined conditions I define in my module.
To do that I tried with a my_module_preprocess_node() function, but didn't succeeded. The new $vars['elements'] is not rendered ...
I hope have been sufficiently clear. really any advice (on the best approach & way) would be very welcome. Wasted so many hours on this ... yet.
Thanks so much
Answer: hook_field_access() implementations are invoked by field_access() using the following code:
  foreach (module_implements('field_access') as $module) {
    $function = $module . '_field_access';
    $access = $function($op, $field, $entity_type, $entity, $account);
    if ($access === FALSE) {
      return FALSE;
    }
  }

The hook is not invoked for the module implementing that field, but for any module implementing the hook.
If you want to override what done by commerce_file_field_access(), you just implement hook_field_access() in your own module.
As field_access() immediately returns FALSE when a hook_field_access() implementation returns FALSE, you can only override what returned from commerce_file_field_access() if your hook is executed before commerce_file_field_access(). This means that your module, when it is installed, should alter the weight associated with it, and assign it a lower value than the value assigned to the Commerce File module. The following is an example of hook_install() implementation for achieving that; it is similar to the code executed in block_install().
function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => -5))
    ->condition('name', 'mymodule')
    ->execute();
}

The same can be done in hook_update_N().
Any value lower than 5 actually works, as the Commerce File module uses the following code:
/**
 * Implements hook_install().
 */
function commerce_file_install() {
  // Make module weight heavier than field module
  db_query("UPDATE {system} SET weight = 5 WHERE name = 'commerce_file'");
}

The alternative of changing the weight of your module, which would influence when every hook in your module is executed, is to alter the order used for that specific hook implementations, using code similar to the following one.
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'field_access') {
    // Move mymodule_field_access() to the top of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}

Comment: Ok, thanks ... and I realized why it didn't work for me.
The API doc says " If no module returns FALSE, the operation is allowed.".
So, as the commerce_file_field_access() returns FALSE, how to override its result?
Comment: I have updated my answer.


nested json object to a one to many model in polymer

Question: just starting with polymer, and need an opinion about using pure javascript Objects as my model vs polymer elements. I have a nested json object I want to map to a multiple one to many custom objects e.g.
Company -> Departments -> Teams -> Employees
I already did the model above using pure javascript Objects as the code below.
I have a separate function for every entity above based on the pattern below. Now As I understand  polymer elements can either be UI related or utility. Any suggestion to make the model more tied to polymer or just stick with keeping the model as below. Thanks in advance for insights.
function Company (json){
   this.companyID = null;
   this.companyName = null;
   this.Departments = null
   for (var prop in json){
        if(this[prop] !== undefined && json[prop] != null ){
          var iterator = json[prop]
          if(   iterator.constructor === Array  ){
            for(var i in iterator){
              var newDepartment = new Department(iterator[i]);
              if(this.Departments == null) this.Departments = [];
              this.Departments.push(newDepartment);
            }

          }else{
            this[prop] = iterator;
          }
        }
      };

}

Comment: updated the answer to include an example for you.
Answer: There are actually a number of talks regarding this subject starting from before these custom markup libraries started hitting the web. The most persuasive one being Web Components and Model Driven Views. This video argues for markup based components and modeling in the front-end and for a number of practical and social reasons.
Focusing specifically on Polymer, there is very little reason to have pure javascript models if there is to be any sort of view attached to them. Reasons for this (aside from the video) include:

9 times out of 10, you are just duplicating a model that is somewhere in the back-end (if you use a back-end framework or storage orm)
This will often result in rendering the model with DOM manipulation. This can be handled easily with Polymer.
Javascript is supposed to be there to do what the web platform cannot natively. Custom markup fixes a lot of that.
Data-Binding and Template-Binding bridge a lot of the issues that MVC solves as a practice. MVC is (and has been) a necessary step, but often for the same reasons that MDV tries to solve out of the box.
Unless your application is a pure Javascript application, most times your client is supposed to be the View which gets the Model from the server. Using custom markup can provide a cleaner separation.
According to the Polymer docs on Data Binding, the model is the element itself. This is obviously, to the devs of Polymer, what it was designed for.

That said, there are plenty of reasons for using a pure Javascript model. I haven't found many that can't be addressed (and addressed well) by utilizing data/template binding, though I have found some. The more I work with Polymer, the smaller that list becomes as I learn newer Polymer techniques that address concerns on that list.
Note on Personal Bias:
Keep in mind that all of the above are biased by my personal view that the development ecosystem for a platform should strive to meet the ideals proposed by that platform. Polymer is the first framework I have found that epitomizes that. The Custom Markup can now easily describe the Content and the presentation layer. And I can rely on a strong storage scheme in the back-end to manage my Model and its data. So for me, the separation of concerns is clear.
Update: An example of One-to-Many Model
This example assumes a single object for your model. Of course, it is quite simple to account for separate objects and is the basis of many model-based UIs.
Company Element
<polymer-element name="x-company" attributes="company" noscript>
    <template>

        <template repeat="{{department in company.departments}}">
            <x-department department="{{department}}">
            </x-department>
        </template>
        <content><content>

    </template>
</polymer-element>

The above is fairly simple. To actually apply the company data, simply get the node and set .company = { obj }... or if in the template of another element, company="{{ ref }}". Note the noscript at the top. It is purely for simplicity and is completely optional. One note: company.departments should be an array of objects. If you do use a script, there is a lot more that can be done with your UI.
Department
<polymer-element name="x-department" attributes="department" noscript>
    <template>

        <template repeat="{{team in department.teams}}">
            <x-team team="{{team}}">
            </x-team>
        </template>
        <content><content>

    </template>
</polymer-element>

Team
<polymer-element name="x-team" attributes="team" noscript>
    <template>

        <template repeat="{{employee in team.employees}}">
            <x-employee employee="{{employee}}">
            </x-employee>
        </template>
        <content><content>

    </template>
</polymer-element>

Employee
<polymer-element name="x-employee" attributes="employee" noscript>
    <template>

        <content><content>

    </template>
</polymer-element>

That's as simple as your model's UI can be. There are a lot of other possibilities. This makes pure use of Shadow DOM, but you may use plenty of other techniques to apply the model to the Light DOM and Content children.
Hopefully, this clears things up for you.
Comment: Thanks a lot for your detailed response, however I king of got lost in the polymer databinding part. How would i address the one to may relationship between polymer elements
Comment: Certainly, I interpreted your question to be whether to and not how. Give me a bit to compose a solution.