Monthly Archives: December 2011

Medical Research Gives Life Meaning

In my post Preserving Steve Jobs, I said:

I have the unorthodox belief that if a person dies, his or her life was largely pointless. They may have achieved major accomplishments and helped massive numbers of people, but they are still gone. If you think of people as databases, their valuable information has been lost. It’s still important to pursue research in mainstream medicine and global health (especially clean water) to make the lives of people more tolerable while they’re alive.

In my post Resurrecting Steve Jobs, I said:

I would like more than anything to be wrong about scientific materialism and have the ability to believe in a peaceful afterlife. I still need more proof. In the interim, it’s more important to invest in ways to make the lives of living people more tolerable.

The last lines of Mona Simpson’s eulogy A Sister’s Eulogy for Steve Jobs make me want to believe. Unfortunately, the predominant opinion of the scientific community is that death is the end. That means life is largely pointless. A person struggles to survive, reproduce, and pass on his or her genes. He or she might work, might fall in love, might fall out of love, might have children, and might seek medical care. Then they encounter death. Even if other people remember them in a positive light, it doesn’t matter to the person who died. They’re still dead.

I hope the scientific materialist perspective is wrong and it turns out that the universe is actually made of math and consciousness. In the interim period in our world as we know it, it makes sense to engage in medical research to the exclusion of all other hobbies. It’s important to examine all potential causes of death and develop science-based ways of avoiding causes of mortality for as long as possible. It’s important to examine every action and assess whether it raises or lowers your chance of death. Since I try to pay attention to evidence-based research, I have to be skeptical of achieving immortality. It’s still possible to make life more tolerable for everyone through medical research.

The primary reason to pursue health for everyone above all other goals is that a world focused on health brings some sense of peace to people while they’re alive. It’s important to alleviate the pain of people while they’re on Earth. More and better medical research can solve every problem that people encounter in life. Improving the physical state of the body and its organs can make life worth living for more people. The condition of the brain determines whether a person finds meaning and enjoyment in life.

I keep a list of written goals of items of varying levels of difficulty in areas that I have had varying levels of success at. Out of all those goals, one is the most important. The goal is health – both my health and the health of everybody in the world. I would love to be healthier than ever before. Helping other people become healthy is also a great way to create lasting friendships.

I enjoy science and think it has amazing ways of explaining the world. Sometimes the belief in living scientifically can translate into moral relativism, where a person starts believing that there’s no such thing as right and wrong. I’m not a moral relativist, and that’s because a world structured in a way that maximizes health and well-being for everyone seems better than other ways of running a society. Providing health and well-being to people is the most important goal in the world. Everything else is just a game. Altruism has been an important component of the successful development of human civilizations. Ensuring the health of every human being provides an opportunity to bring the world’s people together in ways never seen before.

My blog posts from now on will focus exclusively on medical research and biotechnology. No one really cares about my thoughts on finance or metaphysics, or at least they care much more about healing themselves. I’ve learned to search and analyze medical research and am confident that my posts (including ones I’ve already written about health) can improve the lives of millions of people. I’ve been focusing on medical research for months and have taken notes on books about medicine, nutrition, and regenerative medicine. Those posts will show up on my blog next year.

The Best of Barking up the Wrong Tree

Barking up the Wrong Tree is a blog written by Eric Barker, head of marketing at Volition (the division of THQ famous for the Red Faction and Saints Row games) and a successful screenwriter. The blog summarizes research findings that have major significance to understanding and influencing human behavior. This post links to what I feel are some of most fascinating findings posted on his blog.

• Creative people have more sex partners. (Link)

• Men with benevolent sexist beliefs report higher life satisfaction. (Link)

• Women who are intensely interested in politics have more orgasms. (Link)

• Depression can help adolescents disengage from unattainable goals. (Link)

• Women consume fewer calories when eating with a man. (Link)

• People who eat more vitamin C have more sex. (Link)

• The best performing team is made up of two men and one woman. (Link)

• Vaginal intercourse is associated with better psychological and physiological function. (Link)

• Focusing on someone new can help people overcome attachment to a former romantic partner. (Link)

• Self-talk can enhance confidence and reduce anxiety. (Link)

• People like others who move in similar ways to them. (Link)

• Surgeons with voices that express higher dominance and lower concern are more likely to have had malpractice suits filed against them. (Link)

• People can accurately detect an author’s personality based on their writing. (Link)

• People generally overestimate their predicted reactions to negative events. (Link)

• Positive moods last longer in uncertain conditions. (Link)

• Arranged marriages may be happier. (Link)

• Traits that are associated with life satisfaction and happiness. (Link)

• Being primed with intelligent stereotypes leads to improved performance on a test of knowledge. (Link)

• Loving-kindness meditation increases positive feelings. (Link)

• More people have heart attacks around Christmas. (Link)

• Grooming in males and attractive personality in females is associated with better grades. (Link)

• Education, career, and romance are the most common areas of regret. (Link)

• Explaining bad emotional experiences reduces their negative impact. (Link)

• People who have the choice of many potential mates pay more attention to trivial characteristics. (Link)

• Taller people are more intelligent. (Link)

• Pleasure, engagement, and meaning predict life satisfaction. (Link)

• Frequent checking reduces memory accuracy. (Link)

• People who form if-then plans are able to maintain willpower. (Link)

• Neuroticism and low agreeableness are associated with metabolic syndrome while conscientiousness is protective. (Link)

• People in a happy mood make quicker and more consistent judgments when shopping. (Link)

• People who recall their immoral behavior become more involved in moral behavior. (Link)

• Meditation practice increases attention. (Link)

• Thinking about time in terms of money reduces satisfaction. (Link)

• Naps promote performance and alertness. (Link)

• Fish oil increases lean mass and decreases fat mass. (Link)

• Avoiding eye contact can increase depression. (Link)

• Personality traits don’t really change from childhood to adulthood. (Link)

• Management workers are taller than other employees. (Link)

• Expressive writing improves working memory capacity. (Link)

• Information retrieved from memory contributes to an illusion of truth. (Link)

• People’s mood remains about the same through the week. (Link)

• Nostalgia increases a sense of meaning in life. (Link)

• There is little difference in cooperativeness between men and women. (Link)

• Nations with more difficult life conditions are more religious. (Link)

• Shift work and monotonous jobs are associated with higher heart attack risk. (Link)

• Teachers dislike creative students. (Link)

• Unemployed people who write about the thoughts and emotions surrounding their job loss are reemployed more quickly. (Link)

• Rimless glasses yield an increase in perceived trustworthiness but not a decrease in attractiveness. (Link)

• Attractive men write more attractively. (Link)

• Women are more likely to feel that they don’t meet their own standards. (Link)

• Seeing the Apple logo can make people more creative. (Link)

• Agreeableness is the strongest predictor of relationship satisfaction. (Link)

• Left handed men are more generous and left handed women are less altruistic. (Link)

• People told to pray for their partner exhibit less infidelity. (Link)

• Volunteering is associated with more life satisfaction. (Link)

• Introverts and people with more neurotic personalities prefer e-mail over in-person interactions. (Link)

• Exercising at any level is associated with better physical and mental health. (Link)

• Muscle tightening increases self-control. (Link)

• Facial expressions of positive emotion improve attention. (Link)

• Evening people are more intelligent than morning people. (Link)

• Individuals with higher intelligence and self-confidence are more likely to become entrepreneurs. (Link)

• People are better than others at assessing their own level of anxiety, while friends can judge intelligence and creativity. (Link)

• Keeping one’s options open yields lower satisfaction with a decision. (Link)

• Socially aversive traits are positively related to symmetry and prosocial traits are negatively related to symmetry. (Link)

• Lowering voice pitch leads to a greater perception of power. (Link)

• Moderate to vigorous exercise improves sleep quality. (Link)

• Having an upright posture leads to greater feelings of pride in an achievement. (Link)

• Rapport-building behaviors used by retail employees. (Link)

• Autonomy, competence, and relatedness are the keys to feeling good each day. (Link)

• 75% of married couples who choose to separate end up divorcing. (Link)

• Threats are more effective than anger in negotiations. (Link)

• Words are better than gifts in enhancing trust. (Link)

• Modest rule breaking predicts the number of leadership roles taken on by individuals. (Link)

• Punishers feel worse than people who don’t take revenge. (Link)

• People are more inclined to pick leaders with lower-pitched voices. (Link)

• The experience of time affluence is positively related to subjective well-being. (Link)

• Couples who love each other spend more time gazing into one another’s eyes. (Link)

• Women show less message agreement in response to e-mail messages as compared to face-to-face messages. (Link)

• The presence of monetary wealth increases unethical behavior. (Link)

• Impulsivity is associated with obesity. (Link)

• Gain-framed messages engender better message engagement. (Link)

• Having a sense of personal control makes women more likely to initiate relationships. (Link)

• Sunday is the day of the week where people report the lowest subjective well-being. (Link)

• The willingness to enter a competition in hopes of achieving a bigger payoff continues to rise until people are in their 50′s. (Link)

• Mutual gaze increases love between members of the opposite sex. (Link)

• Men who are taller and who have less education have sex more frequently. (Link)

• Eating slowly results in fewer calories being consumed. (Link)

• Men with lower levels of agreeableness have more casual sexual relationships. (Link)

• Workers with a greater propensity to quit are offered higher wages. (Link)

• Vigilant monitoring enhances habit control. (Link)

• Promotions may reduce the risk of developing heart disease. (Link)

• Women gain more weight after marriage and men gain more weight after divorce. (Link)

• Writing about traumatic events speeds up wound healing. (Link)

• Anticipating an interaction with a woman decreases cognitive performance in men. (Link)

• Men who view attractive photos of the opposite sex are more likely to endorse war. (Link)

• Couples with positive relationship illusions have better relationships. (Link)

• Playing video games can increase creativity and reduce nightmares. (Link)

• People with a lower tolerance for unethical conduct have greater life satisfaction. (Link)

• Agreeableness is negatively related to a person’s credit score. (Link)

• People are more likely to forgive when they are reminded of their previous wrongdoings. (Link)

• People are more persuasive when they speak moderately fast. (Link)

• Moderate overconfidence increases productivity and performance. (Link)

• Chewing gum reduces stress. (Link)

• Speaking in a powerful style is more persuasive. (Link)

• Having meaning in life makes people more likeable and attractive. (Link)

• Belonging to social groups improves mental health. (Link)

• Stronger liberalism predicts greater positive affect and stronger conservatism predicts less negative affect. (Link)

• Presenting a confusing pitch and then reframing it to make sense can be persuasive. (Link)

• Being reminded of God can help people resist temptation. (Link)

• People with subtle asymmetries are more inspiring leaders. (Link)

• People in negative moods produce more persuasive messages. (Link)

• Women stop hanging out with cheating girlfriends when they enter a long-term relationship. (Link)

• Ways to be more charismatic. (Link)

• Social interactions enhance cognitive function. (Link)

• Resisting a persuasive message reduces subsequent self-control. (Link)

• Women with feminine voices are more attractive to men. (Link)

• Self-deception enhances motivation and performance. (Link)

• People who feel powerful can withstand more pain. (Link)

• People are happier and more helpful in the presence of pleasant ambient odors. (Link)

• Yoga can treat depression. (Link)

• Non-native speakers are judged as being less credible. (Link)

• There are regional personality differences in the USA. (Link)

• Positive fantasies about the future predict poor achievement. (Link)

• Hope predicts academic achievement above intelligence, personality, and previous academic achievement. (Link)

• Men are happier when they are taller than other men in their reference group. (Link)

• Parents report lower marital satisfaction than nonparents. (Link)

• Men are more attractive when they say they were the ones that dumped their ex-girlfriend. (Link)

• Smile intensity in a Facebook profile photo predicts life satisfaction nearly four years later. (Link)

• Thin women enjoy shopping more than larger women. (Link)

• Income increases subjective well-being, but only up to a certain level. (Link)

• 66% of Americans would keep working after winning the lottery. (Link)

• Women using hormonal contraceptives are less sexually satisfied but more satisfied with the relationship. (Link)

• Divorce can be predicted by how much people smile in photos. (Link)

• The stress of overtime work offsets the gain in income. (Link)

• Personality traits of creative people. (Link)

• Social involvement is worth more than $100,000 in life satisfaction. (Link)

• Older adults are more willing to forgive than younger adults. (Link)

• Higher wages are associated with higher job satisfaction and more anxiety. (Link)

• Self-esteem does not change beyond 30 years of age. (Link)

• Psychopaths can be identified by the words they use. (Link)

• Gratitude promotes relationship maintenance. (Link)

• Cognitive load while practicing can prevent people from choking under pressure. (Link)

• Positive imagery improves mood and behavior. (Link)

• Reflective rumination predicts creativity. (Link)

• Optimistic people only learn from information that reinforces their view of the world. (Link)

• There is a link between narcissism and leader emergence. (Link)

• Materialistic couples have worse relationships. (Link)

• Personality traits can be assessed by body odor. (Link)

• How personality affects which sex acts people prefer. (Link)

• Doing nothing is more effective than venting anger. (Link)

• Making specific plans reduces intrusive thoughts. (Link)

• People who rate their personality as more agreeable have a stronger preference for sweet foods. (Link)

• Taller women want fewer children and more career success. (Link)

• A significant proportion of the variation in voting turnout can be accounted for by genes. (Link)

• Restoring glucose improves self-control. (Link)

• Women who wear makeup seem more attractive, competent, likeable, and trustworthy. (Link)

• Individuals who are more insecurely attached are more likely to notice threats. (Link)

• Behaving communally reduces penalties for women who work in male areas. (Link)

• Positive gossip that praises someone can increase the gossiper’s self-esteem. (Link)

• More attractive women prefer masculine men. (Link)

• Music training software increases verbal intelligence. (Link)

• Observers can accurately determine personality from photographs. (Link)

• There is a correlation between grip strength and sensation seeking. (Link)

• Role clarity reduces work-related stress. (Link)

• People who believe that moral character can change are more trusting. (Link)

• Relationships that are kept secret create more attraction. (Link)

• Third-person imagery increases the accuracy of predictions. (Link)

• There is a connection between chronic stressors and infections. (Link)

• Erotic and aggressive videos increase testosterone in men. (Link)

• Consumer preferences are influenced by lists of product specifications. (Link)

• Writing about your most important values can reduce insecurity and anxiety. (Link)

• Doctors indicate lower pain estimations with regard to patients who are associated with negative personality traits. (Link)

• Most lies are told to individuals that people feel closest to. (Link)

• People overwhelmingly favor physicians who wear professional attire and a white coat. (Link)

• Universal generosity decreases perceptions of prestige and dominance. (Link)

• Muscular men have more lifetime sex partners, short-term partners, and affairs with mated women. (Link)

• Thinking about politicians has a strongly detrimental effect on well-being. (Link)

• People’s ideal partners are of a different height, weight, and body mass index than the partners they have. (Link)

• Reconnecting with old acquaintances on social networks leads to social benefits. (Link)

• People with low self-esteem feel worse after repeating positive statements about themselves. (Link)

• Slow onset smiles lead to more positive evaluations. (Link)

• Leaders speak first and most often. (Link)

• Less sleep is associated with lower resistance to illness. (Link)

• Getting lost is highly associated with cognitive impairment. (Link)

• Limited perceived control over life circumstances is associated with cardiovascular disease. (Link)

• Apologies work better than monetary compensation for reacting to customer complaints. (Link)

• Men with low cortisol levels are more attractive to women. (Link)

• Strong men and attractive women are more prone to anger. (Link)

• Spacing learning events apart increases learning. (Link)

• Productivity increases while creativity decreases in situations with higher levels of job insecurity. (Link)

• A sad mood decreases trust and negatively impacts negotiations. (Link)

• Life satisfaction is the same in the Midwest and Southern California. (Link)

• People are more likely to comply with requests from people who share similarities. (Link)

• Anticipating rapid feedback enhances performance. (Link)

• Novices respond to positive feedback while experts respond to negative feedback. (Link)

• Perceived similarity is a strong predictor of marital well-being. (Link)

• Conspicuous consumption enhances the desirability of men as a short-term mate. (Link)

• Positive mental time travel and being present are both associated with heightened pleasure. (Link)

• Internet job search reduces unemployment durations by 25%. (Link)

• Single women are more interested in a man who is already attached. (Link)

• Apologies inspire forgiveness when they align with victims’ self-construals. (Link)

• Women remember men more when they have a low masculine voice. (Link)

• Having power without status leads to demeaning behaviors toward others. (Link)

• Having compassion for others can reduce stress. (Link)

• People are happier when doing something rather than nothing. (Link)

• Happiness protects against illness. (Link)

• Belief in conspiracy theories may help people attain or maintain a sense of meaning, control, and security. (Link)

• Taking a break to use the internet improves productivity. (Link)

• People who ask themselves whether they will perform a task go on to do better on the task. (Link)

• Men evaluate a dating interaction more positively when women mimic them. (Link)

• Axillary odor pleasantness predicts attractiveness of nonverbal behavior in men. (Link)

• The level of marital conflict doesn’t change over time. (Link)

• Choosing to take breaks can improve creativity and insight. (Link)

• The strongest determinants of job satisfaction are relations with colleagues and supervisors, task diversity, and job security. (Link)

• Rhetorical questions make messages more persuasive. (Link)

• People have a bias to view behaviors as intentional. (Link)

• There is an important genetic component in marital status. (Link)

• Women are more attractive when wearing red. (Link)

• Unmarried people have higher affective pain and psychological disability. (Link)

• The positive effect of internet use is stronger for low income and young individuals. (Link)

• Experts who think unconsciously outperform others. (Link)

• Narcissists think they are more creative. (Link)

• Only children are less liked by classmates and are more likely to be victimized and aggressive. (Link)

• People with symmetrical facial features are more selfish and less cooperative. (Link)

• Having a biological criminal father increases psychopathic personality traits in male offspring. (Link)

• The pursuit of happiness through money is a negative predictor of well-being. (Link)

• Women with sexist attitudes towards other women are more susceptible to the strategies of pick up artists. (Link)

• Asking people about their expectations of giving into a temptation increases their propensity to give in. (Link)

• People who value happiness are more likely to be disappointed. (Link)

• Anchoring to a high number leads to higher salary offers. (Link)

• People who live in the present are more likely to have credit card debt. (Link)

• Men prefer women with attractive bodies in short-term mating and attractive faces in long-term mating. (Link)

• Mortality salience increases self-esteem. (Link)

• Women are perceived as more feminine when they tilt their faces downwards and men are perceived as more masculine when they tilt their faces upwards. (Link)

• Mimicking language in the first ten minutes of a negotiation improves performance. (Link)

• The largest gender differences are in nurturance, smiling, aggression, and sensitivity to nonverbal cues. (Link)

• Forgiveness is associated with lower blood pressure and lower heart rate. (Link)

• Distraction may help in treating depression. (Link)

• Visualizing your best possible self improves and maintains positive mood. (Link)

• Bitterness can negatively impact health. (Link)

• The use of pain diaries actually increases the perception of symptom severity. (Link)

• Women feel less belonging and less motivation when gender-exclusive language is used. (Link)

• Remembering previous successes, observing others doing something daunting, and enlisting others’ support can increase self-efficacy. (Link)

• Practicing gratitude improves mood. (Link)

• Individuals with high levels of power ignore expert advice. (Link)

• Testosterone is positively related to performance in individual competition but negatively related to performance in intergroup competition. (Link)

• People who write about their romantic relationships are more likely to still be dating their romantic partner several months later. (Link)

• Women are more interpersonally warm during periods of high fertility. (Link)

• Petting a stuffed animal improves immune system function. (Link)

• People who are exposed to abstract art have a subsequently higher need for meaning. (Link)

• Positive and optimistic humor is an effective coping strategy. (Link)

• People have an increased tolerance for risk after viewing photos of the opposite sex. (Link)

• People who are friends with those they work with are more likely to be promoted and live longer. (Link)

• Twitter users can entertain a maximum of 100 to 200 stable relationships. (Link)

• Overconfidence increases productivity. (Link)

• Being a grandparent is associated with life satisfaction. (Link)

• Activating a positive superstitious belief can enhance performance. (Link)

• People misremember their forecasts and fail to perceive the extent of their forecasting error. (Link)

• Scenarios in which self-talk works better. (Link)

• Language style matching predicts who pairs up in speed dating. (Link)

• Physical cleansing make people less moralistic. (Link)

• Attractiveness reduces success when the person being evaluated is the same sex as the evaluator. (Link)

• People with exceptional longevity do not have healthier habits than a comparison group. (Link)

• There is no gender difference in how much people are upset by sexual or emotional infidelity. (Link)

• Narcissism positively correlates with life satisfaction for adolescents and emerging adults, but not for adults. (Link)

• College students who receive money from their parents do less well in college. (Link)

• Positive music can help people accept unethical products. (Link)

• Participating in a novel and arousing task improves relationship quality. (Link)

• Women who are primed with romantic cues report less positive attitudes towards science, engineering, and math. (Link)

• Attractiveness predicts well-being and social connectedness among urban but not rural women. (Link)

• Moderate constraints enhance creativity. (Link)

• Women see men as more attractive and sexually desirable when the men are wearing red. (Link)

• Taller men and shorter women have more reproductive success. (Link)

• Men are seen as more attractive when standing next to expensive cars. (Link)

• Women with larger breasts and narrow waists have higher fecundity. (Link)

• Clean scents promote trusting and reciprocity. (Link)

• Text messages can help treat schizophrenia. (Link)

• People who have more sex have better immune systems. (Link)

• Inhibiting prefrontal cortex activity can make people better liars. (Link)

• Omega-3 supplements reduce anxiety and inflammation. (Link)

• Napping improves learning capacity. (Link)

• Optimism reduces the risk of having a stroke. (Link)

• Eating foods with fatty acids improves mood. (Link)

• Being told that anxiety increases performance actually increases performance. (Link)

• People with less honesty and humility are more creative. (Link)

• Men who are risk-takers or easily aroused are more likely to be unfaithful, while dissatisfied women are more likely to cheat. (Link)

• Exposure to forward movement cues activates achievement goals. (Link)

• The more time people spend handling e-mail, the greater their sense of feeling overloaded. (Link)

• The perception of the color red reduces performance. (Link)

• Impulsivity is the strongest predictor of who will be overweight. (Link)

• Playing video games reduces reaction time. (Link)

• Poorer socioeconomic status during childhood is associated with lower facial symmetry. (Link)

• Self-promotion in response to a question is perceived more favorably than self-promotion in other contexts. (Link)

• Work sample tests and general intelligence are the best predictors of work performance. (Link)

• People with higher trust in their feelings predict outcomes better. (Link)

• Ads with sexual content are less offensive to women when they have commitment messages. (Link)

• Regular practice of self-control can improve self-control performance. (Link)

• Male sex drive is stronger than female sex drive. (Link)

• People who deceive others also deceive themselves. (Link)

• Males with greater fat-free mass and/or limb muscle volume lose their virginity sooner and have sex with more partners. (Link)

• Lone inventors are less likely than collaborative people to make breakthroughs. (Link)

• Self-forgiveness predicts better performance. (Link)

• Rejection can reduce a person’s intelligence and increase aggression. (Link)

• The threat of gossip can increase fairness. (Link)

• Using a basket instead of a cart increases the probability of purchasing vice items by nearly 7 times. (Link)

• Flirting at work is negatively related to job satisfaction for men. (Link)

• People who expect to be accepted act more warmly and are perceived as more likeable. (Link)

• Frequent kissing and cuddling predicts happiness in the relationship for men, but not for women. (Link)

• Positive mood increases selfishness and sad mood increases fairness. (Link)

• People solve problems faster when lying down. (Link)

• Household debt leads to deterioration in physical and mental health. (Link)

• The left side of the face is seen as more expressive. (Link)

• Taller men and women have higher incomes. (Link)

• Unfulfilled goals can interfere with later tasks. (Link)

• Cold and incompetent groups are subject to more harassment. (Link)

• Thinking about intelligence as changeable results in greater academic achievement. (Link)

• Social sensitivity and more women in a group improve team performance. (Link)

• Avoiding the use of safety behaviors and self-focused attention can reduce social anxiety. (Link)

• Wealth has a negative impact on the ability of individuals to savor experiences. (Link)

• Sleeping after goal encoding promotes later execution of a goal. (Link)

• Looking at a picture of a loved one can reduce pain. (Link)

• Positive emotion words and “we” words are associated with improved performance. (Link)

• People make up their mind about someone within 100 milliseconds. (Link)

• Belief in progress helps alleviate the aversive experience of low levels of control. (Link)

• Meditation improves attention and control of stress. (Link)

• Playing FPS games promotes cognitive flexibility. (Link)

• Yoga improves sexual function in men. (Link)

• Gardening can reduce stress. (Link)

• Using ingroup pronouns increases perceived familiarity. (Link)

• Energy drinks decrease reaction times. (Link)

• Babyfaced individuals are perceived as less competent. (Link)

• Firstborns have a preference for mastery goals while secondborns have a preference for performance goals. (Link)

• A prominent and sharply raised lip tubercle in a woman’s face is associated with greater odds of vaginal orgasm. (Link)

• A light touch from a female experimenter increases risk taking. (Link)

• Exposure to sexual primes increases intimacy. (Link)

• Affirming a moral identity leads people to act immorally. (Link)

• Experiential purchasing decisions are easier to make and are more conducive to well-being than material purchases. (Link)

• Mating is facilitated by a costly yet intrinsically worthless gift. (Link)

• Chewing gum enhances memory performance. (Link)

• Happiness extends life expectancy. (Link)

• A list of the most promiscuous countries. (Link)

• Self-affirmation facilitates self-control. (Link)

• Spending is lower when money is represented as a large denomination relative to many smaller denominations. (Link)

• Joint bank accounts are associated with higher levels of relationship quality. (Link)

• Expressing gratitude increases perceived communal strength. (Link)

• Viewing emotion-laden images after taking a test enhances retention of the tested material. (Link)

• Mimicry of customers is associated with higher sales rates. (Link)

• Adding flowers and plants to an office increases creativity. (Link)

• Leaders with positive moods enhance team performance. (Link)

• Writing about a traumatic event increases well-being. (Link)

• Exposure to brief videos of nonverbal behavior predicts a teacher’s performance in student evaluations. (Link)

• Women are more likely than men to have a sexual relationship with a co-worker. (Link)

• Empathy decreases during medical school and residency. (Link)

• Poor and hungry men prefer larger women. (Link)

• Lonely people bathe or shower more often. (Link)

• Women pay more attention to status products around the time of ovulation. (Link)

• Men are more likely to accept an apology from an attractive woman and women are more likely to accept an apology from an unattractive person. (Link)

• Subliminal priming of a message related to trust increases behavioral attentions in accordance with the message. (Link)

• Women speak with a higher voice pitch to men they find attractive. (Link)

• Being in a positive mood enhances problem-solving ability. (Link)

• Blacks perceive racially biased white interaction partners more positively. (Link)

• SAT scores predict performance in college. (Link)

• People rate prospective dates optimistically and are then disappointed. (Link)

• The performance of a company can be judged by the CEO’s face. (Link)

• Upper class people pay less attention to a conversation partner. (Link)

• People have more positive thoughts and greater self-esteem when sitting up straight. (Link)

• Up to a certain point, autonomy increases well-being. (Link)

• People who smile perform better on attentional tasks. (Link)

• Detecting deception is easier when placing a cognitive load on the liar. (Link)

• Politically savvy individuals who ingratiate themselves have less distress. (Link)

• Masculine and dominant men give women better orgasms. (Link)

• Reading about stupid people reduces performance on a knowledge test. (Link)

• Adopting dominant poses improves pain tolerance. (Link)

• Sleeping before making a decision improves decision quality. (Link)

• Physically attractive people are viewed with greater distinctive accuracy. (Link)

• There’s not really such a thing as blue states or red states. (Link)

• Cues that affect aging. (Link)

• People who read a passage and then take a test asking them to recall what they had read  end up retain 50% more of the information. (Link)

• Belief in powerlessness impairs performance on executive-function tasks. (Link)

• Weak temptations cause people to give in more than strong temptations. (Link)

• Exposure to an American flag leads to a shift towards Republican beliefs, attitudes, and voting behavior. (Link)

• Happiness levels can change in response to events throughout life. (Link)

• Subjects who have difficulty disengaging from unattainable goals have more inflammation. (Link)

• The same brain networks associated with physical pain are activated when people think about a lover who spurned them. (Link)

• Married women report less stress when holding their husband’s hand. (Link)

• Less urban areas are associated with moderately higher levels of happiness. (Link)

• Older people may be less able to lie and recognize lies. (Link)

• Men who express anger in a professional context are conferred higher status, whereas women who express anger are given lower status. (Link)

• What you say about others reflects back on you. (Link)

• Retail therapy has lasting positive impacts on mood. (Link)

• Planning in advance is the best way to fight stress. (Link)

• The average level of happiness among the wealthiest Americans is only modestly higher than the level of happiness among other groups. (Link)

• It’s better to talk about travel than movies on a first date. (Link)

• Recalling social pain is more painful than recalling physical pain. (Link)

• Factors that contribute to happiness. (Link)

• People who receive more invisible practical and emotional support from their partners report greater declines in negative emotions. (Link)

• Hospital patients who watch humorous films use 60 percent fewer pain-relieving drugs. (Link)

• Employee perceptions affect workplace outcomes more than outcomes affect employee perceptions of their jobs. (Link)

• Posture expansiveness activates at sense of power. (Link)

• Women who display genuine smiles go on to have happier lives. (Link)

• Glucose reduces aggressive behavior. (Link)

• Mastery goals are more socially beneficial than performance goals. (Link)

• Sociosexually unrestricted men and agreeable women show greater mate value accuracy. (Link)

• Facial ratings of executive power correlate with law firm profits. (Link)

• Signing at the beginning of a contract reduces dishonesty. (Link)

• People with long commutes are more likely to get divorced. (Link)

• Factors that are associated with marital and sexual satisfaction. (Link)

• There is a link between perceived unfairness and heart rate variability. (Link)

• Happiness is the most attractive female emotion expression and one of the least attractive male emotion expressions. (Link)

• People who are surrounded by happy people are more likely to become happy. (Link)

• Married women and men have less contact with their parents than never married or divorced people. (Link)

• Certain study techniques can increase performance on tests by 29 to 63 percent. (Link)

• Light touch increases a woman’s compliance with a man’s request. (Link)

• Pessimists do better in law careers. (Link)

• There is a negative relationship between complexity and judged intelligence. (Link)

• Low expertise sources promote persuasion when they express certainty, while high expertise sources promote persuasion when they express uncertainty. (Link)

• Positive expectations predict better health. (Link)

• Spouses who are less forgiving experience declines in aggression. (Link)

• A breakfast high in protein increases satiety and reduces hunger. (Link)

• People feel less guilty about moral transgressions after physically cleansing themselves. (Link)

• Nations that are geographical neighbors have more similar IQs. (Link)

• People are more likely to forgive partner transgressions when their partners have higher mate value. (Link)

• Frequent exercise and religious attendance improve well-being. (Link)

• Early sexual initiation does not cause later risk-taking. (Link)

• People inaccurately predict their feelings and wrongly recall their predictions. (Link)

• Deep-voiced men who speak moderately fast are better at getting people to agree. (Link)

• Inmates with prison tattoos have higher rates of recidivism. (Link)

• People who set conservative goals have a harder time achieving satisfaction than those who set ambitious goals. (Link)

• Factors that are associated with a higher risk of marital separation. (Link)

• People living in more economically unequal states are less agreeable. (Link)

• People at speed dating events focus more on generally agreed upon mate values and more observable characteristics. (Link)

• Men contribute more to charity when observed by a member of the opposite sex. (Link)

• Upward social comparisons are only useful when people think success is attainable. (Link)

• Effects on happiness in the USA and UK. (Link)

• Women who play selectively hard to get are rated better by men. (Link)

• Men prefer a woman who is 1.9 years younger than them and women prefer a man who is 3.5 years older than them. (Link)

• Psilocybin reduces anxiety. (Link)

• An individual’s natural disposition is a more significant predictor of happiness than specific events. (Link)

• A part of the brain shrinks in members of some religious denominations but not others. (Link)

• People select marriage partners on the basis of social and political views. (Link)

• Positive self-presentation facilitates more accurate impressions. (Link)

• The difference between homicidal fantasies of males and females. (Link)

• Ways to detect deception. (Link)

• Envisioning a hopeful future is important for well-being. (Link)

• Men think about sex 18 times a day while women think about sex 10 times a day. (Link)

• Duration knowledge can reduce the stress of a negative experience. (Link)

• The happiest and unhappiest states. (Link)

• People tend to display their real personality rather than their idealized self on social networking sites. (Link)

• People who idealize their partner the most experience the least decline in marital satisfaction. (Link)

• Men park more accurately and faster than women. (Link)

• Sexual restraint is associated with better relationship outcomes. (Link)

• Women are better than men at recalling the appearance of others. (Link)

• People who focus on why they want to achieve goals are more receptive to opportunities. (Link)

• Medical school class presidents die earlier than their classmates. (Link)

• Positive self-talk improves performance. (Link)

• Slightly longer legs are perceived as more attractive. (Link)

• Caffeine undermines collaboration in men and enhances it in women. (Link)

• People are swayed by the type of metaphor used. (Link)

• Answering a similar question is the best way to dodge uncomfortable questions. (Link)

• Female relatives of homosexual and bisexual men are more fertile. (Link)

• Depressed individuals perform better at sequential decision making tasks than their nondepressed peers. (Link)

• People are more likely to avoid situations that allow them to deceive others. (Link)

• Fast talking is most persuasive when trying to convince people who are resistant to a message. (Link)

• Conscientious people are unhappier than others when they become unemployed. (Link)

• Mothers with greater life satisfaction have children with greater verbal intelligence. (Link)

• People give more money to anonymous strangers when God concepts are activated. (Link)

• Making progress in meaningful work is the most important contributor to job satisfaction. (Link)

• Maximizers are less satisfied than satisficers. (Link)

• Women are better at detecting cuteness. (Link)

• Humor predicts mating success in men. (Link)

• Mindfulness meditation improves attention. (Link)

• Individuals can identify altruistic traits in others just from briefly observing them. (Link)

• Risk of death is significantly greater for high scorers in perfectionism and neuroticism. (Link)

• Premenstrual and menstrual women prefer comedy more than women who are at mid-cycle. (Link)

• People who believe in conspiracy theories have more Machiavellian personalities. (Link)

• Satisfied people are more likely to vote than unhappy people. (Link)

• People who watch more fiction on television believe more that the world is fair. (Link)

• Lower class individuals are more generous, charitable, trusting, and helpful than their upper class counterparts. (Link)

• Mimicry improves negotiation outcomes. (Link)

• People who are the most motivated to respond to their partner may also be more likely to break promises. (Link)

• People who take dietary supplements feel invulnerable to health hazards. (Link)

• Women with high levels of desirability and trust are less likely to shy away from high-value men. (Link)

• Fervent believers or disbelievers are happier than people with weak religious beliefs. (Link)

• Snap judgments about neighborhoods tend to be accurate. (Link)

• Persistent perceived job insecurity predicts worse health. (Link)

• People who recall making a purchase for someone else become happier. (Link)

• Perceived availability of alternative partners is associated with lower marital quality. (Link)

• Women with controlling images of God experience more hopelessness, while men with controlling images of God experience less hopelessness. (Link)

• Women gain weight in weaker economic periods and males gain weight in stronger economic periods. (Link)

• Business started by the very rich are more likely to fail. (Link)

• Frequent unimportant posts and divisive topics such as religion and politics lead to unfriending on Facebook. (Link)

• Being near nature reduces the impact of stressful events. (Link)

• Losing weight improves memory. (Link)

• Smiling increases the response to humorous things. (Link)

• Compliance rates are higher when a requester asks a question and then waits for a response. (Link)

• Heritability accounts for almost half of the variance in political beliefs. (Link)

• Reminders of physical cleansing influence moral judgments. (Link)

• The link between gut feelings and intuitive decision making is stronger for people who are aware of their heartbeat. (Link)

• People who blush are trusted more. (Link)

• Use of more “we”-related words is associated with greater relationship satisfaction. (Link)

• College students who believe in a caring and forgiving God are more likely to cheat in school. (Link)

• More grooming time increases wages for men but not for women. (Link)

• Redundant communication helps managers move their products forward more quickly. (Link)

• Men with wide faces are less trustworthy. (Link)

• Students who sit in the front third of the lecture hall are less distracted. (Link)

• People underestimate the likelihood to which others will agree to a direct request for help. (Link)

• Writing letters of gratitude increases happiness and life satisfaction. (Link)

• Older individuals with more positive self-perceptions of aging go on to live longer. (Link)

• The accumulation of everyday stresses is a central trigger for divorce. (Link)

• A wandering mind can cause unhappiness. (Link)

• Testosterone is positively and sizably associated with the number of opposite sex partners in men. (Link)

• Writing about worries before an exam improves test performance. (Link)

• Gratitude promotes social affiliation and strengthens relationships. (Link)

• Tolerance is greater among men than among women. (Link)

• Low household income is associated with more mental disorders. (Link)

• Reminders of goal achievement and small prizes can reduce procrastination. (Link)

• Men with lower levels of antisocial behavior are more likely to marry. (Link)

• People who expect others to act selfishly end up experiencing more uncooperative behavior. (Link)

• What has and hasn’t changed in young people over the past decades. (Link)

• Positive expectations but not positive fantasies predict high effort and successful performance. (Link)

• People are more helpful when at an elevated altitude. (Link)

• Women find married men more attractive than single men. (Link)

• Teddy bears can help people cope with social exclusion. (Link)

• Ethical character is negatively associated with males’ wages. (Link)

• Long-distance dating relationships have more stability than geographically close dating relationships. (Link)

• Religious people are not more charitable. (Link)

• Hungry judges give harsher sentences. (Link)

• Men tend to confess their love first in relationships. (Link)

• Sodium can inhibit stress hormones. (Link)

• Unemployment increases the risk of premature mortality. (Link)

• How environmental cues affect aging. (Link)

• Creativity and mental illness run together in families. (Link)

• Belief in external control is protective for coping with the death of a spouse. (Link)

• In online dating, women are reluctant to contact men with a lower level of education than themselves. (Link)

• Mutually high self control is associated with greater relationship satisfaction. (Link)

• People induced to feel pride show more moral hypocrisy. (Link)

• Goal-setting predicts adult well-being. (Link)

• Shifting into committed relationships is associated with higher levels of subjective well-being. (Link)

• Experience in dating relationships predicts optimism about future dating relationships while parents’ relationships predict optimism about marriage. (Link)

• There are no significant differences in relationship quality between long distance relationships and proximal relationships. (Link)

• People perceive desirable objects as being closer to them. (Link)

• Women exposed to flowers have a more positive response to male solicitation. (Link)

• Predictors of marital well-being. (Link)

• The belief in global warming is affected by how hot the temperature is. (Link)

• Displays of luxury elicit preferential treatment. (Link)

• The state of mood early in the day predicts employee performance. (Link)

• There is a negative correlation between mobile phone penetration and corruption. (Link)

• People who attempt to change their relationship partner don’t have much success. (Link)

• Extraversion and conscientiousness can be judged accurately by handshake. (Link)

• Poor self-esteem during adolescence predicts low earnings during adulthood. (Link)

• Unemployed applicants are viewed as less competent, warm, and hireable. (Link)

• Men are more romantic than women. (Link)

• Botox slows reading of sentences that describe situations that evoke emotion. (Link)

• Perceived attribute similarity is important in high commitment relationships, while perceived dissimilarity is associated with greater liking in low commitment relationships. (Link)

• What people lie about in online dating. (Link)

• Men and women are more similar in poorer countries. (Link)

• Actively disengaged workers rate their lives worse than unemployed workers. (Link)

• Being in a positive mood decreases working memory. (Link)

• Having plants around increases cognitive performance. (Link)

• People who fell in love at first sight don’t have lower quality relationships. (Link)

• Warm and competent people are highly valued. (Link)

• Men break up for reasons of autonomy, openness, and equity while men break up when they feel the relationship lacks a certain magic. (Link)

• Humor reduces argument scrutiny. (Link)

• Intoxicated people give out higher attractiveness ratings. (Link)

• When cognitive resources are depleted, conservatives become more like liberals. (Link)

• Men and women are equally likely to use deceptive self-presentational tactics. (Link)

• World leaders are perceived equally realistic and less relevant than characters in Hollywood movies. (Link)

• Gift recipients are more appreciative of gifts that they specifically request. (Link)

• Ways in which a person’s condition at birth affects their life. (Link)

• Nutritional supplements can increase cognition. (Link)

• People exercise more if they are asked in advance about how much they plan to exercise. (Link)

• People with more knowledge of their friends triggers have better relationships. (Link)

• Betting on information improves memory recall. (Link)

• Prayer reduces anger and aggression even among people who aren’t religious. (Link)

• Taking a nap reduces emotional reactivity. (Link)

• Men who express humor obtain greater compliance from women and a higher positive evaluation. (Link)

• Participants generate more creative ideas on behalf of distant others than for either close others or themselves. (Link)

• Sharing a weakly held negative attitude of a third party can increase closeness between two strangers. (Link)

• Touching heavy, rough, and hard objects can impact decisions about people and situations. (Link)

• College males become more satisfied with their appearance after losing their virginity, while college females become less satisfied with their appearance. (Link)

• Writing about comfort food helps people who are secure reduce loneliness. (Link)

• Vodka is associated with greater homicide rates. (Link)

• How to spend money to increase happiness. (Link)

• States with more infectious disease have lower average IQ. (Link)

• A leader’s experience of heightened power produces verbal dominance, which reduces perception of leader openness. (Link)

• Thinking about how other people can be helpful undermines motivation to expend effort on a goal. (Link)

• Early bilinguals show advantages in tasks that require cognitive flexibility. (Link)

• Couples who reminisce about shared laughter report higher relationship satisfaction. (Link)

• Gifted and nongifted adults do not differ statistically significantly in subjective well-being. (Link)

• The effects of personality traits on finding a job. (Link)

• In Australia, only 46% of men and 58% of women are satisfied with their current frequency of sex. (Link)

• Happy children are less likely to develop mental disorders and are more likely to get divorced. (Link)

• Touch is positively associated with compliance. (Link)

• Sleep deprivation increases sensitivity to positive rewards and diminishes sensitivity to negative consequences. (Link)

• Expressions associated with shame and pride are innate. (Link)

• People with greater feelings of interpersonal security are less materialistic. (Link)

• Weak evidence is less persuasive than no evidence at all. (Link)

• People are more likely to be derogated as their number of sexual partners increases. (Link)

• IQ is associated with per capita GDP. (Link)

• Physical disgust elicits feelings of moral disgust. (Link)

• Information on who displays more consistency. (Link)

• Criminals and scientists both become less effective after they get married. (Link)

• Homework has meaningful effects on math scores but not other scores. (Link)

• Low levels of sleep and low sleep quality are linked to unethical behavior. (Link)

• People are able to identify criminals by looking at faces. (Link)

• The number of sex partners is negatively related to educational attainment in women. (Link)

• Gratitude depends on how much help people receive in comparison to how much help they are accustomed to receiving. (Link)

• People overestimate the potential impact of an apology. (Link)

• Inaction regrets last longer than action regrets. (Link)

• Music lessons increase IQ. (Link)

• Signing your name leads to higher consumer engagement. (Link)

• Consumers infer that scarcer products are of higher quality. (Link)

• Women with MBAs who are more masculine get promoted more than more feminine women. (Link)

• Children whose mothers ate an unhealthy diet have a higher risk of type 2 diabetes. (Link)

• Recalling memories from childhood makes people more ethical and prosocial. (Link)

• The happiest and unhappiest states in the USA. (Link)

• Full-time students are studying less than they used to. (Link)

