Is there a proof $a^2 = b^n$ where $n>2$ that square of an integer does not equals any cube or above?

Question: I might have a silly questions but I am new to math so don't judge to hard, is there a proof that there is no integer for which $a^n = b^2$ where $n>2$ ?
PS The question excludes the case where (a=c^2$)  (b=c^n$). Example( 4 and 8, 16 should be excluded) also solutions a=b=0 or a=b=1 also to be excluded.
Comment: $9^3=27^2$. In general, $(a^2)^n=(a^n)^2$.
Comment: If $a=c^2$ and $b=c^n$, for any natural number $c$, then in fact $a^n=b^2=c^{2n}$.  For instance, $4^3=8^2$.
Comment: Tnx, but I am talking more about the case where a and b are not equal to c^2 or c^n
Comment: @Hivaga you should edit the question to reflect your intentions if you want to exclude the case that satisfies equation.
Comment: @MichaelMorrow that is a good point :)
Comment: Suggestion for the question you appear to be asking: Consider the prime factorizations of $a$ and $b$.
Comment: "The question excludes the case where (a=c^2)(b=cn). Example( 4 and 8, 16 should be excluded) also solutions a=b=0 or a=b=1 also to be excluded."  You should *really* clarify your actual question.  The answer to the question is "no" because it isn't true.  If $a = c^k$ and $b=c$ and $n = 2k$ is, of course, a counter example.  You can't say "but that doesn't count because..." because you didn't clarify what you were actually asking form.
Comment: By the dupe if $n$ is odd then $\,a = c^n, b = c^2\,$ for an integer $\,c,\,$ which is excluded. Thus $n$ is even,  where obviously it *is* solvable: let $\,a = b^{n/2}\ \ $
Answer: Suppose that $a$ and $b$ are positive integers with $a^n = b^2$, where $n> 2$ is an integer.  Then $a = \sqrt[n]{b^2} = [\sqrt[n]{b}]^2$.  You want to know all the ways this can happen.
If $a$ is a perfect square, say $a = c^2$ for a positive integer $c$, then you can take $b = c^n$, and then $a^n = c^{2n} = b^2$.
If $a$ is not a perfect square, then this situation can only happen when $n$ is even.  Indeed, if $a = p_1^{e_1} \cdots p_s^{e_s}$ and $b = p_1^{f_1} \cdots p_s^{f_s}$ are the prime factorizations of $a$ and $b$ (with $e_i, f_i \geq 0$), then $a^n = b^2$ implies that $ne_i = 2f_i$ for each $i$.  The assumption that $a$ is not a perfect square is equivalent to the claim that some $e_i$ is an odd number.  For such $i$, the equation $ne_i = 2f_i$ implies that $n$ is even, as claimed.
So for $n$ even, every positive integer $a$ admits a corresponding positive integer $b$ such that $a^n = b^2$, since you can just take $b = a^{n/2}$ (an integer!).
For example, if $n = 4$, you can take for $(a,b)$ the pairs
$$(1,1); (2^4, 4^2); (3^4,9^2); (4^4,16^2); ...$$
Answer: There is a well known fact that $\sqrt[k]{m}$ (where $m$ is an integer) is an integer only if $m$ is an integer to a $k$ power.
So if $a^2 = b^n$ then either $b$ is a perfect square or $n$ is even.
If $b = c^2$ for some integer $c$ then $a= c^n$ and $a$ is an integer to the $n$th power.
And if $n = 2k$ then $a = b^k$ and $a$ is a perfect $k$ power.  And that's the only way it is possible (although that is quite possible).
I'm not sure what you are looking for but that pretty much exhausts everything.


Views filter criteria multiple content types (Drupal 7)

Question: I have created a view and added the filter criteria content type. I have chosen two content types. They are both being displayed. I would like then further filter one of the content types so that only those which have had a check box selected will display. Is it possible to do this in views?
Thanks,
JP
Answer: This can be done by modifying the Views filter criteria.
Answer: Under Filter Criteria you probably added:
Content Type A
Content type B
Now you can extend this by adding:
Content Type A check-box (is one of: yes or whatever)
Content Type B check-box (is one of: yes or whatever)
Then under Filter Criteria instead of add, click on the arrow and choose "And/Or, Rearrange".
Choose your operator and move the respective fields together.
Then it will look something like this:

Content Type A  AND Content Type A check-box
OR
Content Type B AND  Content Type B check-box
Comment: this leads to this problem for me :
http://drupal.stackexchange.com/questions/55188/views-filter-2-content-types-but-with-condition-of-one-of-them/55191
Answer: When you expose a filter you can select the option "Limit on selected" or something like this, that force the exposed filter to show only selected filter.
Comment: Thanks for answering Sergiod. Actually, I don't want to have an exposed filter. I'm sorry my question wasn't written more clearly. I want to be able to have one of the two content types being currently displayed to be filter by whether or not I've checked off a box that says archive when creating the node.
Answer: I had the exact same issue and I've posted an answer to this with a screenshot at Views Filter 2 Content types but with condition on one of them. Please vote it up if it helps you. Thanks.


Under-saddle pickup not picking up the low E string

Question: Recently, my under-saddle B-Band pickup has gone silent, but only on the low E.
Acoustically, everything sounds just fine. The saddle hasn't been removed recently and everything appears sound.
Any suggestions on how to diagnose the problem? Could the pickup have gone bad in just the one spot? Is it liable to have moved under the saddle?
Comment: You might check to see if the pickup element has slid down towards the high e string.  Your under saddle pickup is long enough to catch all 6 strings but the saddle slot may be long enough to allow for some play or movement.  You must remove the strings in order to remove the saddle to inspect the pickup element.  If you have had any work done on the saddle recently, you might need to be sure that the bottom of the saddle is perfectly straight and evenly contacts the pickup element.
Answer: I had the same problem on an electro-acoustic, but that was after I'd taken the saddle off. The solution was to bed it down properly on the bridge, as the pup needs to have very good physical contact with the saddle. Gentle tapping was the order of the day, till I heard that the string was being picked up.
Answer: If the bottom of your saddle is not flat or too tight this will occur. You can true the bottom up with a plate of glass and some sandpaper checking it with a straight edge and good light. You can also adjust the fit with a scraper or the sandpaper and glass. Typically a saddle should be very snug fit into the bridge but with an under the saddle pickup it should not be loose, but it should be a slip fit so that there is sufficient downward pressure on the piezo crystal.


Converting a FOL formula to a predicate only version

Question:
Suppose there are 2 signatures: $ \sigma_2= \{c, f^1, =^2 \}$ where $c$ is a constant, $f$ is a function symbol of arity 1, and $=$ is a predicate symbol of arity 2. Also, $\sigma_1 =\{R^2,P^1, =^2 \}$, where $R, P, =$ are all predicate symbols with their corresponding arities. Does there exist an algorithm that converts a formula A over $\sigma_2$ to a formula over $\sigma_1$ such that $ \vdash_{FOL}A \leftrightarrow \vdash_{FOL}A'$.

My idea was to replace different terms with variables, and conjoin predicate symbols in $A$ with a $\wedge$ so as if for example $A := =(c, f(f(c)))$, then $A':= =(v_1, v_3)\wedge P(v_1) \wedge R(v_1, v_2) \wedge R(v_2, v_3)$
I know that by this construction, one direction is satisfied, as we can choose $P$ to have 1 item and that will be the interpretation of $c$ in the satisfying model, and $R$ will be the same interpretation of $f$.
However, I am stuck in the other direction, as for example the relation $R$ in the satisfying model may not be  a function and seems like it may cause problems, and in any way I tried thinking how to prove this direction with induction and failed.
Am I going in the right direction? Is there any more simple way to construct $A'$, maybe an algorithm such as this doesn't exist? But then, how is it possible to disprove it?
thanks.
edit: this question was in an exam by a different lecturer than mine, and after asking my TA about this happening in other questions the equality symbol here is agreed upon to be interpreted as the identity relation. I'll try to solve this again using this new info and update the question. Sorry for wasting your time.
Comment: @Eloo: The reason why one uses the symbol $=$ rather than something else is that _things are much easier to read_ if you write $t_1=t_2$ rather than ${=}(t_1,t_2)$. This convention is tacitly assumed whenever well-known binary relations/operators are said to be part of a logical language. (The underlying formalism does not change, it's just that we depict the symbol string "equals sign", "left parenthesis", something, "comma", something more, "right parenthesis" as "something $=$ something more" in human-readable text for ease of communication.)
Comment: In either signature, what's $(x,y)$ supposed to mean? No $(-,-)$ predicate or function symbol exists in either signature...
Comment: @MaliceVidrine notice that it is $=(v_1, v_3)$, so the $=$ is the predicate symbol.
Comment: The prefix form is especially odd looking when there's no extra whitespace, and it looks like you're writing an odd variant of "$:=$", which is what I thought was happening. (You may think no one would ever write that, but...)
Answer: Your idea goes in the right direction, yes. You do, however, need to quantify the new variables you introduce when you translate an atomic formula. Once you're assuming that $R$ and $P$ work like they "should", it will work to bind them all with $\exists$s.
For the other direction, where you have problems:
If you're interested in preserving satisfiability, you can take each full sentence $\psi$ and translate it to
$$ (\forall x\exists! y\, R(x,y)) \land (\exists! y\, P(y)) \land \overline\psi $$
where $\overline\psi$ means $\psi$ with every atomic formula translated according to the scheme you've already found. Then your translated sentence can only be satisfied by structures where $R$ and $P$ behave correctly, such that you can convert the structure back to a structure in the original language.
However, here you're being asked to preserve provability, which is (well known to be) the same as validity. Then you need to translate to
$$ \neg(\forall x\exists! y\, R(x,y)) \lor \neg(\exists! y\, P(y)) \lor \overline\psi $$
such that your translated sentence will automatically be satisfied in the "spurious" structured where $R$ is not functional or $P$ not unique.

If you're careful it is also possible to do everything in the translation of atomic formulas, so you don't need to special case the top level of the formula. An example of this (with a translation between another pair of languages) is shown here.


What is the equivalent of $on("$ionicView.beforeEnter") for Ionic 2?

Question: What is the equivalent of $on("$ionicView.beforeEnter", function() {}) for Ionic 2?
Answer: There are now different view lifecyle hooks like onPageWillLeave() or onPageWillEnter(). Use this as a
reference
With ionic beta 8 the lifecylcle events changed their names. Check out the official ionic blog for the full list of the lifecycle events.


Git and log order

Question: I was trying to create a linear order from "git log" output, but all my attempts failed. What I need to do is map a commit to the next release that contains that commit. I cannot run
git tag --contains <commit>

for each commit, as our repository contains an extremely large amount of commits (more than 300,000).
First I tried using
git log --pretty=format:"%ct%H" | sort --key=1,10

to obtain a linear order based on commit time. However, this does not seem to produce an 100% accurate result. This leads to my first question:
Q1) How does git store commit times, when commits are pushed into the main repository? Does it store the current machine time for each commit, in UTC?
I also looked at "git help log", and the documentation states that by default, git log lists the commits in chronological order. In my project, I checked whether I was introducing any error, but as far I can tell, the code is correct, and the chronological order given by git log is not a linear order. Finally, my question is?
Q2) How can one obtain a linear order from "git log", given that git does not store revision numbers?
Thanks :)
Comment: The attempts are described in the text:

attempt 1) git log --pretty=format:"%ct%H" | sort --key=1,10
attempt 2) simply using the default order (chronological order) as given by git log
Comment: You can add that comment as an answer itself if you want, then others can be able to upvote it. It also means that others will see that this question is answered.
Comment: The question has not been answered. I just posted the comment to clarify that in the text, the attempts that I have tried were indeed mentioned. Sometime before, someone claimed that it was not mentioned in my description, so I added this comment just to make sure :)

Btw, the person who wrote that comments eventually removed his post and down-voted the question :P
Answer: #1: How does git store commit times, when commits are pushed into the main repository? Does it store the current machine time for each commit, in UTC?
From man git-commit:

Git internal format
  It is [unix timestamp] [timezone offset], where [unix timestamp] is the number of seconds since the UNIX epoch. [timezone offset] is a positive or negative offset from UTC.

Based on this, the git internally-used time-format is UNIX epoch time, including the machines UTC offset.
#2: How can one obtain a linear order from "git log", given that git does not store revision numbers?
The method you've used (git log --pretty=format:"%ct%H") will pull data from all branches that have been merged into the current branch.
This makes a "linear order" somewhat difficult. Consider the following [source: git-scm.org]:

So, here we've got several 'topic branches' being worked on. We then decide to keep some (dumbidea and iss91v2), discarding others (iss91). So we're discarding C5 and C6, keeping the other commits, and our post-merge history looks like this [source: git-scm.org]:

(Arrows point from children to parents; C14 is the child of commits C13 and C11).
So now we've got a single HEAD commit which, for arguments sake, we'll assume we're going to release as a RELEASE1 or something. So, to the question: how can we now, having this history, extract a linear, chronologically correct list of commits?
Simple answer: I don't believe you can - or, if you do, I don't believe it'll be what you want.
You could sort the commits linearly, by time:
git log --pretty=format:"%ct %H" | sort --key=1,10

That'll give you a list corresponding to:
C1
C2
... snip ...
C13
C14

Note, however, that this isn't actually a linear history! This is because we've merged some branches together, which were created at the same time. We can't extract a linear history of the parents of C14 (our HEAD), because there isn't one - it's the child of two branches, not the child of a single commit, and that isn't a linear relationship.
So, you argue, perhaps I could get a linear history of just one branch? C14 -> C13 ... C3 -> C1, for example?
This, too, is at minimum very difficult and (more likely) impossible.
This problem is compounded when we've got multiple branches joining (3- or more-way merges). This question goes into some more detail of the reasons you can't extract history of a 'single branch' - when you're looking at the parents of a merge-commit, how do you decide which is the 'single branch' and which is the 'joining-in' branch?

Having said all that, if you examine, for example, the logs for this little repository, in graph format: (I did snip a few commits that weren't useful)

zsh% git log --graph --all --format=format:'%C(blue)%h%C(reset) - %C(green)(%cr)%C(reset)                %C(yellow)%d%C(reset)' --abbrev-commit --date=relative
* 3cf5f06 - (8 weeks ago)  (origin/master, origin/HEAD, master)
* a3a3205 - (4 months ago)
* c033bf9 - (4 months ago)  (origin/svg)
* ccee435 - (4 months ago)
*   f08bc1e - (4 months ago)
|\
| * 48c4406 - (5 months ago)
* | 203eeaa - (4 months ago)
* | 5fb0ea9 - (5 months ago)
|/
* 39bccb8 - (5 months ago)

Note that this history is in chronological order; the branches haven't been 'flattened' into one, though, so it looks a little funky. Each of these commits is contained in the current HEAD (master, origin/master). This is obvious, because both of the forks in the history have been merged together (the merge is at f08bc1e).
#3: What I need to do is map a commit to the next release that contains that commit
If you're interested in an individual commit, this question, or if your releases are tagged will help.
Reading the question, it appears you may want to map each commit to a release; that's a lot of work, and I can't help much with that - I don't think you need to check each commit, though, because branches will be merged in, and if the head of a linear branch is in the release, the linear parents will also be. Unless you've done cherry-picking, or similar.
If you sorted by time, then checked all commits older than your oldest release, recording that commit ID if it was included in the oldest, then the second oldest, etc, and removing the commit from the list when you find a release that contains it, you'll have to check at most number of releases * number of commits; at worst case, no commit is in any release. Best case, releases contain every commit older than itself, which is 300,000 checks. Still a lot, but (to my naive mind), doable.
(Apologies for the long reply).
Comment: For deep-linking you would use the nearest anchor on the page, which in this case happens to be for DATE FORMATS section itself: https://www.kernel.org/pub/software/scm/git/docs/git-commit.html#_date_formats. I use firefox extension show anchors for this exact purpose of adding deep links to my mails. You can view source and find the anchors but it can get tiring.

Git and log order


Title Patterns was printed in exactly its self

Question: Look at image:

If you look to image, you will find a [current-page:page-title] | [site:name] patterns was printed, not replaced to real site name & node title ...etc, I dont know what is wrong was happens...
Token module, Page-title module was enabled, also when i try to change
 PATTERN, its give me an error
 invalid tokens: [current-page:page-title], [site:name].  invalid tokens: [current-page:title]  invalid tokens: [site:name], [site:slogan]. (for front page)
Also, Im clear cach, and run a cron, and trancate table cashes from database manually ....
thanks a lot
Comment: Do you have token and page title modules enabled?
Comment: @Ayesh K yes mate, its was enabled ..
Comment: Hello and welcome. You reported a bug, and bugreports are not allowed here. Also, there is no actual question in your "question" at the moment. And even if you will make it a question, you should give more information: What modules related to tokens and page title was enabled? What tokens are said to be available for title field (screenshot would be nice)? And so on. We can't deal with bugreports and we can't reliably guess without data.
Comment: @Molot, thank you for info, I will do some changes now ...
Answer: I think you should use [current-page:title] instead of  [current-page:page-title]

Run cron manually and clear the performance cache. If it doesn't help then
Reload the same version of the Token module. If you use drush, command is:
drush dl token-[version]
Comment: when I try to change PATTERN, its gie me an error
 invalid tokens: [current-page:page-title], [site:name].
 invalid tokens: [current-page:title]
 invalid tokens: [site:name], [site:slogan]. (for front page)
Comment: Try my updated answer and tell if it helps
Comment: I will try it now, thank you very much .. (I will be back after finished it) ..thanks for help
Comment: Thank you mate, your answer help me really,

When I check a problem, Im not found any token was available in list .. so Im update all module with token also, and its work .. thank you very much for help .. drush token will be resolved a problem ... (Y)


Is there any modality summary statistic?

Question: Is there any kind of (simple) summary statistic that would attempt to estimate the number of modes in a given sample?
I mean, I would like to have some function $f$ that would behave as follows:
$$f(\textrm{observed unimodal data}) \approx 1$$
$$f(\textrm{observed bimodal data}) \approx 2$$
$$f(\textrm{observed N-modal data}) \approx N$$
etc.
Answer: Simple summary statistic? Not really.
Any sort of summary statistic? Yes, but I'm guessing it's a harder problem than you may expect (and that the answers given by these methods are less reliable than you want).
To help motivate the difficulty, consider the following histogram:

I believe looking at this plot, you would want your function to return 2 since there appears to be two clear modes. Note that this is the histogram built by R's hist function with default settings.
But what if we decide to make the histogram a little finer? Now consider if we want 20 bins instead of 7 on the same dataset.

Now maybe you want your function to tell you there are 4 peaks! What about 100 bins?

So many peaks! You can see that the number of modes in our histogram varies wildly with our choice of number of bins (btw: this is simulated data from four very distinct normals with 100 observations from each distribution. So the "true" answer is 4 modes. This would also be considered an easy example as the distributions are so distinct).
While you may think this is just an obvious result of how histograms work, this is a very standard situation in these problems: you have some sort of smoothing parameter (in the histogram context, this would be the number of bins) and as you differ your smoothing parameter, you get wildly different number of reported modes. In general, deciding what value of the smoothing parameter to use is non-trivial.
If you're still very interested, two topics to look into could be kernel density
estimation and Gaussian mixture modeling. But be warned that you should not expect to be able to reliably estimate the true number of modes in the population!


For what real values of $a$ does $\sum_{n=1}^{\infty}{(\frac{an}{n +1})^n}$ converge?

Question:
For what real values of $a$ does the series
$$\sum_{n=1}^{\infty}\left(\frac{an}{n
+1}\right)^n$$
converge?

At first, I wanted to do the root test, but the problem is that $a$ could be negative.  If I take it out of the fraction to get $$\left(\frac{a}{n+1}\right)^n$$ it doesn't meet the criteria of either the Dirichlet or the Abel tests.
Comment: **Hint:** you can use the root test.
Answer: If $a\ne0$ then
$$\left(\frac{an}{n+1}\right)^n=a^n \cdot \left(\frac{n}{n+1}\right)^n = a^n \cdot \left(
\frac{n+1}{n} \right)^{-n}
=a^n\left(1+\frac{1}{n}\right)^{-n}\sim e^{-1}a^n$$
so the given series is convergent if and only if $|a|<1$. The result is clear for $a=0$.
Comment: @SamiBenRomdhane : I guess  you mean $|a|<1$ when you write $|a|<0$...
Comment: can you explain the first thing you did?
Comment: I used these formula $(ab)^n=a^nb^n$ and $a^n=(\frac{1}{a})^{-n}$
Comment: any change of adding a few steps? , i cant seem to achieve that result on my own
Comment: $\sim\sim\sim +1$
Answer: Note that $\left(\frac n{n+1}\right)^n\to \frac1e$, so for $|a|\ge 1$ the summands do not even tend to $0$, whereas for $|a|<1$ you can compare with the geometric series.
Answer: Hint:
$\sum a_n$ converges only if $a_n\rightarrow 0$
For $\sum (\frac{an}{1+n})^n$ Converge we need ???
Please see that $(1+\frac{1}{n})^n\rightarrow e$
..
So, where should $a$ be sitting in?
Answer: The question asks about real values of $a$, but, in order to make this answer more general (so that other versions of this question may be linked to this question as duplicates), I will assume that $\alpha \in \mathbb{C}$.  An expedient approach to the problem is to consider various tests of convergence.  Personally, I like to start with the simple ones, and work my way up.  To my mind, the simplest test of convergence is the ratio test:

Theorem (Ratio Test):  Let $(a_n)_{n=1}^{\infty}$ be a sequence of complex numbers, define
$$L = \lim_{n\to \infty} \left| \frac{a_{n+1}}{a_n} \right|, $$
and let $S$ denote the infinite series $\sum_{n=1}^{\infty} a_n. $

If $L < 1$, then the series $S$ is absolutely convergent (and, therefore, convergent).
If $L > 1$, then the series $S$ is divergent.
If $L = 1$, then the ratio test is inconclusive—the series $S$ may be divergent, conditionally convergent, or absolutely convergent.

In the case of the series in this question, $a_n = \left( \frac{an}{n+1} \right)^n$.  Thus
$$ L
= \lim_{n\to \infty} \left| \frac{ a^{n+1}(n+1)^{n+1} / (n+2)^{n+1} }{ a^n n^n / (n+1)^n } \right|
= \lim_{n\to\infty} \left| \frac{a(n+1)^{2n+1} }{ n^n(n+2)^{n+1} } \right|. \tag{1}$$
It can actually be shown that this limit is $|a|$, but the argument is a little tedious.  If we allow ourselves the use of big-$O$ notation,
$$ \frac{(n+1)^{2n+1}}{n^n(n+2)^{n+1}}
= \frac{n^{2n+1} + O(n^{2n})}{n^n(n^{n+1} + O(n^n))}
= \frac{n^{2n+1} + O(n^{2n}) }{n^{2n+1} + O(n^{2n})}
= \frac{n^{2n+1}}{n^{2n+1} + O(n^{2n})} + \frac{O(n^{2n}) }{n^{2n+1} + O(n^{2n})}. $$
As $n$ goes to infinity, the first term goes to $1$, and the second term vanishes.  Thus
$$ L
= \lim_{n\to\infty} \left| \frac{a(n+1)^{2n+1} }{ n^n(n+2)^{n+1} } \right|
= |a|.$$
That being said, this looks like the kind of problem which is often given to students in a first year calculus course (or, perhaps, a third year complex analysis course), which means that big-$O$ notation may not feel very rigorous.  A more convincing argument might be to compute the limit via binomial expansion of the terms in the fraction, but this is going to be quite tedious, as well.  Doable, but tedious.
Personally, I probably would have looked at the limit in (1) and decided to move on.  The next test I usually choose to apply is the root test.

Theorem (Root Test): Let $(a_n)_{n=1}^{\infty}$ be a sequence of complex numbers, define
$$ L = \lim_{n\to \infty} \sqrt[n]{|a_n|^{n}}, $$
and let $S$ denote the series $\sum_{n=1}^{\infty} a_n$.

If $L < 1$, then the series $S$ is absolutely convergent (and, therefore, convergent).
If $L > 1$, then the series $S$ is divergent.
If $L = 1$, then the ratio test is inconclusive—the series $S$ may be divergent, conditionally convergent, or absolutely convergent.

With $a_n = \left( \frac{an}{n+1} \right)^n$, the limit of interest is
$$
L = \lim_{n\to\infty} \left| \left( \frac{a n}{n+1} \right)^n \right|^{1/n}
= |a| \lim_{n\to\infty} \left| \frac{n}{n+1} \right|
= |a|. $$
This is, I think, a much more straight-forward computation, but it gives us the same result as the ratio test; namely, the series of interest converges absolutely when $|a| < 1$, and diverges when $|a| > 1$.
On the other hand, when $|a| = 1$, both tests are inconclusive.  In general, there is not really a good way of checking for convergence on the boundary of the disc of convergence.  Indeed, there are examples of series which converge for some points on this boundary, and diverge for others (as a simple example, consider the harmonic series, as compared with the alternating harmonic series).  In this case, however, we can do a little better.  Observe that if $|a| = 1$, then
$$ \lim_{n\to \infty} \left|  \frac{an}{n+1} \right|^{n}
= \lim_{n\to\infty} \left[ |a|^n \left( 1 + \frac{1}{n} \right)^{-n} \right]
= \frac{1}{\mathrm{e}}.
$$
In other words, we know that when $|a| = 1$, the general term of the series fails to converge to $0$, which means that the series fails to converge (by the divergence test).  Therefore, we may conclude:

If $|a| < 1$, then the series converges absolutely.
If $|a| \ge 1$, then the series diverges.
Comment: NB:  I am posting this as a kind of canonical answer to this question, which has popped up a number of times on the site.


How can I change the style of a specific CCK field?

Question: I need to change the position to fields of content types. How can I modify the style of a specific field?
When I check the code for knowing the class, I see this:
<code><input id="edit-field-first-name-0-value" class="form-text text" type="text" value="" size="60" name="field_first_name[0][value]">
</code>
Answer: you can review the style in the source code, detecting the 'id' of the specific field.
for example add this rule (according the specific id):

#edit-field-color-value {
color:#00FF00;
}
Comment: remember that the field and his label has a DIV around they, so you can add a CSS, according the ID of this DIV, to control the field and the label.


