What is the best introductory Bayesian statistics textbook?

Question: Which is the best introductory textbook for Bayesian statistics?
One book per answer, please.
Comment: In the replies, **please explain _why_ you are recommending a book** as "the best."
Comment: This is an old thread now, but I came back to +1 a new book "Statistical Rethinking. And in looking the higher-ranking answers in the thread, I think a key distinction hasn't been made: "introductory" for whom? A first course in statistics (that happens to have a Bayesian approach)? An introduction to Bayesian methods for someone with basic undergraduate (non-Bayesian) statistics classes? Or an introduction to Bayesian statistics for a practitioner of non-Bayesian statistics who has finally been persuaded that this Bayesian thing isn't a fad? Very different introductions.
Comment: How can there be more than one answer to a question question phrased like this?
Answer: John Kruschke released a book in mid 2011 called Doing Bayesian Data Analysis: A Tutorial with R and BUGS. (A second edition was released in Nov 2014: Doing Bayesian Data Analysis, Second Edition: A Tutorial with R, JAGS, and Stan.) It is truly introductory. If you want to walk from frequentist stats into Bayes though, especially with multilevel modelling, I recommend Gelman and Hill.
John Kruschke also has a website for the book that has all the examples in the book in BUGS and JAGS. His blog on Bayesian statistics also links in with the book.
Comment: I also vote for Kruschke's book. I've browsed most of the books listed in the answers and this is the one I found most clear. IMO, it is the most clear stats book I have read. It helps a lot that R code is available to match formulas with code. The author starts with very simple examples and builds on them. Very little background is needed. All reviews on Amazon are highly favorable. Hoff's book is my second favorite.
Comment: @Amir's suggestion is a duplicate of this. (The full title of the book is "Doing Bayesian Data Analysis: A Tutorial with R and BUGS".) As a truly introductory book, I've +1'd each.
Comment: updated the title and added a couple of related links.
Comment: Haha, I like the book cover:  "Why the happy puppies? (as if happy puppies needed justification!)"
Comment: My vote also goes to Kruschke's 2010 book. In trying to learn Bayesian statistics, I tried several of them, and this one hit the mark. Hard.
Comment: This is the best introductory book for Bayesian.
Comment: I read the first 8 chapters of this book based on this recommendation, and then I just hit a wall. This book has an odd mixture of writing like it's an introductory book, but then making sudden unexplained jumps in mathematics with no explanation that just leave you scratching your head. Statistical Rethinking, which is mentioned further down this page, does a *much* better job of helping to develop an intuition. You almost need to read it before trying to get through later chapters of Kruschke.
Answer: My favorite is "Bayesian Data Analysis" by Gelman, et al. (The pdf version is legally free since April 2020!)
Comment: I started a PhD in Statistics 9 months ago and to be honest Gelman's BDA is still above me, so I wouldn't call it an introductory text!
Comment: This is an introductory book for people who have a decent amount of statistical background already.
Comment: @naught101 so you downvote without knowing the book?
Comment: The first four or five chapters are truly introductory!  so belongs here.
Comment: @Shane, can you please to this answer explaining why it's your favourite?
Comment: @stucash that's an emotive approach to discussing a disagreement. I guess it depends what kind of introduction you need. When someone asks me for an introduction, the response is to point them to the most compact version of the math needed to actually do something in the area. If that looks like too much work, you then need to question what exactly you get from any approach which requires less work.
Comment: @conjectures Thanks for taking time to reply however I personally found your comment emotive as well. I do understand everyone has their own definition of being introductory but without required details in the answer and the original question, it is hard to say which version of "being introductory" should be applied in this context. That being said, I found naught101's version is as right as yours.
Comment: Gelman et al. is well-regarded but explictly intended for a graduate course. If you don't have substantial prior coursework in statistics, it is largely a waste.
Comment: @conjectures ok so others're lying.
Comment: Just wanted to add: "A good modern book on Baysian inference is Gelman et al. (1995)". The first edition of this book was recommended by the authors of The Elements of Statistical Learning.
Answer: Statistical Rethinking, has been released just a few weeks ago and hence I am still reading it, but I think is a very nice and fresh addition to the really introductory books about Bayesian Statistics. The author uses a similar approach as the one used by John Kruschke in his puppy books; very verbose, detailed explanations, nice pedagogical examples, he also uses a computational rather than mathematical approach.
Youtube lectures and other material is also available from here.
Code ported to Python/PyMC3
Comment: +1 I'm listening through the lectures now. He's very entertaining, and has a good approach. The book is excellent and takes you from basics to hierarchical models. It only assumes that the reader is somewhat scientific, has a reasonable grasp of mathematics (not including calculus) and has heard some things about statistics. It's the book I wish I'd had. The order he presents things in, and his system of asides is brilliant.
Comment: After going through the thread, I tried reading the first chapter of this book, and I found it very difficult as a _non-native English speaker_ and as a _non-scientist_. First I had to go through the words like _epistemology_, _idiosyncratic_, then there are long sentences, which I had to read twice/thrice to understand what tehy means literally (forget about the conclusion of those sentences). Then the very first example is about natural evolution, which sounded Greek to me: _number of sites, number of alleles, neutrality_. The book could be easy for a lot, but could be difficult for many
Comment: I hit a wall trying to work through Kruschke's book where he starting making some big leaps in logic that I just couldn't follow. Luckily, I came across Statistical Rethinking, which so far is the only book I've found that gives you a genuinely intuitive understanding of the topic.
Comment: Glad to see there's a link to the Python notebooks! I don't use R and would prefer to use my time to learn Bayesian inference instead of coding in R (for now!).
Comment: A second edition of this (superb) book will be coming out in [March 2020](https://elevanth.org/blog/2018/07/14/statistical-rethinking-edition-2-eta-2020/).
Comment: 2022 Kindle edition available on Amazon for $8 !!
Comment: the link is broken. I assume you're referring to Richard McElreath's book?
Answer: Sivia and Skilling, Data analysis: a Bayesian tutorial (2ed) 2006 246p 0198568320
books.goo:

Statistics lectures have been a source
  of much bewilderment and frustration
  for generations of students. This book
  attempts to remedy the situation by
  expounding a logical and unified
  approach to the whole subject of data
  analysis. This text is intended as a
  tutorial guide for senior
  undergraduates and research students
  in science and engineering ...

I don't know the other recommendations though.
Comment: This book it excellent. It's short and practical.
Comment: I think this is a much better *introductory* text than Gelman.
Comment: One of my favorites.
Answer: Another vote for Gelman et al., but a close second for me -- being of the learn-by-doing persuasion -- is Jim Albert's "Bayesian Computation with R".
Comment: Agree strongly. Both great books. Start with Bayesian Computation With R, then get Gelman et al.
Comment: Link is dead. Maybe this one? https://bayesball.github.io/bcwr/index.html
Answer: For an introduction, I would recommend Probabilistic Programming & Bayesian Methods for Hackers by Cam Davidson-Pilon, freely available online.
From its description:

An intro to Bayesian methods and probabilistic programming from a computation/understanding-first, mathematics-second point of view.

It's highly visual, cuts straight to the value and backfills gritty details later, has lots of examples, has interactive code (in IPython Notebook).
Comment: I thought this online book was hard to follow / poorly written.
Comment: I think this book is a fantastic intro for programmers to have a great first experience with bayesian stats
Comment: I think the book is fine.
Answer: I thoroughly recommend the entertaining polemic "Probability Theory: The Logic of Science" by E.T. Jaynes.
This is an introductory text in the sense of not requiring (and in fact preferring) no previous knowledge of statistics, but it does eventually employ fairly sophisticated mathematics. Compared to most of the other answers provided, this book is not nearly as practical or easy to digest, rather it provides the philosophical bedrock to why you would want to employ Bayesian methods, and why not to use frequentist approaches. It is introductory in a historical and philosophical, but not pedagogical way.
Comment: This is a brilliant book about Bayesian *thinking* rather than applying Bayesian methods.  I think this is a good companion text to something which goes more into how do Bayesian computations.
Comment: That's a good way of putting it. I think Sivia and Skilling is an ideal companion text for introducing the methods in practice (which has already been suggested in another answer).
Comment: Entertaining and polemic and original, for sure, but definitely not an introductory book.
Answer: Its focus isn't strictly on Bayesian statistics, so it lacks some methodology, but David MacKay's Information Theory, Inference, and Learning Algorithms made me intuitively grasp Bayesian statistics better than others - most do the how quite nicely, but I felt MacKay explained why better.
Comment: And it is available for free download at the authors page: http://www.inference.phy.cam.ac.uk/mackay/itila/book.html
Comment: Like Sivia, this is very nice if you have some physics background and can be rough if not.  Not a good guide to any kind of applied social statistics (for that use Gelman and Hill, or Gelman et al. above) but really *great* for prompting you to really think about the core issues.
Answer: I am an electrical engineer and not a statistician. I spent a lot of time to go through Gelman but I don't think one can refer to Gelman as introductory at all. My bayesian-guru professor from Carnegie Mellon agrees with me on this. having the minimum knowledge of statistics and R and Bugs(as the easy way to DO something with Bayesian stat)  Doing Bayesian Data Analysis: A Tutorial with R and BUGS  is an amazing start. You can compare all offered books easily by their book cover!
5 years later update: I want to add that perhaps one other major way of learning in a fast way(40 mins) is to go through the documentation of a Bayesian Net GUI based tool such as Netica2. It starts with basics, walks you through the steps of building a net based on a situation and data, and how to run your own questions back and forth to "get it!".
Comment: This is a duplicate of @rosser's answer above. As a truly introductory book, I've +1'd each.
Answer: The Gelman books are all excellent but not necessarily introductory in that they assume that you know some statistics already. Therefore they are an introduction to the Bayesian way of doing statistics rather than to statistics in general. I would still give them the thumbs up, however.
As an introductory statistics/econometrics book which takes a Bayesian perspective, I would recommend Gary Koop's Bayesian Econometrics.
Answer: "Bayesian Core: A Practical Approach to Computational Bayesian Statistics" by Marin and Robert, Springer-Verlag (2007).
"Why?": the author explain the why of the bayesian choice and the how very well. It's a practical book, but written by one of the finest bayesian thinkers alive. It's not exhaustive. Other books have that objective. It picks up a few topics that are relevant, useful, and illuminating the foundations.
About "choice": if you really want to delve into bayesian foundation, Xi'an' "The Bayesian Choice" is clear, deep,  essential.
Comment: @Xi'an and gappy, please explain *why* this book can be recommended.  For whom is it suitable?  In what sense is it "best"?
Comment: I do not want to fall into self-promotion. Bayesian Core is a self-contained entry to Bayesian inference for the most common models and to computational methods (R codes provided). It requires some background in probability theory that may be too much for some readers... (It works well with our 4th and 5th year students in France.)
Answer: I don't know why nobody has mentioned the very introductory book on Bayesian:

There's a free PDF version for the book. The book offers enough material for anyone who has very little experience in bayesian. It introduces the concept of prior distribution, posterior distribution, beta distribution etc.
Give it a go, it's free.
http://greenteapress.com/thinkbayes/
Comment: The 2nd Edition is out now. Free online with runnable Python notebooks: https://allendowney.github.io/ThinkBayes2/
Answer: My favourite first undergraduate text for bayesian statistics is by Bolstad, Introduction to Bayesian Statistics.  If you're looking for something graduate level, this will be too elementary, but for someone who is new to statistics this is ideal.
Answer: I have read some parts of A First Course in Bayesian Statistical Methods by Peter Hoff, and I found it easy to follow. (Example R-code is provided throughout the text)
Answer: Coming from non-statistical background I found Introduction to Applied Bayesian Statistics and Estimation for Social Scientists quite informative and easy to follow.
Answer: I quite like Markov Chain Monte Carlo: Stochastic Simulation for Bayesian Inference by Gamerman and Lopes.
Answer: If you're looking for an elementary text, i.e. one that doesn't have a calculus prerequisite, there's Don Berry's Statistics: A Bayesian Perspective.
Answer: I found an excellent introduction in Gelman and Hill (2007) Data Analysis Using Regression and Multilevel/Hierarchical Models. (Other comments mention it, but it deserves to get upvoted on its own.)
Answer: I've at least glanced at most of these on this list and none are as good as the new Bayesian Ideas and Data Analysis in my opinion.
Edit: It is easy to immediately begin doing Bayesian analysis while reading this book.  Not just model the mean from a Normal distribution with known variance, but actual data analysis after the first couple of chapters.  All code examples and data are on the book's website.   Covers a decent amount of theory but the focus is applications.  Lots of examples over a wide range of models.  Nice chapter on Bayesian Nonparametrics.  Winbugs, R, and SAS examples.  I prefer it over Doing Bayesian Data Analysis (I have both).  Most of the books on here (Gelman, Robert, ...) are not introductory in my opinion and unless you have someone to talk to you will probably be left with more questions then answers.  Albert's book does not cover enough material to feel comfortable analyzing data different from what is presented in the book (again my opinion).
Comment: "Good" in what sense?
Comment: Good point. Good as in best introductory Bayesian textbook.  I believe it to be 'better' than Bayesian Data Analysis with R by Albert and I found Bayesian Data Analysis by Gelman et al. to not suffice as an introduction.  After learning some Bayesian material however, it is a good reference.
Answer: Take a look at "The Bayesian Choice". It has the full package: foundations, applications and computation. Clearly written.
Comment: Would not only be a "Bayesian" but rather a "great choice", if the solution manual were vailable for self-study. It seems this is intended for university use only...
Answer: If I had to choose a single text for a beginner, it would be
<code>              Sivia DS and Skilling J (2006) book (see below).
</code>
Of all the books listed below it strives hardest to give an intuitive grasp of the essential ideas, but it still requires some mathematical sophistication from page 1.
Below is a list of Further Readings from my book, with comments on each publication.
Bernardo, JM and Smith, A, (2000) 4 . Bayesian Theory A rigorous account of Bayesian methods, with many real-world examples.
Bishop, C (2006) 5 . Pattern Recognition and Machine Learning. As the title suggests, this is mainly about machine learning, but it provides a lucid and comprehensive account of Bayesian methods.
Cowan G (1998) 6 . Statistical Data Analysis. An excellent non-Bayesian introduction to statistical analysis.
Dienes, Z (2008) 8 . Understanding Psychology as a Science: An Introduction to Scientific and Statistical Inference. Provides tutorial material on Bayes' rule and a lucid analysis of the
distinction between Bayesian and frequentist statistics.
Gelman A, Carlin J, Stern H, and Rubin D. (2003) 14 . Bayesian Data Analysis. A rigorous and comprehensive account of Bayesian analysis, with many real-world examples.
Jaynes E and Bretthorst G (2003) 18 . Probability Theory: The Logic of Science. The modern classic of Bayesian analysis. It is comprehensive and wise. Its discursive style makes it long (600 pages) but never dull,and it is packed ful l of insights.
Khan, S, 2012, Introduction to Bayes' Theorem. Salman Khan's online mathematics videos make a good introduction to various topics, including Bayes' rule.
Lee PM (2004) 27 . Bayesian Statistics: An Introduction. A rigorous and comprehensive text with a strident Bayesian style.
MacKay DJC (2003) 28 . Information theory, inference, and learning algorithms. The modern classic on information theory. A very readable text that roams far and wide over many topics, almost all of which make use of Bayes' rule.
Migon, HS and Gamerman, D (1999) 30. Statistical Inference: An Integrated Approach. A straightforward (and clearly laid out) account of inference, which compares Bayesian and non-Bayesian approaches. Despite being fairly advanced, the writing style is tutorial in nature.
Pierce JR (1980) 34 2nd Edition. An introduction to information theory: symbols, signals and noise. Pierce writes with an informal, tutorial  style of writing, but does not flinch from presenting the fundamental theorems of information theory.
Reza, FM (1961) 35 . An introduction to information theory. A more comprehensive and mathematical ly rigorous book than the Pierce book above, and should ideally be read only after first reading Pierce's more informal text.
Sivia DS and Skilling J (2006) 38 . Data Analysis: A Bayesian Tutorial. This is an excellent tutorial style introduction to Bayesian methods.
Spiegelhalter, D and Rice, K (2009) 36 . Bayesian statistics. Scholarpedia, 4(8):5230.
http://www.scholarpedia.org/article/Bayesian_statistics
A reliable and comprehensive summary of the current status of Bayesian
statistics.
And, here is my book, published June 2013.
Bayes' Rule: A Tutorial Introduction to Bayesian Analysis,
Dr James V Stone, ISBN 978-0956372840
Chapter 1 can be downloaded from:
http://jim-stone.staff.shef.ac.uk/BookBayes2012/BayesRuleBookMain.html
Description:
Discovered by an 18th century mathematician and preacher, Bayes' rule is a cornerstone of modern probability theory. In this richly illustrated book, a range of accessible examples are used to show how Bayes' rule is actually a natural consequence of commonsense reasoning. Bayes' rule is derived using intuitive graphical representations of probability, and Bayesian analysis is applied to parameter estimation using the MatLab programs provided. The tutorial style of writing, combined with a comprehensive glossary, makes this an ideal primer for the novice who wishes to become familiar with the basic principles of Bayesian analysis.
Answer: For complete beginners, try William Briggs Breaking the Law of Averages: Real-Life Probability and Statistics in Plain English
Answer: I simply must to include MCMC in Practice.  It provides an excellent introduction to MCMC, perhaps not as general as other books mentioned, but excellent for gaining insight and intuition.  I would recommend reading it after (or in parallel with) Bayesian Computation with R.
Comment: My view is that mcmc should be avoided and used  as a last resort - it simply takes too long in most cases (though i deal with big data sets where everything is basically mle).  mcmc is a "sledge hammer" to some degree.  Also mcmc is an algorithm for numerical integration.  Nothing more, nothing less.  It should receive the same introductory treatment as other algorithms, such as the laplace method and quadratre.  Otherwise people will develop a narrow view of what "bayesian statistics" is.
Comment: Mcmc should not be the focus of an introduction to bayesian statistics, in my opinion. I think rejection sampling is more appealling as a way to understand how bayesian learning works.  Also, least squares is bayesian (as is maximum likehood), so it too represents a gentler introduction to bayesian statistics, compared to mcmc.
Answer: If you happen to come from the physical sciencies (physics/astronomy) I would recommend you Bayesian Logical Data Analysis for the Physical Sciences: A Comparative Approach with Mathematica® Support by Gregory (2006).
Although the "with Mathematica® Support" part of the title is there only for commercial issues (the usages of Mathematica code are very poor), the good thing about this book is that it is truly an introduction to the subject of probabilities and statistics. It even has some chapters on frequentist statistics. However, once you give it a shot, go for the book of Gelman et. al that a lot of people recommended you. Most of the material in the book of Gregory is taken lightly (if not, it wouldn't be an introduction): Gelman's book has been a truly re-awakening from Gregory's for me.
Comment: Phil Gregory's book is a very nice introduction indeed, somewhat like Bolstad's introduction for people with an advanced mathematical background. There are more resources to be found on Phil Gregory's [website](http://www.phas.ubc.ca/~gregory/gregory.html) and there is also a [supplement](http://bit.ly/1NAT1TR) which addresses hierarchical models and missing data treatment.
Answer: I read:
Gelman et al (2013). Bayesian Data Analysis. CRC Press LLC. 3rd ed.
Hoff, Peter D (2009). A First Course in Bayesian Statistical Methods. Springer Texts in Statistics.
Kruschke, Doing Bayesian Data Analysis: A Tutorial with R and Bugs, 2011. Academic Press / Elsevier.
and I think that the better one to start with is Kruschke's book. It's perfect for a first approach to Bayesian thinking: concepts are explained very clearly, there is not too much mathematics, and there are lots of nice examples!
Gelman et al. is a great book, but it is more advanced and I suggest to read it after the Kruschke's one.
Conversely, I did not like Hoff's book because it is an introductory book, but concepts (and Bayesian thinking) are not explained in a clear way. I suggest to pass over.
Answer: Not strictly Bayesian Statistics as such, but I can strongly recommend "A First Course on Machine Learning" by Rogers and Girolami, which is essentially an introduction to Bayesian approaches to machine learning.  Its very well structured and clear and aimed at students without a strong mathematical background.  This means it is a pretty good first introduction to Bayesian ideas.  There is also MATLAB/OCTAVE code which is a nice feature.
Answer: Bayesian Statistics for Social Scientists. Phillips, Lawrence D. (1973), Thomas Crowell & Co. It's very clear, very accessible, assumes no statistics knowledge, and, unlike Bolstad which I found dry, has some personality.
Answer: This book suggests it is aimed at entry level undergraduate level
Biostatistics: A Bayesian Introduction.  By George G Woodsworth.
Published by John Wiley & Sons
Answer: Computational Bayesian Statistics by Turkman et. al. is a high-quality and all-inclusive introduction to Bayesian statistics and its computational aspects. It has the right mix of theory, model assessment and selection, and a dedicated chapter on software for Bayesian statistics (with code examples). It should serve nicely as a practical textbook for a first course in Bayesian methods.
Answer: A good book from the basics to advanced, and which you can download, is
Andrew Gelman, John Carlin, Hal Stern, David Dunson, Aki Vehtari, and Donald Rubin, Bayesian Data Analysis, http://www.stat.columbia.edu/~gelman/book/
You can also download the first two chapters of
Richard McElreath, A Bayesian Course with Examples in R and Stan, https://xcelab.net/rm/statistical-rethinking/
Comment: I highly recommend Dr. McElreath's book if you don't have rigorous Statistical Inference training.
Answer: Gill, J. (2014). Bayesian Methods: A Social and Behavioral Sciences Approach. 3rd edition.
Written by a political science professor, with social scientists as the target audience in mind. R code is provided.
http://www.amazon.com/Bayesian-Methods-Behavioral-Sciences-Statistics/dp/1439862486/
Answer: Since the type of beginner is not specified in the question, here is my advice for beginning statisticians:
Andrew B. Lawson and Emmanuel Lesaffre (2012): Bayesian Biostatistics
This book was used in the first year of our statistical science master and I found it relatively easy to understand for such a difficult subject. As with the majority of 'biostatistics' books, the examples are mainly clinical biology, but the methods are not restricted to those useful in clinical science. We had had about half a year of statistical education prior to this and besides Bayes theorem, Bayesian statistics hadn't been introduced yet.
What's also nice is that the entire 649 slides of accompanying presentations are available online.
Answer: This book hasn't been mentioned yet, as it's relatively new (2018):
A Student's Guide to Bayesian Statistics by Ben Lambert
In his videos, Lambert explains concepts in a very intuitive manner. This book does the same, explaining why the math works, using plenty of examples, and including problems to work at the end of each chapter.  He incorporates videos into the book, noting in the margin when a particular video complements the given concept being explained.
It's somewhat in the same vein as Statistical Rethinking, but I found both the book and his videos to be more to the point, while still explaining the concepts well.
I'd suggest watching a few videos to get a feel for his style.
Ben Lambert's YouTube channel
Answer: Bayesian Modeling Using WinBUGS by Ioannis Ntzoufras, 2009.
Not only does this book introduce Bayesian methods, but includes everything one needs to immediately start running and diagnosing Bayesian models from simple normal models to generalized linear models to Bayesian hierarchical models. Not impressed yet? An entire chapter on how to set up and run WinBUGS (also useful for OpenBUGS!). Pseudo code and R code side-by-side throughout the book. Everything is illustrated with hands on examples. Also included are a chapter on the predictive distribution and model checking, and a chapter on checking convergence.
It is such an excellent combination of theory, explanation, application, software instruction and code.
Answer: A really introductory book is Will Kurt's Bayesian Statistics the Fun Way. This approaches the logic of Bayesian statistics at a very high level - going through the basics of probability, and how prior information can combine with data to affect posterior probabilities. As an ecologist who didn't have a robust statistical training in gradschool, I still get bogged down by equations. I found Gelman's book way too difficult for my beginner level, but Will's book is finally helping me wrap my mind around the basic concepts. It has fun, practical examples that would have been a nice per-requisite to read before my grad program.
I plan to work my way through John Kruschke's "Doing Bayesian Data Analysis" as a next stepping stone.
Answer: Bishop (2006). Pattern Recognition and Machine Learning (PRML)
If you have ever heard about The Elements of Statistical Learning (ESL), PRML can be treated as a bayesian version of it. The book talks about the most important models in statistical/machine learning from linear regression, NN, SVM to graphical models, all in bayesian perspective. The introduction to EM algorithm, variational inference and MCMC are well written.
Answer: Savage's The Foundations of Statistics helped me understand the why and deeper concepts of Bayesian methods. It's not a how to book, but explains the underlying philosophy of stats.
Answer: I am stunned at how many introductory books there are.  My recommendation is William Bolstad and James Curran's Introduction to Bayesian Statistics. It has several nice elements to it.
First, it covers a large percentage of the conjugate problems and covers all the standard problems in a sophomore-level test for an introduction to statistics course.  It also covers the case when the prior is not conjugate.
Second, it covers the appropriate Frequentist procedure at each point, explaining both.
Third, it derives the solutions and so allows an understanding of the issues at a deeper level.  It, optionally, allows for rigor.
It covers everything a sophomore-level book would cover, except with underlying math included.  It is an upper-division, lower master's level book due to the included math.


iOS game Development with Swift. SKScene/SprikeKit changes?

Question: I'm new to iOS game development, I've been following this tutorial series and if someone doesn't mind taking a peek at this video(near the end) https://www.youtube.com/watch?v=s0hRlSlT6Zw&list=PL6gx4Cwl9DGDgp7nGSUnnXihbTLFZJ79B&index=34 I've copied the entire code but if you look at the touchesBegan function it seems the newer versions of swift have a different function than his,
Here's how his reads
override func touchesBegan(touches: Set NSSet, withEvent event:UIEvent) {

let introLabel = childNodeWithName("introLabel")

if(introLabel != nil) {
    let fadeOut = SKAction.fadeOutWithDuration(1.5)

    introLabel?.runAction(fadeOut, completion: {
        let doors = SKTransition.doorwayWithDuration(1.5)
        let shooterScene = ShooterScene(fileNamed: "ShooterScene")
        self.view?.presentScene(shooterScene, transition: doors)
    })
}

}
mine reads
import SpriteKit

class GameScene: SKScene {

override func didMoveToView(view: SKView) {
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let introLabel = childNodeWithName("introLabel")

    if(introLabel != nil) {
        let fadeOut = SKAction.fadeOutWithDuration(1.5)

        introLabel?.runAction(fadeOut, completion: {
            let doors = SKTransition.doorwayWithDuration(1.5)
            let shooterScene = ShooterScene(fileNamed: "ShooterScene")
            self.view?.presentScene(shooterScene, transition: doors)
        })
    }

}

override func update(currentTime: CFTimeInterval) {
}

GameViewController.swift
import UIKit
import SpriteKit

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    if let scene = GameScene(fileNamed:"GameScene") {
        // Configure the view.
        let skView = self.view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }
}

override func shouldAutorotate() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
        return .AllButUpsideDown
    } else {
        return .All
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

everything written in that method is the same but I'm getting an error unless i put a ! after shooterScene in the line self.view?.presentScene(shooterScene, transition: doors)
Regardless whether or not I add the ! when I click on the screen the transition doesn't occur. Can someone offer a solution?
Comment: Please add the whole code of the scene, nobody wants to look through a video and copy code in order to try and simulate your problem.
Comment: By more code I meant the whole view controllers so that it is easy to simulate the problem.
Answer: It doesn't work because no touch is ever detected. What you need is:
override func touchesBegan(touches: Set<UITouch>?, withEvent event: UIEvent?) {

    for touch: AnyObject in touches! {

        let touchLocation = touch.locationInNode(self)

        button.containsPoint(touchLocation) {
            //Button pressed; move to next scene
        }
    }
}

This is the code that works for me.


indexing is not error but index + index = error

Question: package hello2;

import java.util.Scanner;

public class Today_java {
    public static void main(String[] args) {

        Scanner broken = new Scanner(System.in);
        String input = broken.nextLine();
        char[] charArray = input.toCharArray();

        System.out.println(charArray[0]);
        System.out.println(charArray[1]);
        System.out.println(charArray[2]);

        System.out.printf("%d",charArray[0] + charArray[1] + charArray[2]);
    }
}

run this code print 1, 2, 3 is ok but 1 + 2 + 3 is error
ex) input 123 >> 1 / 2 / 3  > 150
really i can't find error and syntax error
help me... :(
Comment: Hint: `char + char` is resolved by promoting both characters to `int`. So you've got 49 + 50 + 51, as those are the `char` values for '1', '2' and '3'. If you want to parse the whole string as an integer, use `Integer.parseInt`.
Comment: Welcome to Stack Overflow! Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you.
Comment: Thank you for your delicate reply.
Answer: When you print 3 chars and use the "+" operator, it doesn't work as a concatenation operator like for String, because every char has an ASCII value from the ASCII table:

So 1+2+3 works as 49+50+51 = 150.
to print the 3 chars, use
System.out.printf("%c%c%c", charArray[0] , charArray[1] , charArray[2]);

Where %c is to format a char.
Comment: @박상훈 Did it work for you? I mean did you find that it is the answer which you were looking for?
Comment: Yeah, The table above tells me which input value I put in.
Answer: The problem is with add operation on the char
 import java.util.Scanner;

 public class Today {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

         Scanner broken = new Scanner(System.in);
          String input = broken.nextLine();
          char[] charArray = input.toCharArray();

          System.out.println(charArray[0]);
          System.out.println(charArray[1]);
          System.out.println(charArray[2]);

          System.out.printf("%d",Character.getNumericValue(charArray[0]) + Character.getNumericValue(charArray[1]) + Character.getNumericValue(charArray[2]));
    }

}

Answer: System.out.printf("%d",Character.getNumericValue(charArray[0]) +Character.getNumericValue(charArray[1]) + Character.getNumericValue(charArray[2]));

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.


How can I add a variables to my page.html.twig file?

Question: I'm trying to add a variable that i can use in page.html.twig that will add a class to the header region if a field in the node exists.
In template_preprocess_page() i've tried doing the following and have not been able to add a variable:
function theme_preprocess_page(&$variables){
  $variables['header_attributes']['class'] = [];
  $variables['header_attributes']['class'] = array_merge($variables['header_attributes']['class'], ['myClassHere']);
}

I based this off the example for menu preprocess but no new class was added to the  ta
Answer: There is no index called header_attributes inside $variables array no need to create it, there is page index just use it:
Try this out:
function [yourThemeName|yourModuleName]_preprocess_page(&$variables){
  $variables['page']['header_attributes']['class']= 'myClassHere';
}

Note don't forget to clear cache.
In your twig you will get your class by:
page['header_attributes']['class']

Comment: to implement template_preprocess_page(), in the function name theme_preprocess_page(), replace 'theme' with the name of your custom theme.
Implement it in your theme's .theme file.
Then clear cache


What is the solution of $(m^{2}+1)^2=0?$

Question: I understand the solution of $m^{2}+1=0$ is $\iota$. However for sure this solution ($(m^{2}+1)^2=0$) should contain four roots. The answer reads $\pm \iota$ and $\pm \iota$. However I am not able to calculate all the roots. I can arrive at most up to $\pm \iota$ and cannot proceed any further.
Comment: Welcome to Math Stack Exchange.  Sometimes there are "repeated roots."  Consider what is the solution of $(m^2-1)^2=0$
Comment: Welcome to maths SX! There's no other root. There are nevertheless four roots because each  has multiplicity $2$.
Comment: Yes that is true but how do I understand/calculate them?
Comment: Technically, there are two solutions to $m^2+1=0,$ $m=i,$ or $m=-i.$
Comment: Hint: $Y^2=0$ if and only if $Y=0.$
Comment: Does $(m-1)^2=0$ have two zeros? We sometimes say it $2$ roots when we count repeated roots, but there is only one root.
Answer: Hint: $(m^2+1)^2=(m^2+1)(m^2+1)=(m+i)(m-i)(m+i)(m-i)$
Answer: Here the factorisation which, I hope, will make you understand why there are really $4$ roots:
$$(m^2+1)^2=\bigr((m-i)(m+i)\bigl)^2=\underbrace{(m-i)}_{\text{two roots}}{}^2\underbrace{(m+i)}_{\text{two roots}}{}^2.$$
You have $4$ factors, which are equal in pairs.
Answer: Why should it have four roots ? A $4-$degree polynomial has at most four distinct roots...
Here $(m^2+1)^2=0$ implies that $m^2+1=0$, then you have $m=i$ or $m=-i$ in $\mathbb{C}$.
Answer: The solution is obtained by solving $m^{2} + 1 = 0$ which yields $m = \pm i$.
That being said, you have effectively a quartic equation which will have exactly four roots counting multiplicities (repititions).
Here, $-i$ and $i$ are the two distinct solutions, each having multiplicity two.


Yamaha G-String keeps breaking

Question: I have a Yamaha F335 acoustic guitar, and, about two weeks ago, I restrung it using Ernie Ball Silk & Steel Regular strings. However, about a week ago, the G-string snapped around the 3rd fret, and I had no idea why. Assuming it was a one time thing, I went a bought a new string today and put it in, only to have the same thing occur near the fourth fret after only a couple hours of playing.
The gauge of the string is .026, and I don't think that I strum too violently, especially since I spend most of my time fingerpicking (although, both times that the string snapped, I was picking). The guitar is only about 9 months old, and the other strings that I replaced are fine (not snapping). Does anyone know what's wrong here?
Answer: What is likely going on is that your picking strumming technique might be digging in to the G string more aggressively than needed causing it to break.  If that is true you are probably digging in to all the strings a little more than necessary - but there is a very good reason the G string is the one breaking.
The reason the G string is the only one breaking is that it is actually the easiest string to break out of all the strings on an acoustic set with a wound G string.  That is because the steel core of a wound G string (which is where all the tensile strength comes from) is thinner than any of the other strings on the guitar.
So even though the overall gauge of the string is .026 - the core is actually much thinner than your high e string.  The winding around the core does absolutely nothing to add tensile strength to the string which is what determines how much tension the string can withstand before breaking.

I see many guitarist who dig in too deep with their pick when strumming or picking which causes greater deflection of the string thereby creating more tension.  In fact I used to do that as well and I often broke the G string.  You only need to insert the pick just below the string to make it play.  Only the tip of the pick should be below the string in most cases. Of course there are times when the music calls for more aggressive strumming, but strumming too hard will break the G string.
Another thing to check is the gauge of the core of the strings you switched to.  Some types of strings have a thinner core than others with the same overall diameter.  The string types with thinner core under the windings might include silk and steel strings where enough room must be allowed outside the core to accommodate the metal winding as well as the nylon fibers between the winding and the core.
Some manufactures will list the diameter of the core.  If not, you might take some of the winding off one of the broken strings and one of your old strings from the set you were using before you switched, and compare the diameter and rigidity of the core to see if perhaps the new strings you are trying do in fact have a thinner core than the ones you used to use.
If your string was breaking at the saddle, I would suspect a sharp string slot there.  If at the nut - a sharp string slot at the nut.  But since your strings are breaking between the nut and saddle and not in the same place every time, my conclusion is that there is nothing wrong with your guitar.
Try a lighter touch with your picking hand when strumming or picking with your pick.  Or try a different type string with a larger diameter core on the G string.  Or use the same brand and type strings but use a G string from the next heavier gauge offered.
One other thing that could help would be to tune your guitar a half step flat to reduce the overall tension on the G string (as well as all the others).  With reduced tension it can withstand more deflection than it could tuned to regular pitch.  You can use a capo on the first fret if you want your guitar to play as if tuned standard.
Good luck!
Comment: Agree with most, except using a *thinner* gauge wound G may be a better bet., Think oaks and willows. Thinner strings have more propensity to bend rather than break, especially when it won't be under as much tension, as it's a lighter string. Suggest something like .022.
Comment: Thank you for the information. Perhaps I was picking too strongly; I'm going to look into getting a different gauge string (I'm not sure whether to listen to you or @Tim though)
Comment: @ChrisLoonam - try both options - although replacing with an even thicker string will put more strain on the neck and your fingers...
Comment: @ChrisLoonam Thinner will always break easier than thicker regardless of the lower tension.  If you want to prove this try using an .009 gauge high e string from a super light electric set and see how long it lasts before it breaks.  Yes it's very low tension, but that sucker will snap so easy you won't believe it (I know from experience).  Keep in mind I am talking about the gauge of the steel core of a wound string not the overall gauge of string.  If the strings you were using before switching have a thicker core, try going to a G string with same diameter core as the old strings.
Comment: @Tim I understand your logic about bend but don't break but it doesn't hold up with guitar strings in real life in my personal experience.  I have tried super light gauges in the past only to learn that I have to really lighten my touch to keep the thinner strings from breaking.  Also, I just read the reviews for the Ernie Ball Silk and Steel strings OP mentioned and most say it's a very low tension string which may explain the greater propensity for breakage.  Also 3 reviews talked about strings breaking.  The cores are probably thinner (or not even steel) which makes them low tension.
Comment: @ChrisLoonam  I read something about the Earnie Ball Silk and Steel Strings that suggest the wound strings might have a nylon vs. steel core.  If you still have a broken one, please pull some of the metal winding off the core and let me know if it's steel or nylon.  If nylon then that would explain why they break so easy.  The wound G core will always be the thinnest of all the strings so it would be the easiest to break.
Comment: @RockinCowboy The inside of the string had a steel core, not a nylon core. I'm going to take your advice and get a heavier gauge string for it.
Comment: @ChrisLoonam Thanks for the clarification on the steel core.  I thought it must but there is an online music store describing it as a nylon core which I found hard to believe.  Good luck.  Let me know how it goes.  I did not mention this but I would think a heavy pick might lead to more easily broken strings also.  Lighter picks flex before you can apply too much tension.  I use a medium pick (.71).  If I had super light strings on a guitar I might switch to a .60 .

Yamaha G-String keeps breaking


Purpose of `declare` keyword in TypeScript

Question: What is the meaning of the declare keyword?
type Callback = (err: Error | String, data: Array<CalledBackData>) => void;

vs.
declare type Callback = (err: Error | String, data:Array<CalledBackData>) => void;

Cannot find docs that explain the purpose of the declare keyword in TS. Qué significa?
Answer: TL;DR
declare is used to tell the compiler "this thing (usually a variable) exists already, and therefore can be referenced by other code, also there is no need to compile this statement into any JavaScript".
Common Use Case:
You add a reference to your web page to a JavaScript file that the compiler knows nothing about. maybe it is a script coming from some other domain like 'foo.com'. when evaluated the script will create an object with some useful API methods and assign it to the identifier 'fooSdk' on the global scope.
You want your TypeScript code to be able to call fooSdk.doSomething(), but since your compiler does not know fooSdk variable exists, you will get a compilation error.
You then use the declare keyword as a way of telling the compiler "trust me, this variable exists and has this type". The compiler will use this statement to statically check other code but will not trans-compile it into any JavaScript in the output.
declare const fooSdk = { doSomething: () => boolean }

Newer Typescript version require a slightly different syntax:
declare const fooSdk : { doSomething: () => boolean }

In the same vein, you can add the declare keyword to class properties to tell the compiler not to emit any code that would create this property, assuming you have your own code that would create it that the compiler does not know about or does not understand.
Your specific example is different since you are declaring a type, not a variable, types already do not compile into any JavaScript. I do not know if there is any reason to declare a type.
Comment: @fires3as0n I tested and found a different syntax that works on current version Typescript. added to answer.
Comment: `declare const fooSdk = { doSomething: () => boolean }` gives **A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.** and **'boolean' only refers to a type, but is being used as a value here** errors, how does this answer gets such a high rating?
Comment: Can you please add links to the typescript documentation ? It's an almost good answer, and would become a good answer with some links to verify the statements.
Comment: Is it fair to say that a *ambient module* file (`d.ts`) can be used instead of `declare`? In other words, that `declare` is used in the module in question, whereas an ambient module lives outside the file and is brought into scope with a `/// <reference ....`?
Answer: Here is a real world example.
I have a TypeScript React app that uses the Webpack Hot Middleware. The Webpack Hot Middleware is not written in TypeScript, but in good old-fashioned JavaScript. So it has no type declarations that the TypeScript compiler can check against.
When I run my code, the object module from the Webpack Hot Middleware exists, and I can console.log it despite it being good old-fashioned JavaScript hiding in my fancy new TypeScript React app.
The module object also has keys, such as module.hot, and the keys can have values. But the TypeScript design time compiler (in VSCode at least) draws a red squiggly under it saying property 'hot' does not exist. But it does exist!
To make the TypeScript compiler agree, declare it like this:
declare let module: any

The existing module object, now has a type of any, which makes the TypeScript compiler happy now, red squiggly gone and now I can continue to compile and write my other code.
If you remove the keyword declare, and just write let module: any, it will not compile, instead saying that 'module' already exists. That's what "ambient" in the accepted answer means.
Comment: `declare` specifies a type to an already existing variable, not declaring a new one.
Comment: is this like **extern** keyword of C language which was used to declare things that are outside of our source code and compiler cannot access it? Only linker would link them later. so extern would enable the code compilation that otherwise would produce errors
Comment: I love this explanation, so useful: `If you remove the keyword declare, and just write let module: any, it will not compile, instead saying that 'module' already exists. That's what "ambient" in the accepted answer means.`
Answer: From Typescript docs:
Typescript - Working with Other JavaScript Libraries

To describe the shape of libraries not written in TypeScript, we need to declare the API that the library exposes. Because most JavaScript libraries expose only a few top-level objects, namespaces are a good way to represent them.
We call declarations that don't define an implementation "ambient". Typically these are defined in .d.ts files. If you're familiar with C/C++, you can think of these as .h files. Let's look at a few examples.
Ambient Namespaces
The popular library D3 defines its functionality in a global object called d3. Because this library is loaded through a  tag (instead of a module loader), its declaration uses namespaces to define its shape. For the TypeScript compiler to see this shape, we use an ambient namespace declaration. For example, we could begin writing it as follows:
D3.d.ts (simplified excerpt)
declare namespace D3 {
    export interface Selectors {
        select: {
            (selector: string): Selection;
            (element: EventTarget): Selection;
        };
    }
    // (...)
}

Answer: You can use declare to tell the compiler about types before you write any implementation code and TypeScript will be happy.
declare function foo(name: string): string

Comment: Short and sweet :thumbs_up:
Answer: Consider this scenario: You have a Typescript project. Then you decide to write a module in JavaScript for whatever reason and use it in your Typescript code.
// getMyName.js
module.exports = function getMyName(name) {
    return name;
}

Then you import it into your typescript code
// myCode.ts
import getMyName from 'getMyName'; //getMyName is a JS module not typescript

When importing that JS module(allowJs compiler option should be set to false otherwise, JS files will be resolved without any type definitions), Typescript's compiler complains about that module not being a module at all!
Could not find a declaration file for module '/absolute/path/to/getMyName.ts'
This is because Typescript doesn't resolve to JS code by its own. To circumvent this problem we should provide type definition (filename.d.ts) for our JS module. To do so you can use declare and export.
// getMyName.d.ts
declare function getMyName(name: string): string;

export default getMyName;

After that when we import our JS module, typescript doesn't complain about anything because it now has access to the types.
Comment: @AlexanderMills Yes you're right. edited.
Comment: `import getMyName from 'getMyName';` is the `default` export, maybe you meant `import {getMyName} from 'getMyName'`;
Answer: delcare key words use when you import some library not have the declare type files,such as *.d.ts
after that vs eslint not check the syntax and context , will let you pass, if you default use tsc compiler, that the good reason to declare to remove syntax error
Comment: This is not correct; the declare keyword is not for that purpose, but it is used in that scenario.