• People who are unrealistically idealistic about their partners are happier. (Link)

• Downward social comparisons can increase emotional well-being. (Link)

• Compulsive Internet use predicts marital well-being. (Link)

• Women with higher levels of perceived support from family have slower decreases in depressive symptoms. (Link)

• High subjective well-being causes better health and longevity. (Link)

• People act more altruistically after exposure to green products but less altruistically after purchasing green products. (Link)

• Playfulness is associated with better athletic performance. (Link)

• Lower class people have better empathic accuracy. (Link)

• Men attribute high infidelity risk to women with feminine voices and women attribute high infidelity risk to men with masculine voices. (Link)

• Violating norms makes people appear more powerful. (Link)

• Higher levels of bladder control are associated with greater resistance to temptation. (Link)

• Power makes people think their subordinates are sexually interested in them. (Link)

• Wages paid to female employees increase when the CEO has a daughter. (Link)

• The scent of vanilla reduces anxiety. (Link)

• Individuals seen as either markedly low or high in assertiveness are perceived as less effective leaders. (Link)

• Hot temperatures increase aggression. (Link)

• Posture affects the activation of feeling powerful and taking action. (Link)

• People with a higher sense of power experience less distress and less compassion. (Link)

• Anger expressions convey the impression of confidence. (Link)

• Recipients of anger expressions concede more in negotiations. (Link)

• College roommates have an impact on GPA. (Link)

• Husbands and wives are more satisfied when the wives have lower BMIs than their husbands. (Link)

• People overestimate the extent to which their actions and appearance are noted by others. (Link)

• Sit-down meetings are longer than stand-up meetings but they don’t produce better outcomes. (Link)

• Very happy people are much more social and have stronger relationships. (Link)

• A fair working environment is associated with better health. (Link)

• Physical pain alleviates feelings of guilt associated with immoral behavior. (Link)

• Powerful people are more strict in judging others’ moral transgressions and less strict in judging their own. (Link)

• External rewards can promote healthful eating. (Link)

• How top employers evaluate elite education. (Link)

• There is a negative association between expressing creative ideas and leadership potential. (Link)

• Perceived marital bond predicts which couples remain married or get divorced. (Link)

• Leftward lighting increases the attractiveness of a product. (Link)

• Similarity increases persuasiveness. (Link)

• People who watch crime dramas and local news are more fearful of crime and think crime is increasing. (Link)

• Personality traits are associated with a flow state. (Link)

• Eye contact increases credibility in males. (Link)

• Aspirin reduces cancer deaths. (Link)

• Having children is negatively related to well-being. (Link)

• TV programs can provide the experience of belonging. (Link)

• Venture capitalists favorably evaluate entrepreneurs who think in similar ways to their own. (Link)

• Women with higher calorie intake have a greater probability of bearing boys. (Link)

• Viewing the body reduces pain intensity. (Link)

• People underestimate how much they enjoy exercise because of a focus on the unpleasant beginning of exercise. (Link)

• Flattery works even when it is accompanied by an obvious ulterior motive. (Link)

• How individuals perceive others reveals information about their own personality. (Link)

• Witnessing altruism leads to increased altruism. (Link)

• There is an attractiveness bias in favor of attractive opposite-sex candidates and discrimination against attractive same-sex candidates. (Link)

• Superstition can improve performance via self-efficacy. (Link)

• Exposure to a sexily dressed woman increases men’s likelihood of noticing status products. (Link)

• Women with first-born daughters are less likely to marry. (Link)

• People who sit in the center are assessed favorably. (Link)

• Attractive female news anchors reduce the encoding of information presented to men. (Link)

• Anticipating difficult tasks in the future leads to greater effort expenditure on tasks in the present. (Link)

• Caffeine and glucose can improve cognitive performance. (Link)

• Facial masculinity in men is correlated negatively with respiratory disease, while the opposite is true of facial masculinity in women. (Link)

• Thinking of time motivates people to socialize, which increases happiness. (Link)

• Attention training can reduce depressive symptoms. (Link)

• Faces viewed in a positive context are rated as appearing more positive. (Link)

• Increased sociability is associated with a decreased probability of developing a cold. (Link)

• People with unrestricted sociosexual orientation have more sons. (Link)

• Firms with better-looking executives have higher revenues and faster growth. (Link)

• Partnered female serial homicide offenders are more likely to target adult strangers, while solo female murderers are more likely to target family members. (Link)

• The importance of attractiveness, financial prospects, and mutual love has increased in importance when selecting a marriage partner. (Link)

• Happier people are more likely to get married. (Link)

• Exposure to words about heat increases aggressive thoughts. (Link)

• Inducing compassion towards one person leads to compassion for others. (Link)

• Buying generic products reduces self-esteem. (Link)

• Immediate pro-relational behaviors are acts of the heart, while delayed pro-relational behaviors are acts of the will. (Link)

• Men’s cognitive performance declines after a mixed-sex encounter, and this effect is stronger if the woman is attractive. (Link)

• People who receive questions geared at soliciting additional information rate their debate counterpart more favorably. (Link)

• Only 36% of students show improvement on standardized tests after four years of college. (Link)

• High divorce prevalence reduces support for Democratic candidates among men but not among women. (Link)

• Legacy applicants have seven times the odds of admission compared to nonlegacy applicants. (Link)

• Physically attractive parents are more likely to have daughters. (Link)

• Judges with daughters vote in a more liberal fashion on gender issues. (Link)

• Female sexual orientation can be judged by facial characteristics. (Link)

• Glucose can help prevent prejudice. (Link)

• Dieting makes food look bigger. (Link)

• Creative people are more dishonest. (Link)

• Making a fist can help men feel more assertive and powerful. (Link)

• Doubting your doubts can increase confidence. (Link)

• 30% of online daters engage in sexual activity on their first encounter. (Link)

• Liberals become more conservative after being exposed to mortality salience threats. (Link)

• Extraverted leadership enhances group performance when employees are passive, but not when they are proactive. (Link)

• Trust is positively related to physical health. (Link)

• Stand-up comedians show lower conscientiousness, extraversion, and agreeableness. (Link)

• Alcohol sales in an area are associated with the risk of assault. (Link)

• Young black men are 15 times as likely to be murdered as young white men are. (Link)

• Weekend hospital admissions are associated with greater mortality rates than weekday admissions. (Link)

• Physical risk taking by men increases in the presence of an attractive female. (Link)

• Stepparents are more likely to kill their children than genetic parents are. (Link)

• People are more likely to get into fatal crashes on presidential election days. (Link)

• Battered women have more sons than daughters. (Link)

• People with vague goals have a higher rate of improvement. (Link)

• Uncontrollable factors account for 37% of the variance in exam scores. (Link)

• Celebrity stalkers are more likely to be women. (Link)

• Hiding serving dishes can reduce food consumption. (Link)

• Factors that influence happiness. (Link)

• Binge drinking in women is associated with anal sex and STDs. (Link)

• First-born children have greater verbal ability than for children with later birth order. (Link)

• People are happier when the political party they support is in power. (Link)

• A positive attitude is associated with an increased salary. (Link)

• The are correlations between linguistic categories and personality traits in text messaging. (Link)

• People who reflect more about a breakup exhibit less emotional adjustment than people who reflect less. (Link)

• Casual sex relieves depression in depressed young adults but leads to more depression in nondepressed young adults. (Link)

• Women make fewer calls than men but their calls last longer. (Link)

• Nostalgia-based charity appeals work when they evoke important memories for the consumer. (Link)

• College students value increases to their self-esteem more than other pleasurable activities. (Link)

• Depressed people use more first person singular words. (Link)

• Blonde women raise more funds than brunettes. (Link)

• High school students with credit cards are less financially literate than those without credit cards. (Link)

• Women are better eyewitnesses than men. (Link)

• Attractive people are less egalitarian. (Link)

• The non-monetary impact of unemployment has a larger effect on life satisfaction than the monetary aspect. (Link)

• Moving to a new home is more stressful for women than for men. (Link)

• Conservative political candidates are better looking. (Link)

• Greater language style matching predicts greater romantic interest. (Link)

• The conditions under which familiar phrases and literal phrases are most persuasive. (Link)

• The left side of the face is perceived as more emotionally expressive. (Link)

• Having a more homogenous Facebook network is associated with higher life satisfaction and positive affect among European Americans. (Link)

• Women report higher levels of job satisfaction since they have lower expectations. (Link)

• People like other people and things when they have similar names to them. (Link)

• 80% of couples turn their heads to the right to kiss. (Link)

• Being in a happy mood increases innovative thinking. (Link)

• Left-handed women are less altruistic. (Link)

• Women with greater finger tactile sensitivity engage in more partnered sexual behavior. (Link)

• Cohabitors report higher levels of depression than their married counterparts. (Link)

• Possessing a belief in free will predicts better career attitudes and job performance. (Link)

• Losing a competition to a woman makes men want to lift weights. (Link)

• The experience or possession of power increases dehumanization. (Link)

• Institutionalization of the relationship, over-familiarity, and the de-sexualization of roles reduces sexual desire in married women. (Link)

• There are inverse relationships between verbal intelligence and psychopathy. (Link)

• Higher temperatures in the coldest month increase happiness while higher temperatures in the hottest month decrease happiness. (Link)

• The rear middle seat is the safest place in a car crash. (Link)

• Having sex produces the largest amount of happiness in women, while commuting produces the lowest amount of happiness. (Link)

• Left-handed people are more likely to have depressive symptoms. (Link)

• Sex has stronger effects on the happiness of highly educated people than on people with lower levels of education. (Link)

• People who think of mortality are more likely to name their child after themselves. (Link)

• Volunteers are more satisfied with their life than non-volunteers. (Link)

• Positive thinking does not help individuals with high levels of neuroticism. (Link)

• The physical attractiveness of service workers is associated with customer satisfaction. (Link)

• 26% of the variation of happiness in women and 39% in men is influenced by genes. (Link)

• Over 86,000 injuries are caused each year by people tripping over their pets. (Link)

• Performance while using a hands-free phone isn’t better than when using a cell phone. (Link)

• Exposure to sunlight increases consumer spending. (Link)

• People with the personality traits of extraversion and agreeableness are rated as more attractive. (Link)

• Women exposed to romantic lyrics comply more readily to a request for their phone number. (Link)

• Remembering someone’s name facilitates compliance with a request. (Link)

• Performing compassionate actions increases happiness. (Link)

• Consuming processed foods, fried foods, refined grains, sugar, or beer is associated with more mental disorders. (Link)

• Males with low perceived social power are more anxious and aggressive regarding immigrants. (Link)

• Asking how someone feels and then acknowledging that response facilitates compliance with a charitable request. (Link)

• Multilingualism is associated with cognitive test scores beyond other demographic characteristics. (Link)

• Physical attractiveness is the strongest predictor of romantic attraction for both sexes. (Link)

• Variables that are associated with happiness. (Link)

• Women are more attracted to men who are uncertain about whether they like the woman back. (Link)

• People prefer female leaders during intragroup competition and male leaders during intergroup competition. (Link)

• The differences between low-status and high-status messages on the Internet. (Link)

• Expansive posture leads to feelings of power. (Link)

• Physicians’ ratings of pain are influenced by patients’ attractiveness and nonverbal expressions of pain. (Link)

• Handling money is a way to reduce feelings of distress. (Link)

• Speaking into the right ear increases the probability that a person will comply with a request. (Link)

• Interrupting people leads to gains in status. (Link)

• Gay men have lower incomes than straight men, while lesbians have higher incomes than straight women. (Link)

• Oral contraceptives improve memory. (Link)

• Intelligent children are more likely to grow up to use alcohol and drugs. (Link)

• Women were more likely to vote for Barack Obama when they were fertile and when they perceived him as more white than black. (Link)

• The degree of financial consumption in men is directly related to future mating intentions and past mating success. (Link)

• Most people regard themselves as superior to most others at all points in time. (Link)

• People who view their intelligence as unchangeable perceive themselves to be better looking and more feminine after using a Victoria’s Secret shopping bag. (Link)

• People who are more trusting are better at detecting lies. (Link)

• Men are more likely to hit on women who have large breasts. (Link)

• Increasing the number of people victimized by a crime decreases the prison sentence. (Link)

• Participants who are exposed to money spend less time helping others and spend more time alone. (Link)

• Children who are healthier in kindergarten receive greater financial support from their father. (Link)

• Having an endorsement from another party leads to favorable impressions of a client. (Link)

• People who report to better leaders have a lower risk of heart disease. (Link)

• Men are more competitively inclined in the workplace than women. (Link)

• Increasing glucose and oxygen to the brain improves the ability to learn. (Link)

• The quality of early maternal caregiving predicts the extent to which people are comfortable relying on partners decades later. (Link)

• People primed with Christian words become more racially prejudiced. (Link)

• Essays in legible handwriting are evaluated more positively. (Link)

• People respond more positively to homosexual men who sound stereotypically gay and less positively to heterosexual men who sound gay. (Link)

• Neuroticism is unrelated to marital satisfaction when couples engage in relatively frequent sex. (Link)

• There have been significant increases in narcissism over time. (Link)

• Both sexes use a lower-pitched voice when speaking to attractive members of the opposite sex. (Link)

• Differences in the way men and women talk in mixed-sex groups. (Link)

• The economic resources of women are related to divorce among whites, but not among blacks. (Link)

• Facial dominance as determined from yearbook photos predicts career success. (Link)

• Later-borns are better than firstborns at determining kinship among strangers. (Link)

• Personality traits of indoor tanners. (Link)

• Men rate offenses as less severe than women do. (Link)

• White husbands have the highest level of marital happiness and black wives have the lowest happiness. (Link)

• Wives and husbands who spend more time in housework and paid work also have more sex. (Link)

• Meaning and engagement contribute to subjective well-being. (Link)

• Teachers give lower achievement scores to hypothetical students with African-American names. (Link)

• The physical, sincere, and playful styles of flirting are associated with more dating success. (Link)

• Women who fear crime prefer physically formidable men as long-term mates. (Link)

• Religiosity is a determinant of forgiveness. (Link)

• Women prefer prestigious men for long-term relationships and dominant men for sexual affairs. (Link)

• It is more difficult to process immoral information than moral information. (Link)

• Making downward social comparisons with personally known others reduces regret intensity. (Link)

• Northerners use sarcasm more than Southerners. (Link)

• Predictors of dental anxiety. (Link)

• Framing opportunities as negotiations is more intimidating to women. (Link)

• People who manage their free time have better quality of life. (Link)

• Governing parties that raise taxes lose votes in subsequent elections. (Link)

• Patients with Parkinson’s disease are less polite than other people. (Link)

• Gesturing during encoding leads to better memory recall. (Link)

• Women involved in street prostitution are 60 to 100 times more likely to be murdered than other women. (Link)

• Teams who share bad feelings solve complicated problems better and have greater solidarity. (Link)

• People who watch more TV have lower life satisfaction. (Link)

• Women with greater education are less likely to take their husband’s name. (Link)

• Anxiety may reduce pain while paying attention to it increases pain. (Link)

• Enjoyment of coursework and approval of parents are the criteria that students use to pick a major. (Link)

• Having a trustworthy manager can be more important to life satisfaction than getting a raise. (Link)

• Reappraising and accepting anxiety can reduce anxiety. (Link)

• The happiest places also have the highest suicide rates. (Link)

• Speeches with more imagery are more charismatic. (Link)

• Men enjoy housecleaning tasks more than women. (Link)

• Thinking of willpower as not being easily depleted improves performance. (Link)

• Most women are dissatisfied with their breasts, but most men are satisfied with their partner’s breasts. (Link)

• Attractive men receive more job interviews. (Link)

• Tryptophan reduces impulsivity. (Link)

• Residents of an office space outperform visitors in negotiations. (Link)

• Cheerfulness is negatively related to academic success in college. (Link)

• Parents buy healthier food for themselves than for their kids. (Link)

• There is a positive association between store aesthetics and customer satisfaction as well as the amount of money spent. (Link)

• Perceiving an obese eater reduces the viewer’s desire to eat. (Link)

• Believers in the paranormal have a propensity for probabilistic reasoning biases. (Link)

• There is generally no direct effect on outcomes between public defenders and private attorneys. (Link)

• Feeling gratitude predicts marital satisfaction. (Link)

• The largest gender differences occur for agreeableness and neuroticism. (Link)

• Striving for perfection during training predicts higher performance. (Link)

• Men with lower voice pitch have more children. (Link)

• Mild anxiety during training improves later performance. (Link)

• Conservatism and cognitive ability are negatively correlated. (Link)

• Perceiving a lack of partner disclosure is linked to intrusive behavior. (Link)

• Women value social status in mates and men value physical attractiveness in mates across cultures. (Link)

• Black men have more attractive faces. (Link)

• Sex workers derive pleasure from both commercial and private relationships. (Link)

• Higher IQ scores sometimes increase the probability of being in financial difficulty. (Link)

• Women who initiate divorce are more likely to perceive themselves as different from their partner. (Link)

• Police officers with a college education use significantly less verbal force. (Link)

• Faking good traits can fool personality tests. (Link)

• Greater power is associated with more disinhibited behavior. (Link)

• Extraverts use more adjectives. (Link)

• Gesturing increases learning in children. (Link)

• People who use their phones for text messaging rather than talking are more lonely and socially anxious. (Link)

• Victims are more satisfied when the offender understands revenge as punishment. (Link)

• A defendant is much more likely to be sentenced to death if they kill a high-status victim. (Link)

• People whose beliefs are undermined are more likely to advocate for their beliefs. (Link)

• Consumers are more likely to buy unhealthy food when they pay by credit card. (Link)

• Women’s prisons are just as violent as men’s prisons. (Link)

• The door-in-the-face technique can lead to an increase in purchases. (Link)

• The attractiveness of scarcity depends on the product. (Link)

• Hopeful people are more creative. (Link)

• Leisure consumption increases happiness more than other forms of consumption. (Link)

• Caffeine negatively affects academic achievement. (Link)

• Cigarette addiction has more to do with psychosocial elements than nicotine. (Link)

• The more health conscious a household is, the less price sensitive it is. (Link)

• Getting a person to first agree to a series of statements increases persuasiveness. (Link)

• People in the military marry and divorce more. (Link)

• Verbal fluency, adaptability, impulsivity, and self-minimization doesn’t change much from childhood to adulthood. (Link)

• Humor that imposes cognitive demands is better for improving mood. (Link)

• People show a preference for brand names starting with their initials. (Link)

• Firming one’s muscles can increase willpower. (Link)

• Dysgenic fertility has reduced the world’s IQ. (Link)

• Intelligent men have higher quality semen. (Link)

• There is a negative association between intelligence and religious belief in the USA and Europe. (Link)

• People assume that attractive people are more similar to them. (Link)

• Reduced fear conditioning predicts which children become criminals. (Link)

• Visual exposure to a sports drink increases persistence. (Link)

• Correlations between certain variables and subjective well-being. (Link)

• Observers pay more attention to men who display social dominance. (Link)

• People see themselves as more neurotic and open to experience than they are actually perceived by others. (Link)

• Personality traits that predict higher income and job satisfaction. (Link)

• Men are rated as more attractive when in a high status car. (Link)

• Exposure to death-related stimuli increases consumption. (Link)

• The presence or absence of certain variables can tell if a person calling 911 committed the crime. (Link)

• Women have a stronger preference for a socially dominant mate when primed with parenting cues. (Link)

• Some dark side traits have a beneficial effect on leadership skills. (Link)

• More agreeableness is associated with better friendships, career performance, and health. (Link)

• Fathers who hold traditional gender role attitudes are more involved. (Link)

• Lower cognitive ability is associated with more risk aversion and impatience. (Link)

• People follow paid advice more than free advice. (Link)

• Anger promotes analytic processing. (Link)

• Self-talk, emotional control, and relaxation strategies are related to emotional toughness in athletes. (Link)

• People offer more help in the presence of a security camera. (Link)

• Art posters reduce anger and stress in males. (Link)

• The chance of mating with a speed-dating partner is 6%. (Link)

• Women who use hormonal contraceptives have higher levels of jealousy. (Link)

• Personality differences between morning people and evening people. (Link)

• Being first on the ballot improves the chances of winning political office. (Link)

• People with higher levels of certainty in their religious beliefs have greater well-being than those who are less certain. (Link)

• A woman’s sexual health is an extremely strong predictor of relational well-being and a strong predictor of mental health. (Link)

• Inducing religious thoughts increases prosocial behavior. (Link)

• The greater the mismatch between testosterone level and status in the group, the lower is the collective efficacy of the group. (Link)

• Campaign contributions and political connections significantly increase a company’s odds of receiving a contract. (Link)

• Female fertility can be assessed by gait. (Link)

• First impressions of psychopathy can be valid. (Link)

• Perceived cellphone dependence is linked to impulsivity. (Link)

• A feeling of meaning in life is important for life satisfaction. (Link)

• Conscientiousness is positively related to longevity. (Link)

• Breast size changes over a woman’s cycle. (Link)

• Emotionally intense cellphone conversations are even more risky than regular conversations when driving. (Link)

• Items presented on the left are better remembered. (Link)

• Workout performance is better when listening to preferred music. (Link)

• Imagining yourself as a child can improve creativity. (Link)

• Choosing from larger assortments impacts choice. (Link)

• Individuals experiencing a state of power spend more money on themselves. (Link)

• Positive interactions may actually damage the relationships of distressed couples. (Link)

• Older people enjoy reading negative stories about young people. (Link)

• Ways to effectively frame flattery. (Link)

• Psychopaths can assess a target’s vulnerability just by seeing how they walk. (Link)

• Pregnancy has a correlation with happiness for whites but not for blacks. (Link)

• Female fertility increases if a co-worker recently had a child. (Link)

• Intoxicated people interpret more acts as intentional. (Link)

• Church attendance has a significant positive effect on happiness in women. (Link)

• Kindergarten test scores are highly correlated with outcomes such as earnings at age 27, college attendance, home ownership, and retirement savings. (Link)

• Psychological detachment from work during off hours is associated with higher life satisfaction. (Link)