How does someone achieve a desired confidence / accuracy when measuring using uncalibrated instrument?

Question: I have an instrument that measures a value.
It is only possible to measure the value once i.e. the experiment can't be repeated (think recording a car's speed as it drives past).
The instrument is not calibrated.
I have access to n different instruments, each with their own unknown calibration. I might have 4 or 5.
I expect that each instrument will record the value to within 3% of the actual value. But I do not know this for certain, this is just a guess.
How do I work out how many n instruments I need to achieve a desired confidence / accuracy? Is it possible to construct a confidence interval taking into account this unknown? How can the accuracy or inaccuracy from this calibration be represented?
Comment: So, are you saying that you expect each measure to have a variance on the order of 3%, but you don't know how biased each measurement is? That an instrument may be miscalibrated, adding say 10 mph to the velocity, but it will usually be within 3% of the actual speed + 10 mph?
Comment: @dherrera I'm afraid my terminology may be incorrect. I expect that each instrument should produce a result +/- 3% of the actual value, _even though I don't know if that is actually the case / if it is misscalibrated or not_ e.g. a reading of an actual speed of 20mph would be in the range 19.4-20.6mph. Does that make sense? How do I workout how many instruments I would need to make the measurement to achieve a desired confidence overall? Especially if the variance were raised e.g. to 10%
Answer: Say that you have a speed of 20 mph. You will have variability in the measurements of your different devices, and from what you say, you expect each device to be within 3% of the actual value. Let's say then that 3% is the standard deviation of the variability between the different instruments, so the standard deviation between devices is 0.6 mph for your 20 mph real speed. Let's call that standard deviation $\sigma_{device}$.
To solve the problem we next need to make two assumptions:

The 'error' of the devices is independent and identically distributed. Regarding independence, this means that we don't expect that on a given measure all devices overestimate or all devices overshoot (or undershoot) at the same time. Regarding identically distributed, this means that we don't expect some devices to be highly flawed and some highly accurate, but rather they all have similar degrees of precision, at least in principle.
The errors of the devices are spread around the actual value of speed. That is, it's not the case that all devices always overestimate the speed, but rather some overestimate and some underestimate, by on average the same amount.

These are some typical assumptions.
Then, if on average the devices are correct, even if the individual devices aren't, we can add more devices to get a better estimation of what the true speed is, because their errors will average out more as we add more devices.
How variable is the average between the devices, given how variable is each device and how many devices we are averaging? That's just given by the standard deviation of the mean, which is discussed here. That is the variability that the average will have, and it is given by:
$$\sigma_{average} = \frac{\sigma_{device}}{\sqrt{N}}$$
where $N$ is the number of devices that you have. So, say that you have 5 devices with a $\sigma_{device} = 0.6$ as described above, then the formula says that the average will have a standard deviation of $\sigma_{average} = 0.268 mph$. In the assumptions above we assumed that the average is centered around the true mean (20 mph), and $\pm 1.96\sigma_{average}$ is the region that will contain 95% of the average estimates, so 95% of your device averages will be within 19.474 and 20.526.
To get to the number of devices needed, you just need to:

Pick a reference speed
Obtain the corresponding $\sigma_{device}$ that you guess
Pick a $\sigma_{average}$ that is acceptable for your purposes
Solve for $N$

Your specification of the problem is not clear though, so it's not certain whether this specification will match your actual real problem, but it seems like a standard approach to what you describe. And needless to say, the performance of the method will depend on how good your guess of the % of variance of the devices is, whether they are on average correct, etc. Also, we assumed that 3% is the standard deviation of the devices errors, but maybe this would mean that a given measurement would be within 3% of the true mean only ~62% of the time, which is maybe not what you meant by "I expect that each instrument will record the value to within 3% of the actual value." Statistics is not magic, and if you start from wrong assumptions, you will end up with wrong conclusions.
If this answers your question, please consider marking as the accepted answer.
Comment: I didn't explicitly say that they are identically distributed, since OP doesn't seem super well versed in statistics and I wasn't sure how to put that in intuitive terms, like I did for independence. But I think I should just add that there, will edit the question.
Comment: @Chuck sure. The thing is that when you say "I expect that each instrument will record the value to within 3% of the actual value.", that's a very vague statement, so I had to interpret what you meant in statistical terms in order to propose an answer. I chose to interpret it as 3% being the standard deviation of the measurements, which would mean that, for a normal distribution, 62% of the measurements would fall within 3% of the real value. If you meant "95% of the measures fall within 3%", then you'd want the standard deviation to be (3/2)%, and you'd work from there.
Comment: Good answer, but I would think that your assumption 1) is exactly that the measurements are independent and identically distributed. Isn't that so or do we have different models in mind?
Comment: Thank you kindly for your answer. Can you explain a bit more about this statement? `Also, we assumed that 3% is the standard deviation of the devices errors, but maybe this would mean that a given measurement would be within 3% of the true mean only ~62% of the time`? How is that different to your prior explanation of variance?
Comment: Please remember to mark as the accepted answer if it ends up being the one that answers your question.
Comment: I thoroughly appreciate the effort you have gone to answer the question. Thank you for explaining it. Let's just say this has been a learning experience for me.
Comment: @dherrera hey dude. I realise this isn't quite the answer to the question I was asking. Your answer is for measuring a known speed. But I don't know the speed that is being measured in advance. It could be anything between 20-50mph (as an example). 5 separate readings e.g. 35,38,37,37,36. Each with the 3%. Can you advise how this changes your answer? Would it be to take the mean? Then take sigma device as sigma mean? But presumably sigma device would be different for each device as they each measure a different value?
Comment: To get a statistical answer to a question, you need to formulate the question in the language of statistics. Your original question is vague and requires filling in the blanks, so I don't think it's possible to answer exactly the question you have in your mind if you don't narrow it down or give more precise language. Also, you don't seem aware that there's always subtelties to these problems, such as your question of "presumably sigma device would be different for each device as they each measure a different value?", which is a very important question indeed that I can't know the answer to
Comment: Evidently, there's things of your problem that you don't know, and so we have to approximate or assume them. We assume that the possible error of each device comes from the same underlying distribution (i.e. same variability), given a real speed. This is not an easy concept to wrap your head around if you're not used to statistics, but some approximation like this is necessary to approach the problem without more info. You seem to suggest that variability increases with real speed, because it's a percentage of real speed (i.e. 3%)
Comment: If what you want is the average to be withing a given % of the real speed, then the procedure in the question works fine. You just use the % as the $\sigma_{device}$ and the desired % as $\sigma_{mean}$ and use that formula. If you want an absolute value (i.e. errors should be smaller than 1 mph 99% of the times), you'll need to make a bunch of other assumptions and the problem becomes quite complicated. You can alternatively choose a reference real speed that is significant and just compute the N for that.


