Shared posts

25 Apr 16:03

Professor Encourages His Students to Cheat in Order to Teach Them Game Theory

by John Farrier


Peter Nonacs, professor of biology at UCLA, teaches Game Theory in his Behavioral Ecology course. He told his students that for an upcoming exam, they could do anything that would normally be considered cheating:

A week before the test, I told my class that the Game Theory exam would be insanely hard—far harder than any that had established my rep as a hard prof. But as recompense, for this one time only, students could cheat. They could bring and use anything or anyone they liked, including animal behavior experts. (Richard Dawkins in town? Bring him!) They could surf the Web. They could talk to each other or call friends who’d taken the course before. They could offer me bribes. (I wouldn’t take them, but neither would I report it to the dean.) Only violations of state or federal criminal law such as kidnapping my dog, blackmail, or threats of violence were out of bounds. [...]

Once the shock wore off, they got sophisticated. In discussion section, they speculated, organized, and plotted. What would be the test’s payoff matrix? Would cooperation be rewarded or counter-productive? Would a large group work better, or smaller subgroups with specified tasks? What about “scroungers” who didn’t study but were planning to parasitize everyone else’s hard work? How much reciprocity would be demanded in order to share benefits? Was the test going to play out like a dog-eat-dog Hunger Games? In short, the students spent the entire week living Game Theory. It transformed a class where many did not even speak to each other into a coherent whole focused on a single task—beating their crazy professor’s nefarious scheme.

On the day of the hour-long test they faced a single question: “If evolution through natural selection is a game, what are the players, teams, rules, objectives, and outcomes?”

Most students responded by working together:

One student immediately ran to the chalkboard, and she began to organize the outputs for each question section. The class divided tasks. They debated. They worked on hypotheses. Weak ones were rejected, promising ones were developed. Supportive evidence was added. A schedule was established for writing the consensus answers. (I remained in the room, hoping someone would ask me for my answers, because I had several enigmatic clues to divulge. But nobody thought that far afield!) As the test progressed, the majority (whom I shall call the “Mob”) decided to share one set of answers. Individuals within the Mob took turns writing paragraphs, and they all signed an author sheet to share the common grade. Three out of the 27 students opted out (I’ll call them the “Lone Wolves”). Although the Wolves listened and contributed to discussions, they preferred their individual variants over the Mob’s joint answer.

In the end, the students learned what social insects like ants and termites have known for hundreds of millions of years. To win at some games, cooperation is better than competition. Unity that arises through a diversity of opinion is stronger than any solitary competitor.

But that wasn't the end of of Prof. Nonacs's instruction:

But did the students themselves realize this? To see, I presented the class with one last evil wrinkle two days later, after the test was graded but not yet returned. They had a choice, I said. Option A: They could get the test back and have it count toward their final grade. Option B: I would—sight unseen—shred the entire test. Poof, the grade would disappear as if it had never happened. But Option B meant they would never see their results; they would never know if their answers were correct.

“Oh, my, can we think about this for a couple of days?” they begged. No, I answered. More heated discussion followed. It was soon apparent that everyone had felt good about the process and their overall answers. The students unanimously chose to keep the test. Once again, the unity that arose through a diversity of opinion was right. The shared grade for the Mob was 20 percent higher than the averages on my previous, more normal, midterms. Among the Lone Wolves, one scored higher than the Mob, one about the same, and one scored lower

Link | Photo: Alberto G.

23 Apr 16:25

Calvin and Hobbes for Wednesday, April 17, 2013

by Bill Watterson
22 Apr 16:52

The shodan programmer

by michaelochurch
Edison Gustavo

Maybe this is a good case study for the "Cargos e Salários" stuff on Brazilian software companies.

The belt-color meritocracy

Nothing under the sun is greater than education. By educating one person and sending him into the society of his generation, we make a contribution extending a hundred generations to come.” — Dr. Kano Jigoro, founder of judo.

Colored belts, in martial arts, are a relatively modern tradition, having begun in the late 19th century. It started informally, with the practice in which the teacher (senseiwould wear a black sash in contrast against the white uniform (gi) in order to identify himself. This was later formalized by Dr. Kano with a series of ranks, and by replacing the black sash (in addition to a white belt, holding the gi together) with a black belt. Beginners were assigned descending kyu ranks (traditionally, 6th to 1st) while advanced ranks were dan (from 1st up to 10th). At a dan rank, you earned the right to wear a black belt that would identify you, anywhere in the world, as a qualified teacher of the art. Contrary to popular opinion, a black belt doesn’t mean that you’ve fully mastered the sport. Shodan is taken, roughly, to mean “beginning master”. It means that, after years of work and training, you’ve arrived. There’s still a lot left to learn.

Over time, intermediate belt colors between white and black were introduced. Brown belts began to signify nearness to black-belt level mastery, and green belts signified strong progress. Over time, an upper-division white belt began to be recognized with a yellow belt, while upper-division green belts were recognized with blue or purple. While it’s far from standard, there seems to be a general understanding of belt colors, approximately, as following:

  • White: beginner.
  • Yellow: beginner, upper division.
  • Green: intermediate.
  • Purple: intermediate, upper division.
  • Brown: advanced. Qualified to be senpai, roughly translated as “highly senior student”.
  • Black: expert. Qualified to be sensei, or teacher.

Are these colored belts, and ranks, good for martial arts? There’s a lot of debate about them. Please note that martial arts are truly considered to be arts, in which knowledge and perfection of practice (rather than mere superiority of force) are core values. An 8th dan in judo doesn’t mean you’re the most vicious fighter out there (since you’re usually in your 60s when you get it; you are, while still formidable, probably not winning Olympic competitions) because that’s not the point. These belts qualify you as a teacher, not a fighter only. At that level, knowledge, dedication and service to the community are the guidelines of promotion.

Now, back to our regularly scheduled programming (pun intended)

Would colored belts (perhaps as a pure abstraction) make sense for programming? The idea seems nutty. How could we possibly define a rank system for ourselves as software engineers? I don’t know. I consider myself a 1.8-ish ikkyu (1-kyu; brown belt) at my current level of programmer development. At a typical pace, it takes 4-6 years to go from 1.8 to 2.0 (shodan); I’d like to do it in the next two or three. But we’ll see. Is there a scalable and universally applicable metric for programmer expertise assessment? I don’t know. 

To recap the 0.0-to-3.0 scale that I developed for assessing programmers, let me state the most important points:

  • Level 1 represents additive contributions that produce some front-line business value, while level-2 contributions are multiplicative and infrastructural. Level-3 contributions are global multipliers, or multiplicative over multipliers. Lisps, for example, are languages designed to gift the “mere” programmer with full access to multiplicative power. The Lispier languages are radically powerful, to the point that corporate managers dread them. Level-2 programmers love Lisps and languages like Haskell, however; and level-3 programmers create them.
  • X.0 represents 95% competence (the corporate standard for “manager doesn’t need to worry”) at level X. In other words, a 1.0 programmer will be able to complete 95% of additive tasks laid before him. The going assumption is that reliability is a logistic “S-curve” where a person’s 5% competent on tasks 1.0 levels higher, 50% at 0.5 above, and 95% at-level. So a 1.8 engineer like me is going to be about 85% competent at Level-2 work, meaning that I’d probably do a good job overall but you’d want light supervision (design review, stability analysis) if you were betting a company on my work.
  • 1.0 is the threshold for typical corporate employability, and 2.0 is what we call a “10x programmer”; but the truth is that the actual difference in value creation is highly variable: 20x to 100x on green-field development, 3x to 5x in an accommodating corporate environment such as Google, and almost no gain in a less accommodating one.
  • About 62% of self-described professional software engineers are above 1.0. Only about 1 percent exceed 2.0, which typically requires 10-20 years of high-quality experience. The median is only 1.1, and 1.4 is the 85th percentile.
  • At least in part, the limiting factor that keeps most software engineers mediocre is the extreme rarity of high-quality work experience. Engineers between 1.5 and 1.9 are manager-equivalent in terms of their potential for impact, and 2.0+ are executive-equivalent (they can make or break a company). Unfortunately, our tendency toward multiplicative contribution leads us into direct conflict with “real” managers, who consider multiplicative effects their “turf”.

Programming– like a martial art or the board game Go, both being uncommonly introspective on the measurement of skill ad progress– is a field in which there’s a vast spectrum of skill. 2.0 is a clear candidate for shodan (1st dan). What does shodan mean? It means you’re excellent, and a beginner. You’re a beginner at being excellent. You’re now also, typically, a teacher, but that doesn’t mean you stop learning. In fact, while you can’t formally admit to this too often (lest they get cocky) you often learn as much from your students as they do from you. Multiplicative (level 2) programming contributions are fundamentally about teaching. When you build a Lisp macro or DSL that teaches people how to think properly about (and therefore solve) a problem, you are a teacher. If you don’t see it this way, you just don’t get the point of programming. It’s about instructing computers while teaching humans how the systems work.

In fact, I think there is a rough correlation between the 0.0 to 3.0 programmer competence scale and appropriate dan/kyu ranks, like so:

  • 0.0 to 0.4: 8th kyu. Just getting started. Still needs help over minor compilation errors. Can’t do much without supervision.
  • 0.5 to 0.7: 7th kyu. Understands the fundamental ideas behind programming, but still takes a lot of time to implement them.
  • 0.8 to 0.9: 6th kyu. Reaching “professional-grade” competence but only viable in very junior roles with supervision. Typical for an average CS graduate.
  • 1.0 to 1.1: 5th kyu. Genuine “white belt”. Starting to understand engineering rather than programming alone. Knows about production stability, maintenance, and code quality concerns. Can write 500+ line programs without supervision.
  • 1.2 to 1.3: 4th kyu. Solidly good at additive programming tasks, and can learn whatever is needed to do most jobs, but not yet showing leadership or design sense. Capable but rarely efficient without superior leadership.
  • 1.4 to 1.5: 3rd kyu. Developing a mature understanding of computer science, aesthetics, programming and engineering concerns, and the trade-offs involved in each. May or may not have come into functional programming (whose superiority depends on the domain; it is not, in high-performance domains, yet practical) but has a nuanced opinion on when it is appropriate and when not.
  • 1.6 to 1.7: 2nd kyu. Shows consistent technical leadership. Given light supervision and permission to fail, can make multiplier-level contributions of high quality. An asset to pretty much any engineering organization, except for those that inhibit excellence (e.g. corporate rank cultures that enforce subordinacy and disempower engineers by design).
  • 1.8 to 1.9: 1st kyu. Eminently capable. Spends most of his time on multiplier-type contributions and performs them well. Can be given a role equivalent to VP/Engineering in impact and will do it well.
  • 2.0 to 2.1: 1st dan. She is consistently building high-quality assets and teaching others how to use them. These are transformative software engineers who don’t only make other engineers more productive (simple multiplierism) but actually make them better. Hire one, give her autonomy, and she will “10x” your whole company. Can be given a CTO-equivalent role.
  • 2.2 to 2.3+: Higher dan ranks. Having not attained them, I can’t accurately describe them. I would estimate Rich Hickey as being at least a 2.6 for Clojure, as he built one of the best language communities out there, creating a beautiful language on top of an ugly but important/powerful ecosystem (Java), and for the shockingly high code quality of the product. (If you look into the guts of Clojure, you will forget to hate Java. That’s how good the code is!) However, I’m too far away from these levels (as of now) to have a clear vision of how to define them or what they look like.

Is formal recognition of programmer achievement through formalized ranks and colored belts necessary? Is it a good idea? Should we build up the infrastructure that can genuinely assess whether someone’s a “green belt engineer”, and direct that person toward purple, brown, and black? I used to think that this was a bad idea. Why? Well, to be blunt about it, I fucking hate the shit out of resume culture, and the reason I fucking hate it is that it’s an attempt to collate job titles, prestige of institutions, recommendations from credible people. and dates of employment into a distributed workplace social status that simply has no fucking right to exist. Personally, I don’t lie on my resume. While I have the career of a 26-year-old at almost 30 (thanks to panic disorder, bad startup choices, and a downright evil manager when I was at Google) I feel like I still have more to lose by lying than to gain. So I don’t. But I have no moral qualms about subverting that system and I encourage other people, in dire circumstances, to engage in “creative career repair” without hesitance. Now, job fraud (feigning a competency one does not have) is unacceptable, unethical, and generally considered to be illegal (it is fraud). That’s different, and it’s not what I’m talking about. Social status inflation, such as “playing with dates” to conceal unemployment, or improving a title, or even having a peer pose as manager during a reference check? Fair game, bitches. I basically consider the prestige-title-references-and-dates attempt to create a distributed workplace social status to be morally wrong, extortionate (insofar as it gives the manager to continue to fuck up a subordinate’s life even after they separate) and just plain fucking evil. Subverting it, diluting its credibility, and outright counterfeit in the effort to destroy it; all of these are, for lack of a better word, fucking awesome.

So I am very cynical about anything that might be used to create a distributed social status, because the idea just disgusts me on a visceral level. Ranking programmers (which is inherently subjective, no matter how good we are at the assessment) seems wrong to me. I have a natural aversion to the concept. I also just don’t want to do the work. I’d rather learn to program at a 2.0+ level, and then go off and do it, then spend years trying to figure out how to assess individuals in a scalable and fair way. Yeah, there might be a machine learning problem in there that I could enjoy; but ultimately, the hero who solves that problem is going to be focused mostly on people stuff. Yet, I am starting to think that there is no other alternative than to create an organization-independent ranking system for software engineers. Why? If we don’t rank ourselves in a smart way, then business assholes will step in and rank us anyway, and they’ll do a far shittier job of it. We know this to be true. We can’t deny it. We see it in corporate jobs on a daily basis.

A typical businessman can’t tell the difference between a 2.0 engineer and a 1.2 who’s great at selling his ideas. We tend to be angry at managers over this fact, and over the matter of what is supposed to be a meritocracy (the software industry) being one of the most politicized professional environments on earth; but when we denigrate them for their inability to understand what we do, we’re the ones being assholes. They police and measure us because we can’t police and measure ourselves.

So this may be a problem that we just need to solve. How does one get a black belt in programming? Most professional accreditations are based on churning out commodity professionals. We can’t take that approach, because under the best conditions it takes a decade to become a black belt/2.0+, and some people don’t even have the talent. This is a very hard problem, and I’m going to punt on it for now.

Brawlers and Expert Experts

Let’s peer, for a little while, into why Corporate Programming sucks so much. As far as I’m concerned, there are two categories of degeneracy that merit special attention: Brawlers and Expert Experts.

First I will focus on the Brawlers (also known as “rock stars” or “ninjas”). They write hideous code, and they brag about their long hours and their ability to program fast. There’s no art in what they do. They have only a superficial comprehension of the craft. They can’t be bothered to teach others what they are doing, and don’t have enough insight that would make them passable at it anyway. What they bring is a superhuman dedication to showing off, slogging through painful tasks, and kludging their way to something that works just enough to support a demo. They have no patience for the martial art of programming, and fight using brute strength.

Brawlers tend, in fact, to be a cut above the typical “5:01″ corporate programmers. Combine that with their evident will to be alpha males and you get something that looks like a great programmer to the stereotypical business douche. Brawlers tend to burn themselves out by 30, they’re almost always men, and they share the “deadlines is deadlines” mentality of over-eager 22-year-old investment banking “analysts”. There is no art in what they do, and what they build is brittle, but they can do it fast and they’re impressive to people who don’t understand programming.

Let’s think of corporate competition as a fight that lasts for five seconds, because power destroys a person’s attention span and most executives are like toddlers in that regard. In a three-minute fight, the judoka would defeat the brawler; but, in a 5-second fight, the brawler just looks more impressive. He’s going all out, posturing and spitting and throwing feint punches while the judoka seems passive and conservative with his energy (because he is conserving it, until the brawler makes a mistake, which won’t take long). A good brawler can demolish an untrained fighter in 5 seconds, but the judoka will hold his own for much longer, and the brawler will tire out.

With the beanbag coming in after 5 seconds, no one really lands a blow, as the judoka has avoided getting hit but the brawler hasn’t given enough of an opening for the judoka to execute a throw. Without a conclusive win or loss, victory is assessed by the people in chairs. However, the judges (businessmen, not programmers) don’t have a clue what the fuck they just watched, so they award the match to the brawler who “threw some really good punches” even though he failed to connect and would have been thrown to the ground had the fight lasted 5 seconds more.

Where are Brawlers on the engineer competence scale? It’s hard to say. In terms of exposure and knowledge they can be higher, but they tend to put so much of their energy and time into fights for dominance that the quality of their work is quite low: 1.0 at best. In terms of impressions, though, they seem to be “smart and gets things done” to their superiors. Managers tend to like Brawlers because of their brute-force dedication and unyielding willingness to shift blame, take credit, and kiss ass. Ultimately, the Brawler is the one who no longer wishes to be a programmer and wants to become more like an old-style “do as I say” manager who uses intimidation and extortion to get what he wants.

Brawlers are a real problem in VC-istan. If you don’t have a genuine 1.5+ engineer running your technical organization, they will often end up with all the power. The good news about these bastards (Brawlers) is that they burn themselves out. Unless they can rapidly cross the Effort Thermocline (the point at which jobs become easier and less accountable with increasing rank) by age 30, they lose the ability to put a coherent sentence together, and they just aren’t as good at fighting as they were in their prime.

The second category of toxicity is more long-lived. These are the people called Expert Beginners by Erik Dietrich, but I prefer to call them Expert Experts (“beginner” has too many positive and virtuous connotations, if one either takes a Zen approach, or notes that shodan means “beginner”). No, they’re not actual experts on anything aside from the social role of being an Expert. That’s part of the problem. Mediocrity wants to be something– an expert, a manager, a credible person. Excellence wants to do things– to create, to build, and to improve running operations.

The colored-belt metaphor doesn’t apply well to Brawlers, because even a 1.1 white belt could defeat a Brawler (in terms of doing superior work) were it not for the incompetence of the judges (non-technical businessmen) and the short duration of the fight. That’s more of an issue of attitude than capability, I’ve met some VC-istani Brawlers who would be capable of programming at a 1.4 level if they had the patience and actually cared about the quality of their work. It’s unclear what belt color applies; what is more clear is that they take their belts off because they don’t care.

Expert Experts, however, have a distinct level of competence that they reach, and rarely surpass, and it’s right around the 1.2 level: good enough to retain employment in software, not yet good enough to jeopardize it. They’re career yellow belts at 1.2-1.3. See, the 1.4-1.5 green belts have started exposing themselves to hard-to-master concepts like functional programming, concurrency and parallelism, code maintainability, and machine learning. These are hard; you can be 2.0+ and you’ll still have to do a lot of work to get any good at them. So, the green belts and higher tend to know how little they know. White belts similarly know that they’re beginners, but corporate programming tends to create an environment where yellow belts can perceive themselves to be masters of the craft.

Of course, there’s nothing wrong with being a yellow belt. I was a novice, then a white belt, then yellow and then green, at some point. (I hadn’t invented this metaphor yet, but you know what I mean.) The problem is when people get that yellow belt and assume they’re done. They start calling themselves expert early on and stop learning or questioning themselves; so after a 20-year career, have 18 years of experience in Being Experts! Worse yet, career yellow belts are so resistant to change that they never get new yellow belts, and time is not flattering to bright colors, so their belts tend to get a bit worn and dirty. Soot accumulates and they mistake it (as their non-technical superiors do, too) as a merit badge. “See! It’s dark-gray in spots! This must be what people mean when they talk about black belts!”

There’s a certain environment that fosters Expert Experts. People tend toward polarization of opinion surrounding IDEs but the truth is that they’re just tools. IDEs don’t kill code; people kill code. The evil is Corporate Programming. It’s not Java or .NET, but what I once called “Java Shop Politics“, and if I were to write essay now, I’d call it something else, since the evil is large, monolithic software and not a specific programming language. Effectively, it’s what happens when managers get together and decide that (a) programmers can’t be trusted with multiplicative work, so the goal becomes to build a corporate environment tailored toward mediocre adders (1.0 to 1.3) but with no use for superior skill, and (b) because there’s no use for 1.4+, green-belt and higher, levels of competence, it is useless to train people up to it; in fact, those who show it risk rejection because they are foreign. (Corporate environments don’t intentionally reject 1.4+ engineers, of course, but those tend to be the first targets of Brawlers.) It becomes a world in which software projects are large and staffed by gigantic teams of mediocre developers taking direct orders with low autonomy. It generates sloppy spaghetti code that would be unaffordable in its time cost were it not for the fact that no one is expected, by that point, to get anything done anyway.

Ultimately, someone still has to make architectural decisions, and that’s where the Expert Experts come in. The typical corporate environment is so stifling that 1.4+ engineers leave before they can accumulate the credibility and seniority that would enable them to make decisions. This leaves the Expert Experts to reign over the white-belted novices. “See this yellow belt? This means that I am the architect! I’ve got brown-gray ketchup stains on this thing that are older than you!”

Connecting the Dots

It goes without saying that there are very few shodan-level programmers. I’d be surprised if there are more than 15,000 of them in the United States. Why? What makes advancement to that level so rare? Don’t get me wrong: it takes a lot of talent, but it doesn’t take so much talent as to exclude 99.995% of the population. Partly, it’s the scarcity of high-quality work. In our War on Stupid against the mediocrity of corporate programming, we often find that Stupid has taken a lot of territory. When Stupid wins, multiplicative engineering contributions become impossible, which means that everyone is siloized into get-it-done commodity work explicitly blessed by management, and everything else gets thrown out.

Brawlers, in their own toxic way, rebel against this mediocrity, because they recognize it as a losing arrangement they don’t want; if they continue as average programmers in such an environment, they’ll have mediocre compensation and social status. They want to be alpha males. (They’re almost always men.) Unfortunately, they combat it by taking an approach that involves externalized costs that are catastrophic in the long term. Yes, they work 90 hours per week and generate lots of code, and they quickly convince their bosses that they’re “indispensable”. Superficially, they seem to be outperforming their rivals– even the 1.4+ engineers who are taking their time to do things right.

Unfortunately, Brawlers tend to be the best programmers when it comes to corporate competition, even though their work is shitty. They’re usually promoted away from the externalized costs induced by their own sloppy practices could catch up with them. Over time, they get more and more architectural and multiplier-level responsibilities (at which they fail) and, at some point, they make the leap into real management, about which they complain-brag (“I don’t get to write any code anymore; I’m always in meetings with investors!”) while they secretly prefer it that way. The nice thing, for these sociopaths, about technology’s opacity in quality is that it brings the Effort Thermocline to be quite low in the people-management tier.

Managers in a large company, however, end up dealing with the legacy of the Brawlers and, even though blame has been shifted away from those who deserve it, they get a sense that engineers have “too much freedom”. It’s not sloppy practices that damaged the infrastructure; it’s engineer freedom in the abstract that did it. Alien technologies (often superior to corporate best practices) often get smeared, and so do branch offices. “The Boston office just had to go and fucking use Clojure. Does that even have IDE support?”

This is where Expert Experts come in. Unlike Brawlers, they aren’t inherently contemptible people– most Expert Experts are good people weakened by corporate mediocrity– but they’re expert at being mediocre. They’ve been yellow belts for decades and just know that green-belt levels of achievement aren’t possible. They’re professional naysayers. They’re actually pretty effective at defusing Brawlers, and that’s the scary bit. Their principled mediocrity and obstructionism (“I am the expert here, and I say it can’t be done”) actually serves a purpose!

Both Brawlers and Expert Experts are an attempt at managerial arrogation over a field (computer programming) that is utterly opaque to non-technical managers. Brawlers are the tough-culture variety who attempt to establish themselves as top performers by externalizing costs to the future and “the maintenance team” (which they intend never to be on). Expert Experts are their rank-culture counterparts who dress their mediocrity and lack of curiosity up as principled risk-aversion. So, we now understand how they differ and what their connection is.

Solve It!

I did not intend to do so when I started this essay, in which I only wanted to focus on programming, but I’ve actually come upon (at least) a better name for the solution to the MacLeod Organizational Problem: shodan culture. It involves the best of the guild and self-executive cultures. Soon, I’ll get to exactly what that means, and how it should work.

19 Apr 18:34

Arte no quadro negro

by Joe

Uma infância inteira desenhando pênises e tetinhas no quadro. Eu era um gênio.

18 Apr 12:01


by momo

Um curta sobre um pai prestes a se tornar zumbi e seu objetivo de manter sua filha bebê  a salvo.

São 7 minutos sem diálogo e é simplesmente animal.

17 Apr 21:19

CodeSOD: Nine Ways to Tuesday

by snoofle
Edison Gustavo

Java feelings

Devan L. was playing with his young daughter, when she asked him if he knew all of the days of the week. He replied: Sunday, Monday, Frogday, Flubberday, ...

She quickly admonished him for being silly. He told her that he was a very busy man and that there were too many days to remember. They laughed.

Then he went to work and encountered the date utility library code below.

Now he wants to cry.

    //This doesn't roll across month boundaries correctly
    //public Date getTuesdayInWeek(Date in) {
    //    GregorianCalendar gc = new GregorianCalendar();
    //    gc.setTime(in);
    //    gc.add(Calendar.DATE,  Calendar.TUESDAY - gc.get(Calendar.DAY_OF_WEEK));
    //    return gc.getTime();

    public Date getSundayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.SUNDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    public Date getMondayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.MONDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    // Not sure if this will work for leap years
    public Date getTuesdayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.TUESDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    public Date getWednesdayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.WEDNESDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    public Date getThursdayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.THURSDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    public Date getFridayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.FRIDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    public Date getSaturdayInWeek(Date in) {
        GregorianCalendar gc = new GregorianCalendar();
        return new Date(in.getTime() + (Calendar.SATURDAY - gc.get(Calendar.DAY_OF_WEEK))*24*3600*1000);

    public Date getDateInWeek(Date in, int desiredDay) {
        switch (desiredDay) {
            case Calendar.SUNDAY:    return getSundayInWeek(in);
            case Calendar.MONDAY:    return getMondayInWeek(in);
            case Calendar.TUESDAY:   return getTuesdayInWeek(in);
            case Calendar.WEDNESDAY: return getWednesdayInWeek(in);
            case Calendar.THURSDAY:  return getThursdayInWeek(in);
            case Calendar.FRIDAY:    return getFridayInWeek(in);
            case Calendar.SATURDAY:  return getSaturdayInWeek(in);
            default: throw new IllegalArgumentException("unknown desired day: "+desiredDay);

    public Date getReleaseDateInWeek(Date in) {
        return getDateInWeek(in, Calendar.TUESDAY);
[Advertisement] Make your team a DevOps team with BuildMaster. Pairing an easy-to-use web UI with a free base platform, BuildMaster gets you started in minutes. See how and others use BuildMaster to automate their software delivery.
17 Apr 21:18

Qual é a mensagem?

by ProgramadorREAL

Qual é a mensagem?

real historia;
string sender;
sender = "Renan Giacomin";

Usuário: Está dando uma mensagem de erro em inglês toda vez que tento entrar no sistema…
Programador: Certo, e qual é a mensagem?
Usuário: É assim: “Não sei o quê, não sei o que lá, não sei o que lá mais”
Programador: PLOFT!

Camiseta: Tenho que sair logo da Matrix
17 Apr 21:02

Usuários do Reddit e 4chan conduzem impressionante investigação paralela do atentado em Boston

by Ronaldo Gogoni


O atentado ocorrido durante a Maratona de Boston na última segunda-feira, em que duas bombas explodiram próximas à linha de chegada fazendo três vítimas fatais (entre elas uma menina de apenas oito anos de idade), se tornou a maior investigação coletiva da história. Sabendo o poder que os indivíduos tem nas mãos, onde todo mundo anda com uma câmera no bolso, o FBI solicitou a cooperação da população, para que enviassem quaisquer fotos ou vídeos que pudessem ajudar a identificar os prováveis suspeitos.

Porém uma turma resolveu ir além: usuários do Reddit e do 4chan estão conduzindo uma investigação paralela massiva, e com a ajuda de muita gente, chegaram a até mesmo isolar vários suspeitos.

Um usuário do Reddit conhecido apenas como Oops777 abriu um tópico chamado “Find Boston Bombers“, e os usuários começaram a compartilhar diversas fotos, onde comparam não só os restos das mochilas com pessoas as usando momentos antes da explosão, como até mesmo o comportamento dos suspeitos. As fotos estão sendo compartilhadas pelo Flickr e exibidas tanto no 4chan quanto no Reddit e diversos Tumblrs.

Na foto que abre o post, por exemplo, dois suspeitos carregam mochilas bastante similares a que foram coletadas pela polícia.

Nesta outra, note que esse outro suspeito está com uma mochila num momento, e aparentemente sem ela noutro (apaguei o rosto do cara porque né, não há provas concretas). Note também que ele não está prestando atenção à corrida:


Sobre essa mesma foto, note o formato estranho do conteúdo da mochila, que corrobora a teoria das bombas terem sido feitas de panelas de pressão cheias de pólvora, pregos e rolamentos:


Veja o comportamento desse outro suspeito:


Tal situação é uma faca de dois legumes, diria Vicente Matheus: é importante ver que a internet tem o poder para ajudar de verdade quando se é necessário, mas por outro lado esse tipo de vigilantismo é polêmico. As fotos estão sendo divulgadas sem nenhuma distorção do rosto das pessoas, que podem ou não ser os responsáveis. Um usuário lembrou do caso de Richard Jewell, um policial que evitou um atentado a bomba em Atlanta durante as Olimpíadas de 1996, ao encontrar uma bomba e alertar as autoridades. Foi considerado suspeito e, apesar de nunca ter sido indiciado, foi sumariamente condenado pela mídia, o que acabou com sua vida pessoal. Ele passou os anos seguintes processando os canais midiáticos que nunca se retrataram, apesar do real culpado ter sido identificado posteriormente.

Em 2006 o então governador do estado da Geórgia o agradeceu pelos serviços prestados, mas esse reconhecimento veio tarde: com a saúde debilitada e sofrendo de problemas no coração e pulmão além de diabetes, Jewell faleceu no ano seguinte, aos 44 anos.

O usuário Oops777 avisa que todas as informações são repassadas para o FBI, mas eu acredito que deveria haver mais cuidado ao tornar essas imagens públicas; não dá para ter certeza quem tem culpa no cartório e quem não tem, é melhor deixar isso com quem entende do assunto. Mas toda ajuda é bem vinda.

Fonte: The Atlantic.

16 Apr 19:17

The History Of Westeros As Told By The "Game Of Thrones" Opening Credits

The Emmy Award-winning intro is even cooler than you thought.

You know that astrolabe that surrounds the Westerosi sun?

You know that astrolabe that surrounds the Westerosi sun?

Pictured: that astrolabe that surrounds the Westerosi sun.


Those rotating bands depict major events from the history of the Seven Kingdoms

Those rotating bands depict major events from the history of the Seven Kingdoms

An early artist's conception of the astrolabe.


First, the Targaryen dragon attacks some cities and towns.

First, the Targaryen dragon attacks some cities and towns.

House Targaryen conquered Westeros three hundred years before the first episode of Game of Thrones takes place. The dragons they brought with them from their ancient homeland helped Aegon the Conqueror forge the Iron Throne from the swords of the lords they conquered. For three centuries, those dragons kept the Seven Kingdoms under Targaryen rule -- and then the dragons died out.

The Stark wolf, Lannister lion, and Baratheon stag then defeat the Targaryen dragon together during Robert's Rebellion.

The Stark wolf, Lannister lion, and Baratheon stag then defeat the Targaryen dragon together during Robert's Rebellion.

Two decades before the first episode takes place, a Targaryen prince kidnaps Lyanna Stark, the fiancée of Robert Baratheon and sister of Eddard Stark. After Eddard's father and brother are murdered by the Mad King Aerys while petitioning for her release, the Starks and the Baratheons rise up in rebellion against the Iron Throne. House Lannister joins the rebels late in the war, sacking King's Landing and killing the last Targaryen king and his family.

View Entire List ›

16 Apr 15:46

Comic for April 16, 2013

16 Apr 03:33

Rindo sem sorrir

by Joe

Imagina esse cara numa aula super séria rindo que nem uma vadia retardada e o professor nunca descobre quem é.

16 Apr 03:29

Outro dia, outra máquina incrível em Lego

by Carlos Cardoso


O Lego Mindstorms é uma linha de kits fantásticos que permitem que você monte robôs, carros, máquinas programáveis, impressoras 3D (sério) e muito mais. Valem cada centavo. São um exercício excelente para a criatividade, e não me envergonho de me declarar incapaz sequer de entender como algumas das máquinas que esses malucos inventam funcionam.

São uma prova de que a engenharia mecânica está longe de ser uma disciplina estagnada. Que o diga essa traquitana acima, criada por um japonês (claro) com um único motor, capaz de selecionar e classificar 10 tipos diferentes de barrinhas de prástico.

Para quê serve isso? Desculpe, se você precisa perguntar, significa que não entendeu.

Veja funcionando:

09 Apr 18:19

Da série: lógica nos videogames

by Joe


E você aí levando fora até de boneca inflável…

09 Apr 18:11


08 Apr 12:57

Não aparece a logo

by ProgramadorREAL

Não aparece a logo

real historia;
string sender;
sender = "Gustavo Atilla";

Programador: Olha, a logo foi solicitada na instalação, mas ninguém a forneceu. Me mande ela por e-mail que eu a cadastro no sistema…
Usuário: Tudo bem, então. Assim que eu confeccionar a logo eu lhe envio.
Programador: KABOOM!

Camiseta: A pressa é a mãe do precipício (Leminski)
08 Apr 12:52

Eye-Popping Photographs of Hong Kong High-Rise Apartment Buildings

by Michael Zhang

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings 4c21DQq

With a population of over 7 million people packed into an area of 426 square miles, Hong Kong is one of the most densely populated places in the world. As with other places where development cannot expand horizontally, apartment buildings tend to get taller and taller in order to provide living space for all the inhabitants.

German photographer Michael Wolf decided to capture this population density through a series of photographs studying the architecture of these high rises. The project is titled “Architecture of Density.”

The photographs offer a closeup view, turning the buildings into mesmerizing patterns of edges, windows, balconies, and air conditioning systems. In most of the photographs, the buildings completely fill up the frame, and the repetition is disorienting.

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings Uym9KcU

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings MnmliPS

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings YPSewBK

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings UAVy4ik

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings 9AdeFzv

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings G8B9xDi

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings z8ODJqg

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings gtLD7LS

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings iTnsGFs

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings PVurbMA

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings WUh4eUh

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings Nefbjbt

Eye Popping Photographs of Hong Kong High Rise Apartment Buildings vVYB4Oj

The photographs have been published as a hardcover book. Here’s what the description says:

Stunning and sobering, the photographs of high-rise apartment buildings in Hong Kong by German photographer Michael Wolf reveal his personal fascination with life in mega-cities. Having lived there for several years, Wolf began to document Hong Kongs extreme development and complex urban dynamics, and how these factors play into the relationships between public and private space, anonymity and individuality, in one of the most densely populated cities on the planet. His close-up view takes the repetitive facades and colourful palettes out of their architectural context, instead offering urban patterns.

You can find more photographs from this series (and larger versions of these) over on Wolf’s website.

Thanks for sending in the tip, Nienke!

Image credits: Photographs by Michael Wolf and used with permission

06 Apr 23:00

Pesquisadores descobrem como extrair hidrogênio de plantas; método pode reduzir custo de combustíveis

by Ronaldo Gogoni

Yi-Heng Percival Zhang

Uma boa notícia: pesquisadores da Virginia Tech (esse pessoal está com tudo) anunciou ontem que descobriu um método para extrair hidrogênio em grandes quantidades, o que pode ser de grande impacto na produção de combustíveis renováveis. A fonte? Plantas.

O professor de engenharia de sistemas biológicos Yi-Heng Percival Zhang foi quem trouxe a novidade. Ele e sua equipe fizeram um experimento utilizando xilose, um monossacarídeo presente nas plantas, obtendo quantidades enormes de hidrogênio no proceso. Melhor: o método pode ser empregado em qualquer tipo de biomassa.

Melhor ainda: diferente de outros métodos para produção de hidrogênio, a técnica do prof. Zhang não requer uso metais pesados e quase não emite gases do Efeito Estufa na atmosfera.

O Departamento de Energia Norte Americano acredita que o uso do hidrogênio como combustível pode modificar drasticamente o cenário atual de dependência de combustíveis fósseis, além de jogar o preço de produção lá embaixo, já que a xilose é apenas o segundo açúcar mais abundante nas plantas.

Claro, a humanidade ainda vai depender de combustíveis fósseis por muito tempo. Apesar de uma projeção de que o petróleo do mundo só dura mais 40 anos, isso se refere apenas ao que pode ser explorado atualmente. Se formos adicionar as reservas totais de petróleo e pré-sal as quais não temos acesso com o estado atual de nossa tecnologia (mas que não está parada; o Brasil por exemplo é o país com a melhor tecnologia de prospecção em altas profundidades do mundo), nós temos o suficiente para séculos.

Outro problema é que fontes alternativas sempre esbarram no lance de fazer mais com menos. Por exemplo: a gasolina possui uma densidade de energia por massa de 46,9 MJ/kg, ao passo que uma bateria de lítio convencional tem uma densidade entre 0,54 e 0,72 MJ/kg. Trocando em miúdos, 1 kg de gasolina tem quase o mesmo valor energético de uma bateria de celular de 50 kg (hipoteticamente falando).

Uma boa alternativa é o hidrogênio, que possui densidade maior e só deixa um resíduo após a queima: água. E agora que descobriram como produzí-lo em larga escala, resta esperar coisas boas a caminho.

Fonte: VT News via Engadget.

03 Apr 17:48

Da necessidade de canais incomuns para escape de frustração em situações de irritação repetitiva

by joão baldi jr.


Daí que você tem um problema. Não é um problema novo, não é um problema grande, não é um problema dramático, não é um problema inédito, é apenas um problema. Ele já vem de algum tempo, ele já vem consumindo algum esforço, ele já foi comunicado a todas as pessoas com quem você tem contato o bastante para comentar sobre algum problema seu. Com algumas você abordou o problema de forma vaga (“ah, sei como é, também tenho esse problema”), com outros de forma pormenorizada (“então, e por causa disso, disso e disso, isso é um problema, me deixa trazer o retroprojetor, eu fiz umas lâminas”), mas nesse meio tempo o problema persistiu, não foi resolvido, e a duração dele não fez diminuir o seu nível de contrariedade em relação ao problema. Na verdade ele apenas vem aumentando.

E você quer falar sobre ele com sua namorada o tempo todo. Na verdade você tem a impressão de que fala sobre ele com a sua namorada o tempo todo. Mas isso te parece chato, te parece cansativo, e não parece justo com ela. Afinal, quando vocês se conheceram era tudo all fun and games e spray de chantilly e agora você fica nessa de só falar de problemas? Então você tenta evitar. Não acha que consiga, não acha que esteja dando certo, mas se sente um pouco aliviado de pensar que não está falando do problema sempre que está pensando no problema. O que é bom, já que você está sempre pensando no problema.

E você quer falar com sua família sobre o problema. Mas sabe como são famílias. Pra sua mãe todo problema é um grande problema, e ainda mais sendo o seu problema, se trata de um imenso problema. Se você continuar falando com ela sobre o problema ela não vai conseguir falar com você sobre nada além do problema e por mais que você efetivamente não ande pensando em nada além do problema, você gosta de ideia de que, ao menos quando falar com a sua mãe, não vai precisar pensar no problema. Ainda que você vá pensar no problema. Com seu irmão você não fala sobre o problema porque ele te recomendaria malhar e bater no problema, e você não apenas não quer malhar como não acha que violência seja a solução pro problema. Ao menos não por enquanto.

E você tenta se controlar em relação aos seus amigos também, claro. Não que funcione muito bem também, claro. Mas você não quer ser o cara que enquanto todos estão falando de atividades interessantes e divertidas fica falando apenas sobre o próprio problema. Férias em Aruba? Eu tenho um problema. Festinha no sábado. Então, tem meu problema. Estamos pensando em adotar uma criança. Espero que ela nunca tenha o meu problema, porque é um grande problema. Meu problema. Então você tenta evitar falar sobre o seu problema, mas tudo que te passa pela cabeça é o seu problema e no seu íntimo você acha que todos estão sendo meio insensíveis de não levar mais a sério o seu problema, já que ele é o seu problema. Ainda mais porque as lâminas já estavam prontas e o retroprojetor não se carregou sozinho.

E é assim que, num dia normal, você, no tempo que demora pro sinal da maquininha do visa pegar, apenas por falta de qualquer outra válvula de escape, já que tem a sensação de que já encheu sua namorada, sua família, seus amigos e todo mundo mais que você conhece, resolve falar sobre o seu problema pro entregador de pizza. E como o sinal é realmente péssimo, você tem tempo pra falar dos detalhes, contar as nuances, comentar suas aflições e, enquanto finalmente espera o “processando” sair da tela, você ouve uma frase que, ainda que dita no tom mais desinteressado do mundo, te ensina uma valiosa lição sobre as proporções de sofrimento, a relatividade da dor e o empirismo da realidade. “Bem, mas pelo menos você não precisa trabalhar de sábado, final de semana, né, fera? Tem que ver isso aí também”.

Filed under: é como as coisas são, Desocupações, Rio, Sem Categoria, Vida Pessoal, vida profissional Tagged: aí não, aí sim, abrindo o coração, amigos, aprendendo com delivery, é a vida, compartilhamento de informações, diluindo reclamações, dramas da vida real, entregas, máquina do visa, mundo sem sentido, pelo menos eu não trabalho no final de semana e fico sempre grato por isso, pessoas, pizza, problemas, retroprojetor, tem que refletir, teorias, Vida Pessoal
03 Apr 14:38

Obama lança plano para mapear o cérebro humano

by Ronaldo Gogoni

Dependendo do voluntário, é facinho...

Barack Obama veio hoje com um plano ousado. Em comunicado oficial da Casa Branca, o presidente mais legal que os States já tiveram depois do Clinton (hey, a gente se divertiu com a escapada dele) lançou uma iniciativa para desenvolver as ferramentas necessárias para agilizar o mapeamento do cérebro humano, em busca de principalmente providenciar pesquisas em busca de tratamentos mais eficazes – e quem sabe a cura – de doenças graves como a epilepsia e o Mal de Alzheimer. O projeto vai custar a princípio 100 milhões de dólares (troco de pinga tendo em vista o benefício que virá) e recebeu o nome de Brain Research through Advancing Innovative Neurotechnologies ou, simplificando, BRAIN.

É isso aí, um acrônimo recursivo. :)

Através do esforço conjunto, cientistas tentarão completar em alguns anos o mapeamento de todos os neurônios do cérebro. A grandeza do anúncio e pesquisadores envolvidos fizeram a mídia se referir ao BRAIN como o “Projeto Genoma do cérebro”, alusão ao programa realizado nos anos 90 em prol de mapear todo o DNA humano.

Segundo Obama, nomeado cientista-chefe do projeto (apesar de suas notas fracas em física, segundo o próprio), “o computador mais poderoso do mundo não é tão intuitivo quanto o que temos desde que nascemos”.

A iniciativa é louvável, mas devemos lembrar que o cérebro nem de longe é um computadorzinho perfeitinho, na verdade é a maior gambiarra evolutiva que se tem notícia. Ele tem a terrível tendência de ver e ouvir coisas que não existem ou apagar o que não lhe interessa, além de forçar uma percepção errada das coisas. Duvida?

Vi esse no (abraço, André! :))

Entenderam o ocorrido? Devido à forma como evoluímos o cérebro humano possui uma compulsão louca por reconhecer rostos; ele simplesmente IGNORA o que os olhos veem e converte o baixo em alto relevo, pois para ele, faces precisam ser tridimensionalmente positivas. E agora eu deixei você com um curto na sua cachola, entre o que você sabe que está errado e o que o cérebro interpreta como válido!

Eu realmente espero que o projeto dê frutos importantes e duradouros, mas é bom ir devagar com o andor porque nem de longe a empreitada será fácil. No mais, seria interessante se nosso bom doutor Miguel Nicolelis estivesse envolvido no projeto.

Fonte: Mashable.

01 Apr 22:18

Impressora 3D devolve vida a homem que perdeu metade do rosto

by Ronaldo Gogoni

Eric Moger e a prótese

Eric Moger, 60 anos, pode dizer que viu o inferno. Gerente de um restaurante e residente em Essex, Reino Unido, ele estava planejando seu casamento há quatro anos atrás, quando num exame médicos descobriram um tumor maligno do tamanho de uma bola de tênis no lado esquerdo de seu rosto. Pior: ele era agressivo, e o mataria se não agissem rápido.

Após uma cirurgia de emergência, Eric foi salvo, mas a um preço terrível: o câncer foi removido e, com ele, quase todo o lado esquerdo de sua face, incluindo o olho, parte do osso da bochecha e boa parte da mandíbula, restando no lugar uma cratera que deixava sua língua e fossas nasais à mostra. O resultado pode ser visto aqui (NSFW, cuidado, a imagem é FORTE).

Agora, após anos de sofrimento, um dentista britânico usou uma impressora 3D e criou uma prótese para reconstruir o rosto de Moger – e sua vida.

Andrew Dawood é um cirurgião dentista especializado em próteses. Desde 2011 ele reproduz a mandíbula de seus pacientes em 3D de modo a praticar seus procedimentos. Moger foi indicado a ele pelo dr. Nicholas Kalavresos, cirurgião do Hospital Universitário de Londres responsável por salvar sua vida – apesar de destruir seu rosto no processo.

A princípio, plástico cirúrgico não adiantou devido ao tratamento de quimio e radioterapia a que Moger era submetido. A solução foi apelar para escaneamento facail e tomografia computadorizada, de modo a criar um modelo 3D do crânio do paciente, e desenvolver um suporte de titânio para substituir o osso facial removido. Foi fixado ao suporte um molde de plástico na parte de cima de sua boca, de modo que Moger possa se alimentar sem depender de um tubo.

O acabamento foi feito com uma máscara de silicone feita a partir de um molde de nylon do lado direito de seu rosto, que é fixada por magnetos e Moger pode tirá-la quando vai dormir ou tomar banho.

O resultado? Eric Moger descreve:

“Antes, eu costumava ter que segurar minha mandíbula com a mão para manter o rosto parado enquanto falava, e toda vez que eu bebia alguma coisa o líquido escorria pelo meu rosto. A primeira vez que bebi um copo d’água enquanto usava a prótese, nada escorreu. Foi incrível.”

Verdade seja dita: impressão 3D é fantástico. Volta e meia esbarramos em projetos de ciência e medicina que justificam o alto custo de equipamentos e insumos. O problema é que toda vez que o assunto é abordado e alguém aponta os problemas da tecnologia por ainda estar no berço, vem alguém com foice e martelo na mão clamando que ela vai arrasar o capitalismo e todo mundo vai poder imprimir o que quiser em casa. Não é bem por aí. A longo prazo a impressão 3D vai sim se popularizar, mas pelo menos por enquanto não é para o bico da maioria das pessoas; as impressoras 3D precisam de matéria-prima cara e não são a sacolinha do Gato Félix ou o bolso 4D do Doraemon (escolha seu felino favorito) para tirar produtos do nada.

Mas nada disso importa para Eric Moger. Ele recuperou seu rosto, sua auto-estima e sua vida: está de casamento marcado. Ele e Karen Hunger, sua noiva, agradecem pelo milagre alcançado. Um milagre chamado ciência.

Eric Moger e Karen Hunger

Fonte: The Sydney Morning Herald.