Some thoughts on JSON vs. S-expressions (2012) - <AUTHOR> https://eli.thegreenplace.net/2012/03/04/some-thoughts-on-json-vs-s-expressions <comment><USER2> Funny to see this article—I was interning at a company that used S-expressions instead of JSON internally right around the time this post was written. (Seeing it for the first time now though.)

All I can say is that _in practice_ , s-expressions worked _way_ better than JSON. Easy to read as a human, more flexible than JSON, reasonable syntax for working with alternatives (ie variants or sum types) and, of course, comments.

Here's one thing that stood out to me in particular: you could encode formatted text in a way that was pretty easy to read even _without_ formatting:

(Here is a sentence with (i some words) (b emphasized) in (i (b different)) ways.)

I forget if this was _exactly_ the syntax they supported, but it was something like that. You could do something similar with JSON, but it would be way more verbose and harder to parse visually.

Another massive advantage: structural editing in Emacs with Paredit is _incredible_. Once you get the hang of it, it's way faster _and_ less prone to typos than "normal" text editing.

If I ever start my own company, I'd definitely be tempted to standardize on S-expressions as our human-readable format for serialization and config data.

<comment><USER3> > Here's one thing that stood out to me in particular: you could encode > formatted text in a way that was pretty easy to read even without > formatting:

> (Here is a sentence with (i some words) (b emphasized) in (i (b different)) > ways.)

That's feels a little like XML, just without attributes and untyped end-tags.

I've never really understood the hate for XML and the preference for stuff like JSON. I'm a little biased towards XML because my company uses it heavily and I got very familiar with it early in my career, but it seems to make good trade offs for most use-cases where you'd want to use structured text.

<comment><USER4> > That's feels a little like XML, just without attributes

Attributes:

        (p :class 'center'
           (div ...))

> and untyped end-tags.

The end tags are implied by the start tag. Why do you need an end tag? It's just another way to mess up. The following situation is not possible using S-Expressions:

        ...
        <Start>
            500
            <Left>10</Left>
            ...
        </End>

<comment><USER3> > The end tags are implied by the start tag. Why do you need an end tag? It's > just another way to mess up.

It helps with legibility and error-checking of hand-authored documents (at least in documents with varied tags). It doesn't look like fun to figure out where to insert something in a pages-long document with sections that like like ))))))))))))).

It's not another way to mess up, it's another way to make sure you wrote what you meant.

<comment><AUTHOR> This is a fallacy rooted in SGML. With a proper editor, finding where to insert or delete new stuff.

<comment> em-bee ... is easy.

<comment><AUTHOR> Haha--yes, Thanks.

</comment></comment></comment></comment></comment></comment></comment><comment><USER5> I still believe that EDN[0] is one of the best general purpose data serialization formats - definitely a huge upgrade from JSON.

It addresses most of the authors problems while _also having s-expressions_, e.g.:

        (foo bar baz) ;; this is valid EDN

        {:foo [bar baz]} ;; this is also valid EDN

There are parsers for many popular languages, and a language already entirely based on it: Clojure.

[0] [https://github.com/edn-format/edn](https://github.com/edn-format/edn)

</comment><comment><USER6> I disagree. The difference between a dict and a list of key-value pairs should be left as an implementation detail in the receiver, not specified in the protocol.

S-expressions get this right. If the receiver knows they'll be doing a lot of lookup, they can build an indexed structure. If not, they can use something like assoc (which does a linear scan). The linear scan is probably faster with less than 5 entries anyway.

<comment><USER7> I think we mostly agree, but would put it a bit differently.

First, I think performance is a bit of a red-herring in this discussion. If a linear scan is really faster for five entries, a good dictionary implementation could simply switch to that.

Second, and more to the point, there's a obviously a semantic difference between a list of pairs and a dictionary. That's always going to be part of the "protocol" - whether your serialization format is capable of expressing that or not.

However, and I think this is where we agree, there are lots of semantic distinctions that JSON can't express (dates vs. strings, to pick an example I encounter often). So in many cases, you're going to have a deserialization step anyway that validates the JSON values and converts them into the objects you actually want to use in your application. Why, among all the semantic distinctions that JSON doesn't capture, is the list/dictionary distinction so special that it needs this kind of syntactic support in a serialization format?

(BTW, for JSON, the answer is obviously rooted in JavaScript's type system. But while that makes it particularly nice to use JSON to serialize _JavaScript_ objects, the context here is its use as a general-purpose serialization format.)

<comment><USER8> There's a difference between a list of _pairs_ , which is the one that is equivalent to a dictionary, and a list of _lists_ that all happen to have length 2; and between an unordered multiset and an ordered list.

</comment></comment></comment><comment> dan-robertson I've used both json and a cutdown version of sexps (there are no types like numbers or symbols, all atoms are strings so "foo" and foo are the same sexp) a lot.

I felt like sexps were much better for humans to write as you don't need to quote everything. Maybe this could be fixed in a json extension which allows words to be read as strings of themselves but if you extend json you lose any interoperability. Json also doesn't have comments.

There are some arguments for or against alists/plists instead of json "dictionaries". An obvious point is that only one of these allows for non- string keys. A weak concern I have is about using "the wrong type", eg if you use an array you sort of imply an ordering, and an object an unordered mapping, so should you put unordered data like a set in an array or should you have a map full of null values?

In recent years, languages with tagged unions like haskell or rust have become more popular. I feel like there's no satisfying way to write such a thing as json (relying on field names to disambiguate is only sometimes possible and feels tricky to read, having an object with a tag field or an array of [tag, value] feels unnatural. With a sexp you can just write it with a list of tag and args but because everything is lists, it doesn't feel so unnatural.

This isn't related to json vs sexps but having a difference between "123" and 123 in your text format kind of sucks. Either the parser will reject one or go to the trouble of parsing both or there's a semantic difference between them which feels worse. A case it matters in json is that if your number isn't a double you may want to put it in a string so other json reading programs don't turn it into a double and round it to a different value.

<comment><USER9> I don't know how universal this is, but at least in my mind there is a clear semantic difference between 123 and "123". 123 is a number in the mathematical sense, maybe counting or measuring something. It probably makes sense to do arithmetic on it (addition, multiplication, etc.). "123" is a number in the other sense: some kind of identifier that happens to consist of numerical digits; something like a phone number, zip code, serial number, etc. It doesn't make sense to perform arithmetic with it. And if it happens to begin with a "+" or a "0" then it's not ok to just drop that character.

</comment></comment><comment><USER10>
        #S(HASH-TABLE :TEST FASTHASH-EQL (ORANGES . 2) (APPLES . 6) (PEARS . 5))

Could have been an ALIST:

        ((ORANGES . 2) (APPLES . 6) (PEARS . 5))

or even a PLIST:

        (ORANGES 2 APPLES 6 PEARS 5)

Those allow for ordered, and even duplicate keys unlike the hashtable approach. No idea if that's applicable to JSON reading though...

</comment><comment><USER11> For what it's worth, Racket has a pretty terse syntax for literal hash tables:

      > (let ((x (make-hash))) (hash-set! x 1 3) (hash-set! x 'a 5) x)
      '#hash((1 . 3) (a . 5))

They can be read in:

      > (list (read) 30)
      #hash((2 . 4) (a . b))
      '(#hash((a . b) (2 . 4)) 30)

</comment><comment><USER12> Just because the standard lisp reader is readily available doesn't mean you should use it for anything else than code or small chunks of trusted data. Was there ever a question of using regular s-expressions in the same way as json? I don't think I have ever heard people suggest that. Most people either talk about using (read ...) to read trusted config files (which is fine) or to define an s-expression format to address specifically the complaints of the article.

As others have pointed out, there is nothing stopping a lisp reader from reading an alist as a hash-table. That is an implementation detail...

<comment><USER6> Indeed, feeding network-supplied input to a lisp reader is asking for trouble. In principle you can configure a reader to ignore read macros, but every lisp dialect has different footguns.

But they're great for application data storage. HN stores everything as s-expressions.

</comment></comment><comment><USER13> Did the author know what an alist is (hint: check out he assoc function). In any case though, there's no huge difference between the two. The graph structure semantics are assigned by the generator and consumer code.

</comment><comment><USER14> He wants EDN...

</comment><comment><AUTHOR> I do use s-expressions converted from JSON for some API work that I do. While I am not suggesting replacing json with s-expressions, I find it easier to manipulate them.

For those interested, here is a detailed comparison of Lisp JSON conversion libraries [https://sabracrolleton.github.io/json- review](https://sabracrolleton.github.io/json-review).

</comment><comment><USER15> This completely misses the point imo. S-expressions are a simple and fast way to serialise data, _which is then deserialised according to some schema_. It's not up to s-expressions (or json) to represent the end object being deserialised.

<comment><USER16> XML seems similar to S-expressions, in that way.

</comment></comment><comment> em-bee if you want to experiment with using s-expressions and your language doesn't already have a parser/generator, you can find a number of simple parsers/generators on rosettacode:

[http://rosettacode.org/wiki/S-Expressions](http://rosettacode.org/wiki/S-Expressions)

there is also a good discussion on what issues need to be considered on the talk page:

[http://rosettacode.org/wiki/Talk:S-Expressions](http://rosettacode.org/wiki/Talk:S-Expressions)

</comment><comment><USER17> Why would you need key: value representation when (key value) works just as well?

</comment><comment><USER18> JSON is the best interchange format ever invented. I don't understand why anyone would want to change it. It's:

\- Simple

\- Human and machine readable

\- Compatible

\- Searchable

\- Debuggable

\- Relatively fast encoding/decoding

\- Small size

I think Protocol Buffers is yet another misguided attempt to reinvent the wheel. If you did a pros and cons analysis on Protocol Buffers, you'd quickly realize that you lose in simplicity, lose on human readability, lose on compatibility (since it can introduce a reliance on specific type systems which different services will have to agree with), it's less searchable, less debuggable... The only benefit of Protocol Buffers over JSON is that in some languages it's a bit faster to encode and decode... In some environments the speed difference is negligible.

I can't think of any use case where ProtoBuf would be superior. I still don't understand how it could have become so popular. I guess it has Google's name behind it; that must be why.

<comment><USER19> JSON is by far not the universal exchange format. There are plenty of use cases where JSON is not well suited, such as:

\- regular/tabular data where JSON fails at processing speed and/or compressibility. One of the most efficient ways to store for instance a table/array of numbers is packing them as binary IEEE754 stream.

\- encapsulation of other code. Ever put HTML in a string within JSON? It's terrible to read and maintain for a human due to all the escaping. If you ever embedded SVG into XML/HTML or XML/HTML in JSX, you know how easy it can be if you don't have to break your head about escaping.

\- Obviously there is a need for binary json (there exist a lot of proposals/standards). That's quite similar to protocol buffers. The reason is always something about performance.

\- Also there are folks arguing since decades about JSON vs. XML vs. YAML vs. TOML vs .... There are lot of different opinions, and it is hard to say some is superiour to the other.

<comment><USER18> Trying to standardize binary as a flexible and general purpose interchange format is unwise IMO. UDP and TCP (and other protocols at that level) are about as far as we can standardize binary formats - This is as specific as they can be whilst still being generally applicable to a wide range of use cases.

My problem with ProtoBuf is that you can't impose more a more rigid structure and get more compatibility at the same time. A more rigid (statically typed) structure is inherently less compatible/interoperable (requires more integration effort, not less; harder to debug, not human readable, not searchable etc... More integration effort = less compatible, less interoperable).</comment></comment></comment>


The Surf Office is a community driven workspace and accommodation - <AUTHOR> http://www.thesurfoffice.com <comment><USER2> Love it! Gorgeous office space.</comment>


Oxford English Dictionary Could Go Out Of Print Thanks To Internet - <AUTHOR> http://www.huffingtonpost.com/2010/08/30/oxford-english-dictionary_1_n_698588.html <comment><AUTHOR> At least one friend of mine was really bummed when he heard this.</comment>


Ask HN: Why haven't any adventure travel startups taken hold by the mainstream? - <AUTHOR> Just something I've noticed. Maybe I'm missing something. <comment><USER2> 1) The vast majority of working people do not have much (if any) vacation time, nor the job security/financial security to take it.

2) Even if they do, they may have young children, which would prevent them from taking trips of this sort. Not just practically (where to leave the kids?) but also, many parents are reluctant to go to far flung places and participate in relatively risky activities that would increase the likelihood of their child(ren) being left with a disabled parent or worse, without a parent.

3) Requires a big chunk of disposable income, also less common than one would surmise.

4) Many people are simply not interested in adventure travel, preferring, well, normal travel (sightseeing, local cuisine and culture, etc).

There is certainly a market for adventure travel companies (why "startup"?) and they do exist. However, to be mainstream, the product would need to be useful and accessible to the masses, which for the above reasons it is unlikely to be.

</comment><comment><USER3> This graph also has something to do with it:

[http://cepr.net/images/stories/report_images/no-vacation- nat...](http://cepr.net/images/stories/report_images/no-vacation-nation- revisited-fig1-2014-04.jpg)

</comment><comment><USER3> Because there is no room to scale an adventure travel business. The market is niche.</comment>


Bauhaus at 100: its legacy in five key designs - <AUTHOR> https://www.theguardian.com/artanddesign/gallery/2019/jan/21/bauhaus-at-100-its-legacy-in-five-key-designs <comment><USER2> Dieter Rams' design principles can be found in his Wikipedia article at [https://en.wikipedia.org/wiki/Dieter_Rams#%22Good_design%22_...](https://en.wikipedia.org/wiki/Dieter_Rams#%22Good_design%22_principles) by the way. He worked for the company Braun and you will most likely recognize some of the iconic designs when searching for it.

<comment><USER3> There's also a recently released documentary about him: [https://www.hustwit.com/rams/](https://www.hustwit.com/rams/)

<comment><USER4> Thanks, I didn't know about that. Gary Hustwit is the same person that directed Helvetica, which is a classic design film IMO.

<comment><USER5> There is also Objectified, about industrial and product design, which I believe is his best. It has a small segment with Rams in it.

</comment></comment></comment></comment><comment><USER6> The first example being related to typography reminded me that Jan Tschichold was one of those influential typographers who's book, The Form of the Book, along with Raul Rosarivo's Divina Proporcion Tipographica, re-popularized the "Secret Canon" of medieval incunabula and brought the Golden Ratio to bear on book layout. Unfortunately we've lost a lot of that beautiful layout design but it can still be found in a few places. For a while, MacBook screens very closely approximated the Golden Rectangle.

<comment><USER7> Tschichold was a design genius. His first book 'The New Typography' set out the rules for modernist design, rejecting all old forms of design.

Some of the work he did at that time basically set the template for most design we have now. My old design tutor, who's father was one of the UK's leading modernist typographers and knew Tscichold, had a piece of his that she said had almost every modern design cliche, though done for the first time here.

Later, after a run-in with the nazis, he moved to the UK, rejected modernist design ideology as a little too fascist and revived traditional book design. He also designed the Penguin Classics book series - a major design achievement itself.

</comment></comment><comment><USER8> You can download the original Bauhaus books as PDFs from [https://monoskop.org/Bauhaus#Books](https://monoskop.org/Bauhaus#Books)

<comment><USER9> It's a small mention in the article, but there's a single zip file link[1] to avoid downloading each.

[1] [https://drive.google.com/uc?export=download&id=0B2lHLEBLCofZ...](https://drive.google.com/uc?export=download&id=0B2lHLEBLCofZQ2tuNVVYMjdHbVE)

</comment></comment><comment> man-and-laptop Regarding modern architecture, I'm not a fan. It's not like a painting which you can hang up on your wall at your own leisure. No, these are buildings that people _have_ to live in and around. I think London is worse off with the Shard.

I can't comment on the rest.

[edit: removed a paragraph about a tangential topic]

<comment><USER10> Also those chairs are really uncomfortable.

<comment><USER11> Sadly I can't remember where I heard it, it may have been in the documentary "Objectified", but there's a designer that raises an interesting point. It's something along the lines of: "Why are there still uncomfortable chairs? It's a solved problem, we know how to design chairs."

<comment><USER12> Not all chairs should be comfortable. Really comfortable chairs in the subway would be ridiculous.

<comment><USER13> Why?

</comment></comment></comment></comment></comment><comment><USER14> That kitchen _looks_ lovely in the still image, but is it functional? Its jars look hard to reach and dust-prone (unless the idea is to keep a smaller quantity of coffee in-reach and restock that every few days?) and the pull-out drawers look to serve a (negative) dual role of being suboptimal themselves (can only tall people look in them?) and make the over-cupboards slightly more inaccessible.

<comment><USER15> Probably in comparison to what there was before: standalone cabinets with less shelf space, stoves with legs, furniture that could move and didn't match, more to clean around and under hence more dust, and not being efficient with limited space. Given it's version 1.0 it seems pretty good considering what came before!

<comment><USER14> Good points. If it is a "v1.0", this might be an example of the moment of paradigm shift but not "polished" or tweaked to completely contemporary expectations. I'm so used to seeing Bauhaus (esp knock-on or secondary influences a la Dieter Rams) that are so awesome that finding apparent flaws is jarring to me.

Perhaps the article could have done better than a work in progress prototype (if that's indeed what's being observed), or I can get cool with Bauhaus not introducing designs fully formed and perfect as like The Birth of Venus.</comment></comment></comment>


Big oil will die when it becomes cheaper to hail an electric self-driving car - <AUTHOR> https://shift.newco.co/this-is-how-big-oil-will-die-38b843bd4fe0 <comment><USER2> What could validate this article's hypothesis is if Tesla manages to roll out a Class 8 Truck that meets the industry's needs.

Musk tweeted earlier this year "Tesla Semi truck unveil set for September. Team has done an amazing job. Seriously next level."

I am involved in a logistics startup that leverages Class 8 trucks and the specs are brutal.

Our trucks need a 500+ mile range and have to haul 40,000 - 50,000 pounds, and do it 5 - 6 days a week reliably.

It's hard to conceive how an electric drive train & battery array could manage to deliver on those basic specs.

But since 2000 heavy trucks have accounted for 40% of the TOTAL growth in oil demand, and similar gains are projected over the next few decades.(2)

And capital on the fleet side is very organized and effecient.

EG if lifetime operating costs of electric are significantly lower w/a longer useful equipment lifetime adoption will be rapid.

(1) [https://twitter.com/elonmusk/status/852580027178696704](https://twitter.com/elonmusk/status/852580027178696704)

(2) [http://www.iea.org/newsroom/news/2017/july/iea-study- unveils...](http://www.iea.org/newsroom/news/2017/july/iea-study-unveils-key- role-for-trucks-in-global-oil-demand-growth.html)

<comment><USER3> Trucking is one area where the per-mile costs are really important, unlike most passenger cars. The cost of electricity is generally much much less than the cost of fuel, so there's definitely the potential for a compelling offer for hauling, even if its only a subset of all uses of semi trucks.

Electric drive trains are excellent at heavy loads; many huge haul trucks, trains, etc. use diesel electric where the diesel is just a fuel source to generate electricity for the real workhorse, the electric motor.

So it's really just the battery that's the hard part here.

Most EVs get ~3.3 mi/kWh. If the increased air resistance means only a third of that efficiency, a 450 kWh battery would be sufficient for 500 mile range. That's about 3 tons of weight, which is a _lot_ , and take up about 2 feet of space behind the cab, perhaps. But since a diesel engine itself is going to weigh about 1 ton more than the electric motors and inverters, it's not a completely outrageous amount of overage.

Of course, the battery _alone_ for this would be about $100,000k, as much typical tractor cabs these days. So clearly there would be some sort of swap program, and battery usage would be charged.

This all becomes a ton easier if designed for just, say, 250 miles before swapping batteries. But napkin math suggests that 500 miles isn't completely implausible, if you can get over the up front capital costs, and the slightly lower hauling capacity.

<comment><USER4> > Most EVs get ~3.3 mi/kWh.

Not even close. BMW runs electric trucks between production facilities and our 169kWh trucks (Terberg YT202-EV) which haul up to 34,000kg get at most 100km out of that, often less. So you're looking at about 0.6km/kWh or 0.37mi/kWh. It will be more with less stopping (although there isn't a lot of stopping on our routes) but nowhere near your estimate.

<comment><USER3> I appreciate your data! However I wasn't trying to say that trucks will get 3.3 mi/kWh, this was apparently quite confusingly phrased, as I meant passenger vehicles.

My spitball of 1.1 mi/kWh was clearly way too high still.

</comment></comment></comment></comment><comment><USER5> There's a flaw in the argument that individual vehicles will go away: families with kids.

Before I had a baby, ride sharing was fantastic. Now it's basically useless. To transport my baby, I need a car seat of the appropriate size. It's really handy if I can leave a stash of diapers and wipes in the car. A portable high chair is nice, too. Sure, ride sharing is more convenient, but the car seat issue is a show stopper, at least until the ride sharing services catch up or autonomous car safety improves significantly _and_ legislation catches up.

All that being said, the car seat and diaper cache in question live in an EV, and I'm quite happy that I am basically done with the gas station phase of my life.

<comment><USER6> This is a really big point I've never considered!

I don't have kids, so I'm definitely coming from a place of ignorance. On planes and trains I never see car seats used, which I assume is because crashes are so unlikely on those modes of transit.

If self driving cars are as safe as, or safer than, a trip on a train, would it still be a concern?

<comment><USER7> ^ Parent w/ a <1 yr old. Car seats aren't used on planes because a car seat would take up a seat, which costs money. Kids under 2 yrs are free if they sit on your lap at most/all US airlines, so parents would just swap lap-sitting for their kid(s).

Not sure about trains.

I assume that if/when cars are as safe as a plane/train, adults wouldn't even need seat belts but you'd still need a carseat for an infant/toddler because it also stabilizes the child's position. Kids <6mo have no neck control. Kids <10mo can't reliably sit up for long durations. An autodriving car might be safe, but it'd probably still need to make emergency stops / turns. That'd be real bad if there were no carseats.

</comment></comment></comment><comment><USER8> > internal combustion engine has too many moving parts.

It does. But then the simple EVs aren't a that much cheaper than those complicated ICE cars. Where is the $9k efficiency basic model that someone in a lower income bracket could afford? Mention the government incentives and credits and talk about the cheap recharge cost compared to a tank of gas, less maintenance costs, and all of the sudden a lot of people will start listening. Most EV cars start at $20k and up from what I remember. That's more than the MSRP of a new Honda Civic. Few American consumers will choose a more expensive model, with less range, and long recharge cycle. There'd have to be some serious tax incentives/penalties or a huge jump in gas prices for people to start seriously considering EVs as their next car.

I get the point of electric taxis about maintenance, but there are only so many taxis around. Some are even regulated based on a medallion system. So I am afraid just taxis might not be enough to revolutionize the car industry.

<comment><USER9> EV price will mainly depend on how well Li-Ion batteries scale up in a mass market. I'd imagine at some point more and more of the price will go towards the part that cannot be made cheaper (and will actually increase in price with higher demand): Lithium. On the other hand, having efficient refurb/recycle processes for older batteries may solve that, assuming that there's enough Lithium to serve the global market once over in the first place. If not I guess it's either time for a new battery technology or time to mine asteroids or the moon.

</comment></comment><comment><USER10> I love my combustion engine car and don't plan to go electric next time... but this article made me think. And while perhaps a little too optimistic on timeline, I have to concede that his premise regarding moving parts has merit.

<comment><USER11> I love my combustion cars too but the Tesla puts them all to shame. It's just better in every way but two: Initial price and range. Economies of scale and competition will fix the first and recharging stations have already mostly fixed the second. I encourage skeptics to drive one. It's an astonishing vehicle.

<comment><USER12> Puts them to shame how? The Tesla standard of luxury is light years behind that of cars like the S Class. The standard of performance is strictly limited going from 0 to 60, and not sustaining it.

I've driven it, and I've driven other high end cars of it offers very little that you can't find in other high end cars.

The novelty of instant acceleration is fine, but the insulation from wind noise and road noise are still not on par with high end brands even though there's no ICE (and it's not because there's no ICE noise to cover up, in a modern S Class the cabin is almost whisper quiet), and if performance is you goal.

You don't (knowledgeably) get a Tesla because you want the best car, you get one because you want a Tesla. To me cars like the S Class shame the Model S for trying to call itself a "luxury car", and cars like C63 AMGs shame it for calling itself a "performance sedan"

<comment><USER13> Why is accelerating from 0 - 60 in a few seconds so important for people when their journey would largely be for minutes/hours?

Its not like going to office/supermarket/school/college/home is a race.

<comment><USER12> That's kind of my point, it doesn't really matter in everyday driving, and if you're interested in some "spirited driving", you want a car with more wholistic performance.

Instantaneous acceleration is nice for stop and go traffic and city driving, but that's inherent to all EVs (A base model Volt as fast from 0 to 30 as a Model S 85)

</comment></comment></comment></comment></comment><comment><USER14> It would be interesting to see if lithium mining and production could be scaled up fast enough to produce 15+ million cars per year (US only).

Something tells me that this could be an ecological disaster even greater than coal.

The article may be correct on the rationale, but the timing seems fast given everyone's concern about the planet.

Also consider that oil comes from a small hole in the ground, and already has refineries in place to turn it into gasoline, while last year the whole world only produced about 650,000 tons of lithium. Each Tesla uses about 65Kg of it.

<comment><USER15> One car is going to be able to service 4-10 people, old cars will still exist. Think of the transition from incandescent to fluorescent to LED, no one expected that LED would take over so soon, that the efficiencies and bulb life would surpass CFL as quickly. How many LED bulb assembly lines do we need? Probably 1. For the whole world.

</comment></comment><comment><USER16> That's a hell of a bubble the author is in. Good thing he's not talking politics.

ICEs aren't going anywhere for a very long time. Their market share will certainly be reduced for ground transportation but electric power isn't making nearly as much progress in marine or aviation applications. Liquid field are simply too convenient, especially in remote areas. I know city folk sometimes like to forget that everyone else exists but gas/diesel off highway vehicles aren't getting replaced very soon. The service life of a big piece of equipment (e.g. a front end loader) is measured in decades. Even if a silver bullet comes along it will take a long time for everything else to age out. Secondly, standby generators are everywhere. Those aren't being replaced with batteries anytime soon for obvious reasons. Oil is refined for use in plastics, lubricants and a laundry list of other things that are indefensible to modern civilization. Sure, transportation is a big slice of the market for oil and it's going to get smaller but it's not the only slice. Finally, while the first world may adopt electric power soon, other nations will be slower. If the Keystone pipeline isn't carrying crude that will be refined and sold in the US it will be carrying crude that will be refined and sold elsewhere.

This is wishful thinking, nothing more.

I don't have stock in an oil company or anything, the author's claims are just a little too ridiculous for me to ignore.

<comment><USER17> > Their market share will certainly be reduced for ground transportation

And that alone will be enough.

You're right that gas/diesel will never be _completely_ replaced, but it seems that it doesn't need to be in order to suffer a serious decline in usage that radically transforms the energy landscape.

Looking at this graphic [1], ground transportation is the biggest single use case of oil in the United States.

67% of oil consumption in the U.S. goes to the transportation sector, and ~80% of the transportation industry's oil use is for ground travel. A serious decline in that could really hurt the industry and cause the kind of disruption the author was talking about. (Granted, the graphic's from 2004 but I don't have a reason to believe the proportions have fundamentally changed).

[1] [http://afstrinity.com/images/data/oil- transportation.jpg](http://afstrinity.com/images/data/oil-transportation.jpg)

<comment><USER16> Unless something comes along that halves domestic ground travel demand overnight it's not going to hurt the industry too bad. They'll just sell crude to China or whoever. Furthermore, if gas/diesel usage falls then other oil products become cheaper so while lost demand from transportation would not be close to fully compensated for elsewhere it will still be partially compensated for.

It's not the change that hurts, it's how fast the change happens. Think about the kinds of things that have hurt the industry in the past. They've all been very quick.

<comment><USER18> >They'll just sell crude to China or whoever.

So China will stick with gasoline even though it will be more expensive, has to be imported, and the country has terrible air pollution problems?

</comment></comment></comment></comment><comment><USER19> There are some, how to call, secondary effects which can avalanche real quick. For example, if gas stations begin to close (or just give up regular gasoline still selling diesel to trucks) that can become a self strengthening death spiral incredibly fast.

</comment><comment><USER20> > The costs of electric self-driving cars will be so low, it will be cheaper > to hail a ride than to drive the car you already own.

Actually it's nearly to that point for me already. I moved to LA from Hawai'i. In most places in Hawai'i having a car is essential if you want to go anywhere (not so much in Honolulu) - on my island the bus only ran every 2 hours until 4pm on the weekends, and some of the stops were over 5 miles apart.

But now that I live in LA, so any of my needs to go out can be met with Sprouts Amazon Prime Now, Uber and when I really need something coordinated I'll rent a Turo car. And all this costs me less than a monthly car payment would.

<comment><USER19> Don't forget the part where Uber is selling the service below cost...

<comment><USER21> Subsidized Uber rides are proof that venture capitalists love us and want us to be happy.

<comment><USER19> Subsidized Uber rides are proof that venture capitalists ... are interested in the spread of late stage capitalism and destroying the progress in worker welfare that took a hundred plus years to make.

</comment></comment></comment></comment><comment><USER22> There's a fantastic report from UK that studies what would happen to oil companies if demand decreases at the rate needed to hit 2 and 3 degrees warming.

In general, it see oil prices falling and sovereign oil selling the most since they can undercut competition for a diminishing pie (basically a fire sale). The private oil companies get super screwed, with something like 80%+ stranded assets.

[https://en.wikipedia.org/wiki/Carbon_bubble](https://en.wikipedia.org/wiki/Carbon_bubble)

</comment><comment><USER23> However there are other uses for oil other than gasoline like jet fuel, asphalt for roads, making plastics.

<comment><USER24> Your comment reminded me of the idea that "...crude oil is much too valuable to be burned as a fuel."

[http://press.princeton.edu/chapters/s7121.html](http://press.princeton.edu/chapters/s7121.html)

</comment></comment><comment><USER25> While the author makes a lot of interesting points that even I hadn't considered before as an enthusiastic reader of EV news, there are a few glaring holes I need to point out:

\- Pretty much every point the author makes about the rapid takeover of EVs, from being cheaper to hail one instead of owning a gasoline powered car, to the ones relating to owning cars at all, could (and should) be prefixed by "In a city..." because speaking as someone who lives far from an urban sprawl, a lot of this stuff just would not work. Sure EV's work ok out here, though the self driving tech might need more help than most often, but who is buying all of these self driving EV cabs and operating them, and why? The volume just isn't here, you'd get tons of passengers clamoring for a ride between 7am and 9am, then again at 3pm to 5pm, and then it would be near dead the rest of the time.

\- There are no EV technologies (to my knowledge) ready to replace anything beyond a city runabout vehicle. The act of, for example, plowing snow would be insanely taxing on an EV truck (running an electric motor under strain is the best way to wear down the battery), and sure, the mechanical element is definitely true but you'd need some sort of fast-charge system to make it viable, otherwise your trucks are spending hours charging for every hour plowing. And then that's a fairly easy one, electric combines, construction equipment, cranes, tow trucks, I haven't heard of any of these and I look for this sort of thing.

\- Societal inertia is going to be a big factor here, around here we have people driving vehicles from the 70's, not as collector's items or anything like that but as their daily driver. Come on out here and propose to our average Joe the idea of buying a Tesla Model 3 for $37,000, a guy who barely makes $30,000 a year, who buys and drives the cheapest thing on the lot until the wheels fall off and goes and gets something else.

I could go on but it's bed time. Maybe ICE vehicles will be dearth from cities within 10 years, maybe. But even then I kind of doubt it.

<comment><USER26> The US and most developed countries are highly urbanized. The US is 82% urban, most of Europe about 80%, China was 57% in 2016 and increasing every year. [1]

Together, these countries account for over half of the world's oil demand and the urban parts account for most of it. [2]

The impact on urban areas alone would be sufficient to disrupt the whole industry. The disruption will unlikely to be as drastic as what happened to Kodak and Nokia since most people cannot afford to change cars as quickly and changing modes of transportation especially conditioned on self-driving vehicles reaching broad acceptance might take some time. Your point regarding rural areas may be applicable to several developing countries. The author's key points remain valid, although the timeline looks too optimistic.

[1] [http://data.worldbank.org/indicator/SP.URB.TOTL.IN.ZS?year_h...](http://data.worldbank.org/indicator/SP.URB.TOTL.IN.ZS?year_high_desc=true)

[2] [https://en.wikipedia.org/wiki/List_of_countries_by_oil_consu...](https://en.wikipedia.org/wiki/List_of_countries_by_oil_consumption)

<comment><USER27> This data lumps together suburban and true dense urban as 'urban'. Probably over 50% of the U.S. population is suburban, and that population is not going to be served economically by on-demand ride services.[1]

[1] [https://fivethirtyeight.com/features/how-suburban-are-big- am...](https://fivethirtyeight.com/features/how-suburban-are-big-american- cities/)

</comment></comment></comment><comment><USER18> It's important to understand that oil companies all over the world will be going bankrupt if consumption falls 30%.

To start, they all have huge investments that they borrowed money for on the calculation of making a certain level of revenue for 40 or so years.

A big drop in demand will mean less sales, but also that prices per barrel, which are already low, will go down even further. The result would be maybe half the total revenue, so they won't be able to pay off their loans and will have to declare bankruptcy.

</comment><comment><USER28> Gasoline is 100 times more energy dense than a battery. The Tesla roadster adds 800 lbs to the lotus elise upon which it is built. Batteries have a long way to go.

<comment><USER29> And yet combustion vehicles don't have 2000 miles range. Energy density is very important, but you can make up for it with better efficiency.

<comment><USER30> Only because they don't need it. Most people are comfortable with a ~300 mile range, knowing they can refill in 5 minutes. So most cars are built with 10-to-15 gallon tanks.

Build a car with a 30 gallon tank and you could easily be in the neighborhood of 1000 miles range.

</comment></comment></comment><comment><USER31> Electric vehicles have not yet turned out to be more reliable or cheaper to repair. Tesla vehicles are lower than average on both of those measures.

I used to be very optimistic because of how simple electric cars are in theory, but in practice, a century of refinement of internal combustion engines has not yet been beaten.

<comment><USER32> The two Tesla models that are available right now are not 'average' cost vehicles, though. How do the fair against similarly positioned vehicles?

I would expect Teslas to be a bit more expensive to maintain at this point, as parts availability and third party after market parts manufacturers are about non-existent for them. As electric vehicles get more popular and mainstream, this problems (as far as EVs in general) will likely be resolved.

</comment></comment><comment><USER33> He's wildly optimistic on the timeline to the point of delusion, but it's probably true we'll transition to automated electric cars within a few decades.

</comment><comment><USER34> This essay carries little weight if he hasn't put his own money on the Line by betting against oil companies.</comment>


Ask HN: Product Manager Training - J-dawg I'm a developer looking to make the move into a product role.
I would like to take a break from work and do some training to prove my interest and gain some credibility with employers.
Are there "bootcamp" style courses for product roles? If you're a hiring manager, do you pay attention to things like this?
I'm UK based but could potentially travel anywhere for training.
Any personal experiences or recommendations would be greatly appreciated. <comment><AUTHOR> I've heard nonspecific good things about Mind the Product as a conference. They also do trainings. I know nothing about their quality.

[https://www.mindtheproduct.com/product-management- training/](https://www.mindtheproduct.com/product-management-training/)

If you don't mind sparing a day and £550, maybe go to [https://www.eventbrite.com/e/communication-alignment-for- pro...](https://www.eventbrite.com/e/communication-alignment-for-product- managers-training-workshop-london-tickets-69000242583)?

Otherwise, see about joining the London chapter of [https://www.meetup.com/ProductTank/events/](https://www.meetup.com/ProductTank/events/) ?

<comment> J-dawg Great ideas, thank you!

</comment></comment><comment><USER2> I've been thinking about this too. Too many roles want developers to be short- order cooks, processing tickets. I'm not sure a product role is the answer for me, but I'd be interested in the answer to this question.</comment>


TechShop: Open Access Mechanical Workshop - <AUTHOR> http://www.kk.org/cooltools/archives/002777.php <comment><USER2> <http://techshop.ws/>

it's a great place.</comment>


Making software architecture choices analytically with CodeTrend - <AUTHOR> http://www.embracingchaos.com/2013/09/making-software-architecture-choices-analytically-with-codetrend.html

<comment><AUTHOR> Here's an example plot of Rails vs. Django:

[http://www.codetrend.org/compare/django/vs/ruby-on- rails](http://www.codetrend.org/compare/django/vs/ruby-on-rails)</comment>


Google Design Guidelines - <AUTHOR> http://google.com/design

<comment><USER2> Google just launched its new Material Design UI paradigm as Polymer elements, making it available for both open web and Android native apps.

</comment><comment><USER3> A dupe of [https://news.ycombinator.com/item?id=7944893](https://news.ycombinator.com/item?id=7944893).</comment>


Obama on sorting algorithms (YouTube link) - <AUTHOR> http://www.youtube.com/watch?v=k4RRi_ntQc8

<comment><USER2> Not an incredible answer, but surprising that the president at least knows what a bubble sort is.

<comment><AUTHOR> I'm pretty sure it was staged/prepped. I still find it pretty funny, especially the look on his face after he says that bubble sort is not the way to go.

<comment><USER3> of course. Still, pretty good humor "We've got our spies in there" ... ha, that was good.

</comment></comment></comment><comment><USER4> Wasn't this originally done with Peter Norvig and Obama?

</comment><comment><USER5> radix sort ftw!</comment>


Finding and Fixing a Five Second Stall - <AUTHOR> http://the-witness.net/news/2012/12/finding-and-fixing-a-five-second-stall/

<comment> eric-hu While I'm a web dev and not a Windows coder, this post is a great example of why I come back to HN.

> From experience, I've learned that it's always best to fully understand a > problem before you fix it. If you just patch over its symptoms but never > figure out what the problem really was, it will often come back to haunt > you.

Philosophical-level statements like this really help me as a dev, since my one of my biggest hurdles is getting traction for even simple 1-2 line refactors that, in my opinion, can simplify code and improve maintainability. Far too often, I hear "just get it done", and I like to be reminded with statements like this of why "just get it done" doesn't always result in a better bottom line for the company.

>For some reason, I took this concept to heart in a programming sense and have found it is a good rule to code by. My version of the static discipline, adapted for software, is that whenever you are making a modification to a piece of code, you should always leave it in a state of stability equal to or better than how you found it. And preferably the latter.

I try to do this where I can too, and again, appreciate the philosophical explanation. It prepares me to more thoroughly and calmly explain my own work style.

The author laments Windows development, and I can only contrast that with my experience on an open source web stack (Ruby on Rails, Backbone.js). The upside of working with open source is that I can crack open the gem (library) I'm using and investigate the logic myself. I could fix the bugs or extend the code to do what I want. That is pretty cool.

The downside of working with open source software is that documentation is horrid. As the author states, man-hours are finite, and people who write OSS typically don't want to spend their finite hours documenting their code. I just take these as tradeoffs. It seems like Microsoft invests heavily in documentation, but I guess the author's point is that they can still do better.

<comment><USER2> I invariably end up reading the library/framework/whatever sources as well, if only to clarify a particular point of documentation or something.

But, when bughunting, there's often the dilemma of whether to fix the bug at the source (and hopefully, submit a patch to upstream), or to work around it (which can lead to horrific hacks) in your app code.

With the former, you're stuck having to deploy custom packages with your fix in until/if it gets accepted into upstream and a new release is rolled, so all too often I've found myself doing both. I don't know what the solution is; even a perfect patch to a superhumanly responsive maintainer is going to take some time to merge and deploy.

On an entirely unrelated note, a superb way to drive yourself insane is to edit the currently installed system version of the package in question, and then forget that you did some time later.

<comment> eric-hu I'm only about 1-2 years into web dev and OSS, and a couple of months into feeling like I can contribute meaningfully to a gem. With that said, this is my current ideal Github workflow:

\- fork the gem to make changes/fixes \- complete fix and point my app dependency to my branch \- add testing and docs around my fix \- submit pull request to project owner \- point my app dependency back to original gem when merged

That all said, I consider the activity of a gem before I even bother submitting a pull request. If it hasn't been touched in a month, or if there are open pull requests from 1 month or older, I weigh heavily just writing a 'my team only' solution.

This is admittedly selfish, but I'm hedging my time and emotional energy. I don't want to put care into crafting something that I believe to be useful only to watch it sit around unused because someone else doesn't want to review my work.

</comment></comment></comment><comment><USER3> Windows is saddled with baroque interfaces that are there only because they've always been there. Microsoft OS developers try to simulate or stub out old behaviors, in an effort to keep old app code running without breaking anything too badly.

Such a crust of backward compatibility code weighs heavily on a decades-old OS.

<comment><USER4> In fact, if the Windows guys had actually taken this backwards compatibility thing seriously, and failed to tidy things up by deprecating DirectInput, this problem probably wouldn't have arisen. DirectInput has a single simple flag to disable the Windows key :)

"DISCL_NOWINKEY - Disable the Windows key. Setting this flag ensures that the user cannot inadvertently break out of the application".

(I found this flag to work entirely reliably on Win2K and WinXP, and I'm pretty sure it worked on Win98 as well. I think it also kindly disabled a bunch of other things for you, leaving Windows with only Alt+Tab and Ctrl+Alt+Del. Which is basically exactly what you want for anything full- screen.)

</comment></comment><comment><USER5> Oh, the joys of Win32 programming.

Back in the day I wrote networking service that was occasionally failing under stress load with memory corruption. I was staring at rare dumps, re-reading code and documentation to no avail. Finally, after few days of debugging, I went ahead and located debug symbols and sources (oh, I happened to work at Microsoft at the time) for the build of Windows we used at the test lab, it was relatively arcane procedure back then (it got better later, but at the time it was either symbol server doesn't work, or sources don't match).

So I setup gflags with memory guards and windbg and started waiting. After few days of stress run it finally crashed again and there it was - comment in the code of the crashing library saying "OVERLAPPED can be deallocated at this time if completion ports are used, but we save this value to it here anyways for backward compatibility reasons with bla-bla." Glad that you told me guys, I guess now I have to rewrite it and refcount the OVERLAPPED! I still don't know how I could debug it without the source access. (Ironically, it also enlightened me on why service I implemented at the startup before was occasionally crashing as well).

And don't even start me on implementing SSL support in the service.

</comment><comment><USER6> Reading this really brought back memories of when I was writing Windows code. It really felt like half of any project was spent on working around the OS, rather than with it.

<comment><USER7> Now for a lot of developers half of any project is spent working around various browser quirks -- how far we've come!

</comment></comment><comment><USER8> I had the opposite experience yesterday. A colleague and I were tracking down a rare race condition that became more likely with more threads. A signal handler was being re-entered, which the man page suggested shouldn't happen because by default the signal is blocked during handler execution.

Because this was Linux, we were able to read the kernel source to see what actually happens. It turns out that the signal is only blocked for the current thread, and Linux will deliver it to the first unblocked thread instead.

This misunderstanding also came from a less explicit API doc, although not outright incorrect. But because we had full stack source we didn't need guesswork, a good night's sleep or inspiration. Just curiosity and persistence.

There's a zen-like calm to knowing you can always, always follow a bug through the entire system, that everything happens for a reason and you can open an editor and see what those reasons are.

I will miss this deeply if I ever return to closed-platform development.

<comment><USER9> Did you submit a patch for the documentation to make this particular more clear?

</comment></comment><comment><USER10> Is there some 'platform complexity' measurement metric along the lines of a 'code complexity' indicator? It would be useful for finding platforms/languages/environments with less pain and as a way to track improvements as well.

<http://owenfi.com/post/38255106579/windows-keyboard-apis>

<comment><USER11> You could probably take your normal metrics and compute them for the lines of code that specifically contain framework/platform code? Can't say how useful that will be, but I'd be interested to see how those numbers align with my feelings.

</comment></comment><comment><USER12> Reminds me of this one job where we had to call LockWindowUpdate to get an Excel/VBA-based application to perform.

[http://msdn.microsoft.com/en- us/library/windows/desktop/dd14...](http://msdn.microsoft.com/en- us/library/windows/desktop/dd145034\(v=vs.85\).aspx)

<comment><USER13> LockWindowUpdate really isn't that unusual if you understand how painting works in Windows. The terminology behind it is weird and so is the fact that it's one window at a time, but it's not all that strange - it's an old enough primitive that you probably couldn't justify making it a per-window flag bit.

</comment></comment><comment><USER14> My favourite win32 api is this little gem for flushing a file output buffer to the physical disk: <http://support.microsoft.com/kb/148505>

<comment><USER15> I pity the poor tech writer who had to constantly write "Commode.obj" while maintaining a serious tone.

</comment></comment><comment><USER16> They are using a low-level hook to disable the expected behavior of a "get me out of here" key.

They deserve all the stalls they can get. The reason it was so complicated to get this behavior in the first place is because its heavily _discouraged_.

Not to mention that calling SetWindowsHookEx will flag you as a keylogger in every antivirus snakeoil in existence.

<comment><USER17> So heavily discouraged that it was in this Microsoft sample code linked in the OP: [http://msdn.microsoft.com/en- us/library/windows/desktop/ee41...](http://msdn.microsoft.com/en- us/library/windows/desktop/ee416808%28v=vs.85%29.aspx)?

<comment><USER16> That code is offered as part of the extensive documentation that Microsoft provides on its various frameworks.

It by no means sanctions what still remains a terrible hack. A badly written hook could render a users system essentially unusable, and as I explained, its a very common heuristic for anti virus software.

The point remains: the fact that you have to resort to globally hooking all input to break the expected behavior of a key can not possibly serve as an example for bad documentation or bad API design. It in fact proves the very opposite: you have to work very hard to break what users expect.

<comment><AUTHOR> Considering that neither party, those who don't want to enable the windows key during full-screen and those who always depend on the windows key to function normally, is served without an unstable and error prone method it would seem the API is failing both parties in some cases.

I think the author would agree with your last statement. By forcing the applications to handle this logic and break what some users expect the API isn't serving the users or developers well.

</comment></comment></comment></comment><comment><USER18> >> The great thing about programming on Windows is that it is the only commercially viable platform where you can ship software to users without getting approval from a giant bureaucracy <<

I kind of had the feeling I could write code for a Mac and ship it.

Wait, in some sense I have done so before with code for computing fractals I shared with other Mac users in my department. It worked perfectly in my Mac and their Mac.

Wait! I have downloaded and paid for apps straight from some developers websites (top of my mind, or top of my menu bar: Hazel, 1Password, Arq)

So I just stopped my reading there, sadly.

<comment><USER19> I suspect the author means viable for video games, not software. I don't have any proof of this, just the dearth of large-budget games make their way to Mac.

<comment><USER18> Yup, I guess that's the point, but dissing the whole platform because a kind of software product is not particularly buoyant...</comment></comment></comment>


Ask HN: What's your most-used function that you wrote yourself? - <AUTHOR> Obviously, I'm looking for relatively short examples.
Interpret "function" broadly. <comment><USER4> I wrote a C#/.NET function (extension method) called `Becomes` that I use as a replacement for the various `TryParse` methods.

Example:

        let n be an int
        n.Becomes("2") //returns 2
        n.Becomes("sdfsd") //returns n

        0.Becomes("12") returns 12
        0.Becomes("sdssdf") returns 0

Non-contrived example:

        var person = Person.Get(0.Becomes(Request.QueryString["id"]));

Basically, given the expression

        n.Becomes(SOME_STRING)

if `SOME_STRING` can be parsed as whatever the type of `n` is then it returns the the parsed result, else it returns (the value of) `n`.

More technically, `Becomes` returns a `ParseAttemptResult<T>` that is implicitly convertible to `T`. It also has `true` and `false` operators so that it can be used in an expression expecting a `Boolean` (e.g. `if` and the ternary operator`?:`).

Github Repo: [https://github.com/noblethrasher/Parser- Helpers/blob/master/...](https://github.com/noblethrasher/Parser- Helpers/blob/master/ParserHelpers.cs)

</comment><comment><USER5> I offer up this little item since I'm a bit of a stickler for applications using proper grammar. This is nothing complex but I use it all the time. I have versions of the same routine in every language I work in.

       function plural(count, itemName, pluralWord, singLead, plurLead, singFollow, plurFollow) {
          if (((typeof pluralWord != 'undefined') && (typeof pluralWord.valueOf() == 'string')) && (pluralWord.length > 0))
             var outP = count + ' ' + ((count == 1) ? itemName : pluralWord);
          else
             var outP = count + ' ' + itemName + ((count == 1) ? '' : 's');

          var follow = (count == 1) ? singFollow : plurFollow;
          outP += (((typeof follow != 'undefined') && (typeof follow.valueOf() == 'string')) && (follow.length > 0) ? ' ' + follow : '');

          var lead = (count == 1) ? singLead : plurLead;
          return (((typeof lead != 'undefined') && (typeof lead.valueOf() == 'string')) && (lead.length > 0) ? lead + ' ' : '') + outP;
       }

Usage - first simple pluralization:

      alert('There ' + plural(c,'dog','','is','are') + ' in my house');
      c = 1 --> There is 1 dog in my house.
      c <> 1 --> There are 2 dogs in my house.

      alert(plural(c,'dog','','','','is','are') + ' in my house');
      c = 1 --> 1 dog is in my house.
      c <> 1 --> 2 dogs are in my house.

And for non-simple pluralization:

      alert('There ' + plural(c,'company','companies','is','are') + ' on the list');
      c = 1 --> There is 1 company on the list.
      c <> 1 --> There are 2 companies on the list.

      alert(plural(c,'company','companies','','','is','are') + ' on the list');
      c = 1 --> 1 company is on the list.
      c <> 1 --> 2 companies are on the list.

</comment><comment><USER6> I stole this from mongrel2, but the check macro is pretty good for error handling in C

      #define check(A, M, ...)                       \
          if(!(A)) {                                 \
            fprintf(stderr, M "\n", ##__VA_ARGS__);  \
            goto error;                              \
          }                                          \
        }

And you use it like this

      FooClass *create_foo_class()
      {
        FooClass *fc = NULL;
        int rc;
        fc = malloc(sizeof(*fc));
        check(fc != NULL, "allocation failed");

        rc = do_something_to_foo_class(fc);
        check(rc == 0, "do_something_to_foo_class(...) failed");

        return fc;
      error:
        if(fc != NULL) free(fc);
        /* Other cleanup */
        return NULL;
      }

</comment><comment><USER7> Possibly the most critical code in my application:

      #Non-destructive.  Returns the input array/list in randomized order.  Uses approximately O(n) time and O(n) space.
      def self.shuffle_array(array)
        shallow_copy = array.map {|a| a}
        shallow_copy.size.downto(1) {|n| shallow_copy.push(shallow_copy.delete_at(rand(n)))
        shallow_copy
      end

<comment><USER8> Hopefully you've since migrated to Array#shuffle.

<comment><USER7> "If it ain't broke..."

</comment></comment></comment><comment><USER9> history function for ruby console (irb) sessions:

       def history(num=100)
         h = Readline::HISTORY.to_a
         start = [0,h.size-num-1].max
         h.zip((0..h.size).to_a)[start...h.size].each do |cmd,i|
           puts " #{(i).to_s.rjust(4)}  #{cmd}"
         end
       end

I keep it in my .irbrc file, really useful to avoid stepping through command history to find previous commands.

</comment><comment><USER10> connect_to_db(); in PHP. it knows if im in a development or production environment, knows the proper username and password, and connects. Very basic i know, and im sure everyone has written a similar function, but super useful.

</comment><comment><USER11> Probably this one, which I use for testing

        function becho($value, $key = NULL)
        {
            echo '
' . (NULL != $key ? $key . ' = ' : '') . $value . '';
        }

I also like this one

        function s($num)
        {
             return $num == 1 ? '' : 's';
        }

Which I use like

        echo 'Showing ' . $results . ' result' . s($results) . '.';

<comment><USER12>
        function echo_r($x){
            echo '
';
            print_r($x);
            echo '
';
        }

</comment></comment><comment><USER13> Kinda ugly, but:

        (defun my-rename-symbol-at-point ()
          (interactive)
          (let* ((curword (thing-at-point 'symbol))
            (to-word nil))
          (if (null curword)
            (message "No symbol at point!")
            (progn
              (setq to-word (read-string (concat "Replace " curword " with: ")))
              (save-excursion
                (goto-char (point-min))
                (replace-regexp re-curword to-word))))))

</comment><comment><USER14> Haskell:

        (\>) x f = f x

Allows me to write in a more readable manner

        [1..10]
            \> map (*2)
            \> filter (<5)

<comment><USER15> Heh, wrote the same function, except called mine $> because it's really just a flipped $.

</comment></comment><comment><USER16> I guess my alerter. Very simple, but used often. <https://gist.github.com/1039867>

Should emit a small sound when run, useful when running long running tasks so you dont have to pop back to the console window all the time to check if its done.

<comment><USER17> I use a popup :) <https://github.com/trbecker/getbacktowork>.

</comment></comment><comment><USER18> A PHP 'get or else' which replaces

       $some_var = isset($array[$key]) ? $array[$key] : $default;

</comment><comment><USER15> A few months ago I was writing a little application where I was doing a lot of asynchronous calls in javascript and having to track their completion to do some other stuff, it resulted in this:

      // Synchronizes asynchronous calls: sync(functions..., completionHandler)
      var sync = function() {
        var argLength = arguments.length - <USER2>
          , completed = 0
          , callback  = arguments[argLength]

        for (var i = 0; i < argLength; i++) {
          arguments[i](function() {
            completed++;
            (completed == argLength) && callback && callback();
          });
        }
      };

It pretty much takes a number of functions that perform asynchronous operations and execute a callback function upon completion of whatever the async operation is. Once they're all complete it calls the last function it received as a 'completion handler'. Example that I wrote out without bothering to test at all (treat it as pseudo-code):

      var pageData = null;
      sync
        ( function(cb) { $('#pageContainer').fadeOut('slow', cb); }
        , function(cb) {
            $.ajax(
              { url: 'page.html'
              , success: function(msg) {
                  pageData = msg;
                  cb();
                }
              }
            );
          }
        , function() {
            $('#pageContainer').html(pageData).fadeIn('slow');
          }
        );

So that will start by beginning the jQuery fadeOut animation on the pageContainer html element, while immediately doing an ajax call to get another page's data. Once both operations are complete, it will take the new page data, put it into the pageContainer element, and fade it back in.

</comment><comment><USER19> A designers most used function:

In SCSS I use a very simple mixin for rounded corners, something I use frequently when designing sites.

      @mixin radius($dist) {
        border-radius:$dist;
        -moz-border-radius:$dist;
        -webkit-border-radius:$dist;
        -khtml-border-radius:$dist;
        -webkit-background-clip:padding-box;
      }

Then in the class just add:

      @include radius(5px);

<comment><USER20> You might like this boilerplate SASS file that I made to handle a bunch of this type of thing: <https://github.com/mgeraci/Sass-Boilerplate>

I also see this post explaining the presence of the -webkit-background-clip ([http://tumble.sneak.co.nz/post/928998513/fixing-the- backgrou...](http://tumble.sneak.co.nz/post/928998513/fixing-the-background- bleed)), but I don't see that behavior in Safari 5. Potentially fixed? If not, I would certainly add that to my boilerplate.

</comment></comment><comment><USER21> We have a SIP call accounting, rating and routing product that is driven by a SIP proxy that calls a lot of Postgres stored procedures on the backend. (The SIP proxy's configuration is written in a pseudo-programmatic, interpreted scripting language, but one lacking in many basic features and data structure primitives that can be taken for granted in the runtime of a general-purpose programming language, so most of the business layer is in the database of necessity, in addition to all the other reasons for doing it that way.)

All throughout the platform, there are many points at which the ANI/caller ID and the dialed digits (the user part of the request URI) must be "translated", which is a fancy phone switch term for stripping one or more digits and then prepending one or more digits. It was such a common operation that it was genericised into our most oft-used PL/PgSQL utility function:

      -- Character stripping and prefix prepending transformation, which is applied
      -- to the ANI and DNIS at virtually all entry and exit points in the call
      -- processing machine.

      CREATE OR REPLACE FUNCTION strip_prepend_transform(_token varchar,
      						   _strip_digits integer,
      						   _prepend_prefix varchar)
      RETURNS varchar
      AS $$
        DECLARE
          _strip_len		smallint := 0;
        BEGIN
          IF _strip_digits > 0 THEN
      	-- If the strip length given for some reason exceeds the
      	-- actual string length, trim it down so that those digits
      	-- that do exist are still trimmed.

            IF _strip_digits > LENGTH(_token) THEN
              _strip_len = LENGTH(_token);
            ELSE
      	  _strip_len = LENGTH(_token) - _strip_digits;
            END IF;

            _token := SUBSTRING(_token FROM (_strip_digits + 1) FOR _strip_len);
          END IF;

          IF LENGTH(_prepend_prefix) > 0 AND _prepend_prefix <> '' THEN
            _token := (_prepend_prefix || _token);
          END IF;

          RETURN _token;
        END
      $$ LANGUAGE 'plpgsql';

</comment><comment><USER22>
      def random():
        return 4

<comment><AUTHOR> <http://xkcd.com/221/>

<comment><USER22> Oh. my. god. there is a guy on the internet making comics about my life. oO

</comment></comment></comment><comment><USER23> I use the following like so: from($('.foo_element'), 'text')

That way if I change the html structure I don't have to to change a million jquery selectors, I can just change the from function in one place.

        // Access one particular element from another.
        function from(start, end) {
          start = $(start)
          if(start.parent().hasClass('headline') && end == 'node')
            return start.parent().parent()
          if(end == 'nodes')  return start.children('.node')
          if(end == 'headline')  return start.children('.headline')
          if(end.indexOf('.') != 0)  end = '.' + end
          if(start.hasClass('headline'))  return $(start.children(end))
          return start.find('> .headline > ' + end)
        }

(I'm still somewhat new to Javascript, so this may be a well-known pattern.)

<comment><USER24> Maybe I don't understand your use case, but it seems to me your function is masking some other problems. You say you're new to JS, so here's a little unsolicited advice...

If you find yourself retyping the same jQuery selectors over and over, or that the structure changes a lot, then you should be encapsulating that somehow into some other function or object. Instead you're writing a do-it-all function that takes more strokes to type than the original jQuery selectors!

I haven't seen the structure in question, but when I see a class called something very generic like "node", I suspect something else is wrong. If the class isn't specific and at least somewhat meaningful to a person, then you might be solving the problem at the wrong level, using classes when a rethink of the structure might be better.

Also... lack of semicolons is bad style. Lack of braces for if clauses is bad style. Fix it, you'll thank me later. :)

<comment><USER15> "Also... lack of semicolons is bad style. Lack of braces for if clauses is bad style. Fix it, you'll thank me later. :)"

Although a popular opinion, it's still just an opinion -- one I strongly disagree with. Almost all semicolon problems in javascript are not caused by not using them, they're caused by not understanding when they will be inserted. The infamous example:

      function func(param, param2) {
        var meh = 0, gah = 0;

        <some more logic here>;

        return
          { meh: meh
          , gah: gah
          };
       }

Note: using a semicolon did not save you from returning undefined.

My point is that whether you use or don't use semicolons is not the problem. Not understanding when and how they're inserted is the problem.

I also find that people who do not use semicolons have a much better understanding of the few situations where they are actually needed to avoid errors.

</comment></comment></comment><comment><USER25> "src". Takes the name of a variable (usually a function) and searches my source directory for definitions of that variable. The way it recognizes definitions is fairly ad-hoc (it recognizes "def", "mac", "defmemo", and a few others; it doesn't attempt to recognize forms like "(let x 2 (def ...))").

      arc> src.src
      From: /Users/waterhouse/Dropbox/arc3.1/a
      (mac src (name (o strict t))
        `(src-fn ',name
                 ',strict))
      Found 1 results in 1 different files.

"aps". Apropos; derived from the Common Lisp function. Returns all bound variable names of which the supplied argument is a substring.

      arc> aps.mat-
      (fermat-prime mat-add mat-add-mod mat-det mat-det2 mat-expt mat-id
      mat-mod-expt mat-mul mat-mul-mod mat-order mat-trans)

</comment><comment><USER26> A little bit of python that makes it easier to do shell-style scripting.

        def call(cmd):
    	args = shlex.split(str(cmd))
    	p = Popen(args, stdout=PIPE, stderr=PIPE)
    	text = p.stdout.read()
    	if not text:
    		text = p.stderr.read()
    	return text

</comment><comment><USER27> The other
 and print_r()-based solutions don't work quite as well when you're writing an AJAX-based app. I use error_log for everything:

      // PHP error_log() wrapper
      function el($var, $die = true) {
         error_log(var_export($var, true));

         if ($die) {
            die();
         }
      }

Also, Paul Irish's Javascript log() function is amazing. It can be found in boiler plate, but here's the gist:

      // Javascript console.log() wrapper
      window.log = function() {
         log.history = log.history || [];
         log.history.push(arguments);

         if (this.console) {
            console.log(Array.prototype.slice.call(arguments));
         }
      };

</comment><comment><USER28> In multiple languages (perl, haskell), I find myself writing a function that runs a system command and returns False (or sometimes, throws an exception) if it failed nonzero.

Also, in haskell I use these frequently to have monadic versions of some common flow control functions (some nonstandard libraries have similar functions to these but it's easier to write my own):

      whenM c a = c >>= flip when a
      unlessM c a = c >>= flip unless a
      (>>?) = whenM
      (>>!) = unlessM
      -- low fixity allows eg, foo bar >>! error $ "failed " ++ meep
      infixr 0 >>?
      infixr 0 >>!

<comment><USER29> The perl core has a way of detecting non-zero exit statuses:

        $ perl -Mautodie=system -e 'system("/bin/false")'
        "/bin/false" unexpectedly returned exit value 1 at (eval 5) line 13
         at -e line 1

Pretty nice.

</comment></comment><comment><USER30> SetDirectory[ToFileName[({"FileName"} /. NotebookInformation[EvaluationNotebook[]])[[1,1]]]]

Mathematica code. Sets the CWD for file operations for a notebook to the same directory the current file is in. This is not default for Mac OSX.

</comment><comment><USER31> I make lowerTrim and upperTrim functions in any language I work in - <USER3> the case and trim the string. Makes things pretty easy.

        // PHP example
        function lowerTrim($t) {
          return strtolower(trim($t));
        }

I also have matchLeft and matchRight which take two strings and return true if both strings are non-blank and the shorter matches the longer string's prefix/suffix.

My most-used function during debug-phase is pR:

       // especially useful when dealing with PHP arrays/objects
       function pR($a)
       {
         echo '
';
         print_r($a);
         exit;
       }

</comment><comment><USER32> Here is one of my PHP standards... I prefer this to more complex template systems, although the idea is borrowed from Symfony I think. The style I try to adhere to is to only use simple variables and loops in html templates. This is the basic idea:

function render($data, $templateFile) {

        extract( $data );
        ob_start();
        require $templateFile;
        echo ob_get_clean();

}

It turns an array (or DTO object using get_object_vars) into global variables in the template, so this code in a controller

$data->foo = "bar";

Is accessed in the template like this:

<?= $foo ?>

</comment><comment><USER33> JavaScript: Printing to firebug console

      function echo(text)
      {
      	if(!window.console)
      	{
      		alert(text);
      	}
      	else
      	{
      		console.log(text);
      	}
      }

SRC: [http://www.getsocialize.com/static/playground/API%20Playgrou...](http://www.getsocialize.com/static/playground/API%20Playground/js/Harp- JS.js)

PHP: Printing arrays

      function A( $array)
      {
        echo "
"; print_r($array); echo "
";
      }

</comment><comment><USER34>
      // php function for getting an array of filenames for a given directory...

      function dirscan($directory)
      {
        $fileset = array();
        if ($handle = opendir($directory))
        {
          while (false !== ($file = readdir($handle)))
          {
            if (($file != ".") && ($file != ".."))
            {
              $fileset[] = $file;
            }
          }
          closedir($handle);
        }
        return $fileset;
      }

</comment><comment><USER35> This handles my URL vars on almost all of my projects that don't require frameworks.

        //sanitize and return url vars
        function get($fields) {
            if(is_array($fields)) {
                $info = array();

                foreach($fields as $field) {
                    if(get($field) !== false) {
                        $info[$field] = get($field);
                    }
                }

                return $info;
            } else {
                //Single Value
                $field = $fields;

                if(isset($_POST[$field])) {
                    return trim(addslashes(strip_tags($_POST[$field])));
                }
            }

            return false;
        }

And this one has been with me since the first time I had to look up all these details:

        function json_header() {
            header("Expires:" . gmdate( "D, d M Y H:i:s", strtotime("+2 minutes")) . "GMT");
            header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT");
            header("Cache-Control: no-cache, must-revalidate" );
            header("Pragma: no-cache" );
            header("Content-type: application/json");
        }

</comment><comment><USER36> I don't have the exact example here, but I have a PHP function which takes a (newly deprecated) mysql result, and returns an array of rows as associative arrays with the keys lowercased.

I particularly like an alternate version I wrote of that which returns an associative array keyed by a given database field instead of a regular linear array. I don't need it as much, though.

(If this is still active on Monday, I'll post my real code)

</comment><comment><USER37> It annoyed me that in C#, you have to check whether someone is subscribed to an event before raising it. An Extension Method:

        public static bool CheckedRaise<T>(this EventHandler<T> eh, object sender, T e)
            where T : EventArgs
        {
            bool check = eh != null;

            if (check)
                eh(sender, e);

            return check;
        }

<comment><USER4> You probably already know this but another trick is just to assign an "empty" lambda to the event.

        public event SomeDelegate MyEvent = (sender, e) => {};

Or better yet

        public event SomeDelegate MyEvent = delegate {};

<comment><USER37> Yep, but with either of those, it can still be set back to null :)

<comment><USER4> True. I don't use events much but when I do I use the following pattern:

        private SomeDelegate _myEvent = delegate {};

        public event SomeDelegate MyEvent
        {

            add { _myEvent += value; }
            remove { _myEvent -= value; }

        }

<comment><USER37> If I'm not mistaken, that has the same semantics as the standard one line event definition, i.e.:

        public event EventHandler MyEvent;
        // Inside the class, MyEvent is bound to a multicast delegate.
        // Outside the class, MyEvent is bound to an auto-generated add/remove mechanism.
        // So MyEvent can only be set to null or invoked from inside the class.

<comment><USER4> Hmmm, you're right. That's two (C# related) things I learned today.

</comment></comment></comment></comment></comment></comment><comment><USER38> PHP function to perform a basic cURL request and return the result. Got a little bit tired of writing "curl_setopt(...".

<comment><USER39> Typically this is what file_get_contents() is for (with fopen_wrappers enabled) if you just want a simple GET.

<comment><USER40> In newer versions of PHP, you can use `stream_context_create` to make post requests and more, using `file_get_contents`

</comment></comment></comment><comment><USER41> It really only condenses 2 calls down to one, but since I never change some of the parameters, it saves me a bit of time.

      def run( command ):
        process = subprocess.Popen(
          command,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE
        )
        return process.communicate()

</comment><comment><USER42> One line debugger in php. $data is the thing you wish to look at.

        <?php
        echo str_replace('    ', '    ', nl2br(htmlentities(iconv('utf-8', 'utf-8//IGNORE', print_r($data, TRUE)), ENT_QUOTES, 'UTF-8')));
        ?>

<comment><USER31> I just do echo '
' and print_r. Works quite well.

<comment><USER42> unless what your debugging has html in in

<comment><USER31> Very true. Then I do htmlentities or just view-source (which works surprisingly well in Chrome). Usually though it's just arrays and objects for me.

</comment></comment></comment></comment><comment><USER43> For debugging via print statements:

        public int echo(int x, String name)
        {
            System.out.println(name + ":\t" + x);
            return x;
        }

(I also have versions with only x as an argument, and with the other types).

In use:

        this.setPreferredSize(new Dimension(getPreferredSize.getWidth(), echo(getViewportHeight(itemCount), "Viewport"));

In addition to sparing me from System.out.println verbosity, it's really useful in situations like the above where the value you want to print isn't bound to a variable.

</comment><comment><USER44> I wrote this simple Python function to create random strings from various character sets. I wish every NES game that had a password-based save used 'alpha_numeric_hardtoconfuse_lowercase'. There's no telling how many times I've mixed up 1, I, i, and l, pending on the crappy font being used. Same goes with hand-written Windows activation keys.

        # encoding: utf-8
        import random

        CHARACTER_SETS = {
            'alpha':                                                'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',             # 52
            'alpha_lowercase':                                      'abcdefghijklmnopqrstuvwxyz',                                       # 26
            'alpha_uppercase':                                      'ABCDEFGHIJKLMNOPQRSTUVWXYZ',                                       # 26

            'alpha_numeric':                                        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',   # 62
            'alpha_numeric_lowercase':                              'abcdefghijklmnopqrstuvwxyz0123456789',                             # 36
            'alpha_numeric_uppercase':                              'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',                             # 36

            'alpha_hardtoconfuse':                                  'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ',                  # 47 --- Omits: i, l, o, I, O
            'alpha_hardtoconfuse_lowercase':                        'abcdefghjkmnpqrstuvwxyz',                                          # 23 --- Omits: i, l, o
            'alpha_hardtoconfuse_uppercase':                        'ABCDEFGHJKLMNPQRSTUVWXYZ',                                         # 24 --- Omits: I, O

            'alpha_numeric_hardtoconfuse':                          'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789',          # 55 --- Omits: i, l, o, I, O, 0, 1
            'alpha_numeric_hardtoconfuse_lowercase':                'abcdefghjkmnpqrstuvwxyz23456789',                                  # 31 --- Omits: i, l, o, 0, 1
            'alpha_numeric_hardtoconfuse_uppercase':                'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',                                 # 32 --- Omits: I, O, 0, 1

            'alpha_consonants':                                     'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ',                       # 42 --- Omits: a, e, i, o, u, A, E, I, O, U
            'alpha_consonants_lowercase':                           'bcdfghjklmnpqrstvwxyz',                                            # 21 --- Omits: a, e, i, o, u
            'alpha_consonants_uppercase':                           'BCDFGHJKLMNPQRSTVWXYZ',                                            # 21 --- Omits: A, E, I, O, U

            'alpha_numeric_consonants':                             'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ0123456789',             # 52 --- Omits: a, e, i, o, u, A, E, I, O, U
            'alpha_numeric_consonants_lowercase':                   'bcdfghjklmnpqrstvwxyz0123456789',                                  # 31 --- Omits: a, e, i, o, u
            'alpha_numeric_consonants_uppercase':                   'BCDFGHJKLMNPQRSTVWXYZ0123456789',                                  # 31 --- Omits: A, E, I, O, U

            'alpha_consonants_hardtoconfuse':                       'bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ',                        # 41 --- Omits: a, e, i, l, o, u, A, E, I, O, U
            'alpha_consonants_hardtoconfuse_lowercase':             'bcdfghjkmnpqrstvwxyz',                                             # 20 --- Omits: a, e, i, l, o, u
            'alpha_consonants_hardtoconfuse_uppercase':             'BCDFGHJKLMNPQRSTVWXYZ',                                            # 21 --- Omits: A, E, I, O, U

            'alpha_numeric_consonants_hardtoconfuse':               'bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ23456789',                # 49 --- Omits: a, e, i, l, o, u, A, E, I, O, U, 0, 1
            'alpha_numeric_consonants_hardtoconfuse_lowercase':     'bcdfghjkmnpqrstvwxyz23456789',                                     # 28 --- Omits: a, e, i, l, o, u, 0, 1
            'alpha_numeric_consonants_hardtoconfuse_uppercase':     'BCDFGHJKLMNPQRSTVWXYZ23456789',                                    # 29 --- Omits: A, E, I, O, U, 0, 1

            'binary':                                               '01',                                                               # 2  --- Base-2
            'decimal':                                              '0123456789',                                                       # 10 --- Base-10
            'hexadecimal_upper':                                    '0123456789ABCDEF',                                                 # 16 --- Base-16
            'hexadecimal_lower':                                    '0123456789abcdef',                                                 # 16 --- Base-16
            'octal':                                                '01234567',                                                         # 8  --- Base-8
        }

        def random_string(length=32, characters=CHARACTER_SETS['alpha_numeric']):
            random.seed()
            return ''.join(random.choice(characters) for x in range(length))

<comment><USER45> you do realize half of this is already included in builtins, right?

<comment><USER44> No I didn't. Which module? I'll have to RTFM. ;)

<comment><USER46> import string; string.digits, string.lowercase, string.uppercase, string.hexdigits, string.ascii_ _

</comment></comment></comment></comment><comment><USER35> Here are a few bash_profile functions I use often:

        #prints IPs from terminal on OS X
        function ip() {
            IP=`ifconfig -a | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}'`
            echo $IP
        }

        #instantly quits lotus notes
        function kill_lotus() {
            ps auxww | grep -i notes | grep -v grep | awk '{print $2}' | xargs kill -9
        }

<comment><USER47> FWIW, your kill_lotus function is equivalent to:

        pgrep notes | xargs kill -9

</comment></comment><comment><USER48>
       function preint_r($var)
       {
          echo '
';
          print_r($var);
          echo '
';
       }

true genius!

<comment><USER22> I've got the exact same function (also php) but mine is called print_arr() as in array.

<comment><USER32> Heh. Mine is called print_pre.

</comment></comment></comment><comment><USER24> I usually write an isDefined() in JavaScript projects. Testing for typeof foo !== 'undefined' makes me want to vomit.

<comment><USER49> I did the same; I had a simple "def()" and "undef()" function pair, which shrank the code base a tiny bit and made it terribly easy to understand what conditions I was testing for.

Unfortunately, I recently profiled my code and found that those functions were being called an absurd number of times during a moderately complicated page load, so they're gone now. :-(

<comment><USER24> Yeah. Although, in modern browsers, the overhead is really trivial.

I just tried timing it in modern Chrome. The overhead of calling a function like isDefined(), versus typeof x !== 'undefined', seems trivial. On my machine, after 100,000 calls there's a difference of 50ms.

Still, I concede that there are some situations where it would matter, if you were driving an animation. And in older browsers it might matter a lot even in other circumstances.

</comment></comment></comment><comment><USER50> // php function debug_object( $data, $use_var_dump = FALSE ){ echo '
'; if ( $use_var_dump ){ var_dump($data); } else { print_r($data); } echo '
'; }

</comment><comment><USER51> This is a one-line script I use every day to open a text task list, so I've ended up with a directory of well named text files documenting every day I have worked:

$ vim ~/Dropbox/tasks/`date -v-${1-0}d "+%Y%m%d%a"`.txt

</comment><comment><USER52> <?php function getIfSet(&$variable, $default = NULL) { if (isset($variable)) { return $variable; } return $default; } ?>

</comment><comment><USER53> Remove parent links in Wordpress nav using jQuery:

      $('.sub-menu').parent().find('a:first').removeAttr('href').css('cursor','default');

</comment><comment><USER17> A function to fit a rectangular area inside another. I use it whenever I need to fit a view inside a window. Pretty handy.

</comment><comment><USER54>
      * { margin: 0; padding: 0; }

<comment><USER55> Ah, yes. The ol' stop-mucking-with-my-layout line.</comment></comment>