SSL certificates with multiple wildcards

Question: I need to create a range of hostnames for clients of the format (live|test).(clientname).clients.example.org (e.g. live.xyzltd.clients.example.org) which each have their own separate VirtualHost container and run over HTTPS on Apache. Due to the number of sites and the scarcity of addresses, I can't assign one IPv4 per host, nor can I use Server Name Indication (support in current libraries is almost non-existant), and the number of changes to the hostnames means Subject Alternative Name is also out.
Ideally I'd just have a certificate for *.clients.example.org, as that would in theory cover everything, but isn't permitted by RFC 2818. However, since I know that the hostnames will always be of the form * . * .clients.example.org, is it possible to create a certificate which contains multiple wildcards to achieve this? I'll be using a self-signed certificate, so it doesn't matter if this isn't something which is offered on a commercial basis, so long as it's technically possible.
Answer: You can't create certificates with multiple wildcards, it breaks the way certificates are checked.
What you can do however is do *.clients.example.org since even if not permitted by RFC 2818 it's the way it'll actually work with most SSL clients.
Comment: *.clients.example.org won't work with most clients - Firefox and IE for starters.
Comment: Well, then I must be wrong, I have a certificate like that working perfectly for those browsers :/
Comment: Depends on the browser version - FF used to support it and then changed (somewhere in the 3.5.x branch I think).
Comment: It's working for me with Firefox 3.6.8, just double checked right now, but I have to agree with you that using wildcard certificates is a bit of a pain, the browser implementation is poor and gets you diverse results.
Answer: You can't have multiple wildcard characters in the common name, but you can have multiple wildcard Subject Alternative Names. For example, you could add the following SANs:
*.xyzltd.clients.example.org
*.abcltd.clients.example.org
*.defltd.clients.example.org
However, if you only have two subdomains per client, this only cuts the number of names in half. You could change the naming scheme to be testxyzltd.clients.example.org so they would all be covered by one certificate for *.clients.example.org.
Comment: The problem with Subject Alternative Names is not the number of entries, but the number of changes - each time I add/remove a client I'd have to change the certificate. I think I'll probably end up going with xyzltd-test.clients.example.org, which is not as pretty and destroys the hierarchy but should work.


File upload disappears in Web File Manager

Question: I am trying to upload files to our Web File Manager (in Drupal 6.31), and while everything seems to work fine the file does not appear in the directory list afterward. It does not exist on the server either.
I checked the permissions on the default WebFM folder, and it is 775. I am logged in as the first (super admin) user. I am not receiving any error messages. There are no available updates for Drupal Core or WebFM.
What could be going wrong?
Thanks in advance!
Comment: Were you using chrome while uploading files on WF Manager?
Answer: This is a critical bug of Web File Manager module that sates "files are being deleted while browsing WebFM with Chrome" (Considering that you have been using chrome to upload files your Web File Maanger)
For more reference please refer to this.


Diferenças na chamada de métodos

Question: Por que alguns métodos podem ser chamados consecutivamente, exemplo:
string a = "";
a.Replace("a", "b").Replace("b","c");// o replace foi chamado 2x

E outros não podem ser chamados do mesmo jeito?
ClasseA A = new ClasseA();
string a = A.Metodo();

Porque isso acontece e qual a diferença dos 2?
Answer: Neste caso específico a diferença é que o Replace() é um método normal e o ClasseA() é um construtor que retorna um objeto que ele acabou de construir, mas pode chamar ele em cadeia, então a pergunta parte de premissa errada:
public class Program {
    public static void Main() {
        new ClasseA().Metodo();
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Obviamente que este exemplo o objeto não será guardado em variável alguma e no fima deste statement ele será perdido e fica disponível para coleta a qualquer momento. Se for colocar uma variável para guardar um objeto este será o que for devolvido por Metodo() e não o construtor, ou seja, é o último método executado que produzirá algum valor (no exemplo que eu escrevi Metodo() retorna void então não pode ser guardado).
Se deseja que o objeto seja guardado em variável tem que fazer como está na pergunta, mas só porque é o seu objeto, não é que não pode ser assim, você tem a escolha. No seu exemplo o último método da primeira linha é o construtor então a variável receberá o objeto construído, e a seguinte linha aplica um método em cima do objeto referenciado pela variável que recebeu o objeto logo antes.
variavel = new ClasseA().Metodo();

funciona, mas o que será guardado na variável é o valor devolvido pelo método, você pode até fazer que seja o objeto, se for seu desejo, um exemplo artificial seria assim:
using static System.Console;

public class Program {
    public static void Main() {
        var variavel = new ClasseA().Metodo();
        WriteLine(variavel);
    }
}

public class ClasseA {
    public ClasseA Metodo() => this;
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Esta técnica chama-se method chaining e costuma ser usada para criar o que se chama fluent interface. O Replace() da pergunta não usa esta técnica, ele retorna um objeto que ele precisa, não foi retornado o this, muito menos de propósito para poder encadear artificialmente, acredito que isto foi explicado no começo da resposta. Estou colocando esse parágrafo porque as outras respostas adotam isso e não é o que a pergunta está mostrando.
Para entender melhor o que corre no primeiro caso é o seguinte:
string a = "";
var tmp = a.Replace("a", "b")
tmp.Replace("b","c");

Só que esta variável tmp não existe no código porque ela não é necessária. Ao contrário do que muita gente achar variáveis só precisam existir se um valor precisa ser armazenado, nem todos valores precisam, eles podem ser usados de forma direta.
Um exemplo que pode mostrar melhor que esse encadeamento é circunstancial:
Math.Pow(2, 3).ToString()

Aqui ele usa um número para gerar outro número que será a potência e esse número será usado como string. Encadeamento de objetos completamente diferentes.
Qualquer método que retorne um valor pode chamar outro método logo em seguida desde que seja um método que aquele objeto tenha disponível, e todos os objetos possuem métodos já que todos derivam de Object e este possui métodos. Um método que retorne void não pode ser encadeado.
O método é aplicado em cima de um objeto, não importante como ele é obtido, pode ser por uma variável, o mais comum, uma propriedade que se confundo como se fosse uma variável, pode ser um método que retorna um objeto ou pode ser um literal. Percebo que as pessoas se confundem com isso. Exemplo do literais:
10.GetHashCode()
"teste".Replace("s", "x")
new []{1, 2, 3}.IndexOf(2)
(1, 2).ToString()
1..3.ToString()
new StringBuilder("abc").Append("xxx")

O primeiro exemplo é bastante ineficiente, mas o Replace() retorna um objeto novo que ele acabou de criar (isso é importante, por isso é ineficiente), então ele pode ser usado para passar para outro método que seja do mesmo tipo. Note que tem um erro nesse código porque apesar de ter criado dois novos objetos string com modificações, nenhum deles é armazenado em algum lugar e portanto serão perdidos. E se colocar em uma variável é só o resultado do segundo que será armazenado, provavelmente é o que desejam mas criou um objeto sem necessidade e sem perceber, porque provavelmente não sabe que strings são imutáveis em C#.
Reforçando: a pergunta tem a premissa errada que o segundo casos não pide ser feito encadeado se quiser, e o primeiro caso é um encadeamento simples circunstancial e não o design pattern chamado method chaining.
Comment: Achei válidos os argumentos, mas apenas na 2ª parte da pergunta, no que diz respeito as diferenças entre os 2. Agora, entre a primeira parte, o Porque, não entendi. Fiz uma modificação que acho que vai ilustrar melhor.
Comment: Mudar a pergunta depois que ela foi feita e respondida é algo complicado, mas na verdade eu nem sei o que essa mudança significa, ou até pode significar que queria saber outra coisa. Ou talvez não mude nada importante e minha resposta continua sendo a mesma, talvez tenha só invalidado parte do texto. Se tem alguma dúvida ainda, favor demonstrar isso, mas parece que seria algo que não estava na pergunta.
Comment: Eu ia até editar a resposta pra falar sobre a edição, mas nem dá, invalidou a própria pergunta porque agora o segundo caso quer fazer algo completamente diferente, o que era premissa errada se transformou em algo sem sentido, se quer fazer isso que está na pergunta então foi sua escolha não uma determinação da linguagem, você escreveu um código que não chama consecutivo porque era o que queria.
Answer: Isso acontece porque o método publico Replace(), que é definido na classe string, retorna um instância de objeto que, por acaso, é do mesmo tipo de a - neste caso, string.
As chamadas em cadeia resultam do fato de você poder invocar o mesmo método de instâncias - possivelmente diferentes, mas não necessariamente - da mesma classe imediatamente após o retorno do método.
Se isso não fosse possível você teria que armazenar o valor retornado, e invocar o método pela nova referência:
string a = "";
string b = a.Replace("a", "b");
b.Replace("b","c");

Se você identificar os passos individuais da sequência de eventos do seu exemplo, você notará o seguinte:

O método string.Replace() é invocado para a instância a;
O valor retornado é também uma instância de string.
O método string.Replace() é invocado agora para o valor retornado no passo anterior;
O valor retornado é uma string.

Uma outra maneira de visualizar este processo:
public class Program {
    public static void Main() {
        new A()
            .Mesmo().Mesmo().Mesmo().Mesmo();

        System.Console.WriteLine();

        new A()
            .Novo().Novo().Novo().Novo();

        System.Console.WriteLine();

        new A() // Cadeia com chamadas mistas
            .Mesmo().Mesmo().Novo().Mesmo().Mesmo().Novo().Mesmo().Mesmo();
    }
}

public class A { // Declaração de classe

    private int counter = 0; //Contador interno da instância

    public A Mesmo() { // O método Mesmo retorna uma instância de A...
        counter++;
        System.Console.Write($"{counter} ");
        return this; // Neste caso, a mesma instância.
    }

    public A Novo() { // O método Novo retorna uma instância de A...
        counter++;
        System.Console.Write($"{counter} ");
        return new A(); // Neste caso, uma nova instância.
    }
}

No exemplo acima você pode perceber que tanto o método A.Mesmo() quanto A.Novo() retornam instâncias de A, permitindo assim chamadas encadeadas - porém A.Novo() gera novas instâncias enquanto que A.Mesmo() retorna a si mesmo (return this;).
O resultado compilado do exemplo acima é o seguinte:
1 2 3 4
1 1 1 1
1 2 3 1 2 3 1 2

.Net Fiddle
Comment: @Marceloawq quase isso - se dá pela *assinatura* do método chamado (mais especificamente, o tipo retornado pelo método). No momento do retorno você pode utilizar qualquer método disponível para o tipo retornado.
Comment: Então a capacidade de fazer o encadeamento dos métodos se dá pelo(s) construtor(es)?
Answer: Esses métodos que aplicam uma ação ao próprio objeto e retornam o próprio objeto modificado seguem o padrão de projeto chamado Builder.
Exemplo:
// Podemos ter uma classe Pizza definida da seguinte forma:
public class Pizza {
    private TamanhoPizza tamanho;
    private bool comQueijo;
    private bool comOregano;
    private bool comManjericao;

    public Pizza(TamanhoPizza tamanho) {
        this.tamanho = tamanho;
        this.comQueijo = false;
        this.comOregano = false;
        this.comManjericao = false;
    }

    public Pizza ComQueijo() {
        this.comQueijo = true;
        return this;
    }

    public Pizza ComOregano() {
        this.comOregano = true;
        return this;
    }

    public Pizza ComManjericao() {
        this.comManjericao = true;
        return this;
    }

    public void Comer() {
        Console.WriteLine($"Nhami nhami! Que pizza tamanho ${tamanho} ${comQueijo? "e com queijo" : string.Empty} deliciosa!");
        if (comOregano) {
            Console.WriteLine("E ainda com orégano!");
        }
        if (comManjericao) {
            Console.WriteLine("E ainda com manjericão! Hmmm :)");
        }
    }
}

public enum TamanhoPizza {
    Brotinho,
    Media,
    Grande,
    Big,
    Monster
}

Para usar a classe Pizza, poderíamos fazer o seguinte:
public class Program {
    public static void Main(string[] args) {
        Pizza pizza =
            new Pizza(TamanhoPizza.Grande)
                .ComQueijo()
                .ComManjericao();
        ComerPizza(pizza);
    }

    private static void ComerPizza(Pizza pizza) {
        pizza.Comer();
    }
}

Baseado no blog de Luís Ricardo.
Isto é feito para enriquecer a construção do objeto e evita um construtor com muitos parâmetros que, sem a devida documentação, poderia deixar o código mais difícil de ler.

Diferenças na chamada de métodos


How do I pass parameters to an angular service or factory?

Question: This plunker shows it best: http://plnkr.co/edit/y3uacaQSc1MbrWKfb0At?p=preview
but here is the code:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,testFactory) {
  $scope.name = 'World';
  var test_var = "iceland";
  $scope.testFunction = testFactory.testFunction;

});

app.service('testFactory',function(){

  this.testFunction = function(){
    alert(test_var);
  };

})

and in the html:

Hello {{name}}!

right now, as you can see in the plunkr, test_var is undefined this makes sense because its not defined... So I want to pass it from the controller, but if I do something like
$scope.testFunction = testFactory.testFunction(test_var);, then the testFunction executes along with the alert because of the parentheses. But I just want to pass test_var, not execute the function. How can I pass it in?
Answer: Wrap the call in a function so that the call to testFactory.testFunction(test_var) is only invoked when $scope.testFunction() is...
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,testFactory) {
  $scope.name = 'World';
  var test_var = "iceland";
  $scope.testFunction = function() {
    testFactory.testFunction(test_var);
  };
});

app.service('testFactory',function(){

  this.testFunction = function(test_var){
    alert(test_var);
  };

})


Can RUBIK's cube be solved using group theory?

Question: Can RUBIK's cube be solved using group theory? If yes, how can we use it to solve a $2\times2$ Rubiks Cube?
Comment: David Joyner has written a whole book [Adventures in Group Theory: Rubik's Cube, Merlin's Machine & Other Mathematical Toys](http://www.amazon.com/Adventures-Group-Theory-Merlins-Mathematical/dp/0801890136) on the $3 \times 3 \times 3$ Rubik's Cube. In the book, he constructed the (legal) Rubik's group and there is a chapter about solution strategies. If there is an answer for your first question, it is the best place to look for it.
Comment: I soooo greatly doubt it...assuming the solved cube is the group's unit, upon being given the cube in some setting you'd have to recognize what element of the group it represents, and then "bring it back" to the unit element. It looks as hard to do it so as to solve it by purely hand skills.
Comment: @donantonio I know of people who use group theory to solve it. They don't necessarily recognize what the initial jumbled state is, which would be insane given the number of states. However, They know of certain standard moves that allow them to transform the cube into something 'easier', or of an algorithm of moves to move particular tiles.
Comment: @CalvinLin, I seriously doubt they **all** use group theory for that. I know I guy over here that can solve the cube from any given position in 2 minutes approx. (or so he claims...), and for the cases I've seen he certainly has solved it after "messing" seriously the cube. This guy doesn't even have a high school diploma, let alone he's the slightest idea what group theory is. He only claims he has to "look at the given position" and then there are either five or six pre-determined sets of moves to bring it to a simpler form and then solve it...
Comment: See math.stackexchange.com/a/1096593/21820 where I've written up a general and practical solution that applies not only to Rubik's cubes.
Comment: @DonAntonio: It is certainly possible to solve a finite problem like Rubik's Cube by giving a finite recipe which hides any of the mathematical steps used to analyze the problem. It is even possible to derive such a recipe by brute force, knowing nothing about group theory. Nonetheless, as the links provided by achilee hui show, there is some interesting group theory underlying Rubik's cube: a generating set for the group; descriptions of various subgroups and their cosets; etc. A person educated in group theory can learn to solve the cube using that structure...
Comment: … Even more significant, the same structure can be used to study more complicated problems, such as the $4 \times 4 \times 4$ Rubik's cube. As the size of the problem grows, the difficulty of deriving a solution recipe while knowing nothing about group theory becomes insurmountable, but the mathematical method for deriving the solution may work just as well, and may even be generalizable to infinitely many similar problems.
Comment: I know that, @Lee. I was talking of someone *actually* using group theory to *actually* solve the cube. I once met, but did **not** read, a boor or a paper (can't remember right now) about the group theoretical structure of the cube, and even it contained (or perhaps other paper did) strategies to do so...but that seems more like theoretical work, not *actual* solving strategy.
Comment: BTW, I do have the book by Joyner...:)
Answer: The difficult part of answering this question is to decide what it means to "use" group theory to solve the cube.
Clearly it is possible to learn to solve the cube without knowing any group theory, just by memorizing a procedure for doing so. And one can go a long way beyond rote memoization just by geometric/spatial intuition, again without any open appeal to group theory.
On the other hand, many people who solve cubes and do know group theory tend to think in group-theoretic terms while solving, or at least while refining their solving methods. Many well-known combinations can be analyzed as commutators or conjugations of elements in the cube group, which makes it easier to remember them and easier to understand why they work.
When it comes to being sure that one's solution method always works, I don't think there's any reasonable way around some group theory. For example, if you go look up a cookbook method for solving the cube, it doesn't tell you what to do if you end up in a state where the cube is solved except that two corner pieces need to be swapped. At best the cookbook method will assert that this situation cannot occur using legal moves -- but in order to convince yourself that this is true (except by the combined experience of a lot of experiments) you need some kind of proof. And this proof will either be based on the theory of permutation groups, or will effectively reinvent a part of this theory with different words.

I solve 2×2×2 cubes by imagining they are 3×3×3 and doing only those parts of my usual methods that take care of the corner pieces. Doubtlessly there are more efficient ways to go about it.
Answer: I cannot allow this question to go by without mentioning: Morwen Thistlewaite.  This is a British mathematician who used group theory to find the smallest known bounds on how many face twists it takes to reach the solved state from an arbitrary state, along with some knowledge of which twists to take (a.k.a 'God's Algorithm').  Instead of positioning individual cubies in sequence, his is a more holistic approach called 'descent through nested sub-groups'.  It works something like this:
A) Begin with the whole Cube group: G.
B) Pick a set of face twists generating a proper sub-group: H [example: the sub-group generated by twisting faces L, R, F, B, but NOT U, D].  For best results pick H such that |G|/|H| is as small as possible.
C) For each coset of H, find the shortest sequence of twists which will transform any member of the coset to a member of the sub-group [each coset is of the form aH; if b is in aH, then bH=aH; find the element b in aH generated by the fewest twists, and take the twist sequence for the inverse of b].
D) If H=E (i.e H is the trivial sub-group), stop.  Otherwise replace G with H and return to (B).
To solve a scrambled Cube with this approach, one must determine which coset of the top-most sub-group contains the Cube's starting state, and make the sequence of face-twists calculated in (C) for that coset; this will change the cube to a scrambled state within the top-most sub-group.  Repeat for each successive nested sub-group until you reach E; at that point the Cube has been unscrambled.
With this approach Thistlewaite was able initially to show that unscrambling any scrambled state takes no more than 26 (?) twists [source: 'Metamagical Themas' by Hofstadter, in Scientific American (I forget which exact issue)].  Since then he has been able to reduce this number enough to determine the theoretical maximum number of twists required.
Comment: Complementing the answer, check this paper about several solution search algorithms incluiding Thistlewaite, that use group theory

http://www.diva-portal.org/smash/get/diva2:816583/FULLTEXT01.pdf
Answer: [This is just about how commutators and conjugates help with rote memorization. I am yet to understand how the moves were designed]
Ref: https://momath.org/wp-content/uploads/2019/03/How-to-Solve-the-Rubiks-Cube_-All-6-Sides.pdf
For group ${ G }$ and ${ a,b \in G }$ we have commutators ${ [a,b] = aba^{-1}b^{-1} }$ and conjugates ${ a b a ^{-1} }.$
In the context of above document:

In short the main steps are:

White corners: Repeat ${ [R ^{-1}, D ^{-1}] }$
Middle layer: ${ [U, R] [U ^{-1}, F ^{-1}] }$ and ${ [U ^{-1}, L ^{-1}][U, F] }$
Yellow edge pieces: ${ F [R, U] F ^{-1} }$ till yellow cross, then ${ (RU) [R ^{-1}, U] (RU) ^{-1} }$ till yellow edges align
Yellow corner permutation: Repeat ${ [U R U ^{-1}, L ^{-1}] }$
Yellow corner twisting: Effectively like white corners

Edit: Page 4 of Daniel Bump's notes here explains the importance of commutators, and how for example ${ [U R U ^{-1}, L ^{-1}] }$ moves very few pieces in the cube. (Intuitively, because the supports of ${ U R U ^{-1} }$ and ${ L ^{-1} }$ overlap very little). The full course page is here.
Comment: The commutator of two sequences with supports intersecting in a single piece produces a 3-cycle as well as the twists, which makes it easy to solve the cube gradually. That's how I explain it on [my page](https://users.utu.fi/lahtonen/RubikAnim.html). Unfortunately that's in Finnish, but the diagrams+animations may still tell the story :-)
Comment: Thanks for the link! :)


How to substitute regex in AWK?

Question: What is the easiest way to substitute regular expression by AWK script?
My goal is to search pattern:
/a|b/

in sentence:
I read a book "GAWK: Effective AWK Programming", but I can not figure it out.

and substitute it with:
ABC/a|b/ABC

So result will be:
I reABCaABCd ABCaABC ABCbABCook "GAWK: Effective AWK ProgrABCaABCmming", but I cABCaABCn not figure it out.

