Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: What's your most-used function that you wrote yourself?
58 points by jawns on July 16, 2011 | hide | past | web | favorite | 90 comments
Obviously, I'm looking for relatively short examples.

Interpret "function" broadly.

I wrote a C#/.NET function (extension method) called `Becomes` that I use as a replacement for the various `TryParse` methods.


    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

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/...

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);
         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.

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;
    if(fc != NULL) free(fc);
    /* Other cleanup */
    return NULL;

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)))

Your function isn't close to linear. Here are my benchmarks for 10 iterations of sorting:

     100000 -- 120.469834
      10000 -- 1.218803
       1000 -- 0.019961
        100 -- 0.000958

      100000 -- 0.054125
       10000 -- 0.002993
        1000 -- 0.000302
         100 -- 4.1e-05

Hopefully you've since migrated to Array#shuffle.

"If it ain't broke..."

Doesn't that run in quadratic time - or can delete_at() somehow avoid copying all the tail elements in the array?

I know nothing about Ruby, but it's possible if a language implements an array as a linked list so the tail elements don't actually move. (At any rate, I hardly think we're worried about a modern computer workload of at most 25^2 string operations.)

In that case, it couldn't find the element to delete in constant time.

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}"
I keep it in my .irbrc file, really useful to avoid stepping through command history to find previous commands.

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.

Probably this one, which I use for testing

    function becho($value, $key = NULL)
        echo '<br /><span style="background: #FFFFFF; color: #000000;">' . (NULL != $key ? $key . ' = ' : '') . $value . '</span>';
I also like this one

    function s($num)
         return $num == 1 ? '' : 's';
Which I use like

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

    function echo_r($x){
        echo '<pre>';
        echo '</pre>';

Kinda ugly, but:

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


    (\>) x f = f x
Allows me to write in a more readable manner

        \> map (*2)
        \> filter (<5)

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

Inspired by F#'s |> (which was of course inspired by Unix pipes) ?

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.

A PHP 'get or else' which replaces

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

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 - 1
      , completed = 0
      , callback  = arguments[argLength]
    for (var i = 0; i < argLength; i++) {
      arguments[i](function() {
        (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;
    ( function(cb) { $('#pageContainer').fadeOut('slow', cb); }
    , function(cb) {
          { url: 'page.html'
          , success: function(msg) {
              pageData = msg;
    , function() {
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.

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) {
Then in the class just add:

  @include radius(5px);

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...), but I don't see that behavior in Safari 5. Potentially fixed? If not, I would certainly add that to my boilerplate.

Shouldn't border-radius (i.e., no vendor prefix) be last?

Bourbon does this and much more : https://github.com/thoughtbot/bourbon

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 $$
      _strip_len		smallint := 0; 
      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);
  	  _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;
  $$ LANGUAGE 'plpgsql';

  def random():
    return 4

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

Nine is also a good choice - http://dilbert.com/strips/comic/2001-10-25


i wish...

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.)

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. :)

"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>;

      { 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.

> you should be encapsulating that somehow into some other function or object

Hmm, I believe that's what I'm doing here. This pattern is nice because it's small, simple and easily applied anywhere.

> when I see a class called something very generic like "node"

This is for http://taskranger.com Node is a node in the tree. Might make more sense knowing that.

> lack of semicolons is bad style. Lack of braces for if clauses is bad style.

I'm aware of the consensus, but I'm pretty sure it's wrong :) Semicolons and unnecessary braces create noise and take up space. This subtly harms readability. I've been doing this for about a year and have had no problems.

I do appreciate the suggestions, though.

"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
  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)

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

The other <pre> 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) {
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 || [];
     if (this.console) {

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 >>!

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.

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.

I make lowerTrim and upperTrim functions in any language I work in - change 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 '<pre>';

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 );
    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 ?>

JavaScript: Printing to firebug console

  function echo(text)
SRC: http://www.getsocialize.com/static/playground/API%20Playgrou...

PHP: Printing arrays

  function A( $array)
    echo "<pre>"; print_r($array); echo "</pre>"; 

  // 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;
    return $fileset;

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");

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)

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;

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 {};

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

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; }


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.

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

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

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

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

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(
    return process.communicate()

One line debugger in php. $data is the thing you wish to look at.

    echo str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(iconv('utf-8', 'utf-8//IGNORE', print_r($data, TRUE)), ENT_QUOTES, 'UTF-8')));

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

unless what your debugging has html in in

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.

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.

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

        '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']):
        return ''.join(random.choice(characters) for x in range(length))

Similar, in Ruby:

    module Utils
      extend self
      unless defined?(Utils::VALID_CHARS)
        VALID_CHARS = [("a".."z").to_a, ("A".."Z").to_a, ("0".."9").to_a, %w[* $ ! ? ( )]].flatten
        VALID_CHARS_SAFE.delete_if { |v| %w(i l o 1 0).member?(v) }
      def strand(len=12, safe=true)
        chars = safe ? VALID_CHARS_SAFE : VALID_CHARS
        (1..len).collect { chars[rand(chars.size-1)] }.join

you do realize half of this is already included in builtins, right?

No I didn't. Which module? I'll have to RTFM. ;)

import string; string.digits, string.lowercase, string.uppercase, string.hexdigits, string.ascii_

How come your alpha_numerics don't have any numbers in them?

They do at the end?

The scrolling pane fooled me for a second too.

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 | 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

FWIW, your kill_lotus function is equivalent to:

    pgrep notes | xargs kill -9

   function preint_r($var)
      echo '<pre>';
      echo '</pre>';
true genius!

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

Heh. Mine is called print_pre.

Why have I never thought of this?!

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

I completely agree with you, but I would use "foo === undefined" for locals and "this/window.foo === undefined" for globals. You can also test for "== null", if you don't care for null values.

Of course due to a bug in the old (v3) spec, you could redefine the builtin undefined as well as some other builtins like NaN and Infinity, but you shouldn't really be doing that and the spec at least is now fixed.

In the meanwhile, to fight that, this is a commonly used pattern for browsers: (function(window,undefined) {

// code //


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. :-(

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.

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

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

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

Remove parent links in Wordpress nav using jQuery:


A function to fit a rectangular area inside another. I use it whenever I need to fit a view inside a window. Pretty handy.

  * { margin: 0; padding: 0; }

Ah, yes. The ol' stop-mucking-with-my-layout line.

You wrote this yourself?

Registration is open for Startup School 2019. Classes start July 22nd.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact