Constructing infinitely many automorphisms of a free group on two generators to itself

Question: I want to use the universal property of the free group on two generators $F =
F(\{a, b\})$ to construct infinitely many automorphisms of $F$, with the restriction that are not they are not inner automorphisms.
Comment: Indeed to understand the universal property, you need to have a clear idea of the meaning of "extend". If you have sets $X\subset Y$ and $Z$, and a map $f:X\to Z$, a map $g:Y\to Z$ **extends** $f$ if its restriction to $X$ equals $f$. Here this applies to $Y=F$ and $X=\{a,b\}$.
Comment: If you want something concrete, consider the maps $a\mapsto a, b\mapsto ba^n$, $n\in {\mathbb Z}$.
Comment: @TimHowell Because it won't necessarily extend to an automorphism (that is an isomorphism/bijection).
Comment: Why is it not ok to define an arbitrary map, e.g. why is $a \mapsto a^n$, $b \mapsto b^n$ not ok?
Answer: It is well-known that $Aut(F_2)/Inn(F_2)\cong GL_2(\Bbb Z)$, see
Bogopolski.


Pick a cluster for customer locations

Question: On our app customer's visit stores. We would like to assign a City or location as the customer's "home" location, to offer him/her targeted offers. What we've done so far:
Using R, we performed DBSCAN (density based clustering) to cluster the stores the customer visited, we then have a a couple of outliers and clusters with N points each. We are struggling to pick one or two clusters out to assign as primary/secondary markets:
<code>| cluster | points |  meanLat |  meanLon | City |
|---------|--------|----------|----------|------|
|       1 |    100 | X.XXXXXX | X.XXXXXX |    A |
|       2 |     20 | X.XXXXXX | X.XXXXXX |    B |
|       3 |     10 | X.XXXXXX | X.XXXXXX |    C |
</code>
For customer with this result, I think picking cluster 1 makes sense, but I'm failing to find a way to pick one programatically.
For our domain, it only makes sense to pick one if we are confident that the user visits these stores overwhelmingly and we know we might not be able to make the assignment if we have few data and we most wait for the user to visit more stores.
My concrete questions are:
What makes cluster 1 the right choice in this example? Is 130 points enough to pick 100? What I have only 10 points total? Or, what if two clusters had 80 and 60 points? Where is the line?
Answer: This is not a clustering problem what you are facing anymore.
The clusters are just a tool to help you understand the data. Do not assume they are 100% correct or anything. But a cluster may indicate e.g. that east coast and west coast customers exhibit different behavior. But it is then up to you to formalize and validate this concept. At this point it stopped being a clustering problem.
In your case there is no statistical answer to your question. The question whether to assign customers to one group or two is entirely a business decision to make, based on what you are doing with the data. Is not a property of the clustering.
Comment: I'm with you, clustering simply allowed me to group my observations into fewer. I could have used the City name to aggregate observations into a smaller set as well. Past that, are you saying there is no statistical way of qualifying these observations?  What if the problem was worded differently, without clustering?: "Guest 1, visited stores in city A 100 times, city B 20 times, city C 10 times, there is no statistical way of saying that the user is more likely to visit stores in city A in the future?"
Comment: You can do a MLE and you can also argue about estimation errors and confidence intervals if you make enough assumptions. Whether these assumptions are likely to hold or not *we* don't know. This is classic probability theory - it is better explained in the books than we will ever be able to do here because of length.
Comment: Thanks for the detail responses and pointers, I appreciate it. I'll read more about MLE and definitely hit the books for probability theory.

Pick a cluster for customer locations


Do discrete geometric objects exist in the same space as non-discrete geometric object?

Question: Do discrete geometric objects exist in the same space as non-discrete geometric object? I am wondering if the spaces are defined differently in discrete geometry. After reading a little about it, I am still confused as to what purpose discrete geometry serves exactly. It seems to be about the study of graphs, but I don't see how it relates to geometry.
Answer: I'd say discrete geometry mostly takes place in $d$-dimensional Euclidean space for some $d$, often denoted $\mathbb{E}^d$, which is the same thing as $d$-dimensional real space $\mathbb{R}^d$ with the usual Euclidean metric. Plenty of work is done in other settings, though (hyperbolic space, toroids, etc.)
It includes the study of polytopes, like the regular polyhedra (the Platonic solids), Archimedean solids, and so on. This is the focus of Euclid's Elements, making it probably the oldest and longest-studied branch of mathematics there is.
By contrast, geometry which isn't discrete, which I think of as "swoopy" geometry, has only been developed much more recently.
Whenever you're assembling discrete components, like making polyhedra by attaching polygons, or tiling a surface, or designing a space-filling honeycomb or weight-supporting truss, you're doing discrete geometry. The study of crystals, quasi-crystals, and other periodic or aperiodic systems crop up here.
As you mention, embedding graphs in space is another example, like planar graphs, or with distance constraints in three dimensions, which gives us protein folding. (And global positioning, although the geometric aspects aren't the most challenging part of the GPS system.)
Computer graphics are another "purpose" served by discrete geometry. Objects are modeled by a very large number of polyhedra, to which various Euclidean transformations are applied as the viewpoint moves.


What exactly does a non-parametric test accomplish & What do you do with the results?

Question: I have a feeling this may have been asked elsewhere, but not really with the type of basic description I need.  I know non-parametric relies on the median instead of the mean to compare... something.  I also believe it relies on "degrees of freedom"(?) instead of standard deviation.  Correct me if I'm wrong, though.
I've done pretty good research, or so I'd thought, trying to understand the concept, what the workings are behind it, what the test results really mean, and/or what to even do with the test results; however, no one seems to ever venture into that area.
For the sake of simplicity let's stick with the Mann-Whitney U-test, which I've noticed is quite popular (and also seemingly misused and overused too in order to force one's "square model into a circle hole").  If you'd like to describe the other tests as well feel free, although I feel once I understand one, I can understand the others in an analogous way towards various t-tests etc.
Let's say I run a non-parametric test with my data and I get this result back:
<code>2 Sample Mann-Whitney - Customer Type

Test Information
H0: Median Difference = 0
Ha: Median Difference ≠ 0

Size of Customer    Large   Small
Count                    45    55
Median                    2     2

Mann-Whitney Statistic: 2162.00
p-value (2-sided, adjusted for ties):   0.4156
</code>
I'm familiar with other methods, but what is different here?  Should we want the p-value to be lower than .05?  What does the "Mann-Whitney statistic" mean?  Is there any use for it?  Does this information here just verify or not verify that a particular source of data I have should or should not be used?
I have a reasonable amount of experience with regression and the basics, but am very curious about this "special" non-parametric stuff - which I know will have it's own shortcomings.
Just imagine I'm a fifth grader and see if you can explain it to me.
Comment: Yes, I've read that many times.  Sometimes the jargon that wikipedia uses can become overwhelming and although it has an accurate description - it does not necessarily have a clear description to someone who is starting to try to learn the area.

Not sure who downvoted, but I legitimately want just a basic, CLEAR, explanation almost anyone could understand.  Yes, I've tried hard to find one believe it or not.  No need to instantly downvote me and link me to wikipedia.

Anyone ever notice how some teachers are better than others?  I'm looking for a good "teacher" for a concept I'm stuck on.
Comment: No it does not seem to be working as well as a good book.  To paraphrase Stephen Senn, it is odd that statistics is the only science the people demand be understandable at first look.
Comment: The internet alone is actually working better than any book or class ever did for me to be honest - and that goes for any topic.  I apologize for writing "chatty" questions.
Comment: Move on then to a good basic nonparametric statistics text such as Sprent and Smeeton, Hollander and Wolfe, Conover. or find an introductory text that includes Mann-Whitney.
Comment: I can see how in my asking of the question I was missing foundational pieces - like...alot of them.  I was trying to shortcut.

But seeing as this question has reached gold status recently....and the answers here manage to take the chaos and confusion I had, distill them out, and clearly answer them...

That is what SE is about.   Who can provide the best answer?
Comment: I don't know what a fifth-grader is but I would recommend reading basic stuff first e.g. http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U
Comment: For me personally part of the issue is time.  I've also found that, because someone was so clear at explaining something either on Stackexchange or in a video on Youtube - concepts that I could never grasp during an entire semester or from a book made sense in 5-10 minutes.  Think about the videos on Youtube for education of the disicplines like this - there are actual true free-market forces at play that cause everyone to try to explain a concept better than the rest.  Why wouldn't I take advantage of those or here instead of a book?  We are on the internet by the way.
Comment: From looking at your question and the other question you asked recently using the internet alone is not working well for you, as you are evidently very confused. That's why @Peter Flom and I are recommending books. I haven't got other suggestions in reserve. I'd also recommend -- sincerely and in your best interests -- trying to write much more concise, less chatty questions. Your digressive style doesn't help make your questions clear.
Answer:
I know non-parametric relies on the median instead of the mean

Hardly any nonparametric tests actually "rely on" medians in this sense. I can only think of a couple... and the only one I expect you'd be likely to have even heard of would be the sign test.

to compare...something.

If they relied on medians, presumably it would be to compare medians. But - in spite of what a number of sources try to tell you - tests like the signed rank test, or the Wilcoxon-Mann-Whitney or the Kruskal-Wallis are not really a test of medians at all; if you make some additional assumptions, you can regard the Wilcoxon-Mann-Whitney and the Kruskal-Wallis as tests of medians, but under the same assumptions (as long as the distributional means exist) you could equally regard them as a test of means.
The actual location-estimate relevant to the Signed Rank test is the median of pairwise averages within-sample (over $\frac12 n(n+1)$ pairs including self-pairs), the one for the Wilcoxon-Mann-Whitney is the median of pairwise differences across-samples.

I also believe it relies on "degrees of freedom?" instead of standard deviation. Correct me if I'm wrong though.

Most nonparametric tests don't have 'degrees of freedom' in the specific sense that the chi-squared or the t-test of the F-test do (each of which has to do with the number of degrees of freedom in an estimate of variance), though the distribution of many change with sample size and you might regard that as somewhat akin to degrees of freedom in the sense that the tables change with sample size. The samples do of course retain their properties and have n degrees of freedom in that sense but the degrees of freedom in the distribution of a test statistic is not typically something we're concerned with. It can happen that you have something more like degrees of freedom - for example, you could certainly make an argument that the Kruskal-Wallis does have degrees of freedom in basically the same sense that a chi-square does, but it's usually not looked at that way (for example, if someone's talking about the degrees of freedom of a Kruskal-Wallis, they will nearly always mean the d.f. of the chi-square approximation to the distribution of the statistic).
A good discussion of degrees of freedom may be found here/

I've done pretty good research, or so I've thought, trying to understand the concept, what the workings are behind it, what the test results really mean, and/or what to even do with the test results; however no one seems to ever venture into that area.

I'm not sure what you mean by this.
I could suggest some books, like Conover's Practical Nonparametric Statistics, and if you can get it, Neave and Worthington's book (Distribution-Free Tests), but there are
many others - Marascuilo & McSweeney, Hollander & Wolfe, or Daniel's book for example. I suggest you read at least 3 or 4 of the ones that speak to you best, preferably ones that explain things as differently as possible (this would mean at least reading a little of perhaps 6 or 7 books to find say 3 that suit).

For the sake of simplicity lets stick with the Mann Whitney U test, which I've noticed is quite popular

It is, which is what puzzled me about your statement "no one seems to ever venture into that area" - many people who use these tests do 'venture into the area' you were talking about.

- and also seemingly misused and overused

I'd say nonparametric tests are generally underused if anything (including the Wilcoxon-Mann-Whitney) -- most especially permutation/randomization tests, though I wouldn't necessarily dispute that they're frequently misused (but so are parametric tests, even more so).

Let's say I run a non-parametric test with my data and I get this result back:

[snip...]

I'm familiar with other methods, but what is different here?

Which other methods do you mean? What do you want me to compare this to?
Edit: You mention regression later; I assume then that you are familiar with a two-sample t-test (since it's really a special case of regression).
Under the assumptions for the ordinary two-sample t-test, the null hypothesis has that the two populations are identical, against the alternative that one of the distributions has shifted. If you look at the first of the two sets of hypotheses for the Wilcoxon-Mann-Whitney below, the basic thing being tested there is almost identical; it's just that the t-test is based on assuming the samples come from identical normal distributions (apart from possible location-shift). If the null hypothesis is true, and the accompanying assumptions are true, the test statistic has a t-distribution. If the alternative hypothesis is true, then the test-statistic becomes more likely to take values that don't look consistent with the null hypothesis but do look consistent with the alternative -- we focus on the most unusual, or extreme outcomes (the ones most consistent with the alternative) - if they occur, we conclude that the samples we got would not have occurred by chance when the null was true (they could do, but the probability of a result at least that much consistent with the alternative is so low that we consider the alternative hypothesis a better explanation for what we observe than "the null hypothesis along with the operation of chance").
The situation is very similar with the Wilcoxon-Mann-Whitney, but it measures the deviation from the null somewhat differently. In fact, when the assumptions of the t-test are true*, it's almost as good as the best possible test (which is the t-test).
*(which in practice is never, though that's not really as much of a problem as it sounds)

Indeed, it's possible to consider the Wilcoxon-Mann-Whitney as effectively a "t-test" performed on the ranks of the data - though then it doesn't have a t-distribution; the statistic is a monotonic function of a two-sample t-statistic computed on the ranks of the data, so it induces the same ordering on the sample space (that is a "t-test" on the ranks - appropriately performed - would generate the same p-values as a Wilcoxon-Mann-Whitney), so it rejects exactly the same cases.
[You'd think that just using the ranks would be throwing away a lot of information, but when the data are drawn from normal populations with the same variance, almost all the information about location-shift is in the patterns of the ranks. The actual data values (conditional on their ranks) add very little additional information to that. If you go heavier-tailed than normal, it's not long before the Wilcoxon-Mann-Whitney test has better power, as well as retaining its nominal significance level, so that 'extra' information above the ranks eventually becomes not just uninformative but in some sense, misleading. However, near-symmetric heavy-tailedness is a rare situation, outside some specific applications; what you often tend to see in practice is skewness.]
The basic ideas are quite similar, the p-values have the same interpretation (the probability of a result as, or more extreme, if the null hypothesis were true) -- right down to the interpretation of a location-shift, if you make the requisite assumptions (see the discussion of the hypotheses near the end of this post).
If I did the same simulation as in the plots above for the t-test, the plots would look very similar - the scale on the x- and y-axes would look different, but the basic appearance would be similar.

Should we want the p-value to be lower than .05?

You shouldn't "want" anything there. The idea is to find out if the samples are more different (in a location-sense) than can be explained by chance, not to 'wish' a particular outcome.
If I say "Can you go see what color Raj's car is please?", if I want an unbiased assessment of it I don't want you to be going "Man, I really, really hope it's blue! It just has to be blue". Best to just see what the situation is, rather than to go in with some 'I need it to be something'.
If your chosen significance level is 0.05, then you'll reject the null hypothesis when the p-value is ≤ 0.05. But failure to reject when you have a big enough sample size to nearly always detect relevant effect-sizes is at least as interesting, because it says that any differences that exist are small.

What does the "mann whitley" number mean?

The Mann-Whitney statistic.
There's meaning in comparing its value with the distribution of values it can take when the null hypothesis is true (see the above diagram), and that depends on which of several particular definitions any particular program might use.

Is there any use for it?

Usually you don't care about the exact value as such, but where it lies in the null-distribution (whether it's more or less typical of the values you should see when the null hypothesis is true, or whether it's more extreme)
(Edit: You can obtain or work out some directly informative quantities when doing such a test - like the location shift or $P(X<Y)$ discussed below, and indeed you can work out the second one fairly directly from the statistic, but the statistic alone isn't a very informative number)

Does this data here just verify or not verify that a particular source of data I have should or should not be used?

This test doesn't say anything about "a particular source of data I have should or should not be used".
See my discussion of the two ways of looking at the WMW hypotheses below.

I have a reasonable amount of experience with regression and the basics, but am very curious about this "special" non-parametric stuff

There's nothing particularly special about nonparametric tests (I'd say the 'standard' ones are in many ways even more basic than the typical parametric tests) -- as long as you actually understand hypothesis testing.
That's probably a topic for another question, however.

There are two main ways to look at the Wilcoxon-Mann-Whitney hypothesis test.
i) One is to say "I'm interested in location-shift - that is that under the null hypothesis, the two populations have the same (continuous) distribution, against the alternative that one is 'shifted' up or down relative to the other"
The Wilcoxon-Mann-Whitney works very well if you make this assumption (that your alternative is just a location shift)
In this case, the Wilcoxon-Mann-Whitney actually is a test for medians ... but equally it's a test for means, or indeed any other location-equivariant statistic (90th percentiles, for example, or trimmed means, or any number of other things), since they're all affected the same way by location-shift.
The nice thing about this is that it's very easily interpretable -- and it's easy to generate a confidence interval for this location-shift.

However, the Wilcoxon-Mann-Whitney test is sensitive to other kinds of difference than a location shift.
ii) The other is to take the fully general approach. You can characterize this as a test for the probability that a random value from population 1 is less than a random value from population 2 (and indeed, you can turn your Wilcoxon-Mann-Whitney statistic into a direct estimate of that probability, if you're so inclined; the Mann&Whitney formulation in terms of U-statistics counts the number of times one exceeds the other in the samples, you only need scale that to achieve an estimate of the probability); the null is that the population probability is $\frac{1}{2}$, against the alternative that it differs from $\frac{1}{2}$.

However, while it can work okay in this situation, the test is formulated on the assumption of exchangability under the null. Among other things that would require that in the null case the two distributions are the same. If we don't have that, and are instead are in a slightly different situation like the one pictured above, we won't typically have a test with significance level $\alpha$. In the pictured case it would likely be a bit lower.
So while it "works" in the sense that it tends not to reject when $H_0$ is true and tends to reject more when $H_0$ is false, you want the distributions to be pretty close to identical under the null or the test doesn't behave the way we would expect it to.
Comment: +1 Great answer. One of the best and most accessible explanations of the Wilcoxon-Mann-Whitney test I know. Thank you.
Comment: I drew the approximate null distribution (the one in red in the new topmost graph) in as if it's continuous ... but the actual distribution is discrete. The picture is less cluttered that way.
Comment: "In this case, the Wilcoxon-Mann-Whitney actually is a test for medians ... but equally it's a test for means" However, some distributions don't have means whereas their median is well-defined (e.g. Cauchy).
Comment: @caracal While true (it's a point I've made a number of times here), if someone's testing for equality of population means, presumably they already assume they population means are finite. If they don't, they have a problem well before they get to the point of choosing a test. Taking as given that there's a hypothesis of equal (and thereby finite) population means, under the same assumptions that are usually used in order to make it a test of medians (shift alternatives), the WMW is also a test of means.
Answer: Suppose you and I are coaching track teams. Our athletes come from the same school, are similar ages, and the same gender (i.e., they're drawn from the same population), but I claim to have discovered a Revolutionary New Training System that will make my team members run much faster than yours. How can I convince you that it really does work?
We have a race.
Afterward, I sit down and compute the average time for the members of my team and the average time for the members of yours. I'll claim victory if the mean time for my athletes is not only faster than the mean for yours, but the difference is also large compared to the "scatter", or standard deviation, of our results.

This is essentially a [$t$-test][1]. We're assuming that the data arises from distributions with specific parameters, in this case a mean and standard deviation. The test estimates those parameters and compares one of them (the mean). It is, consequently, called a parametric test, since we are comparing these parameters.

"But Matt", you complain, "this isn't quite fair. Our teams are pretty similar, but you--due to pure chance--ended up with the fastest runner in the district. He's not in the same league as everyone else; he's practically a freak of Nature. He finished 3 minutes before the next-fastest finisher, which reduces your average time a lot, but the rest of the competitors are pretty evenly mixed. Let's look at the finish order instead. If your method really works, the earlier finishers should mostly be from your team, but if it doesn't the finish order should be pretty random. This doesn't give undue weight to your super-star!"

This method is essentially the [Mann-Whitney U Test][2] (also called the Wilcoxon Rank Sum Test, Manning-Whitney-Wilcoxon Test, and several other permutations besides!). Note that unlike the $t$-test, we're not assuming that the data comes from specific distributions, nor are we computing any parameters for them. Instead, we're comparing the relative ranks of the data points directly.
That's the major distinction--parametric tests model things with distributions and compare the parameters of these distributions; non-parametric tests....don't and operate more directly on the data. As with parametric tests, non-parametric test statistics are also constructed so that the $p$ values are uniformly distributed on [0,1] under the null hypothesis and clustered towards 0 in the presence of an effect. You would report and interpret them just like the results of a parametric test.
I'm not sure about the relative popularity of parametric and non-parametric methods. Some non-parametric methods (e.g., histograms!) are in nearly universal use; others might be over or under-used. I suspect that the Mann-Whitney U Test ought to be used more, rather than less frequently. It's about as efficient as a $t$-test on normally distributed data and actually does better than the $t$-test on sufficiently non-normal data. It's also fairly robust to outliers. Plus, you can use it on ordinal data too (e.g., finish order rather than just finish time), which makes it more broadly applicable than a $t$-test.
Comment: You actually answered my question exactly the way, and I mean exactly, the way I wanted it to be answered.  Glen edged on the mathematical side more too, and the combination of these two responses made the click for me.  I can't take the reward away from him though - I mean...he's drawing graphs, despite the clarity of your response.  I have a feeling you've had some sort of teaching job in the past. I know there may be some generalizations in the responses here, but I knew I didn't have to buy a book and study it intensely to begin to be able to practically apply non-parametrics on some level
Comment: Aww thanks! I'm not quite ready for a faculty job yet, but I'd like one down the line. FWIW, I think @Glen_b's answer is quite good! Neither of us came out and said this explicitly, but if you're on the fence between a rank sum and a $t$-test, go with the rank sum. I think part of the t-test's popularity is how it fits in nicely with the themes of Stats 101, rather than any intrinsic fitness-for-purpose. Anyway, good luck and feel free to post more questions as they pop up!
Comment: The irony of all this is that I'm not going to use it at all probably, it just bothered me that I couldn't get a straight answer on what it was.  Glen's answer is so much more than I expected and got originally - the best answers I feel I can't describe as any description would prove inadequate.  Like telling someone what the color blue looks like.  If you've read any of whuber's stuff, it sounds like you may have a similar flavor...
Comment: see http://stats.stackexchange.com/questions/18058/how-would-you-explain-covariance-to-someone-who-understands-only-the-mean/18200#18200
Answer: You asked to be corrected if wrong. Here are some comments under that heading to complement @Peter Flom's positive suggestions.

"non-parametric relies on the median instead of the mean": often in practice, but that's not a definition. Several non-parametric tests (e.g. chi-square) have nothing to do with medians.
relies on degrees of freedom instead of standard deviation; that's very confused. The idea of degrees of freedom is in no sense an alternative to standard deviation; degrees of freedom as an idea applies right across statistics.
"a particular source of data I have should or should not be used": this question has nothing to do with the significance test you applied, which is just about the difference between subsets of data and is phrased in terms of difference between medians.
Comment: I believe your take on me asking to "be corrected where wrong" has been the best response so far.  I suppose I needed a few null hypothesis refuted or to learn by process of elimination.  Your response has given me new information I understand - there are still some big holes in my understanding of the topic, but I can't expect perfection.  Perhaps those holes are bigger than I originally anticipated when writing this question and stackexchange wouldn't suffice, no matter how "chatty" I made the question.
Answer: You "want" the same things from a p-value here that you want in any other test.
The U statistic is the result of a calculation, just like the t statistic, the odds ratio, the F statistic, or what have you. The formula can be found lots of places. It's not very intuitive, but then, neither are other test statistics until you get used to them (we recognize a t of 2 as being in the significant range because we see them all the time).
The rest of the output in your block text should be clear.
For a more general introduction to nonparametric tests, I echo @NickCox .... get a good book. Non-parametric simply means "without parameters"; there are many non-parametric tests and statistics for a wide variety of purposes.
Comment: First you ask us to simplify, then you complain that our answers are simple!  If you want to understand the formula for U (or anything else) LOOK at it. If you want something simple, then don't ask for complexities! The Wikipedia entry is an excellent, detailed entry with all the details. You  don't understand it. So. What do you want?
Comment: I appreciate your post, however it actually already reiterates most of what I already know or had assumed unfortunately.  There seems to be some sort of pattern where almost every explanation I get stops at this one specific point.  Perhaps this point is where it becomes too complex to explain or too much effort - I'm not sure.  Either way, it is a pattern I've been experiencing from every source of information I normally use - which would ironically reiterate everyone's book statement.  Perhaps I did not realize the answer was so complex; then again I've seen some intense answer on SE.
Comment: I suppose somewhere in between.   I admittedly am not the best at communicating, and I can understand you're frustration, heh.  It's a trait of mine I actually am very aware of.  To be honest, I think I'll have to think about what I really want - as it's almost like I'm trying to nudge the question enough to where it overlaps into an area I wasn't aware of or didn't previously know about.  It's hard to ask about something you don't understand in general.  I'll just have to come back to this I suppose.
Comment: Yes, ideally, a good book would help; however, it seems unnecessary with today's resources (like stackexchange), wikipedia (sometimes), youtube market competition (did you know for each million views someone gets they get paid $4000?), as well as a variety of other resources.  I generally, just as my learning style, fail pretty hard at simple book learning as well.
Answer: As a response to a recently closed question, this addresses the above as well. Below is a quote from Bradley's classic Distribution-Free Statistical Tests (1968, p. 15–16) which, while a bit long, is a pretty clear explanation, I believe.

The terms nonparametric and distribution-free are not synonymous, and
  neitherterm provides an entirely satisfactory description of the class
  of statistics to which they are intended to refer.…Roughly speaking, a
  nonparametric test is one which makes no hypothesis about the value of
  a parameter in a statistical density function, whereas a
  distribution-free test is one which makes no assumptions about the
  precise form of the sampled population. The definitions are not
  mutually exclusive, and a test can be both distribution-free and
  parametric.…In order to be entirely clear about what is meant by
  distribution-free, it is necessary to distinguish between three
  distributions: (a) that of the sampled population; (b) that of the
  observation-characteristic actually used by the test; and (c) that of
  the test statistic. The distribution from which the tests are "free"
  is that of (a), the sampled population. And the freedom they enjoy is
  usually relative.…However the assumptions are never so elaborate as to
  imply a population whose distribution is completely specified.…The
  reason…is very simple: the magnitudes are not used as such in the
  [nonparametric] test, nor is any other strongly-linked population
  attribute of the variate. Instead sample-linked charachteristics of
  the obtained observations…provide the informatikon used by the test
  statistic.…Thus while both parametric and nonparametric tests require
  that the form f a distribution, associated with observations, be
  fully known, that knowledge, in the parametric case, is generally not
  forthcoming ad the required distribution of magnitudes must
  therefore be "assumed" or inferred on the basis of approximate or
  incomplete information. In the nonparametric case, on the other and,
  the distrbution of the observation characteristic is usually known
  precisely from a priori considerations and need not, therefore, be
  "assumed." The difference, then, is not one of requirement but rather
  of what is required and of certainty that the requirement will be met.


Core Animation and Transformation like zoomRectToVisible

Question: I'm trying to get an effect like the zoomRectToVisible-method of UIScrollview.
But my method should be able to center the particular rect in the layer while zooming and it should be able to re-adjust after the device orientation changed.
I'm trying to write a software like the marvel-comic app and need a view that presents each panel in a page.
For my implementation I'm using CALayer and Core Animation to get the desired effect with CATransform3D-transformations. My problem is, I'm not able to get the zoomed rect/panel centered.
the structure of my implementation looks like this: I have a subclass of UIScrollview with a UIView added as subview. The UIView contains the image/page in it's CALayer.contents and I use core animations to get the zooming and centering effect. The zoom effect on each panel works correcty but the centering is off. I'm not able to compute the correct translate-transformation for centering.
My code for the implementation of the effect is like this:
- (void) zoomToRect:(CGRect)rect animated:(BOOL)animated {
    CGSize scrollViewSize = self.bounds.size;

    // get the current panel boundingbox
    CGRect panelboundingBox = CGPathGetBoundingBox([comicPage panelAtIndex:currentPanel]);

    // compute zoomfactor depending on the longer dimension of the panelboundingBox size
    CGFloat zoomFactor = (panelboundingBox.size.height > panelboundingBox.size.width) ? scrollViewSize.height/panelboundingBox.size.height : scrollViewSize.width/panelboundingBox.size.width;

    CGFloat translateX = scrollViewSize.width/2 - (panelboundingBox.origin.x/2 + panelboundingBox.size.width/2);
    CGFloat translateY = scrollViewSize.height/2 - (panelboundingBox.size.height/2 - panelboundingBox.origin.y);

    // move anchorPoint to panelboundingBox center
    CGPoint anchor = CGPointMake(1/contentViewLayer.bounds.size.width * (panelboundingBox.origin.x + panelboundingBox.size.width/2), 1/contentViewLayer.bounds.size.height * (contentViewLayer.bounds.size.height - (panelboundingBox.origin.y + panelboundingBox.size.height/2)));

    // create the nessesary transformations
    CATransform3D translateMatrix = CATransform3DMakeTranslation(translateX, -translateY, 1);
    CATransform3D scaleMatrix = CATransform3DMakeScale(zoomFactor, zoomFactor, 1);

    // create respective core animation for transformation
    CABasicAnimation *zoomAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    zoomAnimation.fromValue =  (id) [NSValue valueWithCATransform3D:contentViewLayer.transform];
    zoomAnimation.toValue = (id) [NSValue valueWithCATransform3D:CATransform3DConcat(scaleMatrix, translateMatrix)];
    zoomAnimation.removedOnCompletion = YES;
    zoomAnimation.duration = duration;

    // create respective core animation for anchorpoint movement
    CABasicAnimation *anchorAnimatione = [CABasicAnimation animationWithKeyPath:@"anchorPoint"];
    anchorAnimatione.fromValue = (id)[NSValue valueWithCGPoint:contentViewLayer.anchorPoint];
    anchorAnimatione.toValue = (id) [NSValue valueWithCGPoint:anchor];
    anchorAnimatione.removedOnCompletion = YES;
    anchorAnimatione.duration = duration;

    // put them into an animation group
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = [NSArray arrayWithObjects:zoomAnimation, anchorAnimatione, nil] ;

    /////////////

    NSLog(@"scrollViewBounds (w = %f, h = %f)", self.frame.size.width, self.frame.size.height);
    NSLog(@"panelBounds (x = %f, y = %f, w = %f, h = %f)", panelboundingBox.origin.x, panelboundingBox.origin.y, panelboundingBox.size.width, panelboundingBox.size.height);
    NSLog(@"zoomfactor: %f", zoomFactor);
    NSLog(@"translateX: %f, translateY: %f", translateX, translateY);
    NSLog(@"anchorPoint (x = %f, y = %f)", anchor.x, anchor.y);

    /////////////

    // add animation group to layer
    [contentViewLayer addAnimation:group forKey:@"zoomAnimation"];

    // trigger respective animations
    contentViewLayer.anchorPoint = anchor;
    contentViewLayer.transform = CATransform3DConcat(scaleMatrix, translateMatrix);
}

So the view requires the following points:

it should be able to zoom and center a rect/panel of the layer/view depending on the current device orientation. (zoomRectToVisible of UIScrollview does not center the rect)
if nessesary (either device orientation changed or panel requires rotation) the zoomed panel/rect should be able to rotate
the duration of the animation is depending on user preference. (I don't know whether I can change the default animation duration of zoomRectToVisible of UIScrollView ?)

Those points are the reason why I overwrite the zoomRectToVisible-method of UIScrollView.
So I have to know how I can correctly compute the translation parameters for the transformation.
I hope someone can guide me to get the correct parameters.
Answer: Just skimmed over your code and this line is probably not being calculated as you think:
CGPoint anchor = CGPointMake(1/contentViewLayer.bounds.size.width * (panelboundingBox.origin.x + panelboundingBox.size.width/2), 1/contentViewLayer.bounds.size.height * (contentViewLayer.bounds.size.height - (panelboundingBox.origin.y + panelboundingBox.size.height/2)));

You're likely to get 0 because of the 1/ at the start. C will do your multiplication before this division, resulting in values <1 - probably not what you're after. See this
You might find it more useful to breakdown your calculation so you know it's working in the right order (just use some temporary variables) - believe me it will help enormously in making your code easier to read (and debug) later. Or you could just use more brackets...
Hope this helps.
Comment: Both `*` and `/` have the same operator precedence (see your link). This actually means they will be (logically) executed from left to right.


field_view_field()

Question: I'm new to Drupal 8 and Twig and I can't figure out what the equivlent of
field_view_field is? So lets say I did this in Drupal 7 within a template file:
print render(field_view_field('node', $node, 'body', array(
    'type' => 'text_summary_or_trimmed',
    'label' => 'hidden',
)));

How would I output a custom field in drupal 8 template?
Answer: The php equivalent in drupal 8 is:
$build = $node->body->view('view_mode');
$output = \Drupal::service('renderer')->renderRoot($build);

In twig you don't need to render yourself, twig does this for you. So you can simply put the first line in a preprocess function:
function theme_preprocess_hook(&$variables) {
   $variables['body123'] = $node->body->view('view_mode');
}

and output in twig:
{{ body123 }}

Edit: I see you are using a field formatter, not a view mode, and use the preloaded node, so this is the preprocess for a node template:
function mytheme_preprocess_node(&$variables) {
       $variables['body123'] = $variables['node']->body->view(array('type' => 'text_summary_or_trimmed'));
}

Put this in the mytheme.theme file in the theme root directory.
More information is available in the change record.
Comment: Hi, thanks for the rpely, I'm getting a 'Fatal error: Call to a member function view() on null' however when I try to use it from my theme file
Comment: Got rid of that error I was putting it in bartiksub_preprocess_page but now not getting anything back
Comment: There's a small bug in the preprocess code (magic `$node` var). If it's like D7 you should find that in `$variables['node']`
Comment: You have the load $node first. If you use the node that is preloaded, then you can use `$variables['node']` in preprocess.
Comment: Hi, thanks, I'm not totally following, so you mean I need to do: theme_preprocess_hook($node, &$variables) ?
Comment: You did not mention it, is your twig a node template? Then you have to put a `mytheme_preprocess_node(&$variables)` in `your mytheme.theme` file in the root directory of your theme. In a node preprocess function the node is preloaded in `$variables['node'] and you can use the last code example in my answer.
Comment: Hi yeah it's node template. Ok cool I will try that tomorrow! Thanks for your help

field_view_field()


Common session among few websites on different domains

Question: I want to make few webservices, all of them will require login/pass authorization. I want to keep them all sync (one login, one password to all services), but also I want to share session between them.
If user is log in to service A, and open service B its automatically log in to this same account on service B like in service A.
How this is usually implemented?
Comment: What webserver are you using this with?
Comment: Can this be accomplished with ISA/IIS?
Answer: I would consider a database to support the sessions.
You could have a database record that holds key session information. If the database supports BLOB fields you could even hold more complex session data.
The record would have a "cookie thing" that the web service requests would present, the service implementation code would take that "cookie thing" and look in the database table(s) to see if a login event had correctly occurred recently.
(I say "cookie thing" because if it is a webservice it may not actually be a browser coming in).
Answer: This is called a distributed session, implementations vary per webserver.
For Tomcat: http://tomcat.apache.org/tomcat-6.0-doc/cluster-howto.html
For WebSphere: http://pic.dhe.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=%2Fcom.ibm.websphere.nd.iseries.doc%2Finfo%2Fiseriesnd%2Fae%2Fcprs_persistent_sessions.html
You can also store persisted variable in a database, which may be easier in your case.


3d projection Axis inversion problem (Java/Processing)

Question: Brief introduction: Unfortunately I always had problems with math and was never good at it. I'm currently trying to combine math with my knowledge and my passion for programming. In linear algebra, we now have topics of matrix multiplication and 3D projection, which sounds more interesting to me as an enthusiastic programmer than the whole thing with abstract number theories. So I set myself the goal of programming a small 3D game in Processing (Java). My first success was to rotate a Cube in 3 dimensions and had no problems with that.

What I want: After that however I wanted to have a camera perspective for a three-dimensional space. I took the 3D projection matrix from here: Mathematical Formula
The issue: I noticed that when I rotate the camera, the projection (the box in this case) flips horizontally and vertically as seen in the video here. What is happening (timestamp 0:14) and how can I fix it?
This is my code:
import java.util.Arrays;

PVector[] points;

PVector cam, cam_angle, point;

float angle = 0.0;

void setup() {
  //fullScreen();

  size(1000,400);
  noCursor();

  cam = point = new PVector(0, 0, -1000);
  cam_angle = new PVector(0,0,0);

  points = new PVector[] {
    new PVector(-100, -100, -100),
    new PVector(-100, -100, 100),
    new PVector(-100, 100, -100),
    new PVector(-100, 100, 100),
    new PVector( 100, -100, -100),
    new PVector( 100, -100, 100),
    new PVector( 100, 100, -100),
    new PVector( 100, 100, 100),
  };

}

PVector Rotate2d(PVector p, float a) {
  // a = angle

  float[][] m2 = {
    {cos(a), -sin(a)},
    {sin(a), cos(a)}
  };

  float[][] rotated = matmul(m2, new float[][] {
    { p.x },
    { p.y }
    });

  return new PVector(rotated[0][0], rotated[1][0]);
}

PVector Rotate3d(PVector p, float[][] m2) {

  float[][] rotated = matmul(m2, new float[][] {
    { p.x },
    { p.y },
    { p.z }
    });

  return new PVector(rotated[0][0], rotated[1][0], rotated[2][0]);
}

PVector Rotate3d_x(PVector p, float a) {
  return Rotate3d(p,
    new float[][] {
    {1, 0, 0},
    {0, cos(a), -sin(a)},
    {0, sin(a), cos(a)}
    });
};

PVector Rotate3d_y(PVector p, float a) {
  return Rotate3d(p,
    new float[][] {
    {cos(a), 0, sin(a)},
    {0, 1, 0},
    {-sin(a), 0, cos(a)}
    });
}

PVector Rotate3d_z(PVector p, float a) {
  return Rotate3d(p,
    new float[][] {
    {cos(a), -sin(a), 0},
    {sin(a), cos(a), 0},
    {0, 0, 1}
    });
}

PVector Rotate3d(PVector p, PVector a) {
  return Rotate3d_z( Rotate3d_y(Rotate3d_x(p, a.x), a.y), a.z );
}

PVector applyPerspective(PVector p) {
   PVector c = cam;
   PVector co = cam_angle;
   PVector e =  new PVector(0, 0, 100);
  // c = camera position
  // co = camera orientation / camera rotation
  // e = displays surface pos relative to camera pinhole c

  // dx, dy, dz     https://en.wikipedia.org/wiki/3D_projection   :   Mathematical Formula
  float[][] dxyz = matmul(
    matmul(new float[][]{
    {1, 0, 0},
    {0, cos(co.x), sin(co.x)},
    {0, -sin(co.x), cos(co.x)}
    }, new float[][]{
      {cos(co.y), 0, -sin(co.y)},
      {0, 1, 0},
      {sin(co.y), 0, cos(co.y)}
    }),

    matmul(new float[][]{
      {cos(co.z), sin(co.z), 0},
      {-sin(co.z), cos(co.z), 0},
      {0, 0, 1}
    }, new float[][]{
      {p.x - c.x},
      {p.y - c.y},
      {p.z - c.z},
    }));

  PVector d = new PVector(dxyz[0][0], dxyz[1][0], dxyz[2][0]);

  return new PVector((e.z/d.z)*d.x+e.x, (e.z/d.z)*d.y+e.y);
}

// Matrixmultiplikation
float[][] matmul(float[][] m1, float[][] m2) {

  int cols_m1 = m1.length,
    rows_m1 = m1[0].length;

  int cols_m2 = m2.length,
    rows_m2 = m2[0].length;

  try {
    if (rows_m1 != cols_m2) throw new Exception("Rows of m1 must match Columns of m2!");
  }
  catch(Exception e) {
    println(e);
  }

  float[][] res = new float[cols_m2][rows_m2];

  for (int c=0; c < cols_m1; c++) {

    for (int r2=0; r2 < rows_m2; r2++) {

      float sum = 0;
      float[] buf = new float[rows_m1];

      // Multiply rows of m1 with columns of m2 and store in buf
      for (int r=0; r < rows_m1; r++) {
        buf[r] = m1[c][r]* m2[r][r2];
      }

      // Add up all entries into sum
      for (float entry : buf) {
        sum += entry;
      }

      res[c][r2] = sum;
    }
  }

  return res;
}

void draw() {
  cam_angle = new PVector(0.01*(mouseY-width/2), 0.01*(mouseX-height/2), 0);

  background(255);
  translate(width/2, height/2);
  strokeWeight(1);
  fill(0);

  PVector[] points_projected = new PVector[points.length];

  for (int i=0; i < points.length; i++) {
    points_projected[i] =   applyPerspective(points[i]);
  }

  for (int i=0; i < points_projected.length; i++) {
    for (int a=0; a < points_projected.length; a++) {
      // Alle Punkte verbinden
      line(points_projected[i].x, points_projected[i].y, points_projected[a].x, points_projected[a].y);
    }
  }
}

void keyPressed() {
  if (key == 'w') {
    cam.add(Rotate3d(new PVector(0, 0, -20), cam_angle));
  }

  if (key == 'a') {
    cam.add(Rotate3d(new PVector(20, 0, 0), cam_angle));

  }

  if (key == 's') {
    cam.add(Rotate3d(new PVector(0, 0, 20), cam_angle));

  }

  if (key == 'd') {
   cam.add(Rotate3d(new PVector(-20, 0, 0), cam_angle));

  }
}

I also tried changing the values for
// e = displays surface position relative to camera pinhole c
PVector e = new PVector(0, 0, 1000);

around, which didn't help either.
Comment: There are functions in Processing that could simplify some of these tasks: [`camera()`](https://processing.org/reference/camera_.html), [`perspective()`](https://processing.org/reference/perspective_.html) to set projection, [`PMatrix3D`](https://processing.github.io/processing-javadocs/core/processing/core/PMatrix3D.html) to do the matrix to matrix / vector to matrix mulitplication, etc. and PApplet exposes PGraphics buffer `g` which with the `P3D` renderer has handy properties such as https://processing.github.io/processing-javadocs/core/processing/opengl/PGraphicsOpenGL.html#modelview ...
Comment: https://processing.github.io/processing-javadocs/core/processing/opengl/PGraphicsOpenGL.html#camera , https://processing.github.io/processing-javadocs/core/processing/opengl/PGraphicsOpenGL.html#projection though my hunch is you want to familiar yourself with linear albgebra / 3D Math, hence writing your own mini engine. The above may come in handy later on (hence why this is a comment and not an answer).
Answer: The perspective projection formulas, x / z and y / z are valid only when z > 0. If z < 0, it gets flipped: -x / abs(z) and -y / abs(z). So, in case any portions of the model can go to the backside of camera by rotation, you need to clip only valid parts (z > 0) prior to applying perspective projection.
For example, minimal near-plane clipping for the wireframe model can be :
void draw()
{

     :

    //PVector[] points_projected = new PVector[points.length];
    PVector[] points_view = new PVector[points.length];

    for (int i = 0; i < points.length; i++)
    {
        //points_projected[i] = applyPerspective(points[i]);
        points_view[i] = applyViewTransform(points[i]);
    }

    float nearPlane = 1.0F;

    for (int i = 0; i < points_view.length; i++)
    {
        for (int a = 0; a < points_view.length; a++)
        {
            // Alle Punkte verbinden
            if (i == a) continue;
            PVector p0 = points_view[i];
            PVector p1 = points_view[a];
            switch (((p0.z >= nearPlane) ? 1 : 0) | ((p1.z >= nearPlane) ? 2 : 0))
            {
                case 0: // Both ends are in back of camera.
                    continue;
                case 3: // Both ends are in front of camera.
                    break;
                case 1: // p0.z >= nearPlane && p1.z < nearPlane
                    p1 = PVector.lerp(p0, p1, (p0.z - nearPlane) / (p0.z - p1.z));
                    break;
                case 2: // p1.z >= nearPlane && p0.z < nearPlane
                    p0 = PVector.lerp(p1, p0, (p1.z - nearPlane) / (p1.z - p0.z));
                    break;
            }

            //line(points_projected[i].x, points_projected[i].y, points_projected[a].x, points_projected[a].y);

            PVector[] points_projected = {applyPerspectiveTransform(p0), applyPerspectiveTransform(p1)};
            line(points_projected[0].x, points_projected[0].y, points_projected[1].x, points_projected[1].y);

        }
    }
}

Where new functions, applyViewTransform() and applyPerspectiveTransform() were made by splitting applyPerspective() function as follows;

applyViewTransform(): Transform from world-space to camera-space.
applyPerspectiveTransform(): Perspective transform from 3d-space to 2d-screen-space.

.
PVector applyPerspective(PVector p)
{
    PVector d = applyViewTransform(p);
    return applyPerspectiveTransform(d);
}

PVector applyViewTransform(PVector p)
{

    PVector c = cam;
    PVector co = cam_angle;
    //PVector e = new PVector(0, 0, 100);
    // c = camera position
    // co = camera orientation / camera rotation

    // dx, dy, dz     https://en.wikipedia.org/wiki/3D_projection   :   Mathematical Formula
    float[][] dxyz = matmul(
            matmul(new float[][]{
                    {1, 0, 0},
                    {0, cos(co.x), sin(co.x)},
                    {0, -sin(co.x), cos(co.x)}
            }, new float[][]{
                    {cos(co.y), 0, -sin(co.y)},
                    {0, 1, 0},
                    {sin(co.y), 0, cos(co.y)}
            }),

            matmul(new float[][]{
                    {cos(co.z), sin(co.z), 0},
                    {-sin(co.z), cos(co.z), 0},
                    {0, 0, 1}
            }, new float[][]{
                    {p.x - c.x},
                    {p.y - c.y},
                    {p.z - c.z},
            }));

    PVector d = new PVector(dxyz[0][0], dxyz[1][0], dxyz[2][0]);
    return d;
}

PVector applyPerspectiveTransform(PVector d)
{
    PVector e = new PVector(0, 0, 100);
    // e = displays surface pos relative to camera pinhole c
    return new PVector((e.z / d.z) * d.x + e.x, (e.z / d.z) * d.y + e.y);
}


Why won't my xgBoost regressor predict above a certain value, even though it sees higher in training?

Question: I have created my first xgboost regressor. I input some self collected data, which I scale using sklearn's standardScaler. The model is trained on approximately 25,000 samples, and then tested on approximately 7000 examples, which are entirely separate from my training set.
In both the training and test set, the maximum y-label seen is 12. However, my xgboost regressor won't predict a value above approximately 6. See this example of my results:

My question is: What might be causing this? I have tried changing the parameters of the xgboost regressor, changing which factor I input, as well as trying sklearn's  gradientBoostingRegressor. The result is broadly the same whatever I try, which leads me to believe that there is something I don't understand about the process I  am using. I would really appreciate any advice on why this might be occurring, and what I might be able to do to rectify my problem. Thanks in advance.
Answer: I'm about to do something ... possibly dumb.
Here is your image with some "annotations":

In the top-slice the predicted is about the same as the mean of the measured.  There is lots of hand-waving to be had: it is a skewed slice so the right side is sparse, what is a bin-size, etcetera.
The point here is that the CART, the "atom" of both the RandomForest and GradientBoostedMachine performs "averaging" over the leaf for the predictor output.  This means the prediction is going to try very hard to be inside of the training data.  How "inside" it is depends on the data and the model parameters.
See also: some crazy dude making sketches about Random Forests.
Comment: I can somewhat understand what you want to say and I think you are right (I thought the same) but this exposition is quite unclear... (+1 cause you are probably right but yeah... too raw.)
Comment: @usεr11852 - I will try to improve.
Comment: (sorry forgot to upvote originally)


Can vocal range extrema be reached by a lot of practice?

Question: Wikipedia lists the world records and extremes of the vocal range,
can extrema be reached by a lot of practice or were they born with that?
Answer: Overall vocal type (e.g. soprano vs contralto or tenor vs bass) seems to be what you were born with and http://en.wikipedia.org/wiki/Voice_type#Classifying_singers warns of the dangers of misclassification of vocal type, and by implication, attempting to sing at the extremes of one's natural range.
Practice is certainly required to reach the expected range of one's natural vocal type and even then, I think it's easier to extend upward than downward. My own comfortable range without practice used to be G2 to C4 or D4 but when I was regularly singing in a choir was more like F2 to F4 or G4. It would likely have been dangerous to go higher and physically impossible to go lower.
I would think practice should be more about increasing tessitura than absolute range. However, my experience is entirely as a chorist and not as a solo singer.
Comment: This makes sense, unless your vocal chords were extended it would definitely be difficult to go much lower than your natural range.
Comment: I agree, the choice between good tessitura and a damaged voice is quickly made. If I think about it [Greg Pritchard](http://www.youtube.com/watch?v=EeL-G4oX06Q#at=120) is probably jumping from the lowest end of his (extended) vocal range to the highest, he has been practicing since his childhood and would probably also damage his voice beyond that point...


Onclick chama função 2 vezes após de alterar valor no modo desenvolvedor browser

Question: Segue o código:
<button onclick="myFunction(1)">Meu botão</button>

JSFiddle: https://jsfiddle.net/43mt9og8/
Qualquer pessoa pode alterar valor usando F12.

Mudar número myFunction(1) para myFunction(2), e depois clicar botão, chama a função javascript 2 vezes.
Cada vez que muda o número, vai gravando em algum lugar.(Se ele mudar 50 vezes, vai chamar a função com 50 vezes)
Existe maneira antes de chamar a função, verificar quantos números gravados ?
Comment: Código do lado cliente (neste caso javascript) está sempre à mercê de clientes "curiosos", podes dificultar, mas não podes evitar. Podes dificultar por exemplo tirando o atributo "onclick" do html, assim não fica tão visivel. Ex de brincar com o codigo do lado cliente no google: https://postimg.org/image/6xv0q6lml/
Comment: @Miguel, como o cara fez esse site ? http://www.galaxyrom.com/ , nem `f12` ou `botão mouse direito` não funciona.
Answer: Acho que você quer fazer é parar a propagação né, isso que eu entendi.

https://stackoverflow.com/questions/38569422/how-to-stop-event-propagation-on-onclick-event-in-html-attribute

exemplo:

no seu caso ficaria assim:
<button onclick="(function(e) { e.preventDefault(); e.stopPropagation(); myFunction(1); })">Meu botão</button>

Answer: Olá, se a sua preocupação é que os usuários não alterem seu código javascript, você precisará deum código como o abaixo. E se possível separe o arquivo javascript do arquivo html.
<button id="btnId">Meu botão</button>

Comment: Oi @Bruno Gerotto, nessa caso não dá, pois cada botão tem seu valor aleatória.
Comment: Como são gerados esses valores aleatórios dos botões?


How to run a jar file in AIX as a service which will auto restart if crashed?

Question: I have several jar files which I want to run as services on AIX. The service must auto restart if it crashes/ends. How can I achieve this?
I have a shell script which is like this
(
    until java -jar Test.jar; do
        echo "Test Service crashed with exit code $?.  Respawning... " >&2
        sleep 5
    done
)

This works but I want to know if there is a better way to do this? In case machine is rebooted for some reason, the script has to be run manually. I am not an expert on Linux or AIX.
Comment: In Unix these are "demons".   You will need root access to autostart after reboot.
Answer: You can check this page about autostart/restart service/daemon in AIX

inittab entries
Let's look at a entry for inittab that runs a script. Suppose, we want
  to run a script that sends an email to system administrators stating
  that the box is available when the system come up.
The entry for inittab is shown below:
mailout:2:once:/usr/local/bin/mailout > / dev/null 2>&1 #mail users
The above entry can be summarized as follows:
mailout: The unique identifier

2: Run this when the system reaches runlevel two (the default)
      once: Run the script and do not wait for its termination; init will carry on processing inittab. Iif the process fails, init will not
  attempt to rerun it.
      /usr/local/bin/mailout: The full path and script name of the command to run; notice that the output is thrown away to /dev/dull. We
  end with a '#' comment on what the script does.
For completeness, here is the script in question:

!/bin/sh
#mailout
/usr/sbin/sendmail ‑t <<mayday
From: hostname
To: rs6admins
Subject: hostname P‑Series is up
The AIX hostname is now up, please check services.
.
mayday


Re-Training spaCy's NER v1.8.2 - Training Volume and Mix of Entity Types

Question: I'm in the process of (re-) training spaCy's Named Entity Recognizer and have a couple of doubts that I hope a more experienced researcher/practitioner can help me figure out:

If a few hundred examples are considered 'a good starting point', then what would be a reasonable number to aim for? Is 100 000 entity/label excessive?
If I introduce a new label, is it best if the number of the entities of that labeled are roughly the same (balanced) during training?
Regarding the mixing in 'examples of other entity types':

do I just add random known categories/labels to my training set eg: ('The Business Standard published in its recent issue on crude oil and natural gas ...', [(4,21, 'ORG')], )?
can I use the same text for various labels? e.g. ('The Business Standard published in its recent issue on crude oil and natural gas ...', [(55,64, 'COMMODITY')], )?
on a similar note let's assume I want spaCyto also recognize a second COMMODITY could I then just use the same sentence and label a different region e.g. ('The Business Standard published in its recent issue on crude oil and natural gas ...', [(69,80, 'COMMODITY')], )? Is that how it's supposed to be done?
what ratio between new and other (old) labels is considered reasonable

Thanks
PS I'm working with Python2.7 in Ubuntu 16.04 using spaCy 1.8.2
Comment: hey, did you figure it out for your dataset and problem ? Can you please let us know your understanding ?
Comment: @randomSampling I have added the (only) answer below in May last year that summarize the findings of my research into the topic. You would need to go into a bit more detail about what exactly you're asking for me to give you a more detailed response. Also note that this question and answer related to spacy 1.8, spacy >= 2 has fairly detailed documentation for training and extended NER.
Answer: For a full answer by Matthew Honnibal check out issue 1054 on spaCy's github page. Below are the most important points as they relate to my questions:

Question(Q) 1: If a few hundred examples are considered 'a good starting point', then what would be a reasonable number to aim for? Is 100 000 entity/label excessive?

Answer(A): Every machine learning problem will have a different examples/accuracy curve. You can get an idea for this by training with less data than you have, and seeing what the curve looks like. If you have 1,000 examples, then try training with 500, 750, etc, and see how that affects your accuracy.

Q 2: If I introduce a new label, is it best if the number of the entities of that label are roughly the same (balanced) during training?

A: There's trade-off between making the gradients too sparse, and making the learning problem too unrepresentative of what the actual examples will look like.

Q 3: Regarding the mixing in 'examples of other entity types':

do I just add random known categories/labels to my training set:

A: No, one should annotate all the entities in that text, so the example above: ('The Business Standard published in its recent issue on crude oil and natural gas ...', [(4,21, 'ORG')], ) should be ('The Business Standard published in its recent issue on crude oil and natural gas ...', [(4,21, 'ORG'), (55,64, 'COMMODITY'), (69,80, 'COMMODITY')], )

can I use the same text for various labels?:

A: Not in the way the examples were given. See previous answer.

what ratio between new and other (old) labels is considered reasonable?:

A: See answer Q 2.

PS: Double citations are direct quotes from the github issue answer.
Comment: I keep this question open. In case someone with more practical experience wants to weigh in.
Comment: better practical response is needed
Comment: Accepted only existing answer, after after leaving it open for 3 years. Please note that spacy has moved on to newer and better ways... https://spacy.io/


Calculation the location of Ghost Ball

Question: Regarding to scheme as follows, when i move Guiding Line (Purple Colored), Ball A (Ghost) will slide around Ball B on red Axis. For this reason, i need to find β angle to calculate the exact location of the Ball A (Ghost) moving around Ball B.
Ball A can never proceed behind of Ball B that's why max. positions should be tangent to Ball B. My constants are α (Guiding Line angle), da (distance of Ball A center to edge of Ball B) and r (Ball radius). (xa, ya) & (xb, yb) center coordinates of Ball A and Ball B are known. β should be described in terms of following constants.
Explanatory scheme
Comment: How does the Guiding Line guide Ball A (Ghost)?
Comment: Now its not Guiding. When i move guiding line, it generates the alpha angle value. Moreover, i know da and r values, that's why i want to calculate Beta angle to calculate the exact location of Ghost Ball.
Comment: In addition, Ball A and Ball B center coordinates are known so, the issue is to find out Beta angle.
Comment: You may want to proof read your question. "Ball A can never proceed behind of Ball A" makes no sense. Also you might redo the picture with the words in darker colors. Yellow on a white background is almost unreadable. "that's why max. positions should be tangent to Ball B" What should be tangent to Ball B?
Comment: For the record, $\alpha$ is not a constant. It changes with the position of the ghost ball. That makes it a variable. But it is a known variable.
Answer: If I understand correctly, you have an isosceles triangle (the angle "on top" is also $\beta$, where there's the description "Equals $\beta$ in max.Position").
That is, the length of the Guiding Line is also $da + r$.
Thus by the Law of Sines
$$ \frac{ 2r }{ \sin \alpha} = \frac{ da + r }{ \sin\beta } \implies \sin\beta = \frac{da + r}{ 2r } \sin\alpha \quad \text{, or}~~ \beta = \arcsin\bigl(\frac{da + r}{ 2r } \sin\alpha \bigr)$$
Seemingly this comes from a practical task so presumably all the numbers have values such that the arcsine (inverse of sine) can be taken without a hitch.
Comment: Call the angle that is not $\alpha$ or $\beta$, i.e., the one that equals $\beta$ in the max position, $\gamma$

Copying and pasting from Lee David Chung Lin's answer. (As Michael O'Donohue once said, plagiarism is the sincerest form of theft.)

$\frac{ 2r }{ \sin \alpha} = \frac{ da + r }{ \sin\gamma } \implies \sin\gamma = \frac{da + r}{ 2r } \sin\alpha \quad \text{, or}~~ \gamma = \arcsin\bigl(\frac{da + r}{ 2r } \sin\alpha \bigr)$

Then $\beta$ = 180 - $\alpha$ - $\arcsin\bigl(\frac{da + r}{ 2r } \sin\alpha \bigr)$
Comment: But that works only if the ghost ball is in his arbitrarily chosen maximum position. I interpreted the question as wanting a formula for $\beta$ for any position of the ghost ball.
Comment: @SteveB According to his description, the angle $\alpha$ is defined exactly to let the ghost ball be at the max position. Of course, maybe your reading is correct and I'm wrong (I personally find his framing of the question kind of confusing).
Comment: @Steve thanks for your reply, for the max. position, i have tried the formula with following values, α=23.0739, da=200, r=50; it is resulted as β=78.463 which is correct, unfortunately when i have tried for the α=18.3573 value, β is resulted as 109.7037 but it must be 33.5816. Finally this angle is narrower than α=23.0739, β value must be less than 78.463.
Comment: Yeah, I failed to account for the fact that $\gamma$ will be obtuse once the ghost ball moves forward enough, specifically for $\alpha$ < 21.8. When $\alpha$ is smaller than that then $\gamma$ = 180 - $\arcsin\bigl(\frac{da + r}{ 2r } \sin\alpha \bigr)$,
Comment: @SteveB, thanks for your clarification, now everything is ok. I just want to ask you that how you have calculated the threshold value for α as 21.8?
Comment: Sorry about the late reply. My motherboard died. The cutoff angle should be arcsin(2r/(da+r)), i.e., it should be the value of alpha when gamma is 90 degrees.

Calculation the location of Ghost Ball


Integrate readline's kill-ring and the X11 clipboard

Question: In my .zshrc, I use the following snippet to integrate the shell's clipboard and my primary X11 clipboard. Thanks to this integration, I can cut-and-paste text to and from emacs, firefox, and the terminal without having to use the mouse.
kill-line() { zle .kill-line ; echo -n $CUTBUFFER | xclip -i }
zle -N kill-line # bound on C-k

yank() { LBUFFER=$LBUFFER$(xclip -o) }
zle -N yank # bound on C-y

Note: I use this trick on mac os x as well (with pbcopy/pbpaste instead of xclip) and thanks to Synergy my two computers share a single clipboard. Neat. But it doesn't work with readline. And I find myself using readline quite often, for example in (i)python, in gdb, in ncftp...
So here comes my question: is there a way to integrate readline's clipboard with the-rest-of-the-world ?
Of course, I'm thinkging about some .inputrc wizardry here, but any insight/ideas would be welcome.
Comment: I'm not sure what you really want here but I found another tool like xclip
XSEL - http://www.vergenet.net/~conrad/software/xsel/ which seems more powerful
Comment: Thanks for sharing. Actually, what I'm after is a way to call a program like XSEL automatically from readline programs (e.g. bash) when I press Ctrl-K / Ctrl-Y. I guess this comes down to binding shell command to readline key combinations...
Comment: I'd suggest you change your `echo -n` to `print -rn --` (or `printf %s`) above
Answer: Bash 4.0 introduces some new functionality:

NEWS
The command assigned to a key sequence with `bind -x' now sets two new
  variables in the environment of the executed command:  READLINE_LINE_BUFFER
  and READLINE_POINT.  The command can change the current readline line
  and cursor position by modifying READLINE_LINE_BUFFER and READLINE_POINT,
  respectively.

The NEWS file seems to be inaccurate; READLINE_LINE (no _BUFFER) is what's documented elsewhere and actually works.
The following will simulate the behavior of Bash's existing Ctrl+(U|K|Y) but affecting the X selection, though I use Meta/Esc because I don't like overwriting existing functionality.
_xdiscard() {
    echo -n "${READLINE_LINE:0:$READLINE_POINT}" | xclip
    READLINE_LINE="${READLINE_LINE:$READLINE_POINT}"
    READLINE_POINT=0
}
_xkill() {
    echo -n "${READLINE_LINE:$READLINE_POINT}" | xclip
    READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}"
}
_xyank() {
    READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$(xclip -o)${READLINE_LINE:$READLINE_POINT}"
}
bind -m emacs -x '"\eu": _xdiscard'
bind -m emacs -x '"\ek": _xkill'
bind -m emacs -x '"\ey": _xyank'

I still like screen more, but this better answers your question — as long as the only readline application you care about is Bash.
Comment: this is not working for me under bash 4.2.37. Those variables actually do not contain any value.
Comment: thanks ; this is indeed the kind of stuff I wanted. Unfortunately, I'm using zsh as a shell, so when I use readline it is often with _other_ programs than bash :-) I guess I'll have to get used to screen.
Comment: I up-voted this answer and user @Wei_Hu's modification below. See there.
Answer: Personally, I run everything inside GNU screen.  This gives me tons of functionality across all terminal-based programs, not just readline-based ones.  It has its own paste buffer(s), which are shared between all screens in your current session, and can read/write an exchange file (configurable with bufferfile).

A screen selection is made with Ctrl+A, [, <movement>, Space, <movement>;
copied to the paste buffer with Enter;
pasted with Ctrl+A, ];
replaced by the contents of the exchange file with Ctrl+A, <;
and written out to the exchange file with Ctrl+A, >.

Then all you need are little helpers to synchronize /tmp/screen-exchange and the X selection.  Something as simple as this would work.
# ~/.screenrc (or entered at C-a : command prompt)
bind '{' exec sh -c 'xclip -o>~/.screen_exchange'
bind '}' exec sh -c 'xclip -i ~/.screen_exchange'

Of course some nicer bindings and macros would make life easier (this requires C-a { C-a < C-a ] to paste X selection to the terminal), but it's completely up to you.
Answer: I'd like to propose the following _xyank() function based on ephemient's answer:
_xyank() {
    CLIP=$(xclip -o)
    COUNT=$(echo -n "$CLIP" | wc -c)
    READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${CLIP}${READLINE_LINE:$READLINE_POINT}"
    READLINE_POINT=$(($READLINE_POINT + $COUNT))
}

What this does is to move the cursor to the end of yanked text, making it more consistent with other built-in commands.
Comment: thanks as well, but again, my question was for non-bash readline applications :-)
Answer: As I wrote here, I found it can be nicer to have separate keybindings to populate the X clipboard, this is because I often use "kill" for text manipulation in Readline, and I don't want this to wipe out the clipboard each time.
When Readline ever gets the ability to have keybindings which trigger interactions with X, I'd recommend binding ^Xw and ^Xy to copy and paste.
I know this doesn't provide a solution to your question, but I don't have enough rep to say it in a comment.
As for extending Readline with the ability to bind keys to commands, I brought it up on the Readline mailing list, we'll see what Chet says:
https://lists.gnu.org/archive/html/bug-readline/2016-05/msg00002.html


Example using autoInitializePage in JQueryMobile

Question: I am looking for a simple example showing how to use JQueryMobile to render a page that has been dynamically assembled on the client side. $.mobile.autoInitialize used to work a few versions ago, and now we have $.mobile.autoInitializePage but I can't seem to figure out how to do it or find any examples of people that are using it.
My best effort (THIS NOW WORKS - was calling setting autoInitializePage too early before):

    <link class="jsbin" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" rel="stylesheet" type="text/css" />

Result here: http://jsbin.com/apocol/2
Mess around with it here: http://jsbin.com/apocol/2/edit#html
Comment: My problem was that I was setting $.mobile.autoInitializePage = false before loading jquery mobile. I have now fixed it above and it works.
Answer: I am not sure of the performance impact or other possible gotchas but I have used this successfully with dynamically updated pages when I want to force a complete refresh.
$("#MyPage").page("destroy").page();


Hook_Form_Alter Edit Existing Field Type

Question: I am using hook_form_alter in template.php to add datepicker to a field on an exposed view filter.
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == "views_exposed_form"){
    $form['data_2_op'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}

But all it is doing is adding another field into the form, rather than editing the field I have declared. Is there a way I can just add #type > 'date_popup' to an existing field?
EDIT:
Results after using...
drupal_set_message($form_id);  // print form ID to messages
  drupal_set_message(print_r($form, TRUE));  // print array to messages

views_exposed_form
Array (
  [#info] => Array (
    [filter-combine] => Array (
      [operator] => combine_op
      [value] => combine
      [label] => Search Event ID
      [description] =>
    )
[filter-data_2] => Array (
  [operator] => data_2_op
  [value] => data_2
  [label] => Choose Date [description] =>
  )
[filter-data] => Array (
  [value] => data
  [label] => Data field
  [description] => )
  [filter-data_1] => Array (
    [value] => data_1
    [label] => Data field
    [description] =>
    )
  )
[combine] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )
[data_2] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )

Answer: hook_form_alter work only with module implementation. So you have to use it in any module not in template.php
Use the above statement in module like
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == "views_exposed_form"){
    $form['data_2'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}

Comment: Its working, its just adding another field rather than editing it. If i add this as a module, will it automatically edit the field instead?
Comment: Yeah i used drupal_set_message(print_r($form, TRUE)); to print an array and got the field name from there. It inserts the new datepicker field in between the data_2_op field and its label, instead of just altering it. I'll try it in a module to see if it makes a difference. Thanks.
Comment: Nope, That didn't work, putting it into a custom module did the exact same thing that it did in the template.php file.
Comment: Just updated it, its the second field in the exposed filter that Im looking to change.
Comment: I don't know why, but it has suddenly started working! Im using the exact same code I had to begin with, and I had already flushed the cache a few times. Oh well, at least it works! Thanks for you help


terminating with uncaught exception of type NSException while making custom UIButton

Question: I want to make a custom button and give an input inside a selector inside the custom button class, but it give me an error massage. how can I fix it
I was test it in the playground since when I running to simulator the app is crash. this is the error show up in the playground

terminating with uncaught exception of type NSException

this is my code in playground
class customButton: UIButton {

let titleName: String
let selectorName: String

init(titleName: String, selectorName: String) {
    self.titleName = titleName
    self.selectorName = selectorName
    super.init(frame: .zero)

    self.setTitle(titleName, for: .normal)
    self.addTarget(self, action: Selector(selectorName), for: .touchUpInside)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

class viewController: UIViewController {

override func loadView() {
    super.loadView()

    let testButton = customButton(titleName: "Test", selectorName: "handleButton")
    testButton.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(testButton)
    testButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    testButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

func handleButton() {
    print("Pressed")
  }
}

new problem is

Cannot convert a value type of (viewController) -> () expected argument type UIViewController

I make a custom UIButton with target selector as an input, when I try to add input in the custom button it show in Xcode

Cannot convert value of type '(ProfileController) -> () -> (ProfileController)' to expected argument type 'UIViewController

this is my code in my ProfileController and my custom button
class CustomButton: UIButton {

let imageName: UIImage
let selectorName: String
let target: UIViewController

init(imageName: UIImage, selectorName: String, target: UIViewController) {
    self.imageName = imageName
    self.selectorName = selectorName
    self.target = target
    super.init(frame: .zero)

    self.setImage(imageName.withRenderingMode(.alwaysOriginal), for: .normal)
    self.addTarget(target, action: Selector(selectorName), for: .touchUpInside)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

class ProfileController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

let profileID = "profileID"

let profileImageView: UIImageView = {
    let iv = UIImageView()
    iv.image = #imageLiteral(resourceName: "581010.jpg-r_1280_720-f_jpg-q_x-xxyxx").withRenderingMode(.alwaysOriginal)
    iv.contentMode = .scaleAspectFill
    iv.clipsToBounds = true
    return iv
}()

let pickerImage = CustomButton(imageName: #imageLiteral(resourceName: "user-6"), selectorName: "handleImagePicker", target: self) //this is the error message show up in the target: self

Comment: You are using self so you should use lazy declaration as  `lazy var pickerImage: CustomButton = {
        return CustomButton(imageName: #imageLiteral(resourceName: "user-6"), selectorName: "handleImagePicker", target: self)
    }()`
Comment: @Kamran maaaann you are a god I want to worship you hahaha, thank you again it works.
Answer: The app is crashing because in below line you have set target to self in customButton class
self.addTarget(self, action: Selector(selectorName), for: .touchUpInside)

and customButton class don' have method handleButton
handleButton is in viewcontroller so you have to set target to viewcontroller
so you have to make slight modification in your code as below
class customButton: UIButton {

let titleName: String
let selectorName: String
let ViewController:UIViewController

init(titleName: String, selectorName: String,ViewController:UIViewController) {
self.titleName = titleName
self.selectorName = selectorName
self.ViewController = ViewController
super.init(frame: .zero)

self.setTitle(titleName, for: .normal)
self.addTarget(ViewController, action: Selector(selectorName), for: .touchUpInside)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

class viewController: UIViewController {

override func loadView() {
super.loadView()

let testButton = customButton(titleName: "Test", selectorName: "handleButton",ViewController:self)
testButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(testButton)
testButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
testButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

func handleButton() {
print("Pressed")
 }
}

Comment: @Devil_Decoder it still error with the same message
Comment: @Devil_Decoder >libc++abi.dylib: terminating with uncaught exception of type NSException
Comment: @Devil_Decoder in playground the error is the comment I give to you, but In app the error is cannot convert a value type viewController expected argument UIViewController. since my viewController is a UIViewController and have UIImagePickerControllerDelegate, UINavigationControllerDelegate
Comment: @ferryawijayanto i have updated answer did you initialise viewcontroller in init method
Comment: @ferryawijayanto i have updated answer did you initialise viewcontroller in init method
Comment: @Devil_Decoder yes and still have the same error message
Comment: @Devil_Decoder thank you I know the problem, in just like the Kamran did the answer it miss the objc
Answer: You should remove the selector as an initializer argument. You should set the target wherever you are creating the button. Also you need to put @objc for handleButton to be called by the Selector. Your setup will look like this,
class customButton: UIButton {

    let titleName: String

    init(titleName: String) {
        self.titleName = titleName
        super.init(frame: .zero)

        self.setTitle(titleName, for: .normal)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class viewController: UIViewController {

override func loadView() {
    super.loadView()

    let testButton = customButton(titleName: "Test")
    testButton.translatesAutoresizingMaskIntoConstraints = false
    testButton.addTarget(self, action: Selector("handleButton"), for: .touchUpInside)
    view.addSubview(testButton)
    testButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    testButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

@objc func handleButton() {
    print("Pressed")
  }
}

In latest Swift, you should change Selector("handleButton") to #selector(handleButton)

If you want to persist with current implementation then you need to take the target argument in customButton initializer as below,
init(titleName: String, selectorName: String, target: UIViewController) {
    self.titleName = titleName
    self.selectorName = selectorName
    super.init(frame: .zero)

    self.setTitle(titleName, for: .normal)
    self.addTarget(target, action: Selector(selectorName), for: .touchUpInside)
}

Now you will pass the ViewController reference as this,
let testButton = customButton(titleName: "Test", selectorName: "handleButton", target: self)

And don't forget to mark the handleButton with objc as,
@objc func handleButton() {

Comment: it work only just adding using objc, without it the app crashed thank you
Comment: now I have new problems cannot convert value of type viewController expected UIViewController since my viewController have UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate.
Comment: I make a new question
Answer: Remove
self.addTarget(self, action: Selector(selectorName), for: .touchUpInside)

from customButton class. And Add
testButton.addTarget(self, action: Selector(handleButton), for: .touchUpInside)

in viewDidLoad() method.
Also add selector method in viewController class
@objc func handleButton() {
    print("Pressed")
}

Comment: so a target selector cannot give an input in custom class? @Viren_Malhan
Comment: It can. then you have to implement your selector in that class.
Comment: @VirenMalhan its not mendatory
Answer: This line will cause crash:
self.addTarget(self, action: Selector(selectorName), for: .touchUpInside)

In this line you are saying that customButton has a method named selectorName, But actually that method resides in viewController.
if you add this inside customButton class, then
class customButton: UIButton {

let titleName: String
let selectorName: String

  init(titleName: String, selectorName: String) {
    self.titleName = titleName
    self.selectorName = selectorName
    super.init(frame: .zero)

    self.setTitle(titleName, for: .normal)
    self.addTarget(self, action: Selector("handleTap"), for: .touchUpInside)
  }

   required init?(coder aDecoder: NSCoder) {
     fatalError("init(coder:) has not been implemented")
   }
   @objc func handleButton() {
      print("Pressed")
   }
}

OR put add target in ViewController class like,
let testButton = customButton(titleName: "Test", selectorName: "handleButton")
testButton.addTarget(self, action: Selector("handleButton"), for: .touchUpInside)

Answer: In Swift 4.2,
Please use,
self.addTarget(self, action: #selector(handleButton), for: .touchUpInside)

And for handleButton, Obj-C runtime is required in order to look up the method implementation for a given selector,
@objc func handleButton() {
  print("handle button selected")
}

Comment: the selectorName inside #selector is a function, Xcode is complaining. because the selectorName is type of a string. is there a type of function?
Comment: you should use #selector(handleButton), updated the answer


Check which face of a rectangular prism is colliding

Question: I am making a 3D physics engine with simple rectangular prism collisions, with no rotation.
Right now, I am doing collision very simply: (see this website for a nice graphic and more info)
let a and b be rectangular prisms
collide if:
   (min x of a <= max x of b AND max x of a >= min x of b) AND
   (min y of a <= max y of b AND max y of a >= min y of b) AND
   (min z of a <= max z of b AND max z of a >= min z of b)

This works well, but I need to know which surface the rectangles collided on to figure out how to bounce.
Is there a formula to detect which face two rectangular prisms collided on?
Answer: If two rectangular prisms collide (i.e. intersect), it would be ambiguous as to which faces caused the collision:

You would need to know the vectors of the objects in order to determine the faces.
Answer: In my scenario, I realized that the face that caused the collision would be the face with the least intersection.
This is because after the other two axes are set, when trying to make the last axis overlap, it will stop before they can get closer than touching.
Therefore, the axis where a max == b min is the axis where the face is.
Checking which is up or down/left or right is as simple as checking if one object is above or below/left or right of the other object.
Of course, this solution will only work for my scenario with no rotation.


Length of inverse-matrix vector product.

Question: Assume that I have an invertible matrix $A$ and a vector $v$. Let $\|Av\| = k$. Can we deduce the value of $\|A^{-1}v\|$? My guts tell me that $\|A^{-1}v\|$ = $\frac{1}{k}$, but I haven't been able to prove it.
Comment: Why do you mean by deduce? Do you mean knowing **only** $k$ to deduce the value of $\|A^{-1}v\|$?
Comment: @copper.hat I don't think it suggests that the hypothesis is true. I selected it because it lets me deduce the simplest example to disprove my hypothesis: Choose $A$ to be the identity matrix, and let $v$ be an arbitrary vector s.t. $\|v\| \neq 1$. However, I do see that it doesn't directly provide a counterexample. I'm not very familiar with the conventions on this site for choosing the best answer -- should I choose the answer that directly gives a counterexample?
Comment: Oops, ignore my now deleted comment. For some reason I had it in my head that $v$ was a unit vector.
Comment: Coincidentally, I actually meant to pose the question with the requirement that $v$ is a unit vector, but forgot to mention it :) However, a quick experiment in MATLAB convinced that the hypothesis doesn't hold in that case either. I probably should've tried that earlier...
Answer: Take $A=\operatorname{diag} (1,2)$, $v=(1,1)^T$, $w=(0,\sqrt{5})^T$, then
$\|Av\| = \|Aw\| = \sqrt{5}$, but
$\|A^{-1} v\| = \sqrt{5 \over 4}$, $\|A^{-1}w\| = \sqrt{5}$.
Answer: Let $A$ be the identity matrix for example.  You would have $\|v\|=k$ and your gut feeling would tell you $\|v\|=1/k$.
$k$ and $1/k$ are not equal (in general).
Another example would be a rotation matrix, this won't change the length of $v$, the inverse matrix won't change the length either.


When is a graph balanced bipartite?

Question: I have a quick question: is there any sufficient condition (theorem, lemma, proposition,...)

to show that a graph (vertices do not have the same degree) is balanced bipartite?
Answer: No odd cycles (which guarantees that the graph is bipartite) and regular (aka, all vertices have the same degree).
Comment: Well, if the graph is bipartite (which is one condition you have to check) and it has a perfect matching, then it will also be balanced. So you could construct such conditions.
Comment: What if all of vertices do not have the same degree?
Comment: Then, it may or may not be balanced. This was just a sufficient condition. Btw, if you are looking for an algorithm to determine whether a graph is balanced bipartite, then that's easy. Are you looking for such an algorithm?
Comment: Well, to be more precise, I had a bipartite graph $G$ such that its  vertices do not have the same degree. I'm looking for a condition that once it is given, the graph $G$ will be balanced bipartite. I wonder that it may relates to Hall's Marriage Theorem.
Comment: Okay. So now I need some tools to verify whether my graph has a perfect matching or not. Can you suggest any good one?
Comment: You already mentioned Hall's Theorem. If you are looking for "tools" (as in algorithms), then you just as might use an algorithm to answer your question directly, right?
Comment: I look for a "condition" which does not need to be a practical algorithm. Anyway, I would like to see your algorithm. It somehow helps me getting closer the desired answer.
Comment: To [check if a graph is bipartite](http://www.geeksforgeeks.org/bipartite-graph/) you basically perform a BFS and color the vertices. If the graph is bipartite, checking if it is balanced is straightforward.
Answer: One sufficient condition is that the graph has two vertices.
If instead you want a necessary and sufficient condition, then you will not find any efficient one, because it can be used to solve bin packing which is NP-hard.
Answer: You can always check if all cycles are even, and if so check if each partition has the same size by partitioning into vertices at even and odd distances from a vertex.
But to efficiently check whether a graph is balanced bipartite, I would prefer to do a greedy 2-coloring and check if $\#$vertices with same color are equal. With efficient data structures (adj lists) this can be done in $O(n+m)$ time.
EDIT: This works for connected graphs only, else as user21820 points out, is NP hard. It is kind of surprising to see that adding a simple constraint makes the problem very difficult (from linear).
Comment: Note that this is also only a sufficient condition since there may be unconnected components.

When is a graph balanced bipartite?


A family of polynomials for the Taylor expansion of the Lambert-w function

Question: This is an attempt to derive the Taylor expansion at $0$ of the Lambert $w$ function (the branch containing the origin of the solution $w$ to the functional equation  $w(x)e^{w(x)}=x$) without resorting to Lagrange inversion formula, nor complex analysis.
Let the superscript $^{(n)}$, (superscript $^{'}$) denote the $n$-th derivative with respect to $x$ (to $w$ respectively) . It is easy to see that \begin{align*} w^{(1)}=\frac{w}{x}\frac{1}{w+1} .\end{align*}
Then by iterating the derivation process we obtain
\begin{align*} &w^{(2)}=-\frac{w^2}{x^2}\frac{w+2}{(w+1)^3} \\
&w^{(3)}=\frac{w^3}{x^3}\frac{2w^2+8w+9}{(w+1)^5}\\
&\qquad\qquad.....
\end{align*}
Now we start an induction process and we suppose that there is some polynomial $P_n$ such that
\begin{align*} &w^{(n)}=-\frac{(-w)^n}{x^n(w+1)^{2n-1}}P_n(w)
\end{align*}
After some algebra we see that these polynomials must obey the following recursion:

\begin{align*} P_{1}(w)&=1\\P_{n+1}(w)&=\big(n(w +3)-1\big)P_n(w)-(w+1)P_n^{'}(w). \end{align*}
What is the name of these polynomials?
How can it be shown that
$P_n(0)=n^{n-1}$?

First instances:
\begin{align*}
P_1(w)&= \color{red}{1}\\
P_2(w)&=w+\color{red}{2}\\
P_3(w)&=2w^2+8w+\color{red}{9}\\
P_4(w)&=6w^3+36w^2+79w+\color{red}{64}\\
P_5(w)&=24w^4+192w^3+622w^2+974w+\color{red}{625}\\
\end{align*}
Or consider the triangle of numbers $a_{n,k}$ obtained recursively, such that the entries in line $n$ are computed with three consecutive entries from line $n-1$ by
$$ a_{n,k}=n a_{n-1,k-1}+(3n-(k+1))a_{n-1,k}-(k+1)a_{n-1,k+1}$$
with initial conditions $ a_{n,-1}= 0$ , $ a_{0,0}= 1$ and $ a_{0,k}= 0$ for $k>0$.
This makes it clear that $a_{n,n}=n!$, but how could we obtained the closed form $a_{n,0}=(n+1)^n$ ?
Comment: http://oeis.org/A042977 "Triangle $T(n,k)$ read by rows: coefficients of a polynomial sequence occurring when calculating the n-th derivative of Lambert function $W$."
Comment: These polynomials also appear as factors of the expressions in Example 4.3 of Kruchinin, V., "Derivation of Bell Polynomials of the Second Kind" https://arxiv.org/abs/1104.5065
Answer: This answer does not fully address the question of how to compute an explicit formula from the recursion relation (though it indicates a reference which contains a starting point), and so is not a proper answer, but it is too long for a comment, and I expect it might still be useful.
It follows from a comment by Vladimir Kruchinin in OEIS A042977, "Triangle $T(n,k)$ read by rows: coefficients of a polynomial sequence occurring when calculating the $n$th derivative of Lambert function $W$" that $$\color{#df0000}{\boxed{P_n(w) = \sum_{m = 0}^n \left[ \sum_{j=0}^m {2 n + 1 \choose m - j} \sum_{k=0}^j (-1)^k \frac{(n+k+1)^{n+j}}{(j-k)! k!} \right] w^m}} .$$ See under the heading $\texttt{FORMULA}$, and NB that the expression in this answer differs from the one in OEIS entry by a factor of $(-1)^n$ to account for the formulation in the question. This expression can be deduced from Example 4.3 in Kruchinin's preprint "Derivation of Bell Polynomials of the Second Kind".
In particular, to compute the constant term of $P_n(w)$, we can evaluate the inner sum for $j = 0$. Both summations have only a single term, and it simplifies to the conjectured formula, $$\color{#df0000}{\boxed{P_n(0) = (n + 1)^n}} .$$
Comment: This is very relevant and useful, and since I requested for reference, I accept it as an answer; but I agree that it is not entirely satisfactory: the formula for $P_n(w)$ was obtained by making use of the Lambert w function. Given the recursion only, without any other contextual info,  would there be a proof that does not make use of Lambert w ?
Comment: I'm glad you found the answer useful! I don't know any general methods for solving recursion formulas of the form of yours. You might even formulate a new question asking just about methods for solving the recursion. (If you do this, I suggest you link to this question for context.)