Comment: Is there any other reason for using `awk`? There is `sed` for this sort of things.
Comment: I formatted your question for you (see how I indented the text 4 spaces). [edit] your question to explain what `ABC/a|b/ABC` means to you and show what you have tried so far.
Answer: You could try with:
$ awk '{ gsub(/[ab]/,"ABC&ABC")}1' file
I reABCaABCd ABCaABC ABCbABCook "GAWK: Effective AWK ProgrABCaABCmming", ABCbABCut I cABCaABCn not figure it out.

where file is:
I read a book "GAWK: Effective AWK Programming", but I can not figure it out.

Comment: you don't need pipe in the charset.  Also will not filter out any lines where the replacement doesn't happen (including empty lines)
Answer: sed might be better for this task
echo "I re..." | sed 's/[ab]/ABC&ABC/g'

How to substitute regex in AWK?


Why does $\operatorname{Spec}(\prod_1^\infty \Bbb F_2)$ have connected components that are not open?

Question: To be honest, I don't even know how to describe all prime ideals in $\prod_1^\infty \Bbb F_2$. I know we get one for each $n \in \Bbb N$ corresponding to the set of elements that are zero in the $n$-th coordinate, and at least an extra one corresponding to the ultrafilter $F := \{x|x_i\ne 0 \,\text{for at most finitely many }i\}$.
Answer: What you write down is a filter, not an ultrafilter.
The ideals in a product of fields correspond to the filters on the index set. If $\mathcal{F}$ is a filter, the corresponding ideal is $\{a : \{i : a_i = 0 \} \in \mathcal{F}\}$. It follows that the prime ideals (which equal the maximal ideals in that case) correspond to the ultrafilters. The spectrum identifies with the Stone-Čech compactification of the index set.
So your question is really a topological one: Why does $\beta \mathbb{N}$ have a connected component which is not open? Well, it is totally disconnected and not discrete. So take any $p \in \beta \mathbb{N} \setminus \mathbb{N}$, then $\{p\}$ is a connected component which is not open.
Comment: Dear Martin, take any subset of the index set. It either contains finitely many elements (in which case it is in my filter), or its complement contains finitely many elements (in which case the complement is in the filter). Hence my filter cannot be enlarged and is thus an ultrafilter. Where did I reason wrongly?
Comment: Your filter consists of those cofinite sets. The set of prime numbers is not finite and not cofinite.


Show all nested menu links in Drupal 7

Question: How do I display all nested links in

 format in Drupal 7? The default code only displays the 1st level links even though they are arranged in the Drupal admin menu as nested:
<?php if ($main_menu): ?>

 <?php print theme( 'links__system_main_menu', array('links' => $main_menu) ); ?>

<?php endif; ?>

Only the 1st level is displayed in the ff. menu setup:
-Fruits
---Apples
---Oranges
---Lemons
-Cars
---Big car
---Small car
---Fucked up car
-Whatever

Comment: Also there is a menu_block module which allows creating arbitrary amount of customized blocks showing needed portions of menu
Answer: The default $main_menu variable in page.tpl.php is set to menu_main_menu(), which is a contextual view of the main menu tree.
To get your desired output, you need to get the entire menu tree using menu_tree_all_data() and menu_tree_output().
To do this in your theme, create template.php if you haven't already, and add a new preprocess function for the page template:
function THEMENAME_preprocess_page(&$variables) {
  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);
}

Then, in page.tpl.php, you can just use:
<?php print render($main_menu_expanded); ?>

to get a expanded, nested unordered list of the main menu.
For a little more flexibility, you might want to consider the Menu Block module, which will let you create blocks of expanded menus out of the box with its Expand all children of this tree option as well as a host of other options for segmenting menu trees.

Show all nested menu links in Drupal 7


Continuity of a function that is continuous separately

Question: Is the function $f:\mathbb{R^2} \rightarrow \mathbb{R} $ defined as:
$f(x, y) = \frac{xy}{\sqrt{x^2+y^2}} $ if $(x,y) \neq (0,0)$
$f(x,y)=0 $ if $(x, y) = (0,0)$
Continuous in $(0,0)$?
I know that in respect of x and y separately f is continuous.
I was trying to find a curve that will prove that f is discontinuous but all curves that I try doesn't show f discontinuous.
Answer: Hint: Let $x = r\cos \theta$ and $y = r\sin \theta$ then $$f(x,y) = \frac{r^2 \sin \theta \cos \theta}{r} = \frac{1}{2}r\sin 2\theta$$
Alternatively: use $x^2 + y^2 \geqslant 2|xy|$ to get $|f(x,y)| \leqslant \frac{1}{2}\sqrt{x^2 +y^2} \to 0$ as $(x,y) \to (0,0)$.
Comment: I was thinking that $f$ must pass through 0, thanks for the answer


Cumulative counts or counts for Poisson regression

Question: I have a set of data with measurements X1 and X2 across multiple time points, T1, T2 and T3. I would like to conduct a Poisson regression using X1 and X2 on the counts of a phenomenon. An example of how my dataset would like is as follows (pardon my inelegant code):
library(lme4)
set.seed(888)
df <- data.frame(SubID = sort(rep(1:10, 3)), Time = rep(1:3, 10), Count = sample(0:9, 30, replace = TRUE))
df <- data.frame(df, Cumulative.count = unlist(lapply(1:10, function(n) cumsum(df[cbind(c((1:10*3)-2), c(1:10*3))[n,1]:cbind(c((1:10*3)-2), c(1:10*3))[n,2],"Count"]))), x1 = rnorm(30), x2 = rnorm(30), x3 = rnorm(30))

As can be seen, I have 2 "counts" variable. One is cumulative, one is not. My question is should I be doing:
model.count <- glmer(Count ~ x1 + x2 + x3 + (Time|SubID), family = poisson(link = "log"), data = df)

OR:
model.cumulative.count <- glmer(Cumulative.count ~ x1 + x2 + x3 + (Time|SubID), family = poisson(link = "log"), data = df)

Comment: I was of the understanding that in glmm, the points within a grouping variable (in this case would be subjects) would be expected to have a dependent relationship? I might have a misunderstanding of glmm.
Comment: If you have the cumulative counts your points won't be independent. If you do that in a single glm it will violate the assumption of independence.
Comment: Wow. I missed the extra `m` there, reading it as `glm` somehow. Yes, if the form of the resulting dependence is correctly modelled, it shouldn't matter.
Comment: ok would you want to put that as an answer?
Comment: No, I don't think so. I don't feel myself expert enough on glmm's to justify the circumstances relating to the 'if' part of my comment without a fair bit more work on my part. Better to leave it for someone better able to justify it.
Answer: The approach generally taken is to regress the counts on features that were present during the intervals during which the counts accumulated. The length of the interval is used as an offset after applying log() to the values to match the default link for a Poisson model. The data situation described does not justify anything very fancy. A glm model would suffice. The first offset would be log(T1) ,,, assuming T0 was 0 ... and the second offset would be log(T2-T1).
Edit: with the better description/illustration of your data, I would say definitely to go with the first of your alternatives. You are not interested in the cumulative value per period but the incremental value per period. See comment below.
Comment: Thanks for the answer! Point of clarification, do you mean that I just compute the difference in scores for both Y and X?
Comment: That doesn't sound right. I was thinking that you would be computing successive differences in T values to get durations. The logging them as offset values. Then regressing using a log-link and Poisson errors those counts (Y's) on any predictors (X's) that were measured during those intervals.
Comment: thanks for the clarification. I am not sure if I understood you correctly. Given that my T values are consistent across all subjects (i.e. they are all measured at the same fixed time), do I still need to use the offsets? To make things clearer, I have added a reproducible example. Thanks much for your advice.
Comment: The Y would be `Count` (which is same as `diff(c(0, Cumulative.count))` ). The x's are your predictors and this would be in a repeated measures model that appropriately groups data by `SubID` and `Time`. Since your "Time" variable is not really time but instead appears to be a "period marker" I would not `log()` it. You should be able to consider construct contrasts that there is a) no variation over time, b) that there is a rising trend over time, or c) that there is a rise or dip in the middle (quadratic contrast).


Smart_IP homepage redirect

Question: I have a multilingual site. I am browsing from Holland and with the Smart_IP module i am redirecting to the correct language:
http://landberg.at/nl/ or http://landberg.at/de/
My default language is English. But now as user from Holland for example (dutch browser), you are NOT able to switch to the English homepage. This is because the homepage URL in English is http://landberg.at/ >> Then you are automatically redirect to http://landberg.at/nl/
Is there a solution for this?
Answer: I don't know the Smart_IP module's mechanism, but I think you should simply solve your problem outside of Drupal: adding an Apache redirection like Redirect "landberg.at" "landberg.at/en". Somewhat brutal but should work...
Answer: Try to use IP to Locale module. I think this module definitely solve your issue.

IP to Locale provides IP lookup and redirection services for Drupal
  sites.

Smart_IP homepage redirect


Salvar dados de atributo data em um input hidden

Question: Tenho um formulário e gostaria de pegar os valores do atributos 'data-aliquota' e colocar dentro de um input invisível. Não sei como posso fazê-lo.

<form>
  <input type="text" id="cidade" data-aliquota="1.00" name="cidade" value="salvador" />
  <input type="text" id="estado" data-aliquota="2.00" name="estado" value="bahia" />
  <input type="hidden" name="valores" id="valores" />
</form>

A saída deveria ser algo do tipo: "1.00,2.00"
Comment: use attr do jQuery http://api.jquery.com/attr/
Answer: Você pode usar a função data para pegar os valores de aliquota. No exemplo eu armazenei todas as aliquotas em um array e inseri esse array ao input hidden

window.onload = function(){
    var aliquotas = [];
    $("input").each(function(){
        if($(this).data("aliquota") >= 0){
            aliquotas.push($(this).data("aliquota"));
        }
    });

    $("#valores").val(aliquotas);

    console.log($("#valores").val());
}

<form>
  <input type="text" id="cidade" data-aliquota="1.00" name="cidade" value="salvador" />
  <input type="text" id="estado" data-aliquota="2.00" name="estado" value="bahia" />
  <input type="hidden" name="valores" id="valores" />
</form>
Comment: Funcionou perfeitamente, @JrD. Obrigado.


Pytorch Categorical Cross Entropy loss function behaviour

Question: I have question regarding the computation made by the Categorical Cross Entropy Loss from Pytorch.
I have made this easy code snippet and because I use the argmax of the output tensor as the targets, I cannot understand why the loss is still high.
import torch
import torch.nn as nn
ce_loss = nn.CrossEntropyLoss()
output = torch.randn(3, 5, requires_grad=True)
targets = torch.argmax(output, dim=1)
loss = ce_loss(outputs, targets)
print(loss)

Thanks for the help understanding it.
Best regards
Jerome
Comment: what do you mean high ? Look at my answer to see how loss can be computed.
Answer: So here is a sample data from your code with the output, label and loss having the following values
outputs =  tensor([[ 0.5968, -0.8249,  1.5018,  2.7888, -0.6125],
                   [-1.1534, -0.4921,  1.0688,  0.2241, -0.0257],
                   [ 0.3747,  0.8957,  0.0816,  0.0745,  0.2695]], requires_grad=True)requires_grad=True)

labels = tensor([3, 2, 1])
loss = tensor(0.7354, grad_fn=<NllLossBackward>)

So let's examine the values,
If you compute the softmax output of your logits (outputs), using something like this torch.softmax(outputs,axis=1) you will get
probs = tensor([[0.0771, 0.0186, 0.1907, 0.6906, 0.0230],
                [0.0520, 0.1008, 0.4801, 0.2063, 0.1607],
                [0.1972, 0.3321, 0.1471, 0.1461, 0.1775]], grad_fn=<SoftmaxBackward>)

So these will be your prediction probabilities.
Now cross-entropy loss is nothing but a combination of softmax and negative log likelihood loss. Hence, your loss can simply be computed using
loss = (torch.log(1/probs[0,3]) +  torch.log(1/probs[1,2]) + torch.log(1/probs[2,1])) / 3

, which is the average of the negative log of the probabilities of your true labels. The above equation evaluates to 0.7354, which is equivalent to the value returned from the nn.CrossEntropyLoss module.
Comment: @Jérôme MASSOT If it used a threshold in the loss function then it wouldn't be differentiable. Every loss function needs to be "fuzzy" in a sense where even a small deviation from perfect will cause the loss to increase.
Comment: And the loss will not be `0` unless you predict the correct label with a probability of 1. If you look at the first instance where the label is `3`, we predicted that class with a portability of `0.6906`, meaning we are not 100% sure, hence we will incur some amount of loss.
Comment: Ah ok, I was thinking that it uses a threshold of 0.5 to say which class to predict. Now it makes sense, it is using the probability without threshold !! Thanks a lot. :)
Comment: If your question is answered, can you please accept this answer? Thanks.
Comment: Thanks for the explanations but first I am lost with the argmax return : I was thinking argmax will return the index of the max. So when I take the outputs tensor, I wouls have expected argmqx to return [1, 3, 4]...
Comment: In fact, why I am interested in is the Categorical Cross Entropy Loss. So by choosing a target from the argmax of the output, I was expecting to see a loss of 0 as the targets are the indexes of the max found in the outputs ....
Comment: yes it should have 1,3,4. I had messed up the index while printing. Now I have made another run and updated the numbers.


VBA Autofilter Excel 2013?

Question: I've been using a line like:
Cells.AutoFilter 11, "0"

for a while to autofilter column 11 for "0".
I recently updated to Microsoft Office 2013 and now I'm getting an AutoFilter method of Range class failed runtime error with this line.  Is this a compatibility issue with Office 2013 or some other problem?
EDIT:  I should clarify that I am not getting an error with a program I already run, but rather a line which I've used before and is not working for me right now.
EDIT2:
Code:
Dim firstRow As Integer
Dim lastRow As Integer
Dim firstCol As Integer
Dim lastCol As Integer
Dim allRange As Range
Dim vRange As Range
Dim bRange As Range
Dim commentsCol As Integer
Dim commentsColRng As Range
Dim fieldNameCol As Integer
Dim userCol As Integer

If Cells(2, 1) <> "" Then

    firstCol = 1
    lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
    firstRow = 2
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row

    commentsCol = Rows(1).find("Comments").Column '11
    fieldNameCol = Rows(1).find("Field Name").Column '8
    userCol = Rows(1).find("User").Column '4

    Set allRange = Range(Cells(firstRow, firstCol), Cells(lastRow, lastCol))
    Set commentsColRng = Range(Cells(firstRow, commentsCol), Cells(lastRow, commentsCol))

    Cells.AutoFilter Field:=1, Criteria1:="PF"
    Cells.AutoFilter commentsCol, "0", xlFilterValues
    Cells.AutoFilter Field:=2, Criteria1:="0", Operator:=xlFilterValues

End If

I have three autofilters because I'm trying it multiple different ways.
Comment: Hmm, that is strange. Does the `Same` file with `Same` Code work in Excel 2010?
Comment: As an FYI, I just pulled up a copy of Excel 2013 and used code such as yours to test and it worked fine. Are you sure it isn't an issue where the code is running on the `Activesheet` (implicitly since the code doesn't specify a sheet), and you actually need to be filtering a different sheet? Are you sure column 11 has data?
Comment: @SiddharthRout I believe we were originally on Office 2003, so I wouldn't know about 2010.  And a similar line still works from a program which I wrote previously. `Cells.AutoFilter Field:=2, Criteria1:="0", Operator:=xlFilterValues`
Comment: @user3561813  I'll try specifying a sheet but I know column 11 has data
Answer: You might not have anything in column 11.
For example:
     A         B
---------------------
1  field1   field2
2  a             0
3  b             1
4  c             2
5  d            23

Sub Test()
    ' this will succeed because column 2 (B) has something
    Cells.AutoFilter 2, "0"

    ' this will fail because column 3 (C) has nothing to filter on
    ' error message will be AutoFilter method of Range class failed
    Cells.AutoFilter 3, "0"
End Sub

Comment: I know all of column 11 has data.  The line `Cells.AutoFilter Field:=2, Criteria1:="0", Operator:=xlFilterValues` from a previous macro works fine for its program, yet the line `Cells.AutoFilter 11, "0", xlFilterValues` for this one does not.
Comment: Can you upload the Excel sheet somewhere? If we take a look at that, we might be able to help better.
Comment: Updated the original post
Comment: I created the same dataset from the screenshot and ran the code you have with zero problems. The code worked just fine.
Comment: And you're using Excel 2013?
Comment: Hey I created a follow up question.  Look at it if you feel up to it?  http://stackoverflow.com/questions/31747522/vba-different-requirements-when-coding  Thank you

VBA Autofilter Excel 2013?


Quota sampling in R

Question: I was provided surveys with quotas set at the provincial, gender, and employment status levels. I was wondering if it is possible to use survey package in R to perform raking and get the appropriate weights to make my sample more representative?
I am an economist with very limited experience with the survey literature: I am not sure if it makes sense to do the above since I am using a non-probability sample method. Could someone point me in the right direction for some literature on how to handle Quota web surveys?
Comment: To be honest, both. That said, I can for the specific on how to work on quota surveys in `R` on StackOverflow. But I would love some help with how to handle quota samples, especially on how to make them more representative when there is oversampling of some groups.
Comment: Are you asking for R code, or general advice on doing this? If about R, this would be off-topic in here.
Answer: Chiming in a bit late here, but I can provide some advice that may be useful. I've found that there's not much documentation and/or easy examples re: quota sampling (using R), so I went ahead and created my own method utilizing the survey library. For the sake of sharing my method without explicitly posting code, I've summarized the general process below.
Randomized quota sampling using survey weights as probabilities:

Generate weights using the rake function
Randomly sample from that set, using those weights as sampling probabilities. I've generally found that taking a 90% sample is a good starting point.
Iterate steps 1-2 until your desired n is reached.
If you want to optimize your sample for best match regardless of size, you'll want to measure how closely your sample matches your set quotas after each iteration, then pick the sample with the best match. I've found that mean absolute error/deviation works generally well for this purpose.

I'm sure there are libraries out there that can do this for you (perhaps sampling?), but clear examples are hard to come by in their documentation.
Comment: Could you provide a reference for this method? It seems very strange and I'm not sure what it's supposed to achieve. What's the point of step 2? Why would you entirely discard observations?
Answer: Introductory resource for raking with non-probability samples
Quota sampling is just one form of non-probability sampling, and there is a large, active literature on estimation from non-probability samples.
Pew Research recently produced a good, fairly non-technical overview of weighting methods for non-probability web surveys:
https://www.pewresearch.org/methods/2018/01/26/how-different-weighting-methods-work/
This is part of an interesting evaluation study of the effectiveness of such adjustments:
https://www.pewresearch.org/methods/2018/01/26/how-different-weighting-methods-work/
Software options
There are a couple good options for this:

The survey package has a function rake(), documented here:
https://www.rdocumentation.org/packages/survey/versions/4.1-1/topics/rake

The pewmethods R package has a raking function, and an example of its usage is located here:
https://medium.com/pew-research-center-decoded/weighting-survey-data-with-the-pewmethods-r-package-d040afb0d2c2

Quota sampling in R


Para que serve o AuthContext.Provider?

Question: Me deparei com a seguinte linha de código e estou querendo saber o que o AuthContext.Provider faz com esses values o children
 <AuthContext.Provider value={{ signIn, user, logOut, techs, setTechs }}>
      {children}
    </AuthContext.Provider>

Answer: Isso faz com que os filhos desse provider consigam ter acesso aos dados que ele está passando no value. Isso é uma forma de compartilhar estados pela aplicação sem ter quer ficar passando via props e evitar o prop drilling
Em qualquer filho dessa tag você poderia usar algo como
const { user } = useAuth()

e ter acesso aos dados do usuário.
O children seria literalmente a tag filha em relação ao provider. Seria algo mais ou menos assim
<AuthProvider>
  <App />
</AuthProvider>

Nesse caso a Tag App e todos os filhos subsequentes dela podem ter acesso ao contexto AuthContext
Caso queira se aprofundar mais use context

Para que serve o AuthContext.Provider?


Visual Studio C++ 2015 and openMP

