Order for SELECT ... IN (5,100,23) queries

When doing a query like this:
SELECT id FROM users WHERE (users.id IN (899,1084,1095,100,2424,2429,2420))

the order of the returned records is undefined. To force the query to return the records in a given order, you have to add ORDER BY FIELD(id, 899, 1084, ...)

So the query looks like this:
SELECT id FROM users WHERE (users.id IN (899,1084,1095,100,2424,2429,2420)) ORDER BY FIELD(id,899,1084,1095,100,2424,2429,2420);

Riding Rails: Rails 3.0: It's ready!

Rails 3.0 has been underway for a good two years, so it’s with immense pleasure that we can declare it’s finally here. We’ve brought the work of more than 1,600 contributors together to make everything better, faster, cleaner, and more beautiful.

Build a JSON API for a Rails application

Try our Apify gem which solves many problems you will be having.

MPEG LA’s AVC License Will Not Charge Royalties for Internet Video That Is Free to End Users Through Life of License | Business Wire

DENVER--(BUSINESS WIRE)--MPEG LA announced today that its AVC Patent Portfolio License will continue not to charge royalties for Internet Video that is free to end users (known as “Internet Broadcast AVC Video”) during the entire life of this License. MPEG LA previously announced it would not charge royalties for such video through December 31, 2015 (see http://www.mpegla.com/Lists/MPEG%20LA%20News%20List/Attachments/226/n-10-02-02.pdf), and today’s announcement makes clear that royalties will continue not to be charged for such video beyond...

mezzoblue's PaintbrushJS at master - GitHub

PaintbrushJS is a lightweight, browser-based image processing library that can apply various visual filters to images within a web page.

epeli / Underscore.strings / source — bitbucket.org

String manipulation extensions for the Underscore.js javascript library.

Automagical ?-methods for boolean attributes in ActiveRecord

This method is defined automatically and only given for boolean attributes

create_table "users", :force => true do |t|
  t.boolean  "email_confirmed"
end

# you may now say:
User.email_confirmed?

Only allow pictures as Paperclip attachments

validates_attachment_content_type :image, :content_type => /^image\/(jpg|jpeg|pjpeg|png|x-png|gif)$/, :message => 'file type is not allowed (only jpeg/png/gif images)'

Forward HTTP through an intermediary server (Local Port Forwarding)

This will tunnel HTTP requests to one given domain and port through an intermediary SSH server:

ssh -L 8080:targethost:80 tunnelhost

http://localhost:8080 will now connect you to http://targethost:80, tunnelling all data through tunnelhost via SSH.

Note that the connection between tunnelhost and targethost will still be unencrypted in this example.

Change default size of Gnome terminal

Open the configuration file:

gksudo gedit /usr/share/vte/termcap/xterm

Find a line like this:

:co#80:it#8:li#24:\

Change the first and last number to your desired columns and rows:

:co#160:it#8:li#40:\

Save your changes and close all open terminals. New terminals should now open with the new size.

Copy a file over SSH

Ubuntu lets you mount an SSH shell into Nautilus from Places -> Connect to server (select "SSH" as server type).

In order to copy a file over SSH from a shell:

scp filename username@remotehost:

The trailing ":" directs the file to username's home directory on the remote host.

You can also copy a file from the remote host to your local machine:

scp remotehost:remotepath localpath

Using screen for long running tasks

Screen is great for long running tasks, where you want to log in every few hours and days and keep your session alive indefinitely.

To create a new screen, do

screen -Rd screenname

This will also reattach an existing screen with that name.

Once you're in the screen, CTRL+A will bring up the menu, d detaches the screen. You can close your shell, screen and all applications running inside of it will remain alive.

Scrolling inside a screen

  • Bring up the menu with CTRL+A
  • Press Esc
  • You can now scr...

Dumping and importing from/to MySQL in an UTF-8 safe way

In a nutshell: to avoid your shell character set from messing with imports, use -r to export and SOURCE when importing.

Dumping safely

# Do not do this, since it might screw up encoding
mysqldump -uroot -p database > utf8.dump # this is bad

Better do:

mysqldump -uroot -p database -r utf8.dump

Note that when your MySQL server is not set to UTF-8 you need to do mysqldump --default-character-set=latin1 (!) to get a correctly e...

UTF-8ify an existing MySQL database

First do

ALTER DATABASE database_name CHARACTER SET "utf8";
ALTER DATABASE database_name COLLATE "utf8_unicode_ci";

After that, for each table:

ALTER TABLE table_name DEFAULT CHARACTER SET "utf8" COLLATE "utf8_unicode_ci";

This just changes the default character set / collation for each table. To convert them, you need:

ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

Count files in a folder

From the shell:

ls -l | wc -l

jeremyevans's home_run at master - GitHub

home_run is an implementation of ruby’s Date/DateTime classes in C, with much better performance (20-200x) than the version in the standard library, while being almost completely compatible.

Using CSS3PIE cross-domain

Currently not possible as the linked .htc file contains JavaScript which is not explicitly called.

The developers are working on a pure JavaScript solution which will have some downsides but work across different domains.

Error installing the raspell gem

When you get this while installing the raspell gem:

ERROR:  Error installing raspell:  
ERROR: Failed to build gem native extension.

You need some libraries:

sudo apt-get install libaspell-dev

Aspell Error - No word lists can be found for the language XY

When you get this error:

No word lists can be found for the language "de".

An aspell dictionary is missing. Install it with

sudo apt-get install aspell-de

Get TinyMCE editor content as HTML

tinyMCE.activeEditor.getContent()

Submit a form with Prototype

For example, to send a form and populate a preview div with the response.

$('content_form').request({
  parameters: { 'preview': "1" }, // overrides parameters
  onComplete: function(transport){ 
    $('previewContent').update(transport.responseText); 
  }
});

Autofocus a form field with HTML5 or jQuery

In Webkit you can use the HTML5-attribute autofocus:

= form.text_field :title, :autofocus => 'autofocus'

Here is a jQuery fallback for browsers that don't speak HTML5:

var Autofocus = {

  supported: function() {
    return 'autofocus' in document.createElement('input');
  },

  fake: function() {
    $('[autofocus]').focus();
  },

  extend: function() {
    Autofocus.supported() || Autofocus.fake();
  }

};

$(Autofocus.extend);

Fixing Webrat after following an external link

When a Cucumber feature leaves your page through an external Link, Webrat has problems like "Could not find field: "E-mail" (Webrat::NotFoundError)" using your page afterwards. It will also have trouble following redirects.

Fix it with this step:

Given /^I am back on my page$/ do
  webrat_session.header("Host", "www.example.com")
end

MySQL replication how-to

This may be awkward to set up, but will work once you're done.

Fun facts:

  • In case of a connection loss the slave will try to reconnect to the master server and resume replication for the next 24 hours
  • If you want to use your slave as a "real" MySQL server, you basically need to switch off replication (STOP SLAVE; RESET SLAVE; and reset your my.cnf) and restart the MySQL daemon.

Master server configuration

  • Create replication user
    : In the MySQL shell:

      CREATE USER 'replicator'@'%' IDENTI...