• Never-married men are narrowing the health gap between them and their married counterparts. (Link)

• Practicing a speech before an audience improves the quality of the subsequent presentation. (Link)

• Oral sex is correlated with a diminished occurrence of preeclampsia in women. (Link)

• Yellow price tags make people think they are getting discounts even when the price isn’t discounted. (Link)

• Hormonal contraceptives have mood-stabilizing effects. (Link)

• Conservatism is positively related to self-esteem in the elderly. (Link)

• Investing has a genetic component. (Link)

• Longer relationship length correlates with lower prediction accuracy and greater overconfidence in guessing partner preferences. (Link)

• Intelligent people are more likely to be victimized at work. (Link)

• Tall women are perceived as more intelligent, affluent, assertive, and ambitious. (Link)

• Framing a message in terms of thinking or feeling depends on the emotional state of the recipient. (Link)

• Facial dominance of cadets predicts military rank decades later. (Link)

• Tasty food prompts people to seek other rewarding things. (Link)

• Disgusting products are believed to transfer offensive properties to other products via touch. (Link)

• The hairiness of women’s fathers correlates positively with that of their current mates. (Link)

• Eating and drinking while driving increases the risk of a crash. (Link)

• When cohabiting parents marry after childbirth, the child’s early cognitive performance is significantly increased. (Link)

• Higher market participation by women is positively associated with government size. (Link)

• Catholics are more likely to exhibit obsessive-compulsive symptoms. (Link)

• Positive emotions are more effective than negative emotions in improving athletic performance. (Link)

• Men are more likely than women to commit suicide after a divorce. (Link)

• Adolescents who are allowed to drink at home engage in binge drinking more often. (Link)

• Shorter men are better at identifying dominant men. (Link)

• People with high levels of suppressed anger are most likely to become violent when drinking. (Link)

• Women overestimate the degree to which men are interested in sex. (Link)

• Consuming a preferred food makes a person more open to persuasion. (Link)

• Female lawyers with masculine names are more likely to become judges. (Link)

• Cheerful children grow up to be more careless about their health. (Link)

• Experiencing gratitude from a manager can increase performance by 50%. (Link)

• TV ads are more effective when people are paying less attention. (Link)

• People like a group more if they undergo a difficult initiation. (Link)

• There is no significant relationship between the improvement in happiness and the long term rate of growth of GDP per capita. (Link)

• Women have a higher propensity than men to make autocratic decisions. (Link)

• Gun buyback programs reduce suicide rates. (Link)

• People who believe in witchcraft rate their lives worse compared to those who don’t. (Link)

• People who agree that it is never justifiable to engage in ethically questionable behaviors are more satisfied with life. (Link)

• The optimal level of happiness for life outcomes. (Link)

• Viewing ideal male bodies contributes to negative self-evaluations in males. (Link)

• Pain hurts more if people think it was intentionally caused by another person. (Link)

• Asking individuals how much time they would like to donate is a way of increasing the amount of money they donate. (Link)

• Religious households care more about saving and are more risk-averse. (Link)

• Men who are economically dependent on their female partners are more likely to cheat, whereas the opposite is true for women. (Link)

• Name-dropping negatively impacts first impressions. (Link)

• Experiences lead to greater happiness when the purchase goes well and greater unhappiness when the purchase goes badly, as compared to material goods. (Link)

• Having senders and receivers in the same emotional state enhances the transfer of information. (Link)

• The focus on remaining actions increases the motivation to work harder, while a focus on completed actions increases satisfaction. (Link)

• There are different types of female orgasm. (Link)

• Swearing at the beginning or end of a speech increases persuasiveness. (Link)

• Women receive lighter prison sentences. (Link)

• The effect of divorce is weaker in countries where the family is strong and when divorce is more common. (Link)

• Sexual stimuli speed up the perception of time. (Link)

• Thinking aloud improves intelligence. (Link)

• Closing your eyes can increase memory recall. (Link)

• Elite athletes process information faster. (Link)

• Personality traits are closely connected to political orientation. (Link)

• Exercise is a treatment for insomnia. (Link)

• The more a state attempts to insulate citizens against market forces, the greater is satisfaction. (Link)

• How to determine a person’s personality by the words they use. (Link)

• Exposure to subliminal symbols of alcohol increases aggression. (Link)

• Opportunities are more important than preferences in dating. (Link)

• Women prefer men with Byronic traits. (Link)

• Intensity of both positive and negative feelings diminishes under cognitive load. (Link)

• Japanese people are more indecisive than Chinese or American people. (Link)

• Humorously violent ads are more viral. (Link)

• Highly visible tattoos are associated with deviant behavior. (Link)

• Sad and neurotic people are prone to experience nostalgia. (Link)

• Symptoms of type 2 diabetes are associated with reduced forgiveness and cooperation. (Link)

• One fifth of a user’s Facebook friends actually influence their behavior. (Link)

• Sharing good news with others strengthens social relationships. (Link)

• People with large heads are better protected against memory loss associated with Alzheimer’s disease. (Link)

• Common reasons for accepting or rejecting a booty call. (Link)

• Women are more attractive when they wear red and men are more attractive when they own a dog. (Link)

• Decorated offices improve worker performance. (Link)

• Politicians use their dominant hand when they express positive ideas and their nondominant hand when they express negative ideas. (Link)

• Lawyers are overconfident in their predictions. (Link)

• Decision-making abilities change with age. (Link)

• Men are even less aware of the difference between friendliness and sexual interest when they are drunk. (Link)

• Increased sociability leads to happiness. (Link)

• A hyper-empathizing personality is related to psychosis. (Link)

• Relying on internal cues rather than external cues can help prevent obesity. (Link)

• Women prefer men with facial scars for short-term relationships. (Link)

• Friendship variables account for over half of the variance in happiness. (Link)

• Fantasy-prone individuals are better liars. (Link)

• Brief social interaction improves memory and performance on tests. (Link)

• People drive better when their emotions match the GPS voice. (Link)

• White people are seen as prejudiced when they avoid the topic of race. (Link)

• It is better to avoid apologizing after intentionally committed offenses. (Link)

• Obese women are more impulsive. (Link)

• People are happier when they are busy. (Link)

• Women who have good childhood memories of their fathers are likely to choose a mate with similar traits. (Link)

• People trust members of their own gender more. (Link)

• Religiosity does not enhance cooperation. (Link)

• Religious both decreases and increases anxiety. (Link)

• Self-deprecating humor increases attractiveness only among high-status individuals. (Link)

• Boredom predicts decreased marital satisfaction. (Link)

• Humor is an honest indicator of intelligence. (Link)

• People make up their mind about someone within 100 milliseconds. (Link)

• Gratitude predicts greater life satisfaction and better grades. (Link)

• Individuals addicted to cocaine have lower sensitivity to monetary rewards. (Link)

• Engaging in self-presentation can improve a relationship. (Link)

• Overweight and obese women are more likely to have had sex than women of normal weight. (Link)

• Daytime napping is associated with elevated mortality in the elderly. (Link)

• Sexually unrestricted men and women are better at detecting signals of sexual receptivity. (Link)

• An active imagination is associated with better memory in elderly people. (Link)

• There are significant positive associations between androgens and math/science. (Link)

• Intense celebrity worship is the strongest predictor of cosmetic surgery acceptance. (Link)

• People who associate their partner with bad things than with good things are more likely to split up over the next year. (Link)

• Women are more susceptible to the starting point bias and men are more susceptible to hypothetical bias. (Link)

• Men wearing deodorant have more attractive nonverbal behavior. (Link)

• The attractiveness of male dancing correlates with handgrip strength. (Link)

• Back massage reduces forehead wrinkles. (Link)

• Women who use makeup as camouflage are more anxious than women who use makeup for seduction. (Link)

• Women sleep better when they have a partner. (Link)

• A study of Catholics found that heaven is a stronger motivator than hell. (Link)

• Sexual fantasy is positively correlated with intercourse frequency. (Link)

• Fatty foods increase response times and reduce mistakes. (Link)

• Inflated impulse-control beliefs lead people to overexpose themselves to temptation. (Link)

• Psychopathy in men is associated with low body shame while psychopathy in women is associated with high body shame. (Link)

• Men of higher mate value perform more benefit-provisioning and fewer cost-inflicting mate retention behaviors than men of lower mate value. (Link)

• Taller men are more likely to go to college. (Link)

• Attractive women are more extraverted. (Link)

• Expressing remorse leads to lower fines for speeding. (Link)

• Women in the fertile phase of the menstrual cycle have a preference for men with large pupils. (Link)

• States with a higher average IQ have less crime. (Link)

• Grip strength is a predictor of mortality. (Link)

• Starting a new relationship and having employment-related gains have the greatest effect on happiness. (Link)

• Men who have feminine characteristics are less likely to have a heart attack. (Link)

• 27% of men and 10% of women have sex within 24 hours of meeting. (Link)

• Sharing the best events of the day improves a relationship. (Link)

• Angry people are more likely to seek out disconfirming information. (Link)

• Pay comparison reduces effort. (Link)

• People with low self-esteem are drawn to celebrities. (Link)

• Women who are serial cohabitors or who have low intimacy are more likely to divorce. (Link)

• High assertiveness worsens relationship and low assertiveness limits goal-achievement. (Link)

• The participation in physical activity makes people three times happier than the loss in happiness associated with being unemployed. (Link)

• Subjective well-being is increased by actual income but lowered by aspirational income. (Link)

• People with low self-esteem leave their jobs when their earnings increase. (Link)

• Southerners are more likely to get upset over offenses. (Link)

• People in bad marriages are much less happy than unmarried people. (Link)

• Sexy voices are associated with body symmetry in both men and women. (Link)

• Tall men have greater cognitive and noncognitive ability. (Link)

• Multicultural learning experiences increase creativity. (Link)

• Younger people are more likely to associate happiness with excitement while older people are more likely to associate happiness with feeling peaceful. (Link)

• Negative emotions increase the desire to learn from mistakes. (Link)

• Women with declining fertility think more about sex and have more sex. (Link)

• Unintentional publicity and mild reprimand enhances moral emotions and intentions to apologize without increasing hostility. (Link)

• Wealthy consumers high in need for status display loud luxury goods. (Link)

• Modesty is an unattractive trait in men. (Link)

• Money impairs people’s ability to savor positive emotions. (Link)

• Women become entrepreneurs because of genetics. (Link)

• Shoplifters have lower ratings on emotional stability, conscientiousness, and agreeableness, and higher levels of extraversion. (Link)

• Shyness is linked to marital problems among newlyweds. (Link)

• Toddlers who lie early become more intelligent later. (Link)

• Cooperators may be more emotionally expressive than non-cooperators. (Link)

• Consumers judge an offer to be more attractive when a seller offers a better price or more benefits to another group. (Link)

• Witnessing rudeness decreases performance on tasks. (Link)

• Countries with fewer males have more violent crime. (Link)

• People become more traditional in their gender-role attitudes and behavior following the birth of a child. (Link)

• Unemployed people are happier when they have unemployed friends, but they remain out of work longer. (Link)

• Psychological detachment, relaxation, and mastery experiences during the weekend help recover from the work week. (Link)

• Single women are less likely to invest in risky assets than married women are. (Link)

• Sexual satisfaction increases marital quality. (Link)

• Brazilians are the most kind to strangers whereas Malaysians are least kind. (Link)

• High anchors increase performance judgments. (Link)

• Monetary rewards reduce intrinsic motivation. (Link)

• Older adults report lower intensity positive emotions with new friends and higher intensity positive emotions with family members. (Link)

• Anger increases risk-taking in men and disgust decreases risk-taking in women. (Link)

• Men with a monotone voice and more dominant linguistic content have more sex partners. (Link)

• Doodling improves memory recall. (Link)

• Women become friends based on similar levels of attractiveness. (Link)

• Higher male imprisonment has lowered the likelihood that women marry. (Link)

• Large drunk men are more aggressive. (Link)

• Preferred music increases pain tolerance. (Link)

• Emerging adults’ self-reported mating desires vary little with age. (Link)

• The prevalence of psychopathic traits is higher among corporate professionals than that found in community samples. (Link)

• Gratitude increases relationship connection and satisfaction. (Link)

• More attractive political candidates are more likely to get elected. (Link)

• Middle-born children are less risk-averse. (Link)

• Women are more risk-averse than men. (Link)

• Predictors of divorce. (Link)

• Unattractive defendants are more likely to be convicted of a crime and receive harsher sentences. (Link)

• Product evaluations are higher when consumers perceive a product as having been touched by an attractive person. (Link)

• Sexually permissive people and high sensation-seekers more frequently look for casual sex online. (Link)

• The children of self-employed parents perform worse in college. (Link)

• Women cheat more on a task when faced with competitive pressure. (Link)

• Happiness increases life expectancy. (Link)

• In regions that have suffered from high levels of infectious diseases, people report lower levels of sociosexuality, extraversion, and openness. (Link)

• Levels of psychological distress predict later infidelity. (Link)

• Women with low emotional intelligence have more sexual problems. (Link)

• Men with higher conformity to masculine norms are less likely to ask for help. (Link)

• Facial ratings of competence and leadership predict the amount of profits made by companies run by female CEOs. (Link)

• Individuals with high levels of flow during leisure time report higher levels of positive affect. (Link)

• Women with younger husbands have higher mortality rates. (Link)

• More intelligent individuals go to bed later on weeknights and wake up later on weekdays. (Link)

• Women with high sex drive are more likely to be bisexual. (Link)

• Women are better at detecting emotion since they pay more attention to the eyes. (Link)

• Overconfident CEOs are more innovative. (Link)

• Athletes get better jobs. (Link)

• Income inequality decreases tolerance of homosexuality. (Link)

• Waitresses with large breasts, blond hair, and small bodies receive bigger tips. (Link)

• Men are rated as more desirable when surrounded by women, while women are rated as less desirable when surrounded by men. (Link)

• People who are concerned about pathogens have more negative attitudes towards obese people. (Link)

• The type of male body language that attracts women. (Link)

• Hating your ex can help you get over a breakup. (Link)

• Higher intelligence and dependability predict lower mortality. (Link)

• Men and women don’t differ in their self-reported desires for marriage and children. (Link)

• Taller people have more positive emotions. (Link)

• Women with longer legs have more children. (Link)

• Tall men and women of average height are less likely to be jealous. (Link)

• Women are less likely than men to think of sexual activity as being considered sex. (Link)

• Warmer conditions induce greater social proximity, use of more concrete language, and a more relational focus. (Link)

• Adults can’t detect when children lie. (Link)

• Men who are taller than average and women who are shorter than average make more money. (Link)

• Women respond positively to bad gifts, while men do not. (Link)

• Chewing gum can relieve stress. (Link)

• Reasons why people fake orgasms. (Link)

• A peak in early career success is associated with a shorter lifespan. (Link)

• Perceived understanding is more important than actual understanding in a relationship. (Link)

• Displaying aggression reduces anxiety in men. (Link)

• Handling a gun makes men more aggressive. (Link)

• Social rejection increases creativity. (Link)

• Legal experts anchor their sentencing decisions to numbers that have been presented to them. (Link)

• Alcohol reduces anxiety but not fear. (Link)

• The will to live makes a difference in deciding what time people die. (Link)

• Female athletes have better sexual function. (Link)

• A high ceiling height increases feelings of freedom. (Link)

• Single people are unfairly stereotyped and discriminated against. (Link)

• Religious people are more charitable on days when they visit their place of worship, but not on other days. (Link)

• People become stronger when they imagine themselves doing good deeds or harming others. (Link)

• Happiness precedes successful outcomes in life. (Link)

• Yoga improves sexual function in women. (Link)

• Believing that you can improve your negotiating ability is associated with higher performance in negotiations. (Link)

• Frequent cannabis use is associated with higher numbers of sexual partners. (Link)

• People attribute negative motives to those with differing attitudes. (Link)

• Performance-related pay is associated with increased job satisfaction. (Link)

• Powerful individuals act more in situation-consistent ways and less in situation-inconsistent ways. (Link)

• Disengaging from unattainable goals is associated with better self-reported health. (Link)

• Women who work part-time have higher work satisfaction than women who work full-time. (Link)

• Novel and challenging activities in a shared context can increase marital satisfaction. (Link)

• Women dislike commuting more so than men. (Link)

• Gifts (but not cash gifts) increase worker productivity. (Link)

• Happier people are better citizens. (Link)

• Men pursue status-related consumption more after being exposed to advertisements with mating cues. (Link)

• Debtors are likely to be more obese than nondebtors. (Link)

• The states in which people are most satisfied with life. (Link)

• Qualities that affect response rates in online dating. (Link)

• Inmates with more Afrocentric features receive harsher sentences. (Link)

• Judgments of a woman’s sociosexuality are highly correlated with the woman’s self-reported sociosexuality. (Link)

• Female candidates are more likely to receive a callback for entry-level jobs, with the difference being largest in female-dominated occupations. (Link)

• People are liked more if they tell positive lies but respected more if they tell the truth. (Link)

• People are more likely to mark errors and award lower grades when using red pens. (Link)

• Testosterone is associated with cognitive performance. (Link)

• Culture has a larger effect on female sexuality than on male sexuality. (Link)

• Marijuana facilitates sexual arousal in women, but not in men. (Link)

• For women, high self-esteem is associated with higher standards in low investment relationships for women, whereas men with high self-esteem have lower standards. (Link)

• Leaders who receive numerical feedback react more favorably than those who receive text feedback. (Link)

• Obese women are less likely to be accepted into either cohabitation or marriage, and obese men are less likely to be accepted into cohabitation but not marriage. (Link)

• How scents affect who you like. (Link)

• Women are more angered by sexual rejection than men. (Link)

• Wives’ degree of relationship commitment has stronger effects on emotional outcomes than husbands’ degree of relationship commitment. (Link)

• Delaying acceptance decisions increases the likelihood of accepting low offers. (Link)

• Perceived job insecurity can be more harmful than actual job loss. (Link)

• Daters pay more attention to physical characteristics when faced with abundant choice. (Link)

• Love is most important in Western countries and least important in developing Eastern countries. (Link)

• Most people are happy in 86% of 43 nations studied. (Link)

• The heritability of subjective well-being is nearly 80%. (Link)

• People with higher levels of subjective well-being have higher rates of job satisfaction. (Link)

• Being thwarted from achieving a desired outcome increases the desire to obtain it but reduces its attractiveness. (Link)

• Exposure to fast food symbols increases reading speed and preference for time-saving products. (Link)

• Mimicry increases liking. (Link)

• A positive mood magnifies whether a person trusts another individual or not. (Link)

• Counterfactual thinking can add meaning to your life. (Link)

• Low sexual frequency is associated with higher levels of relationship dissolution among cohabiting couples. (Link)

• Number of sexual partners, dysfunctional impulsivity, satisfaction with current relationship, and quality of relationship alternatives predict infidelity. (Link)

• Perceived lack of control is linked to paranoia. (Link)

• Women who smile signal warmth whereas men who smile signal confidence. (Link)

• Women try to sabotage more successful women. (Link)

• Shifting from self-worth goals to learning goals helps deal with depression. (Link)

• Intelligence and creativity increases male attractiveness. (Link)

• SSRIs reduce aggression in alcoholics. (Link)

• More attractive women desire wealthy partners whereas less attractive women desire partners with good looks. (Link)

• People who feel closer to their families are less trusting of strangers. (Link)

• Close relatives of successful students show an increased risk of psychosis. (Link)

• Men fall in love when they overestimate a woman’s sexual interest and attractiveness, whereas women fall in love when they have a higher sex drive. (Link)

• Selfless individuals have lower mortality rates. (Link)

• Spouses who have more sex have less attachment insecurity. (Link)

• Mobile phones can help prevent smoking. (Link)

• Women are held to stricter standards for promotion. (Link)

• Movement synchrony leads to greater liking. (Link)

• Cities with longer commutes have fewer women who work. (Link)

• The price of getting married affects marriage rates. (Link)

• Avoidant attachment has fewer associations with relationship problems in the USA than in other countries. (Link)

• Increases in prescriptions for psychiatric drugs are associated with decreases in violent crime. (Link)

• Fear of unemployment predicts future unemployment. (Link)

• Perceptions of team trust are determined by the least trusted member of the group. (Link)

• Listening to songs with prosocial content increases helping behavior. (Link)

• Discussing feedback entraps people in their previous biases. (Link)

• Showing cleavage improves women’s chances of getting hired by men. (Link)

• Kindness at work is less optional for women than it is for men. (Link)

• Subjective well-being is lowered by aspirational income. (Link)

• Writing about successful personal experiences improves performance on tests. (Link)

• Valuing gender norms negatively affects sexual pleasure for both men and women. (Link)

• Overweight consumers experience lower self-esteem when seeing ads with models of any size. (Link)

• Binge drinking the night before an exam doesn’t impact the performance of college students. (Link)

• Couples with a female breadwinner have a higher risk of divorce. (Link)

• Thinking fast can increase happiness. (Link)

• Men with attractive faces have significantly more masculine shoulder-to-hip ratios. (Link)

• Having a daughter leads parents to reduce their smoking, drinking, and drug use. (Link)

• Black and Latino job applicants with clean backgrounds are no more likely to receive a callback or job offer than whites who were released from prison. (Link)

• Alcohol consumption reduces student performance. (Link)

• Being in natural environments leads to more intrinsic motivation. (Link)

• Men are drawn to a wider range of women when they feel stressed. (Link)

• The season of birth is associated with health and professional outcomes. (Link)

• Early retirement has a negative impact on cognitive ability. (Link)

• Healthy people are more likely to be hired and unhealthy people are more likely to get laid off. (Link)

• Happiness increases productivity. (Link)

• Sleep time decreases when the economy does better. (Link)

• Attractive men are less satisfied by marriage. (Link)

• Studying in a group is less effective. (Link)

• Husbands are more likely to cheat when their wives are pregnant. (Link)

• Women have a higher risk of divorce if their parents divorced. (Link)

• Parenthood hastens marital decline. (Link)

• Assassinating autocrats promotes democracy. (Link)