Question: I want to know the behaviour of the VC++ compiler with /openmp. I'm using a third party library (OpenMVG) that comes with the cmakefilelist. So I generated the Visual Studio solution to compile it.
CMake recognizes the openmp capability of the compiler and in VS everithing compiles fine.
But when it comes to execution, I get different results everythime I run the program. And if I run 2 instances of the program at the same time, the results are even worse.
So I looked a little bit inside the source code and I found out that openmp is used with list and map iterators
<code>#pragma omp parallel
for (Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end() && bContinue; ++iter)
{
  pragma omp single nowait
  {
    ... process ...
  }
}
</code>
I searched on the web and it seems that Visual Studio only supports openMP 2.0. So does it support list iterators? Can this be the problem? How does openMP 2.0 behave with list iterators?
Thanks in advance fo any answer
Comment: The [full code](https://github.com/openMVG/openMVG/blob/944254c65691b3b7c5fe54d5bdbe312c90de252f/src/openMVG/sfm/pipelines/sfm_features_provider.hpp) is a reimplementation of a parallel walk over a collection with no random-access iterator without tasks. Everything except a minor race condition that only triggers if there is an error encountered while loading one of the views seems to be compliant with OpenMP 2.0. Either the error occurs somewhere else in the code or the MS OpenMP runtime has trouble implementing overlapping `single` regions. Have you considered filing an issue on GitHub?
Comment: The basic concept of this code is to run the entire loop on all threads, but the inner code of the loop only on single threads. This basically works, but whether this is correct or performs well depends on many things that you don't show. To get a helpful answer, you must provide a [mcve].
Comment: Exactly what did you expect to happen anyway? It's a basic premise in parallel programming that your data structures must be suitable in order for parallelization to work. You can process the list items in parallel, sure, but walking the list is inherently single-threaded. It takes O(N) _sequential_ steps to find the N'th item, no shortcuts.
Comment: As I am getting strange results I was just asking if the fact that Visual Studio implements the version 2.0 of openMP could be the problem, as the library is using list iterators (not supported by 2.0).
I've tried to compile the library without openmp support and the results look stable at every execution
Answer: The code doesn't do what you probably think it does. It creates a set of threads, each of which executes that same loop.
Note that OpenMP in Visual Studio doesn't really support C++, it treats it as a C dialect. In particular, <code>/openmp</code> doesn't support iterators, since that's C++ only. It only supports (some) C loops.
Also note that OpenMP is an old standard, predating even C++98. Since C++11, C++ has native threading capabilities.
Comment: OpenMP supports C++ random access iterators since 3.0 (2008!). The most recent version of OpenMP is from November 2015, there is a new draft from November 2016. The only issue is Visual Studio implementing a 16 year old version.
Comment: I don't get your last paragraph. C++11 does have built-in threads, but it provides none of the worksharing functionality of OpenMP.
Comment: I found the full code the OP refers to and consequently retract my previous statement. It's basically a reimplementation of a dynamically scheduled `for` construct for a container class with no random-access iterator type using only constructs from OpenMP 2.0. It could have been implemented using explicit tasks, but those come in later versions of the standard.
Comment: OpenMP is still "regularly" updated, e.g. with atomics support added in 2013 and in that sense not "old". Only VS refused to support any version above OpenMP 2.0. Your last line also suggests that OpenMP and c++ threads are "comparable", but there is a big difference in letting OpenMP setup the threadpool automatically vs. building it yourself
Comment: @Zulan: Fair point, made it clearer that I was talking about OpenMP as implemented by Visual Studio. As for "old standard", you could also call it an "early standard" if you like that better. It long provided a capability that C++ lacked until 2011.
Comment: @HristoIliev: Would you use that for the problem in the question?
Comment: The problem in the question is incomplete. The code as shown makes little sense unless there are explicit OpenMP task constructs within the `single` construct, which is a pretty common idiom.

Visual Studio C++ 2015 and openMP


How to fix CA1051 on fields in xaml code?

Question: I am running FxCop against my Silverlight code and appear to be getting a lot of CA1051 error codes:
Error, Certainty 90, for DoNotDeclareVisibleInstanceFields

Target       : #msgTextBox  (IntrospectionTargetMember)
Resolution   : "Because field 'MessagingControl.msgTextBox' is
               visible outside of its declaring type, change its accessibility
               to private and add a property, with the same accessibility
               as the field has currently, to provide access to it."
Help         : http://msdn.microsoft.com/library/ms182141(VS.100).aspx  (String)
Category     : Microsoft.Design  (String)
CheckId      : CA1051  (String)
RuleFile     : Design Rules  (String)
Info         : "Instance fields that are visible outside of the type
               that declares them, limit your ability to change the
               implementation details for those data items. Use properties
               instead. They do not compromise usability or performance
               and they do provide flexibility in that they conceal
               the implementation details of the underlying data."
Created      : 25/11/2011 10:59:54  (DateTime)
LastSeen     : 25/11/2011 14:57:49  (DateTime)
Status       : Active  (MessageStatus)
Fix Category : NonBreaking  (FixCategories)

Most of these seem to be from x:Name in the xaml so I don't think it can be fixed? Is there anything I can do to fix these errors apart from suppressing them all?
Answer: The default visibility for control fields is set to internal.
use  x:FieldModifier="<modifier>" e.g.  <TextBox x:Name="msgTextBox" x:FieldModifier="private" /> to control this behavior.
Comment: Well, simple and easy fix! Thank you very much. The other thing I found is that the alternative in many of these cases is to remove the x:Name altogether if it's unused as that seems to remove another warning


How to tell if there is strong evidence one brand is preferred over another?

Question: Two new varieties of cheese, V1 and V2, are to be compared. In order to establish if there was a
significant/real overall difference in consumer response to the two varieties, a study was conducted. Fifty
consumers were randomly assigned into two equal groups, Group 1 to taste V1, and Group 2 to taste V2.
Each variety of cheese was scored over ten characteristics, with each characteristic being given a rating
between 1 and 9 (1=strongly dislike, 9 = strongly like). Consumers in Group 1 scored variety V1, and
consumers in Group 2 scored variety V2. The ratings for each consumer were then added to give a total
score for that variety. The total scores from the consumers in each group are given in Table 2 below.

The question given is "what can you conclude from the 0.006 figure"? The answer is The probability of the difference in the mean scores of V2 – V1 of at least 9.92 occurring by chance is only 0.006. So V2 is
significantly preferred, as 0.006 < 0.05.
I am a bit confused at what the answer means. Does it mean that there is a 0.994 chance that it did not occur due to chance or something else?
Answer: Your data. First, I digitized your data (approximately) from the dot plots at the top
of your figure and entered them into R. [My version of your data may not be exactly correct, but close
enough for what I want to do.]
x1 = c(30,38,41,41,42, 43,45,53,53,54, 56,57,63,64,64,
       66,66,67,67,69, 73,83,84,88,90)
x2 = c(48,59,60,61,61, 62,63,65,67,67, 67,68,68,71,71,
       71,74,75,78,79, 79,80,83,84,84)

summary(x1); sd(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  30.00   45.00   63.00   59.88   67.00   90.00
[1] 16.2694    # SD x1
summary(x2); sd(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   48.0    63.0    68.0    69.8    78.0    84.0
[1] 9.059985   # SD x2

mean(x2) - mean(x1)
[1] 9.92

The scores in the second group were higher by 9.92 points.
So it looks as if Brand 2 was favored over Brand 1. The
question is whether the difference is large enough, considering
the variability in scoring, to be declared 'significantly different'
in a statistical sense.
The scores may not be exactly normally distributed, but there are
several points in favor of assuming they are approximately normal.

Each score is the sum
of ten components, and such scores are often approximately normal.

The dot plots show no marked skewness or extreme outliers.

Both data vectors x1 and x2 are found to be consistent with
sampling from normal populations, according to a Shapiro-Wilk
normality test. (In both tests, P-values are far above $0.05).$

.
shapiro.test(x1)$p.val
[1] 0.5010366
shapiro.test(x2)$p.val
[1] 0.4639407

Welch one-sided, two-sample t test. Therefore, it seems reasonable to use a two-sample t test to judge
whether the observed difference of 9.92 is statistically significant.
Because the sample standard deviations of x1 and x2 are somewhat different,
I will use a Welch 2-sample t test, which accommodates samples with different
variability. The null hypothesis is that the two populations have equal
means $H_0: \mu_1 = \mu_2$ and the one-sided alternative is that the first
group has a smaller mean than the second $H_a: \mu_1 < \mu_2.$
t.test(x1,x2, alte="less")

        Welch Two Sample t-test

data:  x1 and x2
t = -2.6635, df = 37.579, p-value = 0.005661
alternative hypothesis:
   true difference in means is less than 0
95 percent confidence interval:
      -Inf -3.639094
sample estimates:
mean of x mean of y
    59.88     69.80

The verdict whether or not to reject $H_0$ has to be stated in terms of
the data because we have access to the data (and have no way of knowing
exact values of population means $\mu_1, \mu_2.)$
The P-value $0.005661$ of the test indicates that the difference between the
sample means is relatively large. If the population means were equal (as
stated by $H_0,$ then there are fewer than 6 chances in 1000 that we would observe
such a large difference (or a larger one) between sample means.
By 'relatively', I mean that the sizes and variability of the samples have
been taken into account in assessing how to interpret the size of the difference
between sample means.  [If you like, you can take a look at the formula for
the t statistic and its degrees of freedom df: you will see sample sizes
$n_1 = n_2 = 25$ and sample standard deviations $S_1 and S_2$ in these formulas.]
The image in your Question shows the P-value $0.006$ which indicates that if population means were equal as large a difference (or larger) between sample means as we have observed would occur very rarely. That's 6 chances in 1000; not exactly the same as for the Welch t test I showed above, but both P-values strongly indicate rejection of $H_0$ in favor of $H_1.$
It is common to test hypotheses at the 5% level, which means that 1 chance in 20
is often considered strong enough evidence to reject $H_0.$
If there is a question whether the assumptions for a t test are met, statisticians
look for other ways to find a P-value that will use sample sizes and variabilities
of the two samples to judge whether an observed difference is large enough to be
called 'statistically significant'.
Permutation test. In your question it seems that a permutation test is used to find a useful P-value.
You can read about permutation tests in Wikipedia, which gives some of their history and shows several elementary examples. There are many kinds of permutation tests and
from your question I can't tell which of them was done; only the results are shown, not the procedure.
So I will do a permutation test of my own, hoping it will give you a general idea what
is involved.

First, we need a 'metric', a way to measure the difference between the scores in samples x1 and x2. As my metric, I will choose the difference in sample means: $D_\mathrm{obs} = \bar X_2 - \bar X_1.$

Second, I will perform permutations of the data. Specifically, we have $n_1+n_2 = 50$ scores in the two groups combined. Strictly at random, I will pick 25 of the 50 to put into group 1 and put the remaining 25 into group 2. For each such permutation I will find $D^* = \bar X_2^* - \bar X_1^*$ where the *'s mean that permuted groups rather than original groups are used.

Third, I will do $B = 10,000$ of these permutations of the data and get a $D^*$ from each one of them. Information about the sample sizes and variabilities of the data
gets used in all of this permuting and averaging. So I will get a useful 'permutation distribution' of the 10,000 $D^*$s.

Finally, I will compare the permutation of $D^*$s with the original $D_{\mathrm{obs}} = 9.92.$ The proportion of $D^*$s that is larger than or equal to $D_{\mathrm{obs}}$ will be the P-value of the permutation test.

The following R code assumes that the data vectors x1 and x2 are already present
in R.
d.obs = mean(x2) - mean(x1)
x = c(x1, x2)
g = rep(1:2, each=25)

set.seed(1234)
B = 10^4;  d.prm = numeric(B)
for (i in 1:B) {
 g.prm = sample(g)  # randomly scrambles groups
 d.prm[i] = mean(x[g.prm==2]) - mean(x[g.prm==1])
}
mean(d.prm >= d.obs)
[1] 0.0064

hdr="Permutation Distribution of Group Mean Differences"
hist(d.prm, prob=T, br=30, col="skyblue2", main=hdr)
 abline(v=d.obs, col="red")

The P-value $0.0064$ from my permutation test is about the same as
the P-value from the permutation test in your Question. A permutation
test is a random procedure (depending on random permutations of the
observations into two groups), so results might differ slightly from
one run to another.
In any case my permutation P-value and the one in your Question are
essentially the same. Both are small enough to lead to rejection of $H_0.$