postfix opendkim DKIM-Signature and Domainkey-Signature

Question: Running postfix on CentOS 6 as an edge relay for a while now, so all our outgoing mail is routed through one point with opendkim signing the mail. This works great. I was originally using dkim-filter/dkim-milter (I believe) but switched to opendkim a couple of years back.
But one thing I've been meaning to get around to for a long time is getting the DomainKey-Signature header added in addition to the DKIM-Signature. I realise that DomainKeys is the older spec and is technically replaced by DKIM but I think there's still a reasonable number of systems that verify both (e.g.: Gmail).
Would this involve multiple milters, one for DKIM and another for the older DomainKeys?
I'm not too happy about the idea of having to maintain 2 sets of configurations and signing tables etc, as I have to add/remove relay domains reasonably frequently.
Anyone know if it's possible to add both signatures within opendkim?
Answer: The DomainKeys standard was never implemented, at least not through RFC. RFC 4870 even states at the very top:

Status of This Memo
This memo defines a Historic Document for the Internet community.
It does not specify an Internet standard of any kind.

It was obsoleted by RFC 4871 and both RFCs are dated May 2007.


Compare two list with out using linq for update History

Question: Hi i'm working on a project written in c# webform and it requere loghistory of changes if some one updated the data i should be inserted to logs table but i need to capture which column or which field is being update.
so i think comparing 2 list the oldList before update and the list after update
if i have this class
public myClass class{
public string col1{get; set;}
public string col2{get; set;}
public string col3{get; set;}
}

and list like this with datas
List<myClass > old = new List<myClass >();
List<myClass > new = new List<myClass >();

how can i compire this 2 and get the column and the old and new data of the difference with out using Linq because the application is a existing and uses .net 2.0 framework so i belive Linq is not availavle yet in this.
I'm not requered to update the framwork for some reason.
Comment: I give you the `for` loop and `if` statement... *.Net Framework 2* (2005 complaint).. When you tried this, what wasn't working for you?
Comment: yes i can compare the data's how can i canture which column has the difference sorry im still newbie
Comment: A string, a list of strings?
Comment: `if(old[i].col1 != new[i].col1) Console.WriteLine("Col1 is diffrent")`
Comment: yes that will do im thinking of shorcut because i have many columns
Comment: usually, there is some logging system in the database engine, why not using that to your advantage ? for instance, in SQL Server, you could use Trigger to access `inserted` and `deleted` tables which would store the new and old values for the table, which it can be reused to for instance insert them in a permeant log table to track the changes, then you just use this table to view these changes in your application.
Answer:
Implement IComparable interface in your class

public class myclass : IComparable<myclass>
        {
            public string col1 { get; set; }
            public string col2 { get; set; }
            public string col3 { get; set; }

            public int CompareTo(myclass obj)
            {
                return this.col1.CompareTo(obj.col1);
            }
        }

Then sort your list and iterate through it

            oldlist.Sort();
            newlist.Sort();
            for (int i = 0; i < oldlist.Count; i++)
            {
                string oldcol1 = oldlist[i].col1;
                string newcol1 = newlist[i].col1;
            }


Map $f: S^n \to S^n$ that extends over $D^{n+1}$ must identify a pair of antipodal points

Question: There is a problem in Armstrong's Basic Topology in chapter 9.3 that I just can't seem to solve by myself, neither have I found a solution online. It goes as follows:

Suppose we have a map $f:S^n \to S^n$ that extends over $D^{n+1}$ in the sence that there is a map $F:D^{n+1}\to S^n$ with $F|_{S^n}=f$. Then there exists a $x\in S^n$ such that $f(x)=f(-x)$.

My idea was to glue two $D^{n+1}$ along $S^n$ to obtain the $S^{n+1}$ and a map $\tilde{F}:S^{n+1}\to S^n$ induced by $F$. Then by the Borsuk Ulam theorem I get a $x\in S^{n+1}$ s.t. $\tilde{F}(x)=\tilde{F}(-x)$, but I can't see how to get a $x\in S^n$ with this property.
Armstrong also states that $f$ having even degree is already sufficent, any hint on how to see that would also be much apprechiated.
Comment: An application $f : \mathbb{S}^{n} \longrightarrow \mathbb{S}^{n}$ , extends continuously for $F : \mathbb{D}^{n+1} \longrightarrow \mathbb{S}^{n}$ if, and only if, $\text{deg}(f) = 0$
Comment: See also https://math.stackexchange.com/q/3472652 for a nice proof.
Answer: A map $h:S^n\to S^n$ such that for all $x, h(-x) = -h(x)$ has odd degree (see e.g. here, or here for an easier proof when $n$ is odd - it has been pointed out to me that the even case can be deduced from the odd case by taking suspensions, which makes for an overall easier proof)
So assume an $f$ of even degree exists with no $x$ such that $f(x)=f(-x)$. Then one may define $g(x) := \frac{f(x)-f(-x)}{||f(x)-f(-x)||}$ which is well-defined and continuous, and satisfies $g(-x) = -g(x)$, so $g$ has odd degree.
However, one may also define $H(x,t) := \frac{tf(x)-(1-t)f(-x)}{||tf(x)-(1-t)f(-x)||}$, $t\in [0,1]$
Indeed if $tf(x) = (1-t)f(-x)$ then by taking the norm we get $t=1-t$ so $t=\frac{1}{2}$ so $f(x) = f(-x)$ which contradicts the assumption.
Now $H(-, \frac{1}{2})=g$ so $f\sim g$. Therefore $g$ has even degree. That's absurd.
It follows that there is $x$ such that $f(x)= f(-x)$. In the first special case, if there is an extension $F$ of $f$, then $f$ is nullhomotopic, so has degree $0$, which is even.


Exclusão Física vs Exclusão Lógica

Question: Qual a vantagem de fazer exclusão lógica (Ex: Setar uma flag indicando que o registro está ativo ou não), ao invés de realizar exclusão física?
É uma prática comum? É segura?

Derivada de: Physical vs. logical / soft delete of database record?
Comment: @bfavaretto Me indicaram. Nada supera o poder das massas :D
Comment: Realizar exclusão física na maioria dos casos não é recomendo, porque você não poderá reativar o tal registro. O que é uma funcionalidade a menos em sua aplicação/sistema, sendo que não há motivos para deleta-lo fisicamente.
Comment: @Gabe, curiosidade: como você achou a fonte original?
Answer: Geralmente, use a exclusão física somente quando você sabe com certeza que não irá precisar mais do registro na tabela.
Use a exclusão lógica quando pode ser possível que você:

possa precisar restaurar o registro em algum momento (undelete)
obter informações dos registros deletados (várias vezes requisições do cliente e não do usuário).

A decisão sobre usar uma ou outra depende individualmente de cada caso. Mas na maioria dos casos o mais recomendado é usar a exclusão lógica quando há a mínima probabilidade de haver restauração dos registros deletados.
Uma query WHERE tabela.Excluido = 0 não costuma denegrir performance, recaindo a preocupação mais sobre o tamanho de dados a armazenar. E claro, sobre a possibilidade de restaurar.

Uma alternativa também usada, em tabelas que possam vir a ter um tamanho gigante com um proporção alta de excluídos, é que mover os registros  para outra tabela exclusiva para Excluidos para não afetar a performance da tabela principal.
Porém nesse caso, deve-se tomar o cuidado porque pode ser possível que não possam ser restaurados facilmente caso tenham um PK com autoincremento.
Normalmente são usados para consultas de "históricos".
Esse caso pode ser usado também em questões legais, como guardar dados sobre os logins efetuados pelos usuários num site durante X anos em contraste com o dados somente informativos ao usuário/cliente do seu último login num site.
Answer: Vantagens de usar uma deleção lógica:

Auditorias: se você usar um campo data-hora para guardar a deleção, ao invés de um simples booleano / string, você pode saber quando foi deletado. E você pode usar índices e pesquisas sem problemas com isto, pois sua pesquisa será do tipo WHERE dtExclusao = NULL ou algo assim.
Deleção mais fácil: não precisa se preocupar em manter algumas integridades na hora de fazer a deleção, já que não é feita uma deleção em cascata.
possibilidade de no futuro implementar alguma solução de inteligência/BI, já que haverá um histórico de todos os dados que poderão ser utilizados

Desvantagens:

você vai ter que controlar a deleção no seu código, sempre lembrando de ter um WHERE para poder deixar os deletados de fora
se a tabela for muito grande e fragmentada (com alguns dados não-deletados bem espaçados no meio de vários dados deletados), a performance poderá cair, pois as tabelas são guardadas em "páginas" no disco, com algumas sendo carregadas na memória. Se os dados não-deletados estiverem todos em poucas "páginas", ótimo. Mas se o seu índice disser que tem um dado válido em cada página, o seu banco vai perder um tempo enorme lendo cada página para memória, extraindo só a linha que você precisa, e carregando a próxima página. Neste caso, para contornar isto, valeria a pena ter uma tabela de dados ativos e jogar os que forem apagados para outra tabela.
os dados da deleção em cascata continuam todos nas mesmas tabelas, ou seja, um registro é marcado como apagado na tabela pai, mas nas tabelas filhas nada indica se o dado ainda está sendo usado ou não, e as tabelas podem ficar grandes, sem conseguir jogar dados para uma tabela especial dos que foram apagados
tempo / custo de backup: já que os backups completos (full) terão um monte de dados que na verdade foram deletados
demora para gravar dados: se os índices são grandes (já que as tabelas podem ser grandes, armazenando todos os registros excluídos), a cada gravação de um novo dado pode exigir um grande tempo de construção do índice, e assim cada ação de gravar pode ter uma performance baixa
Answer: Bom, a vantagem ou desvantagem dos dois tipos de exclusão depende muito das necessidades do seu sistema.
Antes de decidir qual é a melhor prática para o seu caso, recomendo dar atenção aos seguintes aspectos:

Setar uma flag para indicar se o registro está ativo ou não implica ter que realizar checagens (claúsulas WHERE) em cada query desse ponto em diante;
Desempenho pode ser sim um grande problema ocasionado por optar pela exclusão lógica, portanto é preciso levar em conta a complexidade de seu banco de dados e as relações entre as entidades a fim de verificar se isso realmente seria um empecilho ou não;
É imprescindível realizar uma análise da frequência com que determinado dado previamente excluído é requisitado/buscado. Através disso, você saberá se o melhor a se fazer é utilizar um campo bit, criar uma tabela adicional que guardará determinada informação ou simplesmente adicionar campos que contenham data de modificação, alteração e/ou exclusão para um controle mais amplo.

Se é necessário manter registros inativos, vá em frente e use backups para guardar seus dados, implemente triggers que os desviem e poupe recursos conforme o necessário.
Em suma, dar permissões aos usuários que realmente devam ter o poder de exclusão, descartar aquilo que impede a otimização de seu sistema e promover uma boa interatividade máquina-usuário é sempre a melhor alternativa.
Answer: Existem dois propósitos principais:
O primeiro é que você não perde a informação definitivamente, ela permanece em algum lugar para fins de auditoria por exemplo (existem soluções melhores para isso, como manter registros especiais de histórico).
Segundo, é manter os relacionamentos. Por exemplo, vamos ver o caso típico que é desativar usuários de um sistema:
Enquanto estava ativo, esse usuário realizou operações, cadastros, etc. Cada uma dessas entidades fica ligada ao usuário responsável através de campos do tipo "id_usuario", "created_by", etc, tudo apontando para aquela linha da tabela de usuários. Se eliminasse esse usuário usando um DELETE, todos esses registros ficariam quebrados, apontando para um usuário que não existe. Nessa hora é conveniente apenas inativar o usuário, assim ele não consegue mais entrar no sistema, e ao mesmo tempo você pode consultar os registros deixados por ele que estarão apontando para o usuário correto.
Se é uma prática comum:
Em algumas organizações isso é obrigatório, é simplesmente proibido dar DELETE em registros na base. Mesmo quando não precisaria. Por isso o ideal é mesmo avaliar cada situação e ver qual a melhor solução. Em muitos casos a exclusão lógica realmente é útil, e em outros você terá que usá-la mesmo não sendo :-)
Comment: bem lembrado da integridade referencial
Answer: Evite a exclusão lógica para não ficar com dados inúteis e irrelevantes no seu banco de dados.
Utilize a exclusão lógica somente quando for necessário! É sim uma prática comum e segura, na medida em que o código da aplicação cuide corretamente do caso (o framework Laravel, por exemplo, cuida das exclusões lógicas com extrema facilidade para o desenvolvedor).
A pergunta que resta é: quando seria necessário usar exclusão lógica?
Através da exclusão lógica, você pode recuperar o dado "deletado", ou seja, você preserva histórico, e mantém integridade no banco de dados.
Um exemplo: um produto numa loja virtual. Na medida em que existam pedidos feitos contendo esse produto, será conveniente fazer uma exclusão lógica do produto. Assim, é possível identificar os itens em pedidos pretéritos, mesmo que o produto possa ser "excluído". Ou seja: com a exclusão lógica do produto, você preserva os dados desses pedidos.
Há muitos outros casos onde a exclusão lógica é útil, importante e valiosa. Mas se não for útil nem necessária, o melhor é fazer a exclusão física mesmo, para não deixar a base de dados poluída.

Exclusão Física vs Exclusão Lógica


Has anyone used the ConstraintRelationship class for Dynamics CRM?

Question: As documented here there is a property on the AppointmentRequest class for the CRM webservice that allows you to add constraints to what possible appointments are returned from a search.
The actual constraint is specified as an xml string, but I can find almost no documentation about it. Can any one point me to any relevant resources?
Answer: I was never able to find any quality documentation on this property or an accepted schema.  About all that is available (that I've found) exists on this example from the SDK: Schedule A Resource
You can kind of see how you would limit the search results to a set of resources/users.  The list of which properties can be replaced for "name" in the example is in the article ConstraintRelation.Constraints Property.
Hope this helps...
Comment: Also, you might try looking through the CRM 3 SDK.  When I was looking for the error codes that can be returned for one of the scheduling messages... they were not in the CRM 4 SDK but WERE present in the CRM 3 SDK.  Go figure.


Is there a drum module that doesn't have sound banks, just sends the MIDI signal out through USB or Bluetooth?

Question: I bought a used Roland TD-4KP with added mesh pads and cymbals.
The things is that the TD4 module that comes with it doesn't have the aux input for a 3rd cymbal, and some pads, like the toms, have a single trigger.
Is there some device that just takes the trigger input from stereo audio jacks, and sends the MIDI notes through USB or bluetooth and that's it? No sound banks, no nothing.
Clarification:
I only need one specific function of electronic drums, which is turning my trigger hits into midi notes to output to my PC and use VSTs.
The problem with most drum modules is that they don't have enough trigger inputs for the pads and cymbals I want to use, and the ones that do are usually high-end and thus very expensive.
I'm wondering if there is such a thing.
Comment: Why don't you want sound banks?  If you don't want sound coming from the module, just don't plug a speaker in.
Comment: Are you looking for a drum trigger module? But even those typically include some sounds. Specific recommendations are off-topic.
Comment: Voting to leave open; to my mind this is not a "what is the best X" question but a "how do I Y" question.
Comment: I have the feeling that a module like that would be at least as expensive as one with sound banks just because it would fit a very small market niche. Even if it was cheaper to produce, sharing the fixed costs over smaller market would make it cost more.
Comment: Thanks, it's not that I don't want sound banks, but rather that I'm not going to use them, because I want to use VSTs only, and not pay for a full fledged drum module where I only want a part of it.
Comment: The round 5-pin connector on the side of the device "15" in the manual, page 7. Will send the triggers. One would need a midi to usb cable/adapter or a computer audio interface with a midi in.
Comment: Thanks, @Yorik, the problem with this set is that it has too little trigger inputs, and even some of them are mono, namely the toms, which don't have a rim trigger.
I need more trigger inputs.
Answer: There are a few available on the market.
Ddrum DDTi,
Alesis Trigger IO,
Roland TMC-6.
No sounds, just a midi interface. The Ddrum and Alesis are pretty much the same interface, Midi out as well as USB/Midi for triggering samples in your DAW.
Answer: It depends if you want to expand your kit with an additionnal module or replace your module with one with more inputs.
For extend your kit, there is eDrumIn but out of stock until 2024 right now or one of references listed in the answer of Christopher Williams.
For replacing your module with a one with more input, there is MegaDrum where you can have 32 stereo inputs for a decent price but can be hard to configure.
Comment: Yeah, for replacing the current module. I just want my e-drums go directly into this box and the proper midi signal is output to the PC, and to have as many inputs as possible.


Unique URL for each image (preferably with only a hash appended) which shows the popup image directly

Question: I'm using the Magnific popup script.
The script is great, but what I'm missing is that the URL (www.mysite.com/?rel=gallery) is not changing, regardless of which image is shown in the popup, so nobody can link to my one image directly, just to my whole gallery.
It would be great if every image would append a unique hash (#mypic1 etc., preferably grabbed from the id of the image or its wrapper) to the URL. It should be only a hash so the site is not reloaded each time when browsing the gallery itself.
This unique URL (www.mysite.com/?rel=gallery#mypic1), if linked to from an external site, of course, should open the popup with the image#mypic1 directly.
Comment: I guess it's magnific-popup, as mentionned as a tag. Not clear, I admit. - http://dimsemenov.com/plugins/magnific-popup/
Comment: You need to tell us what library you use for the pop-up.
Comment: My apologies for not making that clear.  I saw an earlier user with my exact question and attached a bonus.
Answer: Here's the code:
$('.image-link').magnificPopup({
    ...
    ...
    callbacks: {
        elementParse: function(item) {
            // Function will fire for each target element
            // "item.el" is a target DOM element (if present)
            // "item.src" is a source that you may modify
            window.location.hash = item.src;
        }
    }
});

window.location.hash will write "#something" in the URL and it won't reload the page.
You can write whatever you want in the hash.
If you're using PHP, you would catch the hash using the following code:
<?php
$url = "";
$parsed_url = parse_url($url);
$hash = isset($parsed_url['fragment']) ? $parsed_url['fragment'] : '';
?>

Comment: Awesome, this was the clue I was seeking. Had actually read that part of the doc but the phrase "to parse the source..." threw me off.
Comment: Then adding the line `$('a[href="'+window.location.hash.substr(1)+'"').trigger('click')` will trigger the popup that generated the hash when the page is reloaded.
Comment: Exactly :)
Keep in mind that you should have any event binded to this HTML element. Otherwise, you'll have a "bubble" effect.


probability of getting one suit

Question: Qn : Cards are drawn one at a time, without replacement from a deck of 52 playing cards until only cards of one suit is left. What is the probability that the cards left are all diamonds?
Help in this question will be much appreciated. i have no clue as to how to even begin doing this question.
Comment: 1/4 due to symmetry?
Comment: The solution provided is very elegant. A simple symmetry argument helps us eschew complicated combinatorics !
Answer: Rhetorical question as hint:
Would the probability that it are e.g. spades differ from the probability that it are diamonds?
Comment: @user230452 Indeed. There are $4$ candidates and they have equal probability to be "elected" as the remaining suite.
Comment: So it is absolutely irrelevant to count the number of ways it is possible to have cards of only one suit remaining ?
Comment: Wow. Nice observation.

probability of getting one suit


How to redirect to another page after submitting the ctools modal form

Question: Actually i want to redirect to some other page after submitting the multistep ctools modal form .I have tried using form_state['redirect] and drupal_goto in submit function but didnt work.
function get_quote_menu(){

$items=array();
$items['get_quote'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'get_quote_form',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
$items['get_quote/%ctools_js/details'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'quote_ajax_details_form',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
return $items;
}
function quote_ajax_details_form($js = NULL, $step = NULL){

if ($js) {

    ctools_include('modal');
    ctools_include('ajax');
 }
  $form_info=array(

    'id' => 'quote_details',
    'path' => "get_quote/" . ($js ? 'ajax' : 'nojs') . "/details/%step",
    'show trail' => TRUE,
    'show back' => TRUE,
    'show cancel' => TRUE,
    'show return' => FALSE,
    'next callback' =>  'get_quote_details_next',
    'finish callback' => 'get_quote_details_finish',
    'cancel callback' => 'get_quote_details_cancel',

    'order' => array(
        'start' => t('View the plans and premiums best suited to you
in 4 straight forward steps.'),
        'second'=>t(''),
    ),

    'forms' => array(
        'start' => array(
            'form id' => 'get_quote_start',
       ),
       'second'=>array(
            'form id'=> 'get_actual_quote_details',
       )
    ),
);

$object_id = 1;

if (empty($step)) {
// We reset the form when $step is NULL because that means they have
// for whatever reason started over.
get_quote_cache_clear($object_id);
$step = 'start';
}

// This automatically gets defaults if there wasn't anything saved.
$object = get_quote_cache_get($object_id);

$form_state = array(
'ajax' => $js,
// Put our object and ID into the form state cache so we can easily find
// it.
'object_id' => $object_id,
'object' => &$object,
);

ctools_include('wizard');
$form = ctools_wizard_multistep_form($form_info, $step, $form_state);
$output = drupal_render($form);

if($js){

$commands=array();

if($output===FALSE  || !empty($form_state['complete'])){

  $commands[] = ajax_command_html('#ctools-sample', finish($form_state['object']));
  $commands[] = ctools_modal_command_dismiss();

}else if(!empty($form_state['cancel'])) {

    $commands[] = ctools_modal_command_dismiss();

}else {

     $commands = ctools_modal_form_render($form_state, $output);
}

 print ajax_render($commands);
 exit;
}else{

 return $output;

 }
}
 function get_quote_start($form, &$form_state){
            $form['first_name'] = array(

'#title' => t('Your Name'),
'#type' => 'textfield',
'#size'=>20,
'#default_value' => $form_state['object']->first_name,
'#attributes'=>array(
    'placeholder'=>t('First Name'),
    'id'=>array('quote-first-name'),
),
//'#required'=>true,
);
$form['middle_name'] = array(
'#type' => 'textfield',
'#default_value' => $form_state['object']->middle_name,
'#size'=>20,
'#attributes'=>array(
    'placeholder'=>t('Middle Name'),
    'id'=>array('quote-middle-name'),
 ),
//'#required'=>true,
);
 return $form;
}
 function get_quote_start_submit(&$form, &$form_state){

global $user;

 $form_state['object']->uid=$user->uid;
}
function get_actual_quote_details($form, &$form_state){
$form['adults']=array(

    '#type'=>'select',
    '#title' => t('Adults'),
    '#options'=>array(
        1=>1,
        2=>2,
        3=>3,
    ),

 );
return $form;
}
function get_actual_quote_details_submit(&$form, &$form_state){

    // Not working redirect
       // drupal_goto('node/add/page');
        $form_state['redirect]='node/add/page',
}

Comment: Finally after some research i have solved the issue using ctools api.I have implemented below code in mine form submit handler.  ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect('node/add/page');// Redirect to url u want.
    print ajax_render($commands);
    exit;
Comment: can you post your code with this question?!
Comment: @Aboodred1 I have attached the code above .Pls have a look
Answer: This is a bit old, but hopefully it'll help someone. Down where you write your commands[] array. Change it to something like this. In the submit function of one of the earlier forms I set the redirectpath parameter on the object, then i just use that in ctools_ajax_command_redirect() after calling the dismiss modal function ctools_modal_command_dismiss().
  // If $output is FALSE, there was no actual form.
  $commands = array();
  if ($output === FALSE || !empty($form_state['complete'])) {
    // Dismiss the modal.
    $finish = _aap_main_add_finish($form_state['object']);
    $commands[] = ctools_modal_command_dismiss();
    ctools_add_js('ajax-responder');
    $commands[] = ajax_command_html('#ctools-sample', $finish);
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect($form_state['object']->redirectpath);
  }
  else if (!empty($form_state['cancel'])) {
    // If cancelling, return to the activity.
    $commands[] = ctools_modal_command_dismiss();
  }
  else {
    $commands = ctools_modal_form_render($form_state, $output);
  }

Answer: Add destination for links.
I have also similar problem with drual modal form. After user registration and forgot password I have to send it on thanks page.
Create tpl file and make registration link using below code.
<?php
echo l('Sign up here', 'user/register', array('query'=>array('destination'=>'thanks')));
?>

Create tpl file and make forgot password link using below code.
<?php
print l('Forgot Your Password?', 'user/password', array('query'=>array('destination'=>'thanks')));
?>

Answer: @Hitesh Jain : Thank you for the answer. Your comment helped me.
Just adding this as an answer so that it can help others.

ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('node/add/page');
// Redirect to url u want.
print ajax_render($commands);
exit;
Answer: I recommend you strongly to use rules  module. there is no need to programming, simply add event and action and it works great.


How to open product detail when user click on product image?

Question: I am new in Drupal and I am working on one commerce website using drupal commerce module.
The problem is arise in my website is-->
I am used views for display products with product image,title, price etc fields.
But I want to know that when user click on product image the new page will open and in that page display 3 related images of that product with detail information.
I want to give link for product image to open that clicked image product with detail.
Please help me to solved this problem...!
Answer: In view add "nid" fields before image field and make exclude from display.
Click on image field.
Go to "Rewrite Results" section.Check "output this field as link" .In the "link path" put the 'nid'. It will take you the details page of product.
...
You can also create tpl file for product content type details page.
Enjoy
Comment: Thanks Sir, But in view I was selected commerce products, hence there was no any field like "nid"?
Comment: Ok go to "advanced" section in view and click on "Relationships".Check here by adding some relation related to content.Then check the field available like nid. Else instated of searching nid do the same thing using title.Means in link path put [title] with site url.
Comment: Yaa, It's working but it show's popup window for admin to enter value.
Comment: I am not getting you.Which one works for you.It will better if you go for details.
Comment: I give link path to image like [title] and when I click on product image it shows me popup window, to edit product details.
Comment: it will be better put screen shot of both product details page and view page.


Why do we use Kullback-Leibler divergence rather than cross entropy in the t-SNE objective function?

Question: In my mind, KL divergence from sample distribution to true distribution is simply the difference between cross entropy and entropy.
Why do we use cross entropy to be the cost function in many machine learning models, but use Kullback-Leibler divergence in t-sne? Is there any difference in learning speed?
Comment: See here for some intuition on KL:  https://stats.stackexchange.com/questions/188903/intuition-on-the-kullback-leibler-kl-divergence/189758#189758
Answer: KL divergence is a natural way to measure the difference between two probability distributions. The entropy $H(p)$ of a distribution $p$ gives the minimum possible number of bits per message that would be needed (on average) to losslessly encode events drawn from $p$. Achieving this bound would require using an optimal code designed for $p$, which assigns shorter code words to higher probability events. $D_{KL}(p \parallel q)$ can be interpreted as the expected number of extra bits per message needed to encode events drawn from true distribution $p$, if using an optimal code for distribution $q$ rather than $p$. It has some nice properties for comparing distributions. For example, if $p$ and $q$ are equal, then the KL divergence is 0.
The cross entropy $H(p, q)$ can be interpreted as the number of bits per message needed (on average) to encode events drawn from true distribution $p$, if using an optimal code for distribution $q$. Note the difference: $D_{KL}(p \parallel q)$ measures the average number of extra bits per message, whereas $H(p, q)$ measures the average number of total bits per message. It's true that, for fixed $p$, $H(p, q)$ will grow as $q$ becomes increasingly different from $p$. But, if $p$ isn't held fixed, it's hard to interpret $H(p, q)$ as an absolute measure of the difference, because it grows with the entropy of $p$.
KL divergence and cross entropy are related as:
$$D_{KL}(p \parallel q) = H(p, q) - H(p)$$
We can see from this expression that, when $p$ and $q$ are equal, the cross entropy is not zero; rather, it's equal to the entropy of $p$.
Cross entropy commonly shows up in loss functions in machine learning. In many of these situations, $p$ is treated as the 'true' distribution, and $q$ as the model that we're trying to optimize. For example, in classification problems, the commonly used cross entropy loss (aka log loss), measures the cross entropy between the empirical distribution of the labels (given the inputs) and the distribution predicted by the classifier. The empirical distribution for each data point simply assigns probability 1 to the class of that data point, and 0 to all other classes. Side note: The cross entropy in this case turns out to be proportional to the negative log likelihood, so minimizing it is equivalent maximizing the likelihood.
Note that $p$ (the empirical distribution in this example) is fixed. So, it would be equivalent to say that we're minimizing the KL divergence between the empirical distribution and the predicted distribution. As we can see in the expression above, the two are related by the additive term $H(p)$ (the entropy of the empirical distribution). Because $p$ is fixed, $H(p)$ doesn't change with the parameters of the model, and can be disregarded in the loss function. We might still want to talk about the KL divergence for theoretical/philosophical reasons but, in this case, they're equivalent from the perspective of solving the optimization problem. This may not be true for other uses of cross entropy and KL divergence, where $p$ might vary.
t-SNE fits a distribution $p$ in the input space. Each data point is mapped into the embedding space, where corresponding distribution $q$ is fit. The algorithm attempts to adjust the embedding to minimize $D_{KL}(p \parallel q)$. As above, $p$ is held fixed. So, from the perspective of the optimization problem, minimizing the KL divergence and minimizing the cross entropy are equivalent. Indeed, van der Maaten and Hinton (2008) say in section 2: "A natural measure of the faithfulness with which $q_{j \mid i}$ models $p_{j \mid i}$ is the Kullback-Leibler divergence (which is in this case equal to the cross-entropy up to an additive constant)."
van der Maaten and Hinton (2008). Visualizing data using t-SNE.
Comment: Can I somehow 'favourite'  answers? I want to save this one because it is a very nice explanation
Comment: Thanks, glad it's helpful to you. You can mark a question as a favorite to save the whole thread, by clicking on the star icon below the vote buttons. You can view your list of favorites on your account page.
Comment: Awesome answer. It hits all the right points.


Infinite surface area but fixed volume for a cylinder?

Question: Problem:

The volume of a cylinder equals $V$ cubic inches, where $V$ is a constant. Find the proportions of the cylinder that minimize the total surface area.

Since we want to minimize the surface area, we want to find the critical points, which are $r=0$ (where $\frac{dS}{dr}$ is undefined) and $r=h/2$ (where $\frac{dS}{dr}$ is equal to zero). We can immediately ignore $r=0$ as being a possible solution because $V$ is a non-zero value. This leaves $r=h/2$, the book's answer to this problem, or in other words, the surface area is minimized when the radius is equal to half the height. But how do I know that the radius equalling half the height minimizes and not maximizes the surface area? The book's explanation for this is:

With $V$ fixed, we can choose $r$ and $h$ so as to make $S$ as large as we like.

How can volume be fixed but surface area be infinite. When I look this up I find Gabriel's Horn, but the 3D figure we are talking about here is a cylinder.
Comment: The area is not infinite, but you have have cylinders of arbitrarily large area.  It's like saying that there are arbitrarily large natural numbers; none of them is infinite.
Comment: No one has said the surface area is infinite.  Saying "we can make the surface area as large as we like" means it is unbounded, not infinite.
Comment: To know whether $r=h/2$ "minimizes and not maximizes the surface area", test by first derivative or second derivative of $S$.
Comment: @saulspatz I get what you are saying and that's actually what I thought at first, but the whole point of the book's statement is to disprove that there is no such thing as a maximum surface area, which is why $r=h/2$ is automatically a minimized value.
Comment: @peterwhy how can I even use those tests when no values are given
Comment: I don't get what you are saying.  There is no such thing as a maximum positive integer, and yet none of them is infinite.  As @user247327 said, the area is unbounded.
Comment: @saulspatz If you read MJD's answer, I think you will get what I mean. I'm pretty much asking how for a fixed volume, a cylinder can have infinite surface area. MJD proved this is possible. Think of rolling the cylinder like playdoh infinitely.
Comment: No, you misunderstand his answer.  He shows how to make the volume as large as desired, but it never becomes infinite.
Comment: @saulspatz No he says it becomes infinite by saying "You can't maximize the surface area".
Comment: You don't seem to know what "infinite" means.  Try reading the examples I gave about positive integers, and thinking about them.
Comment: @saulspatz I see what you mean now. I was not being careful with the word infinite.
Comment: Glad you got it.
Comment: @saulspatz I should have said you can keep changing the radius and height so that the surface area values keep getting bigger and bigger and this series of values approaches infinity. I thought you were disagreeing with me about not being able to maximize surface area when that was not the case.
Answer: Take a  piece of clay and roll it into a cylinder.  Say it has length $\ell$ and radius $r$.  Then its volume is $\ell\cdot \pi r^2$.   And its surface area (not counting the two ends) is $\ell\cdot 2\pi r$.
Now roll out your cylinder so that it becomes longer and thinner.  Say it's only half as thick as before, the radius has decreased to $\frac r2$.  But of course the volume must be the same because the amount of clay is the same.  Since the $\pi r^2$ is one-fourth as big, the length must be four times as big to make it work out.   The cylinder is half as thick, but four times as long.
That means that the new surface area, $4\ell\cdot 2\pi \frac r2$, is twice as large as it was.  Which makes sense: the cylinder is longer and thinner, so more of it is at the surface.
Now roll it to be half as thick again.  The volume is still the same, but again the surface area doubles.  Think about how quickly a thin clay snake will dry out, compared with a thick chunky cylinder. Why?  Because it has so much more surface area for the same volume of clay.
You can keep rolling the snake, and increase the surface area as much as you want.  You can't maximize the surface area, because you can always double the surface area by rolling the snake to be half as thick and four times as long.

(Other examples to consider: You can take the same clay cylinder and smear it into a thin flat sheet that covers the whole earth.  Its surface area will be the same as the earth's!  But its volume is the same as it always was.
A kitchen sponge has a small volume, but a very big surface area.  As you add more holes to the sponge, the surface area increases even though the volume of the sponge is getting smaller.)

It's important to notice that at no point does the snake have an infinite surface area.  We can roll it out as thin as we like, and make the surface area as large as we like, but it's always a snake with finite length and finite surface area.  What if the radius of the snake goes all the way to zero?  Well, that doesn't really make sense.  It's not a cylinder any more, it's a line, and a line doesn't have a surface area.
But we can use this rolling process to make a shape that does have an infinite surface area!  Start with the same cylinder, and instead of rolling out the whole thing to be half as thick, roll out just the right half, leaving the left half the way it was.  The left half's surface area stays the same, and the right half's surface area doubles, so the total surface area has increased from $\frac12+\frac12$ to $\frac12 + 2\cdot\frac12 = 1.5$.  The surface area has increased by 50%, and in particular the right half has as much surface area as the original cylinder.
Now take just the right half (which is now just as long as the original cylinder was) and roll out its right half. Again the volume of the part we roll out doubles, so the total surface area now goes from $\frac 12 + \frac12 + \frac12 $ to $\frac12 + \frac12 + 2·\frac12 = 2$.
We can keep doing this as long as we like, making this spindle thing longer and longer, and again we can make the surface area as large as we want.    But this time it's a little different than when we rolled the whole snake.  There, to make the snake infinitely long, we would have had to make its radius go to zero, and then we wouldn't have a solid figure any more.  But no part of the spindle has a radius of zero.  It gets thinner and thinner as you go along it to the right, but every part of it has a positive, nonzero thickness.   So you can take the spindle all the way to infinity, and then it has an infinite surface area, but its volume stayed the same the whole time.
This spindle is Gabriel's Horn.
Comment: How come when I look up "infinite surface area, fixed volume", only Gabriel's horn shows up? You've proved that other 3D shapes can also take on this characteristic.
Comment: @user532874: as others have pointed out, none of these cylinders has infinite surface area. Please take a  while to digest this fact.
Comment: @TonyK MJD says "You can't maximize the surface area"
Comment: @user532874: Yes, that's true. You can make the surface area 100, or 1000, or 10000, or... But you can't make it infinite. Please take a _little bit longer_ than ten minutes to digest this fact.
Comment: @TonyK I see what you mean now. I was not being careful with the word infinite.
Comment: @TonyK so the distinction between Gabriel's horn and a cylinder is that you can have 1 gabriel's horn in front of you and you will observe infinite surface area but you cannot have 1 cylinder in front of you and observe infinite surface area. You can keep changing the radius and height of the cylinder so that the surface area values keep getting bigger and bigger and this series of values approaches infinity.
Comment: @user532874: Yes, that's right.
Comment: @user532874 I added a section to the end that tries to explain how the Gabriel's Horn thing is different.  It's a very subtle difference!  I hope this helps.


Force heartbeat change active node

Question: Is there a way to force heartbeat change active node?
Or may be force to node to release resources so that one of other node take it.
Ubuntu 12.04
Heartbeat
Answer: You should have some scripts (probably in /usr/share/heartbeat) called
hb_standby
hb_takeover
You can run hb_standby on the active node to release resources.

Force heartbeat change active node


Mysql COUNT by date only part of DATETIME

Question: I have a table like below
 +-----+--------------+---------------------+
 | id  | url          | visit_date          |
 +-----+--------------+---------------------+
 |  1  + 60           | 2012-06-23 18:15:49 |
 +-----+--------------+---------------------+
 |  2  + 60&ref=qr    | 2012-06-23 12:15:49 |
 +-----+--------------+---------------------+
 |  3  + 54           | 2012-06-23 18:15:49 |
 +-----+--------------+---------------------+
 |  4  + 5            | 2012-06-24 18:15:49 |
 +-----+--------------+---------------------+
 |  5  + 60           | 2012-06-25 13:15:49 |
 +-----+--------------+---------------------+
 |  6  + 60           | 2012-06-25 19:15:49 |
 +-----+--------------+---------------------+

I want to group results my date only. so the result would be if for example I only wanted url with 60.
  +-------------+------------------+
  |visit_date   |count(visit_date) |
  +-------------+------------------+
  |  2012-06-23 |        2         |
  +-------------+------------------+
  |  2012-06-25 |        2         |
  +-------------+------------------+

I have tried the following but obviously I get every date due to the time difference.
  SELECT visit_time, COUNT( visit_time )
  FROM tracking
  WHERE query_string LIKE  '%60%'
  GROUP BY visit_time

is it possible to do this only by the date ignoring the time?
Answer: Yes, you can. Just use DATE() function.
SELECT DATE(visit_time), COUNT( visit_time )
FROM tracking
WHERE query_string LIKE  CONCAT('%', '60' ,'%')  -- makes readable
GROUP BY DATE(visit_time)

Answer: Use this
GROUP BY date(visit_time)


Dúvida: resposta aleatória

Question: Programa que faz uma pergunta e responde aleatório, e se a resposta não ajudar ele repeti, na hora do sim ele vai, mas quando coloca não ele 'buga'
import random
from time import sleep
pergunta = str(input('Oque você deseja saber?'))
print('PENSANDO...')
for contagem in range (0,3):
    sleep(1)
respostas = ['Não sei', 'Talvez', 'Não sei oque responder', 'Você sabe a resposta é só pensar mais um pouco', 'nao estou no nivel dessa pergunta', 'OK', 'Sim', 'Não ', 'Banana', 'Massa',]
print(random.choice(respostas))
aprovaçao = str(input('Essa resposta te ajudou?'))

if aprovaçao == 'sim':
    pritn('Volte sempre')

elif aprovaçao == 'nao':
    print('PENSANDO...')
    for contagem in range(0, 3):
        sleep(1)
    print(random.choice(respostas))
aprovaçao1 = str(input('Essa resposta te ajudou?'))
if aprovaçao1 == 'sim':
    pritn('Volte sempre')

elif aprovaçao1 == 'nao':
    print('PENSANDO...')
    for contagem in range(0, 3):
        sleep(1)
    print(random.choice(respostas))
aprovaçao3 = str(input('Essa resposta te ajudou?'))
if aprovaçao3 == 'sim':
    pritn('Volte sempre')

elif aprovaçao3 == 'nao':
    print('PENSANDO...')
    for contagem in range(0, 3):
        sleep(1)
    print(random.choice(respostas))

Comment: Detalhe: `input` retorna uma string, então `str(input(...))` é redundante e desnecessário, faça apenas `input(...)`. E se quer pausar por 3 segundos, não precisa do `for`, faça apenas `sleep(3)`.
Answer: Seu programa estava bugando pois você estava perguntando diversas vezes, usando vários ifs ao invés de um laço de repetição.
Olhe como o programa deveria se comportar:
import random
from time import sleep
pergunta = str(input('Oque você deseja saber? '))
respostas = ['Não sei', 'Talvez', 'Não sei oque responder', 'Você sabe a resposta é só pensar mais um pouco', 'nao estou no nivel dessa pergunta', 'OK', 'Sim', 'Não ', 'Banana',     'Massa',]
while pergunta != 'sim': # este será um loop enquanto a resposta for diferente de "sim"
  print('PENSANDO...') # a cada resposta, ele irá printar "PENSANDO..."
  sleep(3) # espero 3 segundos
  print(random.choice(respostas)) # printa uma possível resposta
  pergunta = str(input('Esta resposta responde sua pergunta? ')) # pergunta se o usuário está satisfeito com a resposta, se sim o programa acaba
print('Volte sempre!')

Dúvida: resposta aleatória