• Curiosity is correlated with better memory recall. (Link)

• Ways to deal with narcissists. (Link)

• People find humor funnier when it matches their implicit preferences. (Link)

• Depression improves the accuracy of predictions. (Link)

• The amount a woman spends on alcohol is the best predictor of how sexual she is. (Link)

• Poor language fluency shields nonnative individuals from negative evaluation. (Link)

• It’s useful to be moderately overconfident. (Link)

• Shifting attention and focusing on benign outcomes reduces anxiety. (Link)

• It’s more difficult to tell people from other ethnic groups apart. (Link)

• Expressing negative emotion is associated with positive relationships. (Link)

• University teachers don’t improve with more experience. (Link)

• Positive stereotypes can improve performance. (Link)

• Having an elder male sibling lowers reproduction. (Link)

• Expressive writing helps fight depression. (Link)

• Powerful people focus on whether rules or principles were violated, whereas powerless people focus on the consequences. (Link)

• A breach of trust during a first impression leads to long-term negative consequences. (Link)

• Both sexes are more attentive to images of attractive women. (Link)

• Crossing your arms increases persistence. (Link)

• The odds of deciding an election are the same as winning the lottery. (Link)

• Traits that correlate with handgrip strength. (Link)

• How to increase the effectiveness of debt collection. (Link)

• How to persuade older adults. (Link)

• Heat and anger are connected. (Link)

• Women with higher incomes have higher rates of marriage. (Link)

• The most effective nap time is ten minutes. (Link)

• People can detect extraversion and conscientiousness by looking at a person’s face. (Link)

• Retirement has a negative impact on cognitive ability. (Link)

• People blame victims to reassure themselves that the world is fair. (Link)

• A surprised facial expression improves memory recall. (Link)

• Black women with lighter skin are more likely to get married. (Link)

• Women with high numbers of sex partners have more masculine traits. (Link)

• Keeping a romance secret is stressful. (Link)

• Priming with positive stereotypes can increase performance. (Link)

• Attractiveness improves the odds of winning elections. (Link)

• Less powerful people laugh more when speaking with powerful people. (Link)

• Men who are in romantic relationships have lower testosterone levels. (Link)

• Women have less accurate online dating photos than men. (Link)

• Acetaminophen is the leading cause of liver failure. (Link)

• Economics students are less generous than other students. (Link)

• Racism is correlated with cardiovascular disease. (Link)

• Women are more racist when more fertile. (Link)

• Biological children are treated better than adopted children. (Link)

• Conservatives are happier than liberals. (Link)

• Poor people pay more for things. (Link)

• Marathon runners have memory loss. (Link)

• High self-esteem reduces materialism. (Link)

• People are happier when they live in richer neighborhoods in poorer counties. (Link)

• Men lie about their height and women lie about their weight in online dating profiles. (Link)

• Men show activation in reward centers of the brain when looking at images of women with an hourglass figure. (Link)

• Greater social status correlates with more dopamine receptors in the brain. (Link)

• Medical treatment can make people overconfident in their health. (Link)

• Interruption makes good experiences more pleasurable. (Link)

• Positive illusions about your partner’s attractiveness correlate with relationship quality. (Link)

• Being nostalgic makes you feel less lonely. (Link)

• A map of the happiest and least happy places on Earth. (Link)

• Playing video games can reduce nightmares. (Link)

• Fiction is more persuasive than non-fiction. (Link)

• Personal disclaimers often backfire. (Link)

• Liberals and conservatives dream differently. (Link)

• Workers are most motivated by making progress. (Link)

• Aspects of physical appearance that affect reproductive success. (Link)

• Unwanted advice-giving is detrimental to marriages. (Link)

• Factors that increase tips at restaurants. (Link)

• Caffeine can increase persuasion. (Link)

• Darkness increases dishonesty. (Link)

• Glucose enhances self-control. (Link)

• Parental characteristics affect mate choice. (Link)

• Cosmetics increase women’s attractiveness and status. (Link)

• Factors that affect trustworthiness. (Link)

• Women with masculine personalities are more likely to be harassed. (Link)

• Couples who use “we” language have higher levels of marital satisfaction. (Link)

• Relationships are more positive when the wife is more attractive than the husband. (Link)

• Older adults make more investment mistakes. (Link)

• People who are skilled at impression management benefit more from suck-up tactics than those who are bad at it. (Link)

• Data on drug use in the workplace. (Link)

• Making choices leads to reduced self-control. (Link)

• Convicts who are portrayed as more apelike are more likely to be executed. (Link)

• People don’t really know what they want in a romantic partner. (Link)

• Relational insecurity is perpetuated by expressing insecurity. (Link)

• People who perceive themselves as powerful are more effective liars. (Link)

• Feeling like a victim increases selfish behavior. (Link)

• Prayer increases forgiveness. (Link)

• People who are intrinsically spiritual are more desirable. (Link)

• Abstract language is more persuasive. (Link)

• Attractive women and strong men are more likely to feel entitled. (Link)

• Picture size improves performance of e-commerce sites. (Link)

• Powerful faces are perceived as Republican and warmer faces are perceived as Democratic. (Link)

• Self-control is contagious. (Link)

• Men with tattoos and piercings signal higher biological quality. (Link)

• Flattery improves the effectiveness of advertising. (Link)

• Women’s preference for masculine men is correlated with how disgusted they are by pathogens. (Link)

• High IQ investors outperform less intelligent investors. (Link)

• Genetic influences on political beliefs. (Link)

• Avoidant people are more concerned by sexual infidelity while secure people are more concerned by emotional infidelity. (Link)

• The psychology of terrorists. (Link)

• Cell phone exposure may protect against and reverse Alzheimer’s disease. (Link)

• When narcissists are more charming. (Link)

• Teachers with high levels of grit have better performance. (Link)

• Women who live with a mate gain more weight than those who live without one. (Link)

• People with more body art exhibit more deviant behavior. (Link)

• Death row inmates are frequently intellectually disabled with a history of trauma. (Link)

• How genes affect divorce. (Link)

• Power can make people hypocritical. (Link)

• Tetris helps treat post traumatic stress disorder. (Link)

• How to increase the money you get from eBay auctions. (Link)

• Keys to a long marriage. (Link)

• Beliefs that influence medical recovery. (Link)

• Being poor is deadlier than smoking or obesity. (Link)

• The social strategies of popular and unpopular kids. (Link)

• Factors that affect tips of waitresses. (Link)

• Having children makes you think like your parents. (Link)

• How to create false memories. (Link)

• How the SAT predicts college performance. (Link)

• The type of haircut that makes women attractive. (Link)

• Where attractiveness matters. (Link)

• Exaggerate potential threats to resist temptation. (Link)

• Information on who becomes friends after romantic breakups. (Link)

• Playing video games improves reaction time. (Link)

• The facial ratio and aggressiveness in men. (Link)

• Marriage increases the odds of weight gain. (Link)

• What affects people’s ideas of fairness. (Link)

• Personality can be judged by physical appearance. (Link)

• Hourly employees are happier than salaried employees. (Link)

• How intelligence affects startup success. (Link)

• Data on rates of infidelity. (Link)

• The optimal price for starting negotiations and auctions. (Link)

• The number of competitors you face affects how well you perform. (Link)

• Males have more personality than females across multiple species. (Link)

• Exposure to luxury items leads people to think more about themselves than others. (Link)

• Data on who gets cosmetic surgery. (Link)

• Uninsured ER patients are twice as likely to die. (Link)

• The belief in hell correlates with economic growth. (Link)

• Adolescents with high or low intelligence are less likely to have sex. (Link)

• The passer ratings of quarterbacks are correlated with attractiveness. (Link)

• Depression is as deadly as smoking. (Link)

• Romantic rivalry increases religiosity. (Link)

• Children who are less fearful have an increased risk of becoming a criminal. (Link)

• Data on which groups of people have insomnia. (Link)

• More than 9 out of 10 Americans have had premarital sex. (Link)

• The younger the bride, the more money spent on an engagement ring. (Link)

• Income inequality drives church attendance. (Link)

• Pre-eclampsia is less likely in women who had an exclusive sexual relationship with the biological father. (Link)

• Attractive politicians get more votes. (Link)

• People can judge personality traits based on first impressions. (Link)

• Hiring practices of managers vary by race and ethnicity. (Link)

• Practicing competence leads to momentary stress but longer-term benefits. (Link)

• The top ten trustworthy states. (Link)

• Bad driving has a genetic component. (Link)

• TV crime dramas distort viewers’ perceptions of the justice system. (Link)

• Approximately 75% of all homicides are between people who know each other. (Link)

• Generous people avoid situations where they are expected to be generous. (Link)

• Hungry men prefer women who are heavier and older. (Link)

• People prefer items that come first or last in a sequence of items. (Link)

• Students learn better if they first make an unsuccessful attempt to retrieve information. (Link)

• Attractive people are more trusting when they think they can be seen. (Link)

• Women are getting unhappier. (Link)

• People with more positive perceptions of aging are more likely to practice healthy behaviors. (Link)

• Late evidence disclosure and stronger evidence produce higher confession rates. (Link)

• Status and attractiveness are important parts of men’s and women’s self-concepts, respectively. (Link)

• Changes in the popularity of college majors. (Link)

• Predicting behavior based on physical characteristics. (Link)

• People in positions of power who do not perceive themselves as competent are more likely to lash out at others. (Link)

• Mimicry improves speed dating success for women. (Link)

• Birth control pills affect choice of partner. (Link)

• What people lie about. (Link)

• Men are more disturbed by sexual infidelity, while women are more disturbed by emotional infidelity. (Link)

• Genes heavily influence exceptional cognitive ability. (Link)

• People or objects moving from left to right are perceived as having more power. (Link)

• Women prefer men who are already in a relationship. (Link)

• Sold-out products enhance consumer desire. (Link)

• Subliminal messaging is more effective when the message is negative. (Link)

• People pay attention to babies in ads. (Link)

• Behavior spreads through social networks. (Link)

• There is a connection between psychosis and creativity. (Link)

• Anticipating an interaction with an obese person gives normal-weight people a sense of dominance. (Link)

• More information about others leads to less liking. (Link)

• Viewing a photo of a loved one can reduce pain. (Link)

• Women decide to have sex for many different reasons. (Link)

• Praising effort improves performance more than praising intelligence. (Link)

• Willpower is a limited resource. (Link)

• The width-to-height ratio of men’s faces correlates with their level of aggression. (Link)

• There is a negative relationship between optimism and entrepreneurial success. (Link)

PHP and MySQL 24-Hour Trainer

PHP and MySQL 24-Hour Trainer is a book by Andrea Tarr. This post has some notes from the book. The book itself has much more information as well as helpful examples. The book also comes with a DVD featuring video tutorials.

• PHP files use the .php file extension.

• The echo function tells the processor to output data.

• The include function tells the processor to take the file that you specify and insert it in place of the include statement.

• A block of PHP code starts with <?php and ends with ?>

• One type of comment starts with //

• Another type of comment starts with a /* and ends with a */

• Create the ending tag, bracket, or parenthesis when you create the beginning tag, bracket, or parenthesis.

• Leave error reporting on while developing and turn it off when your code goes into production.

• Variables start with a dollar sign and you assign the variable a value using the = sign.

• To assign a string to a variable, use the = sign.

• You can use a period to concatenate strings.

• String functions include: strlen(), htmlspecialchars(), ucfirst(), ucwords(), trim(), strtolower(), strtoupper()

• Ways to assign values to numeric variables:

=

+=

-=

*=

/=

%=

• Numeric operators:

+ is Addition

- is Subtraction

* is Multiply

/ is Divide

% is Remainder

++ is Increment

– is Decrement

• Enabling display_errors in the php.ini file is a way to display errors during development.

• Common issues to check when your code isn’t working: typos, missing echo, case, semicolons, misplaced or missing closing braces, assignment versus comparison, $ on variables, quotes, array number

• An array holds multiple values in a single variable.

• You can nest arrays within arrays to make multi-dimensional arrays.

• To see what’s in an array, use the print_r() function.

• A Boolean variable value is either true or false.

• A variable is null if you haven’t assigned it to a value or if you assigned it to NULL.

• You can use the define() function for working with constants.

• Date and time functions: time(), date(), strftime(), mktime(), strtotime(), getdate()

• The $_GET function stores values from a form sent with method=”get”

• The $_POST function stores values from a form sent with method=”post”

• Cookie functions: setcookie(), $_COOKIE

• The filter_var() function is involved with cleansing data.

• The basic if statement consists of the condition being evaluated along with the code to be executed enclosed in curly braces.

• Use an else statement if you want to have code execute if the condition is not met.

• An elseif statement can add a condition on the else statement.

• Comparison operators for if/else statements:

==

===

!=

<>

<

>

<=

>=

• When using the OR operator, the condition is true if any of the conditions are true.

• Use the AND operator when you need all conditions to be true before executing a block of code.

• The not (!) operator is used for negating.

• The statement switch is used to perform specific blocks of code depending on conditions, when you want to compare the same variable or expression to several different values.

• A while loop executes a block of code while a given condition is true.

• With a do/while loop, the condition is checked after running the block of code instead of before.

• The for loop executes a block of code a given number of times.

• The foreach loop loops through all the elements in an array or object.

• You can use continue if you are done with a particular loop iteration and want to jump to the start of the next iteration.

• Superglobal variables: $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV, $_SERVER

• Predefined keys in the $_SERVER superglobal: PHP_SELF, SERVER_NAME, DOCUMENT_ROOT, HTTP_REFERER, HTTP_USER_AGENT, SCRIPT_FILENAME, SCRIPT_NAME, REQUEST_URI

• You can pass more than one parameter to a function.

• When variables are created within a function, they are automatically created as local variables and can be seen only within the function.

• If you want to know if a function performed correctly and it does not have data to return, you would return true or false.

• The commands include, include_once, require, and require_once can be used to organize your files by grouping your functions in their own files.

• When the form is submitted, the data is passed to either the GET or the POST variable, depending on the method attribute.

• The header() function can redirect pages.

• An object is an instantiation of a class that contains properties and methods.

• Begin a class declaration with the word Class followed by the name of the class. The body of the class goes in curly brackets. Put property definitions next, followed by the methods.

• The property declaration starts with the scope keyword (public, protected, or private) followed by the property.

• To instantiate a class, use a require_once to include it.

• Assigning a method to a variable or using it returns a value.

• Using a method enables you to handle any other actions that need to be done when you change the property.

• Getter and setter methods access properties outside of a class.

• Private and protected methods are used when they are needed only within the class or they are using variables that are available only within the class.

• You can make a base class and then create subclasses that inherit all the public and protected properties and methods in addition to their own properties and methods.

• An abstract class can contain both regular and abstract methods.

• Categories of conditions that can produce errors: variable types and values, existence of a resource, validity of user supplied data

• Functions for verifying types and values in variables: is_numeric(), ctype_digit(), is_bool(), is_null(), is_float(), is_double(), is_int(), is_string(), is_object, is_array

• Error handling has four parts: try, throw, catch, Exception

• For security purposes you should check variables for the proper type of data, for malicious data, and for any character substitutions required.

• To prevent cross-site request forgeries when using forms, use randomly generated tokens on the form and verify those tokens when you use the data.

• A MySQL statement followed by a semicolon is a command.

• Identifiers are the names of objects in MySQL such as databases, tables, indexes, and columns.

• PDO has the main PDO class, the PDOStatement class for prepared statements, and the PDOException class for errors.

• Text strings in MySQL: CHAR, VARCHAR, TEXT

• Binary strings in MySQL: BINARY, VARBINARY, BLOB

• TEXT type sizes: TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT

• BLOB type sizes: TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB

• Integer types: TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT

• When you assign the AUTO_INCREMENT attribute to a field, MySQL generates a unique sequential number for each new row.

• SQL commands and clauses commonly used with PHP and MySQL: INSERT, SELECT, FROM, WHERE, JOIN, UPDATE, REPLACE, DELETE, TRUNCATE, LIMIT, ORDER BY

Java Programming 24-Hour Trainer

Java Programming 24-Hour Trainer is a book by Yakov Fain. This post has some notes from the book. The book itself has much more information as well as helpful examples. The book also comes with a DVD that contains video tutorials.

• Java is a case-sensitive language.

• Popular Java IDEs include Eclipse, NetBeans, IntelliJ IDEA, and RAD.

• Packages are used to better organize multi-file projects and for data protection.

• Each Java program has at least one class.

• Classes in Java may have methods (aka functions) and fields (aka attributes or properties).

• To create an instance of a class means to create the object in the computer’s memory based on the class definition.

• Program variables must be declared first and then you can assign them values either at the time of declaration or later on in one of the class methods.

• To store values that never change, you need to declare a constant by adding the keyword final to the declaration line.

• Java data types: byte, short, int, long, float, double, char, boolean

• If you declare a variable inside any method, the variable has a local scope.

• If a variable has to be accessible from more than one class method, declare it on a class level.

• All primitive data types have corresponding wrapper classes that contain useful methods dealing with respective data types.

• The if statement is used for determining whether some condition is true or false. The execution of a program will change based on the answer to this question.

• The keyword extends is used to indicate that one class has been inherited from another.

• Method overloading means having a class with more than one method having the same name but different argument lists.

• When a program creates an instance of a class, Java invokes the class’s constructor.

• Constructors have these characteristics: called when the class is being instantiated, must have the same name as the class they’re in, can’t return a value

• Constructors are typically used to assign initial values to class variables.

• The keyword super enables you to explicitly call the method or a constructor from the ancestor’s class.

• The keyword this is useful when you need to refer to the instance of the class from its method.

• The keyword static indicates that the class variable will be shared by all instances of the same class.

• An array is used for storing multiple values of the same type.

• When you know in advance how many times you want to repeat an action, use the for loop.

• The while loop is used when you do not know the exact size of the array, but just the condition of exit from the loop.

• The if statement allows you to check a certain condition and redirect the program to execute code accordingly.

• The switch statement is used when the program execution is defined based on multiple selections.

• Potential access levels for Java classes, methods and member variables: public, private, protected, package

• If a class is declared abstract (by using the keyword abstract) then it can’t be instantiated.

• JFrame is a Swing container that can hold UI controls.

• Swing layout managers: FlowLayout, GridLayout, BoxLayout, BorderLayout, CardLayout, GridBagLayout

• Swing widgets: JButton, JLabel, JCheckBox, JRadioButton, JToggleButton, JScrollPane, JSpinner, JScrollBar, JSlider, JProgressBar, JComboBox, JList, JTabbedPane, JTable, JTextField, JTextArea, JPasswordField, JFormattedTextField, JEditorPane, JToolTip, JTree, JViewPort, ImageIcon

• ActionListener is used for processing button clicks in Swing.

• More Swing listeners: FocusListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, WindowListener

• An inner class defined as static can only access static variables of the outer class.

• Five Java keywords that can be used for exception handling: try, catch, finally, throw, throws

• A try block can have multiple catch blocks to provide handling for more than one type of error.

• The throw statement is used to throw Java exception objects.

• To create and populate an ArrayList object you should first instantiate it, and then add instances of other objects to ArrayList by calling the method add()

• The get() method extracts a particular element from ArrayList.

• The Hashtable and HashMap classes offer a convenient way of storing and accessing the elements of a collection.

• The Properties class can be used to work with properties using key/value pairs.

• The class ListIterator supports going through a list in both directions via the next() and previous() methods.

• A program can read or write any file with one of the subclasses of InputStream or OutputStream.

• The class BufferedInputStream works as a middleman between FileInputStream and the file itself.

• The class BufferedOutputStream works as a middleman between FileOutputStream and the file itself.

• The class File allows you to rename or delete a file, perform an existence check, create a directory, and more.

• Some methods of the File class: createNewFile(), delete(), renameTo(), length(), exists(), list(), lastModified(), mkDir()

• The Socket and ServerSocket classes are used for network communications.

• Multi-threading involves the Thread class.

• You can use the sleep() method of Thread to make the processor available to other threads.

• You can call the interrupt() method on a thread to stop it.

• The setPriority() method of the Thread class lets you control a priority of a thread.

• The keyword synchronized prevents race conditions from happening.

• These methods of the Object class are relevant to threads: wait(), notify(), notifyAll()

• Using the ReentrantLock class in java.util.concurrent.locks may improve the performance of your code.

• The utility class Executors has static methods for creating executors.

• Some data structures for programming with threads that are in the java.util.concurrent package are queues and collections.

• Commonly used classes for working with databases are: Connection, Statement, ResultSet, DataSource, RowSet

• The JTable Swing Component enables you to present data in a grid with rows and columns.

• The bind() method binds an remote method invocation server to a name.

• To create a servlet, write a class that extends from HTTPServlet.

• Event listeners involved in working with servlets are: ServletContextListener, HttpSessionListener, ServletRequestListener

• Predefined variables you can use in JSP pages: request, response, out, session, exception, page, pageContext, application, config

• Some of the JSP directives: page, include, attribute, taglib

• You can define a bean’s scope using the scope attribute of the tag jsp:useBean

• Bean scopes: page, request, session, application

• Some of the main JMS classes and interfaces that enable you to send and receive messages: Queue, QueueConnection, QueueConnectionFactory, QueueSession, QueueSender, QueueReceiver, TopicPublisher, TopicSubscriber, Topic, Message

• Types of JMS messages: TextMessage, ObjectMessage, BytesMessage, StreamMessage, MapMessage

• Using an asynchronous callback onMessage() is the best way to receive messages.

• Types of session beans in EJB: stateless, stateful, singleton

• EntityManager will execute your JPA requests to read from or write into a database.

• Core interfaces in the Criteria API: CriteriaBuilder, CriteriaQuery, Root, TypedQuery, Join

JavaScript Step by Step

The second edition of JavaScript Step by Step is written by Steve Suehring. This post has some notes from the book. The book itself has much more information as well as helpful examples.

• A JavaScript program consists of statements formed from tokens, operators, and identifiers placed together in an order that is meaningful to a JavaScript interpreter.

• JavaScript fits within <script> tags.

• Tips for using JavaScript: Emphasize function over form, Follow standards, Render correctly in multiple browsers, Use appropriate technologies at appropriate times

• JavaScript is case sensitive.

• A multiline comment begins and ends with /* and */ respectively.

• Semicolons are used to delineate expressions in JavaScript.

• JavaScript statements come in two basic forms, simple and compound.

• Reserved words in JavaScript: break, case, catch, continue, debugger, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with

• Words reserved for future use: class, const, enum, export, extends, import, super

• Words reserved for future use when in strict mode: implements, interface, let, package, private, protected, public, static, yield

• Strict mode adds enhanced error checking and security and is enabled with this syntax: “use strict”;

• Six data types in JavaScript: numbers, strings, booleans, null, undefined, objects

• The isNaN() function is used to determine whether a number is legal or valid.

• The Math object is a built-in object used for working with numbers.

• The length property on a string object gives the length of a string.

• The substring method returns the characters from the first argument up to but not including the second argument.

• Some commonly used string methods besides substring include slice, substr, concat, toUpperCase, toLowerCase, match, search, and replace

• Variables are declared with the var keyword.

• Variables are globally scoped when they are used outside a function.

• The Date object includes methods that are helpful when working with dates.

• The RegExp object provides ways to work with regular expressions.

• Operators: additive operators, multiplicative operators, bitwise operators, equality operators, relational operators, unary operators, assignment operators, the comma operator

• The if statement evaluates an expression and, based on the results, determines which code executes within a program.

• The if statement examines the validity, or truthfulness, of a condition to determine whether the code within the conditional (inside the braces) is to be executed.

• Using else if and else, you can create multiple levels of conditions, each of which is tested in turn.

• The ternary conditional uses the question mark operator to create a compact if/else construct.

• The switch statement can test a variable for several values and then execute code based on whichever case matches.

• A while loop executes the code contained within its braces until a condition is met.

• The do…while statement executes the code contained in its braces at least once.

• You can use a for loop to create a loop in which the conditions are initialized, evaluated, and changed in a compact form.

• The for…in loop iterates through the properties of an object, returning the names of the properties themselves.

• The for…each loop iterates through the properties of an object, returning the values of the properties.

• A JavaScript function is a collection of statements, either named or unnamed (anonymous), that can be called from elsewhere within a JavaScript program. Functions can accept arguments, which are input values passed into the function. Within a function, those arguments passed into the function can be acted upon and the results returned to the caller of the function via a return value.

• When a function finishes executing its code, it can return a value to the caller by using the return keyword.

• With an anonymous function, the function is defined and tied to a variable.

• Closure refer to the existence of variables outside a function’s normal execution context.

• Objects have properties and methods.

• Classes define sets of objects that share the same properties and methods.

• You can create an object in Javascript either by using the new keyword or by using curly braces.

• After creating an object, you can assign properties and methods to it.

• You can use the in operator to test whether a given property already exists within an object.

• You can use the new Array() explicit constructor to group a set of values into an object and then access those values through a numbered index value.

• The length property of an array returns the number of elements in the array.

• You can add elements to an array by using the concat() method, the join() method, the push() and pop() methods, the shift() and unshift() methods, or the slice() method

• Some methods of the array object: reverse(), map(), indexOf(), lastIndexOf(), every(), filter(), some(), splice()

• The encodeURI() method encodes URIs so that they can be used according to the standard.

• The window object has several child objects: document, frames, history, location, navigator, screen, self/window/parent

• Selected properties of the window object: closed, defaultStatus, name, opener, parent, status, top

• Selected methods of the window object: addEventListener(), attachEvent(), blur(), focus(), close(), detachEvent(), removeEventListener(), open(), print()

• Selected methods of the window object for moving and resizing: moveBy(), moveTo(), resizeBy(), resizeTo()

• Properties of the screen object: availHeight, availWidth, colorDepth, height, width

• The navigator object provides several properties that assist in the detection of various elements of the visitor’s browser and environment.

• The location object gives you access to the currently loaded URI, including any information about the query string, the protocol in use, and other related components.

• The history object – specifically the back(), forward(), and go() methods – provides ways to move forward and backward through the visitor’s browsing history.

• The getElementById() and getElementsByTagName() methods are used for retrieving elements.

• These objects contain groups of elements from a document: document.anchors, document.forms, document.images, document.link

• The getAttribute() method is used for getting attributes.

• The setAttribute() method is used for setting attributes.

• The createElement() method of the document object creates or adds an element to a document.

• You can add an element to a document using the appendChild() method.

• You can remove nodes from a document using the removeChild() method.

• The Window object’s events include mouseover(), mouseout(), load(), and click()

• DOM 0 and DOM level 2 events:

onblur() – blur

onchange() – change

onclick() – click

ondblclick() – dblclick

onfocus() – focus

onkeydown() – keydown

onkeypress() – keypress

onkeyup() – keyup

onload() – load

onmousedown() – mousedown

onmousemove() – mousemove

onmouseout() – mouseout

onmouseover() – mouseover

onmouseup() – mouseup

onsubmit() – submit

onunload() – unload

onreset()

onresize()

onselect()

• The typeof operator is the primary mechanism used to implement feature testing.

• Global functions involved in JavaScript timers: setTimeout(), clearTimeout(), setInterval(), clearInterval()

• You can create cookies by using the document.cookie property

• Reading cookies with JavaScript involves taking the cookies from the document.cookie object and making a call to the split method.

• To remove a cookie, clear its value and set its expiration date to some time in the past.

• Using getElementById() and the style object is an effective way to change a style.

• The try portion of the try/catch set of statements encapsulates a block of JavaScript. When the script executes, any exceptions that are thrown in the try block are caught by the catch statement. You can then handle the error within the JavaScript placed in the catch block.

• The finally statement contains code that gets executed regardless of whether the try statement’s code succeeded or the catch handler executed. You can use a finally block to make sure that some code executes every time.

• You can import an XML document using the XMLHttpRequest() object.

• To send AJAX requests to the web server, use a combination of the open() and send() methods of the XMLHttpRequest object.

• The requestObj variable provides helpful methods for processing a response.

• Popular JavaScript libraries and frameworks include: jQuery, YUI, MooTools

• After including the jQuery library in a page, you can use $() as a shortcut to a jQuery function.

• You can connect to elements during the load or onload event of the page by connecting through the .ready() utility function of the document element.

• You use selectors to identify and group the elements on which a jQuery function is executed.

• The .attr() function of jQuery is used for retrieving and setting attributes.

• The .bind() function connects an event handler to an event.

• These jQuery functions are used for sending data to and from a server:

.load()

.post()

.get()

.ajax()

.getJSON()

• The .show() and .hide() functions show and hide elements of a page.

• The .toggle() function shows or hides an element based on its current state.

• jQuery UI includes the .draggable() and .droppable() functions for moving elements.

Beginning Java 7

Beginning Java 7 is a book by Jeff Friesen. This post has some notes from the book. The book itself has much more information as well as helpful examples.

• The public reserved word makes main() visible to the startup code that calls this method.

• The static reserved word causes the method to associate with the class instead of associating with any objects created from this class.

• The void reserved word indicates that the method doesn’t return a value.

• Three popular IDEs for Java development are Eclipse, IntelliJ IDEA, and NetBeans.

• Comments embed documentation in source code.

• A Javadoc comment occupies one or more lines of source code.

• An identifier consists of letters, digits, connecting punctuation characters, or currency symbols.

• A type identifies a set of values (and their representation in memory) and a set of operations that transform these values into other values of that set.

• Primitive types and their reserved words:

Boolean: boolean

Character: char

Byte integer: byte

Short integer: short

Integer: int

Long integer: long

Floating-point: float

Double precision floating-point: double

• A variable declaration minimally consists of a type name, optionally followed by a sequence of square bracket pairs, followed by a name, optionally followed by a sequence of square bracket pairs, and terminated with a semicolon character.

• Java supports several kinds of literals: string, Boolean true and false, character, integer, floating-point, and null

• Operators: Addition, Array index, Assignment, Bitwise AND, Bitwise complement, Bitwise exclusive OR, Bitwise inclusive OR, Cast, Compound assignment, Conditional, Conditional AND, Conditional OR, Division, Equality, Inequality, Left shift, Logical AND, Logical complement, Logical exclusive OR, Logical inclusive OR, Member access, Method call, Multiplication, Object creation, Postdecrement, Postincrement, Predecrement, Preincrement, Relational greater than, Relational greater than or equals to, Relational less than, Relational less than or equal to, Relational type checking, Remainder, Signed right shift, String concatenation, Subtraction, Unary minus, Unary plus, Unsigned right shift

• When evaluating a compound expression, Java takes each operator’s precedence into account to ensure that the expression evaluates as expected.

• Statements assign values to variables, control a program’s flow by making decisions and/or repeatedly executing other statements, and perform other tasks.

• The assignment statement assigns a value to a variable.

• Decision statements: if, else, switch

• Loop statements: for, while, do-while

• A class is a template for manufacturing objects, which are also known as instances.

• You must first declare the class by using a header (consisting of the reserved word class followed by a name that identifies the class) and a body (starting with an open brace character and ending with a close brace and including declarations between the braces).

• You can create objects by using the new operator with a constructor.

• When creating an array, specify new followed by a name that identifies the type of values that are stored in the array, followed by one or more pairs of square brackets that signify the number of dimensions occupied by the array.

• Entity attributes are described via instance fields.

• You can declare an instance field by minimally specifying a type name, followed by an identifier that names the field, followed by a semicolon character.

• You can declare an instance method by minimally specifying a return type name, followed by an identifier that names the method, followed by a parameter list, followed by a brace-delimited body.

• A method is invoked by using the member access operator.

• Method invocations require a method-call stack to keep track of the statements to which execution must return.

• A method call includes a list of arguments being passed to the method.

• Java’s return statement lets a method or a constructor exit before reaching the last statement.

• Recursion is a scenario where a method calls itself.

• Method overloading lets you introduce methods with the same name but different parameter lists into the same class.

• Java provides four levels of access control: Public, Protected, Private, Package-private

• A class initializer is used to initialize a loaded class via a sequence of statements.

• An instance initializer is used to initialize an object via a sequence of statements.

• The reserved word extends is used for specifying a hierarchical relationship between two classes.

• Object’s methods:

Object clone()

boolean equals(Object obj)

void finalize()

Class<?> getClass()

int hashCode()

void notify()

void notifyAll()

String toString()

void wait()

void wait(long timeout)

void wait(long timeout, int nanos)

• The clone() method duplicates an object without calling a constructor.

• The equals() method is reflexive, symmetric, transitive, and consistent.

• Java supports four types of polymorphism: coercion, overloading, parametric, subtype

• An abstract class can contain non-abstract methods in addition to or instead of abstract methods.

• At minimum, the header of an interface declaration consists of the reserved word interface followed by a name that identifies the interface. The body starts with an open brace character and ends with a close brace. Between these delimiters are constant and method header declarations.

• The implements reserved word is used for implementing an interface by a class.

• Four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, local classes

• A package is a unique namespace that can contain a combination of top-level classes, other top-level types, and subpackages.

• The package statement identifies the package in which a source file’s types are located.

• The import statement imports types from a package by telling the compiler where to look for unqualified type names during compilation.

• Constructors and methods of Throwable:

Throwable()

Throwable(String message)

Throwable(String message, Throwable cause)

protected Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

Throwable(Throwable cause)

void addSuppressed(Throwable exception)

Throwable fillInStackTrace()

Throwable getCause()

String getMessage()

StackTraceElement[] getStackTrace()

Throwable[] getSuppressed()

Throwable initCause(Throwable cause)

void printStackTrace()

void setStackTrace(StackTraceElement[] stackTrace)

• A method indicates its intention to handle one or more exceptions by specifying a try statement that includes one or more appropriate catch blocks. The try statement consists of the word try followed by a brace-deliminted body. You place code that throws exceptions into this block.

• A catch block consists of the reserved word catch, followed by a round bracket-delimited single-parameter list that specifies an exception class name, followed by a brace-delimited body. You place code that handles exceptions whose type match the type of the catch block’s parameter list’s exception class parameter in this block.

• Assertion statements begin with the reserved word assert.

• Generics are used for declaring and using type-agnostic classes and interfaces.

• A generic type is a class or interface that introduces a family of parameterized types by declaring a formal type parameter list.

• Generics support five kinds of type arguments: Concrete type, Concrete parameterized type, Array type, Type parameter, Wildcard

• An enum is an enumerated type that is expressed via the reserved word enum.

• java.lang.Math is an API for working with math.

• java.lang.Package is an API for working with packages.

• Primitive type wrapper classes: Boolean, Byte, Character, Double, Float, Integer, Long, Short

• An object’s levels of reachability: strongly reachable, softly reachable, weakly reachable, phantom reachable

• The Reference API consists of five classes located in the java.lang.ref package: Reference, ReferenceQueue, SoftReference, WeakReference, PhantomReference

• The Reflection API lets applications learn about loaded classes, interfaces, enums, and annotation types.

• Instances of type String represent sequences of characters.

• The java.lang.StringBuffer class is used for working with string buffers.

• The java.lang.System class provides access to system-oriented resources, including standard input, standard output, and standard error.

• The Threading API consists of one interface (Runnable) and four classes (Thread, ThreadGroup, ThreadLocal, and InheritableThreadLocal).

• Collections Framework core interfaces include: java.lang.Iterable, Collection, List, Set, SortedSet, NavigableSet, Queue, Deque, Map, SortedMap, and NavigableMap

• Collections Framework implementation classes include: ArrayList, LinkedList, TreeSet, HashSet, LinkedHashSet, EnumSet, PriorityQueue, ArrayDeque, TreeMap, HashMap, LinkedHashMap, IdentityHashMap, WeakHashMap, EnumMap, AbstractCollection, AbstractList, AbstractSequentialList, AbstractSet, AbstractQueue, and AbstractMap

• Collections Framework utility classes include: Array and Collections

• Collection Methods:

boolean add(E e)

boolean addAll(Collection<? extends E> c)

void clear()

boolean contains(Object o)

boolean containsAll(Collection<?> c)

boolean equals(Object o)

int hashCode()

boolean isEmpty()

Iterator<E> iterator()

boolean remove(Object o)

boolean removeAll(Collection<?> c)

boolean retainAll(Collection<?> c)

int size()

Object[] toArray()

<T> T[] toArray(T[] a)

• List-specific Methods:

void add(int index, E e)

boolean addAll(int index, Collection<? extends E> c)

E get(int index)

int indexOf(Object o)

int lastIndexOf(Object o)

ListIterator<E> listIterator()

ListIterator<E> listIterator(int index)

E remove (int index)

E set(int index, E e)

List<E> subList(int fromIndex, int toIndex)

• ArrayList supplies three constructors:

ArrayList()

ArrayList(Collection<? extends E> c)

ArrayList(int initialCapacity)

• LinkedList supplies two constructors:

LinkedList()

LinkedList(Collection<? extends E> c)

• TreeSet supplies four constructors:

TreeSet()

TreeSet(Collection<? extends E> c)

TreeSet(Comparator<? super E> comparator)

TreeSet(SortedSet<E> s)

• HashSet supplies four constructors:

HashSet()

HashSet(Collection<? extends E> c)

HashSet(int initialCapacity)

HashSet(int initialCapacity, float loadFactor)

• NavigableSet-specific Methods:

E ceiling(E e)

Iterator<E> descendingIterator()

NavigableSet<E> descendingSet()

E floor(E e)

NavigableSet<E> headSet(E toElement, boolean inclusive)

E higher(E e)

E lower(E e)

E pollFirst()

E pollLast()

NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

NavigableSet<E> tailSet(E fromElement, boolean inclusive)

• Queue-specific Methods:

boolean add(E e)

E element()

boolean offer(E e)

E peek()

E poll()

E remove()

• PriorityQueue supplies six constructors:

PriorityQueue()

PriorityQueue(Collection<? extends E> c)

PriorityQueue(int initialCapacity)

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

PriorityQueue(PriorityQueue<? extends E> pq)

PriorityQueue(SortedSet<? extends E> ss)

• Deque-specific Methods:

void addFirst(E e)

void addLast(E e)

Iterator<E>

descendingIterator()

E element()

E getFirst()

E getLast()

boolean offer(E e)

boolean offerFirst(E e)

boolean offerLast(E e)

E peek()

E peekFirst()

E peekLast()

E poll()

E pollFirst()

E pollLast()

E pop()

void push(E e)

E remove()

E removeFirst()

boolean removeFirstOccurrence(Object o)

E removeLast()

boolean removeLastOccurrence(Object o)

• Map-specific methods:

void clear()

boolean containsKey(Object key)

boolean containsValue(Object value)

Set<Map.Entry<K,V>> entrySet()

boolean equals(Object o)

V get(Object key)

int hashCode()

boolean isEmpty()

Set<K> keySet()

V put(K key,V value)

void putAll(Map<? extends K,? extends V> m)

V remove(Object key)

int size()

Collection<V> values()

• Map.Entry Methods:

boolean equals(Object o)

K getKey()

V getValue()

int hashCode()

V setValue(V value)

• TreeMap supplies four constructors:

TreeMap()

TreeMap(Comparator<? superK> comparator)

TreeMap(Map<? extends K, ? extends V> m)

TreeMap(SortedMap<K, ? extends V> sm)

• The HashMap class provides a map implementation that is based on a hashtable data structure. HashMap supplies four constructors:

HashMap()

HashMap(int initialCapacity)

HashMap(int initialCapacity, float loadFactor)

HashMap(Map<? extends K, ? extends V> m)

• The IdentityHashMap class provides a Map implementation that uses reference equality instead of object equality when comparing keys and values.

• The WeakHashMap class provides a Map implementation that is based on weakly reachable keys.

• The EnumMap class provides a Map implementation whose keys are the members of the same enum.

• SortedMap-specific Methods:

Comparator<? super K> comparator()

Set<Map.Entry<K,V>> entrySet()

K firstKey()

SortedMap<K,V> headMap(K toKey)

Set<K> keySet()

K lastKey()

SortedMap<K,V> subMap(K fromKey, K toKey)

SortedMap<K,V> tailMap(K fromKey)

Collection<V> values()

• NavigableMap-specific methods:

Map.Entry<K,V> ceilingEntry(K key)

K ceilingKey(K key)

NavigableSet<K> descendingKeySet()

NavigableMap<K,V> descendingMap()

Map.Entry<K,V> firstEntry()

Map.Entry<K,V> floorEntry(K key)

K floorKey(K key)

NavigableMap<K,V> headMap(K toKey, boolean inclusive)

Map.Entry<K,V> higherEntry(K key)

K higherKey(K key)

Map.Entry<K,V> lastEntry()

Map.Entry<K,V> lowerEntry(K key)

K lowerKey(K key)

NavigableSet<K> navigableKeySet()

Map.Entry<K,V> pollFirstEntry()

Map.Entry<K,V> pollLastEntry()

NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, KtoKey, boolean toInclusive)

NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)

• The java.util.concurrent.ExecutorService interface extends Executor and whose implementation is usually a thread pool.

• The Future interface provides methods for canceling a task, for returning a task’s value, and for determining whether or not the task has finished.

• Five commonly used synchronizers: countdown latches, cyclic barriers, exchangers, phasers, semaphores

• Lock provides more extensive locking operations than can be achieved via the synchronized reserved word.

• The java.util.concurrent.atomic package provides classes that support lock-free, thread-safe operations on single variables.

• Fork/Join largely consists of these classes: ForkJoinPool, ForkJoinTask, ForkJoinWorkerThread, RecursiveAction, RecursiveTask

• The java.util.Objects class consists of class methods for operating on objects.

• Objects Methods:

<T> int compare(T a, T b, Comparator<? super T> c)

boolean deepEquals(Object a, Object b)

boolean equals(Object a, Object b)

int hash(Object… values)

int hashCode(Object o)

<T> T requireNonNull(T obj)

<T> T requireNonNull(T obj, String message)

String toString(Object o)

String toString(Object o, String nullDefault)

• JDialog, JFrame, JWindow, and two other Swing containers use panes to organize their contained componets/containers.

• Swing supports root, layered, content, and glass panes.

• JComponent introduces tooltips, borders, and the option of creating nonrectangular components.

• The JButton class describes a button component.

• Pluggable look and feel classes: BasicLookAndFeel, MetalLookAndFeel, MultiLookAndFeel, NimbusLookAndFeel, SynthLookAndFeel, GTKLookAndFeel, MotifLookAndFeel

• You can introduce a Swing-based canvas class by subclassing JComponent and overriding its paint() method.

• The File class declares the File[] listRoots() class method to return the root directories of available filesystems as an array of File objects.

• File Methods for learning about a stored abstract pathname:

File getAbsoluteFile()

String getAbsolutePath()

File getCanonicalFile()

String getCanonicalPath()

String getName()

String getParent()

File getParentFile()

String getPath()

boolean isAbsolute()

• File Methods for learning about a file or directory:

boolean canExecute()

boolean canRead()

boolean canWrite()

boolean exists()

boolean isDirectory()

boolean isFile()

boolean isHidden()

long lastModified()

long length()

• File Methods for obtaining directory content:

String[] list()

String[] list(FilenameFilter filter)

File[] listFiles()

File[] listFiles(FileFilter filter)

File[] listFiles(FilenameFilter filter)

• File Methods for creating files and manipulating existing files:

boolean createNewFile()

static File createTempFile(String prefix, String suffix)

static File createTempFile(String prefix, String suffix, File directory)

boolean delete()

void deleteOnExit()

boolean mkdir()

boolean mkdirs()

boolean renameTo(File dest)

boolean setLastModified(long time)

boolean setReadOnly()

• RandomAccessFile is used for creating and/or opening a file for random access in which write and read operations can occur until the file is closed.

• RandomAccessFile Methods:

void close()

FileDescriptor getFD()

long getFilePointer()

long length()

int read()

int read(byte[] b)

char readChar()

int readInt()

void seek(long pos)

void setLength(long newLength)

int skipBytes(int n)

void write(byte[] b)

void write(int b)

void writeChars(String s)

void writeInt(int i)

• The java.io package provides several output stream and input stream classes that are descendents of the abstract OutputStream and InputStream classes and are used for performing I/O operations.

• OutputStream Methods:

void close()

void flush()

void write(byte[] b)

void write(byte[] b, int off, int len)

void write(int b)

• InputStream Methods:

int available()

void close()

void mark(int readlimit)

boolean markSupported()

int read()

int read(byte[] b)

int read(byte[] b, int off, int len)

void reset()

long skip(long n)

• The concrete FileOutputStream class lets you write a stream of bytes to a file and the concrete FileInputStream class lets you read a stream of bytes from a file.

• Filter output streams are created from subclasses of the concrete FilterOutputStream class.

• Filter input streams are created from subclasses of the concrete FilterInputStream class.

• The concrete BufferedOutputStream and BufferedInputStream filter stream classes improve performance by minimizing underlying output stream write() and underlying input stream read() method calls.

• The concrete DataOutputStream and DataInputStream filter stream classes provide methods to write or read primitive type values and strings in a platform-independent way.

• The concrete ObjectOutputStream class initiates the serialization of an object’s state to an object output stream.

• The concrete ObjectInputStream class initiates the deserialization of an object’s state from an object input stream.

• Java supports externalization via the java.io.Externalizable interface, which declares the public methods void writeExternal(ObjectOutput out) and void readExternal(ObjectInput in)

• The Writer and Reader classes perform character I/O.

• The concrete OutputStreamWriter class encodes characters written to it into bytes according to the default or specified character encoding.

• The concrete InputStreamReader class decodes characters from bytes according to the default or specified character encoding.

• FileWriter is a convenience class for writing characters to files.

• FileReader is a convenience class for reading characters from files.

• The java.net package provides Socket and ServerSocket classes for performing TCP-based communications.

• The java.net package provides DatagramSocket, DatagramPacket, and MulticastSocket classes for performing UDP communications.

• ServerSocket declares four constructors:

ServerSocket()

ServerSocket(int port)

ServerSocket(int port, int backlog)

ServerSocket(int port, int backlog, InetAddress bindAddr)

• The URL and URLConnection classes are used for accessing URL-based resources.

• The URLEncoder and URLDecoder classes are used for encoding and decoding URLs.

• The URI class is used for performing URI-based operations.

• The java.sql.DriverManager class and the javax.sql.DataSource interface are used for communicating with a data source.

• Java implements SAX 1 through the javax.xml.parsers package’s abstract SAXParser and SAXParserFactory classes and implements SAX 2 through the org.xml.sax package’s XMLReader interface and through the org.xml.sax.helpers package’s XMLReaderFactory class.

• Java provides the JAX-WS, JAXB, and SAAJ APIs for working with web services.

• The javax.jws package provides these annotation types: HandlerChain, Oneway, WebMethod, WebParam, WebResult, WebService

Effective Java

Effective Java is a book by Dr. Joshua Bloch, Chief Java Architect at Google. The book describes 78 guidelines for effective Java development. This post has some notes from the book. The book itself has much more information as well as helpful examples.

1. Consider static factory methods instead of constructors

One advantage of static factory methods is that, unlike constructors, they have names. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

2. Consider a builder when faced with many constructor parameters

The telescoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.

The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

3. Enforce the singleton property with a private constructor or an enum type

Making a class a singleton can make it difficult to test its clients.

A single-element enum type is the best way to implement a singleton.

4. Enforce noninstantiability with a private constructor

Attempting to enforce noninstantiability by making a class abstract does not work.

5. Avoid creating unnecessary objects

Prefer primitives to boxed primitives and watch out for unintentional autoboxing.

6. Eliminate obsolete object references

Nulling out object references should be the exception rather than the norm.

Whenever a class manages its own memory, the programmer should be alert for memory leaks.

A common source of memory leaks is listeners and other callbacks.

7. Avoid finalizers

Finalizers are unpredictable, often dangerous, and generally unnecessary.

You should never do anything time-critical in a finalizer.

You should never depend on a finalizer to update critical persistent state.

There is a severe performance penalty for using finalizers.

Explicit termination methods are typically used in combination with the try-finally construct to ensure termination.

The finalizer should log a warning if it finds that the resource has not been terminated.

8. Obey the general contract when overriding equals

Don’t override the equals method if any of these conditions apply: Each instance of the class is inherently unique. You don’t care whether the class provides a “logical equality” test. A superclass has already overridden equals and the superclass behavior is appropriate for the class. The class is private or package-private and you are certain that its equals method will never be invoked.

Five requirements of the equals contract: Reflexivity, Symmetry, Transitivity, Consistency, Non-nullity

Once you’ve violated the equals contract, you don’t know how other objects will behave when confronted with your object.

There is no way to extend an instantiable class and add a value component while preserving the equals contract.

Do not write an equals method that depends on unreliable resources.

Advice for a high-quality equals method: Use the == operator to check if the argument is a reference to this object. Use the instanceof operator to check if the argument has the correct type. Cast the argument to the correct type. For each “significant” field in the class be sure to check if that field of the argument matches the corresponding field of this object. When you are finished writing your equals method ask yourself three questions (Is it symmetric? Is it transitive? Is it consistent?).

9. Always override hashCode when you override equals

The key provision that is violated when you fail to override hashCode is that equal objects must have equal hash codes.

Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance.

10. Always override toString

Providing a good toString implementation makes your class much more pleasant to use.

When practical, the toString method should return all of the interesting information contained in the object.

Whether or not you decide to specify the format, you should clearly document your intentions.

Provide programmatic access to all of the information contained in the value returned by toString.

11. Override clone judiciously

If you override the clone method in a nonfinal class, you should return an object obtained by invoking super.clone

In practice, a class that implements Cloneable is expected to provide a properly functioning public clone method.

Never make the client do anything the library can do for the client.

The clone method functions as another constructor. You must ensure that it does no harm to the original object and that it properly established invariants on the clone.

The clone architecture is incompatible with normal use of final fields referring to mutable objects.

A fine approach to object copying is to provide a copy constructor or copy factory.

12. Consider implementing Comparable

13. Minimize the accessibility of classes and members

Make each class or member as inaccessible as possible.

Four possible access levels, listed in order of increasing accessibility: private, package-private, protected, public

Classes with public mutable fields are not thread-safe.

It is wrong for a class to have a public static final array field, or an accessor that returns such a field.

14. In public classes, use accessor methods, not public fields

If a class is accessible outside its package, provide accessor methods.

If a class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields.

15. Minimize mutability

To make a class immutable, follow these five rules: Don’t provide any methods that can modify the object’s state. Ensure that the class can’t be extended. Make all fields final. Make all fields private. Ensure exclusive access to any mutable components.

Immutable objects are inherently thread-safe. They require no syncrhonization.

Immutable objects can be shared freely.

Not only can you share immutable objects, you can also share their internals.

Immutable objects make great building blocks for other objects.

If a class cannot be made immutable, limit its mutability as much as possible.

Make every field final unless there is a compelling reason to make it nonfinal.

16. Favor composition over inheritance

Unlike method invocation, inheritance violates encapsulation

17. Design and document for inheritance or else prohibit it

The class must document its self-use of overridable methods.

A class may have to provide hooks into its internal workings in the form of judiciously chosen protected methods.

The only way to test a class designed for inheritance is to write subclasses.

You must test your class by writing subclasses before you release it.

Constructors must not invoke overridable methods.

Neither clone nor readObject may invoke an overridable method, directly or indirectly.

Designing a class for inheritance places substantial limitations on the class. The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed.

18. Prefer interfaces to abstract classes

Existing classes can be easily retrofitted to implement a new interface.

Interfaces are ideal for defining mixins.

Interfaces allow the construction of nonhierarchical type frameworks.

Interfaces enable safe and powerful functionality enhancements.

You can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.

It is far easier to evolve an abstract class than an interface.

Once an interface is released and widely implemented, it is almost impossible to change.

19. Use interfaces only to define types

The constant interface pattern is a poor use of interfaces.

20. Prefer class hierarchies to tagged classes

Tagged classes are verbose, error-prone, and inefficient.

21. Use function objects to represent strategies

22. Favor static member classes over nonstatic

If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration.

23. Don’t use raw types in new code

If you use raw types, you lose all the safety and expressiveness benefits of generics.

You must use raw types in class literals.

24. Eliminate unchecked warnings

Eliminate every unchecked warning that you can.

If you can’t eliminate a warning, and you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with an @SuppressWarnings(“unchecked”) annotation.

Always use the SuppressWarnings annotation on the smallest scope possible.

Every time you use an @SuppressWarnings(“unchecked”) annotation, add a comment saying why it’s safe to do so.

25. Prefer lists to arrays

26. Favor generic types

27. Favor generic methods

The type parameter list, which declares the type parameter, goes between the method’s modifiers and its return type.

28. Use bounded wildcards to increase API flexibility

For maximum flexibility, use wildcard types on input parameters that represent producers or consumers.

Do not use wildcard types as return types.

If a user of a class has to think about wildcard types, there is probably something wrong with the class’s API.

If a type parameter appears only once in a method declaration, replace it with a wildcard.

29. Consider typesafe heterogeneous containers

30. Use enums instead of int constants

To associate data with enum constants, declare instance fields and write a constructor that takes the data and stores it in the fields.

Switches on enums are good for augmenting external enum types with constant-specific behavior.

31. Use instance fields instead of ordinals

Never derive a value associated with an enum from its ordinal. Store it in an instance field instead.

32. Use EnumSet instead of bit fields

Just because an enumerated type will be use in sets, there is no reason to represent it with bit fields.

33. Use EnumMap instead of ordinal indexing

It is rarely appropriate to use ordinals to index arrays. Use EnumMap instead.

34. Emulate extensible enums with interfaces

While you cannot write an extensible enum type, you can emulate it by writing an interface to go with a basic enum type that implements the interface.

35. Prefer annotations to naming patterns

There is simply no reason to use naming patterns now that we have annotations.

All programmers should use the predefined annotation types used by the Java platform.

36. Consistently use the Override annotation

Use the Override annotation on every method declaration that you believe to override a superclass declaration.

37. Use marker interfaces to define types

Marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not.

If you find yourself writing a marker annotation type whose target is ElementType.TYPE, take the time to figure out whether it really should be an annotation type, or whether a marker interface would be more appropriate.

38. Check parameters for validity

39. Make defensive copies when needed

You must program defensively, with the assumption that clients of your class will do their best to destroy its invariants.

It is essential to make a defensive copy of each mutable parameter to the constructor.

Defensive copies are made before checking the validity of the parameters, and the validity check is performed on the copies rather than on the originals.

Do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.

40. Design method signatures carefully

Choose method names carefully.

Don’t go overboard in providing convenience methods.

Avoid long parameter lists

Long sequences of identically typed parameters are especially harmful.

Prefer two-element enum types to boolean parameters.

41. Use overloading judiciously

The choice of which overloading to invoke is made at compile time.

Selection among overloaded methods is static, while selection among overridden methods is dynamic.

Avoid confusing uses of overloading.

A safe, conservative policy is never to export two overloadings with the same number of parameters.

42. Use varargs judiciously

Don’t retrofit every method that has a final array parameter; use varargs only when a call really operates on a variable-length sequence of values.

43. Return empty arrays or collections, not nulls

There is no reason every to return null from an array- or collection-valued method instead of returning an empty array or collection.

44. Write doc comments for all exposed API elements

To document your API properly, you must precede every exported class, interface, constructor, method, and field declaration with a doc comment.

The doc comment for a method should describe succinctly the contract between the method and its client.

It is no longer necessary to use the HTML <code> or <tt> tags in doc comments. The Javadoc {@code} tag is preferable because it eliminates the need to escape HTML metacharacters.

No two members or constructors in a class or interface should have the same summary description.

When documenting a generic type or method, be sure to document all type parameters.

When documenting an enum type, be sure to document the constants.

When documenting an annotation type, be sure to document any members.

45. Minimize the scope of local variables

The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.

Nearly every local variable declaration should contain an initializer.

Prefer for loops to while loops.

Keep methods small and focused.

46. Prefer for-each loops to traditional for loops.

Three common situations where you can’t use a for-each loop: Filtering, Transforming, Parallel iteration

47. Know and use the libraries

By using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you.

Numerous features are added to the libraries in every major release, and it pays to keep abreast of these additions.

Every programmer should be familiar with the contents of java.lang, java.util, and, to a lesser extent, java.io

48. Avoid float and double if exact answers are required.

The float and double types are particularly ill-suited for monetary calculations.

Use BigDecimal, int, or long for monetary calculations.

49. Prefer primitive types to boxed primitives

Applying the == operator to boxed primitives is almost always wrong.

When you mix primitives and boxed primitives in a single operation, the boxed primitive is autounboxed.

Autoboxing reduces the verbosity, but not the danger of using boxed primitives.

When your program does unboxing, it can throw a NullPointerException.

50. Avoid strings where other types are more appropriate

Strings are poor substitutes for other value types.

Strings are poor substitutes for enum types.

Strings are poor substitutes for aggregate types.

Strings are poor substitutes for capabilities.

51. Beware the performance of string concatenation

Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n.

To achieve acceptable performance, use a StringBuilder in place of a String.

52. Refer to objects by their interfaces

If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.

If you get into the habit of using interfaces as types, your program will be much more flexible.

It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.

53. Prefer interfaces to reflection

Problems with reflection: You lose all the benefits of compile-time type checking. The code required to perform reflective access is clumsy and verbose. Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

You can obtain many of the benefits of reflection while incurring few of its costs by using it only in a very limited form.

Create instances reflectively and access them normally via their interface or superclass.

54. Use native methods judiciously

It is rarely advisable to use native methods for improved performance.

55. Optimize judiciously

Strive to write good programs rather than fast ones.

Strive to avoid design decisions that limit performance.

Consider the performance consequences of your API design decisions.

It is a very bad idea to warp an API to achieve good performance.

Measure performance before and after each attempted optimization.

56. Adhere to generally accepted naming conventions

57. Use exceptions only for exceptional conditions

Exceptions should never be used for ordinary control flow.

A well-designed API must not force its clients to use exceptions for ordinary control flow.

58. Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

Use checked exceptions for conditions from which the caller can reasonably be expected to recover.

Use runtime exceptions to indicate programming errors.

All of the unchecked throwables you implement should subclass RuntimeException.

59. Avoid unnecessary use of checked exceptions

60. Favor the use of standard exceptions

61. Throw exceptions appropriate to the abstraction

Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.

While exception translation is superior to mindless propagation of exceptions from lower layers, it should not be overused.

62. Document all exceptions thrown by each method

Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag.

Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration.

If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment.

63. Include failure-capture information in detail messages

To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception.”

64. Strive for failure atomicity

Generally speaking, a failed method invocation should leave the object in the state that it was in prior to the invocation.

65. Don’t ignore exceptions

An empty catch block defeats the purpose of exceptions.

At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.

66. Synchronize access to shared mutable data

Synchronization is required for reliable communication between threads as well as for mutual exclusion.

Do not use Thread.stop

Synchronization has no effect unless both read and write operations are synchronized.

Confine mutable data to a single thread.

When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization.

67. Avoid excessive synchronization

To avoid liveness and safety failures, never cede control to the client within a synchronized method or block.

As a rule, you should do as little work as possible inside synchronized regions.

68. Prefer executors and tasks to threads

69. Prefer concurrency utilities to wait and notify

Given the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead.

It is impossible to exclude concurrent activity from a concurrent collection; locking it will have no effect.

Use ConcurrentHashMap in preference to Collections.synchronizedMap or Hashtable

For interval timing, always use System.nanoTime in preference to System.currentTimeMillis

Always use the wait loop idiom to invoke the wait method; never invoke it outside of a loop.

There is seldom, if ever, a reason to use wait and notify in new code.

70. Document thread safety

The presence of the synchronized modifier in a method declaration is an implementation detail, not a part of its exported API.

To enable safe concurrent use, a class must clearly document what level of thread safety it supports.

Levels of thread safety: immutable, unconditionally thread-safe, conditionally thread-safe, not thread-safe, thread-hostile

71. Use lazy initialization judiciously

Under most circumstances, normal initialization is preferable to lazy initialization.

If you need to use lazy initialization for performance on a static field, use the lazy initialization holder class idiom.

If you need to use lazy initialization for performance on an instance field, use the double-check idiom.

72. Don’t depend on the thread scheduler

Any program that relies on the thread scheduler for correctness or performance is likely to be nonportable.

Threads should not run if they aren’t doing useful work.

Resist the temptation to “fix” the program by putting in calls to Thread.yield

Thread.yield has no testable semantics.

Thread priorities are among the least portable features of the Java platform.

73. Avoid thread groups

Thread groups are obsolete.

74. Implement Serializable judiciously

A major cost of implementing Serializable is that it decreases the flexibility to change a class’s implementation once it has been released.

A second cost of implementing Serializable is that it increases the likelihood of bugs and security holes.

A third cost of implementing Serializable is that it increases the testing burden associated with releasing a new version of a class.

Implementing the Serializable interface is not a decision to be undertaken lightly.

Classes designed for inheritance should rarely implement Serializable, and interfaces should rarely extend it.

You should consider providing a parameterless constructor on nonserializable classes designed for inheritance.

Inner classes should not implement Serializable.

The default serialized form of an inner class is ill-defined.

75. Consider using a custom serialized form

Do not accept the default serialized form without first considering whether it is appropriate.

The default serialized form is likely to be appropriate if an object’s physical representation is identical to its logical content.

Even if you decide that the default serialized form is appropriate, you often must provide a readObject method to ensure invariants and security.

Using the default serialized form when an object’s physical representation differs substantially from its logical data content has four disadvantages: It permanently ties the exported API to the current internal representation. It can consume excessive space. It can consume excessive time. It can cause stack overflows.

If all instance fields are transient, it is technically permissible to dispense with invoking defaultWriteObject and defaultReadObject, but it is not recommended.

Before deciding to make a field nontransient, convince yourself that its value is part of the logical state of the object.

You must impose any synchronization on object serialization that you would impose on any other method that reads the entire state of the object.

Regardless of what serialized form you choose, declare an explicit serial version UID in every serializable class you write.

76. Write readObject methods defensively

When an object is deserialized, it is critical to defensively copy any field containing an object reference that a client must not possess.

Do not use the writeUnshared and readUnshared methods.

77. For instance control, prefer enum types to readResolve

If you depend on readResolve for instance control, all instance fields with object reference types must be declared transient.

The accessibility of readResolve is significant.

78. Consider serialization proxies instead of serialized instances

Rails 3 in Action

Rails 3 in Action is a book written by Yehuda Katz, former Chief Technologist of Strobe (acquired by Facebook!!!) and Ryan Bigg, a prolific Stack Overflow participant. The book guides the reader through creating a help desk ticketing application throughout the chapters. This post has some notes from the book. The book itself has much more information as well as helpful examples.

• Popular sites that use Rails include Groupon, Twitter, Yellow Pages, Basecamp, and GitHub.

• To generate an application, run the rails command and pass it the new argument and the name of the application you want to generate.

• The scaffold command generates a model, a controller, and views based on the name passed after scaffold.

• Test::Unit is used for test-driven development. RSpec and Cucumber are used for behavior-driven development.

• The Gemfile is used for tracking which gems are used in your application.

• Running bundle install –binstubs at the root of your application tell the Bundler gem to read your Gemfile and install the gems specified in it.

• By default, Rails uses the SQLite3 database system.

• The command rake db:migrate generates a database schema file.

• A RESTful controller has seven actions: index, show, new, create, edit, update, destroy

• All migrations have a change method in them when they are first defined.

• You can combine flash and redirect-to by passing the flash as an option to the redirect_to.

• In Ruby, instance variables that aren’t set return nil as their values.

• The validates_uniqueness_of validator works by checking to see if a record matching the validation criteria exists already. If this record doesn’t exist, the validation will pass.

• The create method is similar to the new method, but it attempts to create an object and then a database record for it rather than just the object.

• The create! method raises an ActiveRecord::RecordInvalid exception if any of the validations fail.

• The factory_girl gem provides ways to use factories to create new objects for your tests.

• The destroy action allows you to delete projects.

• Rails inspects any array passed to helpers, such as redirect_to and link_to and determines what you mean from the values.

• Devise is an authentication gem that provides user management functionality.

• To restrict actions to admin users, you can implement a before_filter that checks not only whether the user is signed in but also whether the user is an admin.

• By default, a find on a model searches all records in the related table, but you can add a scope method to your model to allow you to search on restricted sets of records.

• You can define routes that respond only to POST, PUT, and DELETE requests using the post, put, and delete methods, respectively.

• The CanCan gem provides helper methods (such as the cannot? and can? methods) to use in controllers and views.

• The automatic escaping of strings in Rails 3 stops malicious output being put into forms accidentally.

• For all intents and purposes, has_and_belongs_to_many works like a two-way has_many.

• The Searcher gem provides the functionality of parsing the labels in a query and determines how to go about finding the records that match the query.

• You can use the Rack::Test::Methods module in the rack-test gem to make sure that requests to URLs provided by your application return valid API responses in JSON and XML formats.

• Automatic tools suck as Puppet, Chef, Babushka, and Git Pusshten help with deploying Rails applications.

• Capistrano provides an easy way to configure and deploy versions of an application to one or many servers.

• The cap deploy:migrations command deploys the application.

• OmniAuth integration is available in Devise.

• The Kaminari gem offers pagination capabilities.

• The caches_page method enables page caching.

• With caches_action, you can change the path of where the file is cached by using the cache_path option passed to caches_action.

• To build a basic Rack application, you only need to have an object in Ruby that responds to the call method.

• Sinatra is an exceptionally lightweight Ruby web framework that’s perfect for building small applications, such as those that serve an API.

• You can run the rake middleware command within your Rails application’s directory to see the list of middleware currently in use by your Rails application.

• The ActionDispatch::Static class is responsible for serving static requests in the development environment for your application.

The Rails 3 Way

