data snippets

How to store form data in a cookie with jQuery and the cookie plugin

Tagged data, persist, jquery, form, cookie  Languages javascript
/**
 * Makes form data persistent by storing the data in cookies.
 */
(function($){
  /**
   * Load value from cookie, and set cookie when value is changed.
   */
  $.fn.persist = function(namespace) {
    if(!namespace) {
      namespace = "";
    }
    return this.each(function() {
      var $this = $(this);
      var id = $this.attr('id');
      var cookie_name = namespace + id;
      var value;

      // Store changes in a cookie
      $this.change(function() {
        $.cookie(cookie_name, $this.val());
      });

      value = $.cookie(id);
      // Don't overwrite value if it's set
      if(!$this.val()) {
        $this.val(namespace + value);
      }
    });
  };
})(jQuery); 

$(document).ready(function(){
  $('.persistent').persist();
});

How to create random data with Postgres

Tagged postgres, random, data  Languages sql

This example creates random data from a predefined list of valid values:

insert into transactions(description, price, timestamp) values(
  ('{Bought cat,Bought dog,Bought house}'::text[])[ceil(random()*3)],
  ('{10,20}'::int[])[ceil(random()*2)],
  NOW() - '1 day'::INTERVAL * ROUND(RANDOM() * 100)
)