The Rails 3 Way (2nd edition) is a book by Obie Fernandez, the Ruby on Rails developer known for his important roles in ThoughtWorks, Hashrocket, and RightPay – and his leadership in the Rails community. This post has some notes from the book. The book itself has much more information as well as helpful examples. The last couple hundred pages of the book provide an API reference.

• The current environment can be specified via the environment variable RAILS_ENV

• Bundler is the preferred way to manage your application’s gem dependencies.

• The Ruby-based manifest file named Gemfile is introduced into the root of your Rails project directory and handles gems other than those belonging to Rails itself.

• You can add a :git option to the call to gem to specify a gem by its source repository.

• Every time you modify the Gemfile, or if you introduce dependencies not yet installed, invoke the install command.

• The bundle install command packages up all the gems in the vendor/cache directory.

• Three files involved in setting up the entire Rails stack: boot.rb, application.rb, environment.rb

• Configuration settings are in their own Ruby files in the config/initializers directory.

• The Inflector class transforms strings from singular to plural, class names to table names, modularized class names to ones without, class names to foreign keys, etc.

• Automatic class reloading behavior is governed by the config.cache_classes setting.

• Extensions to Ruby’s NilClass are used to help developers figure out what’s wrong with their code.

• Setting consider_all_requests_local to true causes Rails to display developer-friendly error screens.

• Logger severities: debug, info, warn, error, fatal

• The log folder of your Rails application holds three log files corresponding to each of the standard environments.

• The routing system maps URLs to actions by applying rules that you specify using a special syntax in the config/routes.rb file.

• A route can include one or more hardcoded segment keys, in the form of key/value pairs accessible to controller actions in a hash via the params method.

• The basic way to define a route is to supply a URL pattern plus a controller class/action method mapping string with the special :to parameter.

• The URL pattern string can contain segment keys.

• It’s possible to code a redirect directly into a route definition by using the redirect method.

• You can trigger a branching on respond_to by setting the Accept header in the request.

• Naming a route is done by using the optional :as parameter in a rule.

• The scope method accepts these options: :controller, :path, :as, :constraints

• Typing rake routes lists the routes in Rails projects.

• Routes that deal with a particular resources are singular, whereas routes that deal with collections of related resources are plural.

• Resource routes accept a :shallow option that helps to shorten URLs.

• Like new and create, the edit and update actions go together: edit provides a form, and update processes the form input.

• Rack is a modular interface for handling web requests that has support for many different web servers.

• You can access and manipulate the Rack middleware stack during initialization via config.middleware

• The entry point to a request is an instance of ActionDispatch::Routing::RouteSet

• Partial templates allow you to organize your template code into small files.

• Rendering options include :action, :template, :partial, :inline, :text, :json, :xml, :nothing, :content_type, :layout, :status

• The layout method can accept either a String, Symbol, or boolean, with a hash of arguments after.

• The redirect_to method request a different URL.

• Filters have access to request, response, and all the instance variables set by other filters in the chain or by the action.

• A filter can take one of three forms: method reference, external class, or block

• The Around filter wraps an action, executing code both before and after the action.

• The :only or :except options limit filters to specific actions.

• The before_filter and around_filter methods can halt a request before the body of a controller action method is run.

• Valid parameters to the verify method include :params, :session, :flash, :method, :xhr, :add_flash :add_headers, :redirect_to, :render, :only, :except

• The :text option of the render method optionally accepts a Proc object, which can be used to stream on-the-fly generated data to the browser or control page generation on a fine-grained basis.

• The send_data method includes the options :filename, :type, :disposition, and :status

• The send_file method includes the options :filename, :type, :disposition, :status, :url_based_filename

• The set_table_name and set_primary_key methods let you use any table and primary names you want, but you have to specify them explicitly in your model class.

• Migrations let you define default attribute values by passing a :default option to the column method.

• The class method new creates a new instance of an Active Record model.

• Invoking find with the key of the specific instance you want to retrieve can find an existing object by its primary key.

• The attributes method returns a hash with each attribute and its corresponding value as returned by read_attribute.

• The reload method resets the attributes of an Active Record object.

• The clone method produces a copy of an Active Record object.

• Dynamic finder methods begin with find_by or find_all_by_

• Dynamic scopes operate via method_missing.

• The find_by_sql method takes a SQL select query and returns an array of Active Record objects based on the results.

• The update_all class method of Active Record is useful for updating multiple records at once.

• The destroy method removes an object from the database and prevents you from modifying it again.

• The order method takes one or more symbols (representing column names) or a fragment of SQL, specifying the desired ordering of a result set.

• Connections are created via ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection

• The ActiveRecord::ConnectionAdapters::DatabaseStatements module has useful methods like: begin_db_transaction(), commit_db_transaction(), delete(sql_statement), execute(sql_statement), insert(sql_statement), rollback_db_transaction(), select_all(sql_statement), select_one(sql_statement), select_value(sql_statement), select_values(sql_statement), update(sql_statement)

• Methods available on connection: active?, adapter_name, disconnect!, reconnect!, raw_connection, supports_count_distinct?, supports_migrations?, tables, verify!(timeout)

• Associations typically appear as methods on Active Record model objects.

• Some AssociationCollection methods: all, any?, many?, average, build, calculate, clear, count, create, create!, delete, delete_all, destroy, destroy_all, empty?, find, first, include?,  last, length, maximum, minimum, new, replace, size, sum, uniq

• The belongs_to class method expresses a relationship from one Active Record object to a single associated object for which it has a foreign key attribute.

• Options that can be passed in a hash to the belongs_to method are :autosave, :class_name, :conditions, :counter_cache, :dependent, :foreign_key, :include, :inverse_of, :select, :polymorphic, :primary_key, :readonly, :touch, :validate

•  The has_many association allows you to define a relationship in which one model has many other models that belong to it.

• Options for has_many are :after_add, :after_remove, :as, :autosave, :before_add, :before_remove, :class_name, :conditions, :counter_sql, :dependent, :extend, :finder_sql, :foreign_key, :group, :having, :include, :inverse_of, :limit, :offset, :order, :primary_key, :readonly, :select, :source, :source_type, :table_name, :through, :uniq, :validate

• The has_many :through association lets you specify a one-to-many relationship indirectly via an intermediate join table.

• Options for has_many :through are the same as the options for has_many.

• A one-to-one relationship is declared in Active Record using the has_one and belongs_to methods together.

• Some of the most relevant has_one options are :as, :class_name, :conditions, :dependent, :order

• Methods for the AssociationProxy class: proxy_owner, proxy_reflection, proxy_target, reload, reset

• Declarative validations: validates_acceptance_of, validates_associated, validates_confirmation_of, validates_each, validates_format_of, validates_inclusion_of, validates_exclusion_of, validates_length_of, validates_numericality_of, validates_presence_of, validates_uniqueness_of, validates_with

• Common validation options are :allow_blank, :allow_nil, :if, :unless, :message, :on

• To declare a scope, use the scope class method, passing it a name as a symbol and some sort of query definition.

• Callback hooks available during a save operation: before_validation, before_validation_on_create, after_validation, after_validation_on_create, before_save, before_create, before_update, after_create, after_update, after_save

• Callback hooks available during delete operations: before_destroy, after_destroy

• Callback hooks available during transactions: after_commit, after_commit_on_create, after_commit_on_update, after_commit_on_destroy, after_rollback, after_rollback_on_create, after_rollback_on_update, after_rollback_on_destroy

• Options available to all calculation methods are :conditions, :include, :joins, :order, :group, :select, :distinct

• Calculation method: average, count, maximum, minimum, sum

• The yield keyword is used in making layout and action templates collaborate.

• Standard instance variables: assigns, base_path, controller, cookies, flash

• The ActiveModelHelper module contains helper methods for quickly creating forms from objects that follow Active Model conventions.

• The error_message_on and error_messages_for methods help you add formatted validation error information to your templates in a consistent fashion.

• The FormHelper module provides a set of methods for working with HTML forms.

• Form inputs: check_box, email_field, file_field, hidden_field, label, number_field, password_field, radio_button, range_field, search_field, telephone_field, submit, text_area, text_field

• RecordIdentificationHelper encapsulates naming conventions for dealing with records such as Active Record models or Active Resource models.

• The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.

• The I18n API is involved in internationalizing applications.

• The memcache session storage option lets you use your memcache server as the repository for session data.

• Authlogic is a flexible and unobtrusive authentication framework for Ruby applications.

• Devise is a highly modular Rack-based authentication framework.

• The to_xml method provides easy and automatic XML generation.

• Builder::XmlMarkup is the class used internally by Rails when it needs to generate XML.

• The Action Mailer framework offers support for sending and receiving email.

• Page caching is triggered by use of the caches_page macro-style method in a controller.

• The caches_action method executes controller filters prior to serving the cached HTML file.

• To use fragment caching, use the cache method of Action View, which takes a block and lets you wrap content that should be cached.

• The expire_page and expire_action methods let you explicitly delete content from the cache, so that it is regenerated on the next request.

• Options for cache storage:

ActiveSupport::Cache::FileStore

ActiveSupport::Cache::MemoryStore

ActiveSupport::Cache::MemCacheStore

• Options that can be passed to fetch to provide different types of behavior for different stores are :compress, :expire_in, :force, :race_condition_ttl

• RSpec is a Ruby domain-specific language for specifying the desired behavior of Ruby code.

• RSpec methods: describe, context, let, let!, before, after, it, specify, expect, pending, should, should_not, its, mock, stub, mock_model, stub_model

• RSpec tools: RSpactor, watchr, Spork, Specjour, RCov, Heckle

• To install ruby gems, add them to your Gemfile and run rake bundle.

• Railties are classes that extend from Rails:Railtie and provide hooks into Rails initialization for add-on libraries.

• Delayed Job is a background processing library.

• Resque is a background processing framework that supports multiple queues and is optimized for handling extremely large numbers of jobs efficiently.

Programming iOS 4

Programming iOS 4 is a book by Matt Neuburg. This post has some notes from the book. The book itself has much more information as well as helpful examples.

• The #import command is used for including Apple’s .h files.

• An Objective-C method is defined as part of a class and has three aspects:

1. Whether it’s a class method or an instance method

2. Its parameters and return value

3. Its name

• The declaration for a method has three parts:

1. Either + or -, meaning that the method is a class method or an instance method

2. The data type of the return value, in parentheses

3. The name of the method, split after each colon. Following each colon is the corresponding parameter, expressed as the data type of the parameter, in parentheses, followed by a placeholder name for the parameter.

• Whenever in a method call an object of a certain type is supposed to appear, you can put another method call that returns that type.

• Using the id type causes the compiler to stop worrying about the relationship between object types and messages.

• The term @selector() is a directive to the compiler, telling it that what’s in the parentheses is a message name.

• The purpose of subclassing is not merely so that a class can inherit another class’s methods; it’s so that it can define methods of its own.

• Two main types of items that the @interface section might contain: instance variables and method declarations

• Class methods are useful for two main purposes: factory methods and global utility methods

• You should always call alloc and the initializer in the same line of code.

• Instance methods within a class that call each other constantly do so by sending messages to self.

• The keyword super is used for overriding an inherited method but still being able to access the overridden functionality.

• Key-value coding is a way to translate from a string to an instance variable accessor.

• Navigators in Xcode include: Project navigator, Symbol navigator, Search navigator, Issue navigator, Debug navigator, Breakpoint navigator, Log navigator

• Editing more than one file or seeing multiple views in Xcode can be achieved in three ways: assistants, tabs, and secondary windows

• Never touch anything in a project folder via the Finder. Instead, do all your interaction with the project through the project window in Xcode.

• Three build phases in Xcode: compile sources, link binary with libraries, copy bundle resources

• A scheme unites a target (or multiple targets) to be built with a build configuration.

• The main nib file is designated by the Info.plist key NSMainNibFile

• To use a framework in your code, you must do these two things: import the framework’s header and link to the framework

• By default, three frameworks are linked into your target: Foundation, UIKit, Core Graphics

• Four inspectors that appear only when you’re editing a nib file: Identity inspector, Attributes inspector, Size inspector, Connections inspector

• Two important libraries for when you’re editing a nib: Object library and Media library

• The Localizable.strings file is used for localization.

• The InfoPlist.strings file stores localized versions of Info.plist key values.

• An exception breakpoint causes your app to pause at the time an exception is thrown or caught, without regard to whether the exception would crash your app later.

• A symbolic breakpoint causes your app to pause when a certain method is called, regardless of what object called it or to what object the message is sent.

• Xcode’s version control facilities concentrate on git and Subversion.

• Some important settings in Info.plist: CFBundleVersion, UIStatusBarStyle, UISupportedInterfaceOrientations, UIRequiredDeviceCapabilities

• A category allows you to reach into an existing class and define additional methods.

• NSRange is a struct that has the integers location and length.

• NSString is the Cocoa object version of a string.

• An NSDate is a date and time.

• An NSNumber is an object that wraps a numeric value.

• NSValue is NSNumber’s superclass.

• NSData is a general sequence of bytes and is immutable.

• NSIndexSet expresses a collection of ordered integers.

• An NSArray is an ordered collection of objects and is immutable. NSMutableArray is mutable.

• An NSSet is an unordered collection of distinct objects.

• An NSDictionary is an unordered collection of key-value pairs. The mutable subclass of NSDictionary is NSMutableDictionary.

• NSNull supplies a pointer to a singleton object.

• A property list is a string (XML) representation of data.

• Categories of NSObject methods:

1. Creation, destruction and memory management: alloc, copy, initialize, dealloc

2. Class relationships: class, superclass, isKindOfClass:, isMemberOfClass:

3. Object introspection and comparison: respondsToSelector:, description, isEqual:

4. Message response: doesNotRecognizeSelector:

5. Message sending: performSelector:

• Reasons for events: User events, Lifetime events, Functional events, Query events

• The instance of NSNotificationCenter is the basis of a mechanism for sending notifications.

• Parameters for notifications: addObserver:, selector:, name:, object:

• An NSTimer gives off a signal after the lapse of a certain time interval.

• A built-in Cocoa class has an instance variable, usually called delegate.

• Many Cocoa delegate method names contain the modal verbs should, will, or did.

• An action is a message emitted by an instance of a UIControl subclass to notify you of a significant user event taking place in that control.

• Actions for control events:

UIButton – All “Touch” events

UIDatePicker – Value Changed

UIPageControl – All “Touch” events, Value Changed

UISegmentedControl – Value Changed

UISlider – All “Touch” events, Value Changed

UISwitch – All “Touch” events, Value Changed

UITextField – All “Touch” events except the “Up” events, all “Editing” events

• Typical application lifecycle scenarios:

The app launches freely – Your app delegate receives the messages application:didFinishLaunchingWithOptions: and applicationDidBecomeActive:

The user clicks the Home button – Your app is frontmost, it is suspended, and your app delegate receives the messages applicationWillResignActive: and applicationDidEnterBackground:

The user summons your suspended app to the front – Your app delegate receives the messages applicationWillEnterForeground: and applicationDidBecomeActive:

The user double-clicks the Home button – If your app is frontmost, your app delegate receives the message applicationWillResignActive:

The user, in the app switcher, taps on your app’s window – The app delegate receives the message applicationDidBecomeActive:

The user, in the app switcher, chooses another app – If your app is frontmost, your app delegate receives the message applicationDidEnterBackground:

The screen is locked – If your app is frontmost, your app delegate receives the message applicationWillResignActive:

The screen is unlocked – If your app is frontmost, your app delegate receives the message applicationDidBecomeActive

The user holds the screen-lock button down – If your app is frontmost, your app delegate receives the message applicationWillResignActive:

The user, as the device offers to shut itself down, cancels – If your app is frontmost, your app delegate receives this message – applicationDidBecomeActive:

The user, as the device offers to shut itself down, accepts – If your app is frontmost, your app delegate receives the messages applicationDidEnterBackground: and applicationWillTerminate:

• The way Cocoa derives the name of an accessor from the name of an instance variable is through key-value coding.

• The fundamental key-value coding methods are valueForKey: and setValue:forKey:

• The static analyzer (in Product->Analyze) and Instruments (in Product->Profile) are helpful for debugging memory management mistakes.

• You must never release an object that you have not either retained or obtained via alloc or copy. You must always eventually release an object that you have either retained or obtained via alloc or copy.

• when you send autorelease to an object, that object is placed in the autorelease pool, and a number is incremented saying how many times this object has been placed in the autorelease pool.

• Key-value observing is made up of three stages: registration, change, notification

• The app’s window is an instance of UIWindow.

• A UIView has a superview property and a subviews property.

• A view’s frame property, a CGRect, is the position of its rectangle within its superview, in the superview’s coordinate system.

• Automatic resizing of subviews depends on the superview’s autoresizesSubviews property.

• The superview is sent the layoutSubviews message whenever it is resized.

• A view’s transform property alters how the view is drawn.

• Classes like UIImage and UIImageView are used for displaying images.

• You can use the function UIGraphicsBeginImageContext to create a graphics context suitable for use as an image, then draw into the context, then call UIGraphicsGetImagefromCurrentImageContext, and then UIGraphicsEndImageContext

• A UIView partners with CALayer for animation.

• A layer has a superlayer property and a sublayers property. There are methods addSublayer:, insertSublayer:atIndex:, insertSublayer:below:, insertSublayer:above:, replaceSublayer:with, and removeFromSuperlayer

• A sublayer’s position within its superlayer is defined by its position and its anchorPoint.

• The CAScrollLayer provides methods for moving a layer’s bounds origin as a way of repositioning its sublayers.

• Four methods that can provide or draw a layer’s contents on demand: override display, overridedrawInContext:, implement displayLayer: or drawLayer:inContext: by specifying the CALayer’s delegate property

• Properties for resizing and positioning the contents of a layer: contentsGravity, contentsRect, contentsCenter

• CALayer subclasses that provide self-drawing ability: CATextLayer, CAShapeLayer, CAGradientLayer

• The zPosition property lets you place layers at different depths with respect to other layers.

• A layer can have a shadow, which is defined by its shadowColor, shadowOpacity, shadowRadius, and shadowOffset properties.

• A layer’s presentation layer can be accessed through its presentationLayer property.

• You can animate a UIView directly with these attributes: alpha, backgroundColor, bounds, center, frame, and transform

• The setAnimation UIView class methods are: setAnimationDuration:, setAnimationRepeatAutoreverses:, setAnimationRepeatCount:, setAnimationCurve:, setAnimationStartDate:, setAnimationDelay:, setAnimationDelegate:, setAnimationsEnabled:, setAnimationBeginsFromCurrentState:

• The CATransaction class method setAnimationTimingFunction: takes as its parameter a media timing function (CAMediaTimingFunction).

• CAAnimation properties: animation, delegate, duration, timingFunction, autoreverses, repeatCount, repeatDuration, cumulative, beginTime, timeOffset, speed, fillMode

• CAPropertyAnimation properties: keyPath, additive, valueFunction

• CABasicAnimation properties: fromValue, toValue, byValue

• CAKeyframeAnimation properties: values, timingFunctions, keyTimes, calculationMode, path

• An action is an object that implements runActionForKey:object:arguments:

• Every UIEvent reporting a change in the user’s finger configuration contains one or more UITouch objects.o

• Touch phases described by a UITouch instance’s phase property: UITouchPhaseBegan, UITouchPhaseMoved, UITouchPhaseStationary, UITouchPhaseEnded, UITouchPhaseCancelled

• Four methods inherited by a UIView corresponding to UITouch phases: touchesBegan:withEvent, touchesMoved:withEvent:, touchesEnded:withEvent:, touchesCancelled:withEvent:

• Useful methods and properties of a UITouch: locationInView:, previousLocationInView:, timestamp, tapCount, view, type, timestamp

• A gesture recognizer is a subclass of UIGestureRecognizer and is an object attached to a UIView that has the methods addgestureRecognizer: and removeGestureRecognizer:, and a gestureRecognizers property.

• There are built-in UIGestureRecognizer subclasses for six common gesture types: UITapGestureRecognizer, UIPinchGestureRecognizer, UIRotationGestureRecognizer, UISwipeGestureRecognizer, UIPanGestureRecognizer, UILongPressGestureRecognizer

• View hit-testing uses the UIView instance method hitTest:withEvent:

• A UIBarButtonItem inherits from UIBarItem a title property and an image property.

• A UIScrollView is a view whose contents are larger than its bounds.

• Properties that affect scrolling: scrollEnabled, scrollsToTop, bounces, alwaysBounceVertical, alwaysBounceHorizontal, directionalLockEnabled, decelerationRate, showsHorizontalScrollIndicator, showsVerticalScrollIndicator, indicatorStyle, contentInset, scrollIndicatorInsets

• A table view (UITableView) is a scrolling interface for presenting a single column of rectangular cells (UITableViewCell).

• These methods are used for refreshing table data: reloadData, reloadRowsAtIndexPaths:withRowAnimation:, reloadSections:withRowAnimation:

• To present a popover, you need a UIPopoverController and a view controller.

• Text can be displayed in these ways: UILabel, UITextField, UITextView, UIWebView, Core Graphics, NSString, Core Text

• Controls and other views are: UIActivityIndicatorView, UIProgressView, UIPickerView,  UISearchBar, UIControl, UISwitch, UIPageControl, UIDatePicker, UISlider, UISegmentedControl, UIButton, UINavigationBar, UIToolbar, UITabBar

• UIView subclasses that construct and present modal dialogs: UIAlertView, UIActionSheet

• Audio functions: AudioServicesPlayAlertSound, AudioServicesPlaySystemSound

• Classes supplied by the Media Player framework: MPMoviePlayerController, MPMoviePlayerViewController

• UIImagePickerController is a view controller whose view provide a navigation interface to choose an item from the photo library.

• A map is presented through a UIView subclass, an MKMapView.

• Information about the device’s change in speed and orientation using its accelerometer is provided through the UIEvent and UIAccelerometer classes.

• You can obtain information on a file or directory from an NSFileManager instance.

• A simple HTTP request is made through an NSURLConnection object.

• NSNetService can be used to search for services over Bonjour.

• Undo is provided through an instance of NSUndoManager.