Rails Style Params in Python and Flask
Ruby on Rails does a great job of parsing arrays in form data and populating a params hash, for quick and easy access in your controllers. For instance Gives you params[:item] # => ["item 1", "item 2"] Flask doesn't do this work f...
Written by Sean Behan on 11/04/2018
How to Reset and Clear a Form Field or Textarea with Stateless Components in React
Stateless components are nice. They are simple to use and understand but can become tricky when you start thinking about data and how to manage state. In general, the consensus seems to be that if your UI is going to need state, then at least the componen...
Written by Sean Behan on 10/21/2018
Parsing URL Parameters with Swift
Here is an extension you can use in your Swift (v4) projects that makes it easy to parse parameters from a url. Given a url like, "http://example.com/?x=1&y=2", you can extract the x and y parameters into a key, value data structure. Here is the s...
Written by Sean Behan on 09/23/2018
How to Handle Uploading Really Large Files in PHP
PHP has some default limits that do not work out of the box when you want to work with uploading very large files. So there are a few configuration changes you have to make to the defaults that come with PHP. These are defined in you php.ini file. The...
Written by Sean Behan on 09/20/2018
How to Chunk Large Files in Swift
How to Chunk Large Files in Swift (4.1) It takes a bit of work but this is the solution I found that finally worked, thanks to this Stack Overflow thread https://stackoverflow.com/questions/46464177/split-data-in-chunks-and-upload-to-server The example ...
Written by Sean Behan on 09/15/2018
How to Get GPS Location Information from Address String with Swift and iOS CLGeocoder
You can use CLGeocoder geocodeAddressString method. It will return an array of CLPlacemark objects that contain gps coords and city, location info. let address = "Burlington, Vermont" CLGeocoder().geocodeAddressString(address, completionHandler...
Written by Sean Behan on 06/11/2018
How to Get GPS Location Information from a Photo or Movie with Swift and UIImagePickerController
This code assumes you're using the UIImagePickerController. If not you will need to get an image url another way. But, If you are using UIImagePickerControllerDelegate then it will supply the asset's url in the `info` dictionary . From the asset's url...
Written by Sean Behan on 06/11/2018
How to Dynamically Call a Method from a String in Swift
You have to subclass NSObject class Car : NSObject { func drive(){ print("Driving..") } } let car : Car = Car() car.perform(NSSelectorFromString("drive"))
Written by Sean Behan on 06/09/2018
How to Check if Your iOS or MacOS App is Connected to the Internet
Is your app connected to the internet? You can use this standalone class to check! There are no dependencies so you can copy/paste it into your project without needing to install another framework. With this class it's as simple as running `Reachabili...
Written by Sean Behan on 06/08/2018
How to Flush or Erase Cache of Your XCode iOS or MacOS Cocoa App
If you're working with an XCode application, either iOS or MacOS, and want to do a completely clean build and delete the cache, it's simple. Execute this command from the command line.. defaults delete your.apps.bundle.id Where "your.apps.bundl...
Written by Sean Behan on 06/08/2018
How to Just Get SQL Statement Error with SQLAlchemy Python Database Wrapper
If you're working with SQLAlchemy, the best database driver for Python, and want to see only SQL syntax errors, you need to use the StatementError exception class. On it, is an attribute `orig`, that contains just the SQL syntax error... and not any data...
Written by Sean Behan on 05/10/2018
Extension for Encoding and Decoding Strings in Base64 in Swift
Here is an extension to base 64 encode and decode strings in Swift (3) extension String { func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: ....
Written by Sean Behan on 05/02/2018
Using Selenium to Drive Firefox Browser for Web Automation
There are a lot of practical uses for automating user behavior in a browser. Everything from testing your web application to logging into Twitter and auto following people. But first you have to install the tools. Here is everything you need to run yo...
Written by Sean Behan on 03/09/2017
How to Import/Export a Database from One Heroku App to Another Heroku App
Heroku is awesome! Let's say we want to copy a production database to a staging database. We can use the `pg:backups:restore` command to accomplish this. Here is an example. For the source database we are using the `production-app-name` and for stagi...
Written by Sean Behan on 03/07/2017
Trigrams, Bigrams and Ngrams in Python for Text Analysis
Creating trigrams in Python is very simple trigrams = lambda a: zip(a, a[1:], a[2:]) trigrams(('a', 'b', 'c', 'd', 'e', 'f')) # => [('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e'), ('d', 'e', 'f')] You can generalize this a little bit more ...
Written by Sean Behan on 03/06/2017
How to Enable UUIDs in Postgres
The first thing you'll need to do is enable the extension create extension "uuid-ossp"; To test that it's working select uuid_generate_v1(); For more info on which version of the algorithm you should use refer to the documentation. ...
Written by Sean Behan on 03/03/2017
Extract Domain Names From Links in Text with Postgres and a Single SQL Query
This query and pattern will return urls in text all within a single SQL query. select substring(column_name from '.*://([^/]*)') as domain_name from table_name; And here it is in a larger query, say for retrieving page view counts for referrers. ...
Written by Sean Behan on 11/23/2013
Python String Format Precision of Float
You can use string interpolation in combination with a dictionary for simple formatting. print "My name is %(name)s and I have $%(change)0.2f in change in my pocket!" % { 'name': 'Sean', 'change': 00.23 } # My name is Sean and I have $0.23 in chang...
Written by Sean Behan on 11/20/2013
Change the Default Controller Name in Rails Functional Tests
Rails will infer the controller you want to test from the class name of the test case. For example... class PeopleControllerTest < ActionController::TestCase end will test the app/controllers/people_controller.rb. To change this is trivial. Us...
Written by Sean Behan on 10/23/2013
How to Boot Up Multiple Sinatra Applications at the Same Time with Foreman
Foreman is a process management gem for ruby applications. It is used in combination with a Procfile for configuration instructions. A typical Procfile looks something like this [name] : [script to execute] Example Rack application Procfile ...
Written by Sean Behan on 10/15/2013
How To Increase or Change the File Upload Size in the PHP ini file for Wordpress
You need to find which configuration ini file has been loaded by PHP. The easiest way to do this is to run the phpinfo() function from the command line. php -r "phpinfo(); " | grep -i "loaded configuration file" You should see something like...
Written by Sean Behan on 08/24/2013
A Regular Expression to Generate Dash Separated Slugs AKA Pretty URLs
This regular expression matches non alphanumeric characters in a string. r = /[^a-z0-9]{1,}/i You can use it to create URL friendly slugs. slug = "hello world!".gsub(/[^a-z0-9]{1,}/i, '-').downcase # => hello-world In combination wit...
Written by Sean Behan on 08/22/2013
How to Extract the Title From an HTML Page with Ruby
This snippet will make a request to this page and extract the title from the title tag. require 'open-uri' html = open('http://www.seanbehan.com/how-to-extract-the-title-from-an-html-page-with-ruby').read title = html.match(/(.*)/) { $1 } pu...
Written by Sean Behan on 08/22/2013
Deploying Wordpress on Heroku
> This post is out of date - Heroku officially supports PHP now w/ buildpacks Heroku runs Apache version 2.2.22 PHP version 5.3.10 Deploying Wordpress to Heroku requires that you throw the Wordpress source into a Git repository. So download th...
Written by Sean Behan on 03/02/2017
Installing Ruby with RVM without Xcode using CLANG
I am not using the full Xcode package on my laptop. Instead I'm using the command line tools, offered by Apple as a separate and much smaller install. I haven't had too many issues, aside from not being able to use the FileMerge program that ships with ...
Written by Sean Behan on 06/24/2012
How to Add Additional Sub Directories to the Default Rails Test:Unit File Structure
# Edit Rakefile in project root # # Add a new rake test task... E.g., rake test:lib, below everything else in that file... # Alternatively, add a task in lib/tasks/ directory and plop in the same code namespace :test do desc "Test lib source" ...
Written by Sean Behan on 06/17/2012
Transform Matching Text with Gsub in Ruby and Regular Expression
Here is a gist that demonstrates how easy it is to transform text using #gsub and a block with Ruby. "Scs Epc Score".gsub (/scs|epc/i) { |i| i.upcase } # => SCS EPC Score For more helpful string extensions in Ruby check out our Ruby Gem on GitHub...
Written by Sean Behan on 06/17/2012
Rails Send_File in Production Delivers an Empty File
If you're running Rails in production it will by default be configured to let apache or nginx send files for you. If you're handling file downloads yourself with send_file send_file("path/to/file.txt") you will notice that the downloaded files are empty...
Written by Sean Behan on 06/17/2012
Simple String Concatenation of a Collection Written as a Helper for Rails
At Railsconf last week I took Greg Pollack's online course Rails Best Practices. The interface is gorgeous and the instructions are excellent. One of the lessons involved taking a partial and moving it into a helper. I was reminded how difficult such a si...
Written by Sean Behan on 06/17/2012
How to Copy and Paste to/from the Global Register with Tmux on Mac OS X
Using the system clipboard with tmux on OS X is broken. I really like tmux but having copy and paste is kind of important for me. Here is my attempt to get it back with a simple bash script until I find something better. The approach is to take a named pi...
Written by Sean Behan on 06/17/2012
Installing Ruby on Rails 3, MySQL, Git, Ruby Enterprise Edition, Passenger (Mod_Rails) on Ubuntu with Rackspace Cloud.
Short and sweet. Here all the commands I run in this order to set up a brand new box. It usually takes about 10 - 15 minutes on a 256 MB RAM instance. Compiling Ruby Enterprise Edition, which is super easy, will take the most amount of time. It will seem ...
Written by Sean Behan on 06/17/2012
Execute Javascript When Using Link_to_function To Include a Partial in Rails
If you use the link_to_function to replace content in a div with content from a partial, any javascript that you include in the partial will not be executed. It is instead included, but will do nothing. Obviously, this isn't the desired behavior. Why woul...
Written by Sean Behan on 06/17/2012
Rails Select Tag and Onchange Event Calling a Remote Function with Default Option Selected
Here is a little code snippet that will fire off a request to update_client_path when you change the select field. This stands alone, rather than being apart of a larger form. The Client::CATEGORY argument is a hash, which I populated manually in my Clien...
Written by Sean Behan on 06/17/2012
Ruby Enterprise Edition and Passenger ./script/console production fails and instead returns Loading production environment (Rails 2.3.5) Rails requires RubyGems >= 1.3.2. Please install RubyGems and try again: http://rubygems.rubyforge.org
After installing Ruby Enterprise Edition, REE, and Passenger on Ubuntu you may see this error message when you run script/console for the first time ./script/console production # => Loading production environment (Rails 2.3.5) Rails requires RubyGems >=...
Written by Sean Behan on 06/17/2012
Installing and Using Rvm on Mac OS X, Creating Gemsets and Reverting to Original Environment
What is RVM and why should you use it? RVM is a Ruby interpreter, version management tool. In short, it enables you to switch between different versions and releases of Ruby (for instance, version 1.8.6, 1.8.7, jruby 1.9.2, ruby enterprise edition) on the...
Written by Sean Behan on 06/17/2012
Collection Select Helper and OnChange Event in Rails
Given a collection of Active Record objects, you may use the collection_select helper method to produce a select form field. You need to pass in a number of arguments to the helper function. 1) object - your model object used in the collection 2) method ...
Written by Sean Behan on 06/17/2012
Repost
This post is inspired by http://pupeno.com/blog/really-resetting-the-database/#comment-1179. But as my blog mostly serves as a reference for my future self, I'd like to reprint this little snippet of code here as well. namespace :db do desc "Crush a...
Written by Sean Behan on 06/17/2012
The Context of Markup vs Expressions of Equality in Determining the Meaning of Angled Brackets
In the Wordpress editor (html mode) you'll need to become friends with < and > if you plan on showing any code (php, html... xml, most languages actually) that readers will want to understand. I never thought about it, but assumed that the lt and...
Written by Sean Behan on 06/17/2012
Simple Activity Stream Implementation in Rails
There are many ways to tackle the Facebook style activity stream feature for your app. The simplest approach, which you can tack on at almost any moment, is what I'll describe here. You don't have to create a new model for news feed items or create any po...
Written by Sean Behan on 06/17/2012
TODO and Custom Annotations in Rails Applications
While writing software it's common to leave comments for your future self. For instance, if you have written some code but realize that it should be refactored to be more efficient, you may place something along the lines of "TODO: change active record fi...
Written by Sean Behan on 06/17/2012
Deploying to Dreamhost
Remember to include the host declaration in the database.yml file when you deploy to Dreamhost. Dreamhost does not use "localhost" which is typically the default setting when using the mysql adapter and developing locally or even on a small site. At lea...
Written by Sean Behan on 06/17/2012
Moodle's Most Important Function Gets No Attention
Arguably the most important function in the Moodle API, is the create_course function. One would think... after all Moodle is an LMS. Courses are the bread and butter for course management platforms, right? Taking a look at the function in the course/lib....
Written by Sean Behan on 06/17/2012
Recursively Zip Up a Directory while Excluding Certain Files Based on File Extension Type
In the example below, I'm going to zip up a directory that includes images in both PNG and PSD file formats. However, I want to exclude the PSDs because they are huge! zip -r my-compressed-dir-without-psd.zip directory-to-zip -x '*.psd'
Written by Sean Behan on 06/17/2012
Uncompress A Bz2 File Using Tar Command
Uncompress a bz2 file using tar command tar --use-compress-program bzip2 -xvf your-file-to-uncompress.tar.bz2 @source http://www.kde.gr.jp/help/doc/kdebase/doc/khelpcenter/faq/HTML/bzip2.html...
Written by Sean Behan on 06/17/2012
Get Child Categories of Parent Category on Single Post in Wordpress
I was hoping to find a function in the Wordpress API, that goes something like this... the_child_categories("Vermont"); // print Burlington, Brattleboro... etc if this post has any child categories of Vermont But I could not. The result that I did ...
Written by Sean Behan on 06/17/2012
Offset an Element with Relative Position Property with CSS Without Taking Up Any Space in the Document
Using CSS positioning it's possible to offset an element and collapse its width and height where it would normally appear. Wrapping the content in an absolute positioned element, the space that the element would normally take up is collapsed. <div st...
Written by Sean Behan on 06/17/2012
Thematic Function Reference
I could not find a listing of all thematic theme functions for Wordpress online. So the following is just a recursive grep of the thematic directory. grep -rh "function thematic_" * Each function needs to prepended with "thematic_" when adding as a actio...
Written by Sean Behan on 06/17/2012
Very Simple Breadcrumb Navigation in Rails with Before_filter
This may not be the ideal solution. This just manages request.referers in a session variable, then looping over each unique path prints a link to the screen. It's more of a "history" than a hierarchy for resources in an application. It is however, pretty ...
Written by Sean Behan on 06/17/2012
Installing RedMine PM Software on Apache with Phusion and REE and Seeing a 404 Page Not Found Error on Installation
If you follow the instructions on how to install the Rails Redmine PM Software (available here) and are using Apache with Passenger (REE), you need to delete the .htaccess file that is kept in RAILS_ROOT/public directory. Otherwise you'll see a 404 page n...
Written by Sean Behan on 06/17/2012
Change database column names for form validations in Rails
When you use validations in Rails, db column names are used as 'keys' for error messages. This is usually the preferred way to go about it because this maps nicely to the form fields. However, if you use a virtual attribute this may not be the case. For e...
Written by Sean Behan on 06/17/2012
Defining Application Constants for Ruby on Rails Application
The best place to keep application constants which are environment specific is in config/environments directory. For instance... # in RAILS_ROOT/config/environments/development.rb APP_DOMAIN = "localhost" # in RAILS_ROOT/config/environments/production.rb...
Written by Sean Behan on 06/17/2012
Rails Plugin Acts as Taggable on Steriods
You can download it here http://github.com/suitmymind/acts-as-taggable-on-steroids as well as read usage info (which is for the most part reprinted here). ./script/plugin install http://svn.viney.net.nz/things/rails/plugins/acts_as_taggable_on_steroids ....
Written by Sean Behan on 06/17/2012
Install and Serve a Rails Application from PHP Subdirectory Using Apache, Phussion Passenger and Ruby Enterprise Edition
Here is how to install a Rails application out of a subdirectory (rather than as a subdomain) with the Apache web server(Apache2). In this example I'm going to use my own blog which is a Wordpress installation and serve a Rails application from the subdir...
Written by Sean Behan on 06/17/2012
Using the PHP Mail Function with Additional Headers
Pass a fourth parameter to the mail() function with the header information. <?php $to = "jane@example.com"; $subject = "Hello World!"; $body = "This will be sent from email-addr@example.com"; $headers = "From: email-addr@example.com\r\nX-Mailer: php";...
Written by Sean Behan on 06/17/2012
Grab a Twitter Status without the Twitter API
Quick and dirty way to grab the users status messages without having to go through the twitter api (not having to authenticate that is). You can grab the RSS feed and indicate the number of statuses returned with the count param. I wrote this function for...
Written by Sean Behan on 06/17/2012
Me in 3D
My friend Andy made this 3D rendering of me using LIDAR (Laser Detection and Ranging). In the first image you can see me holding up my hand along with a number of file cabinets. The cube in the center is a table used to calibrate the device. In this sh...
Written by Sean Behan on 06/17/2012
Ruby on Rails, jQuery and YUI API Docs Available as Mac OS X Dictionary Binaries
I came across an awesome tool this morning. Priit Haamer has chunked Ruby on Rails, jQuery, and some of YUI documentation into native Mac OS X dictionary binaries. This lets you search those API docs from Spotlight, TextMate, any application that uses the...
Written by Sean Behan on 06/17/2012
My First Data Visualization McCain V. Obama Election Results
Here is my first data visualization. I used the Processing programming language and an SVG map of the United States. ...
Written by Sean Behan on 06/17/2012
Reading, Writing, Removing Files and Directories in Ruby
These aren't all of them, but I think they are some of the most useful. # making a directory in another directory that doesn't yet exist... FileUtils.mkdir_p '/path/to/your/directory/that/doesnt/exist/yet' # recursively remove a directory and the conten...
Written by Sean Behan on 06/17/2012
Accessing Links in Nested TD Cells with Prototype
There must be a better way to do the following with PrototypeJS. I want to loop over nested links inside of table td cells and apply a class to the row that the link is in when the link is clicked. If a user clicks on another link the class will be remov...
Written by Sean Behan on 06/17/2012
Rails Paperclip Plugin Options for Attaching Files
I usually change some of the default settings when I use the Paperclip plugin. For most of my projects I don't like having separate directories for each image that is uploaded. I prefer, in this instance, to put avatars of different sizes together under o...
Written by Sean Behan on 06/17/2012
link_to_function Rails Ajax Reference
Link_to_function syntax for Haml template. Notice the "|" pipe which will allow for new lines in your code. = link_to_function( "Add Line Item") | {|page| page.insert_html :bottom, :invoice_line_items, | :partial => "line_item", :locals=>{:line_item=...
Written by Sean Behan on 06/17/2012
Python Zlib Compress DeCompress
import zlib regular_string = 'this is my string' compressed_string = zlib.compress(regular_string) decompressed_string = zlib.decompress(compressed_string) print compressed_string print decompressed_string
Written by Sean Behan on 06/17/2012
Installing Scala on Mac OS X Leopard
I followed the instructions from here http://arvinderkang.com/2009/09/01/installing-scala-on-snow-leopard/ but I used version 2.7.6 (rather than .5) I installed scala under /usr/local/scala so I had to include it to my path. Type vim .bash_profile expor...
Written by Sean Behan on 06/17/2012
Cool Conditional Syntax in Ruby (on Rails)
Ruby is beautiful @posts = if true Post.all else [] end Simply elegant!
Written by Sean Behan on 06/17/2012
Deploy Sintra App on Ubuntu Using Apache2 and Phusion Passenger Module
Check it out http://sinatra.seanbehan.com/ This assumes Apache2 and the Phusion Passenger module have already been installed. If not you can get up to speed w/ this resource http://seanbehan.com/ruby-on-rails/new-ubuntu-slice-apache-mysql-php-ruby-on-rail...
Written by Sean Behan on 06/17/2012
Using sendmail to send mail on ubuntu box
I normally install postfix for my MTA. However, I've never really used sendmail so I'd decide to give it a whirl for a new application I'm working on. I don't use it for anything but handling the mail that the application needs to send out, like new user ...
Written by Sean Behan on 06/17/2012
Problem slash Bug in Rails with attr_accessor and Datetime Select Fields
Looks like there is a problem with using the attr_accessor method with datetime form fields http://dev.rubyonrails.org/ticket/8983 In Rails 2.3.2, for me at least, the problem seems to be popping up again. While trying to process a date for credit card v...
Written by Sean Behan on 06/17/2012
Trouble Using Attr_Accessor in Rails Models and Forms
You might use the attr_accessible method to create getters and setters for a class that has attributes which don't map directly to corresponding fields in a database. For example let's take the scenario where you are processing a credit card transaction. ...
Written by Sean Behan on 06/17/2012
Gem Information with Gem List
If you want to get version information about a gem the easiest way to do it is with this command gem list For example gem list activemerchant will output the activemerchant versions I have installed. You can pass only part of the name like gem list ...
Written by Sean Behan on 06/17/2012
Make Rails Lib Module Methods Available to Views
If you create a module in the lib/ directory of your Rails application you won't have access to those methods in your views. If you don't want to put those methods in a helper file, you need to add a method to your module that makes them available for you...
Written by Sean Behan on 06/17/2012
Email Obfuscation and Extraction from Text with Rails
There is a helper method for handling the obfuscation of email addresses in Rails. mail_to "me@domain.com", "My email", :encode => "hex" # => My email If you want to then extract an email address(or all email addresses) from a block of text here is the...
Written by Sean Behan on 06/17/2012
Postfix, ActionMailer and OpenSSL Fix on Ubuntu
If you run into problems using ActionMailer > 2.2, Postfix and OpenSSL while sending mail from your application, try changing the following: vim /etc/postfix/main.cf Change smtpd_use_tls=yes to smtpd_use_tls=no OpenSSL support with Postfix does ...
Written by Sean Behan on 06/17/2012
Rails: Expiring a cached page with namespaces and sweepers
I've got some pages that are cached using their permalinks on the filesystem, such as http://example.com/about-us.html which will need to map to RAILS_ROOT/public/about-us.html ... The issue I have is that I use a namespace for the admin area and the cont...
Written by Sean Behan on 06/17/2012
Rails Migrations and Auto Incrementing Migration Prefix Number
In your environment.rb file turn off timestamped migrations like so: config.active_record.timestamped_migrations = false
Written by Sean Behan on 06/17/2012
Sample Rails Database Config for MySQL
Sample Ruby on Rails database config file for connecting to mysql. production: adapter: mysql encoding: utf8 reconnect: false database: db_production pool: 5 username: db_user password: db_password #socket: /tmp/mysql.sock #this may vary ...
Written by Sean Behan on 06/17/2012
Rails Prototype JS and TinyMCE Autosave
TinyMCE is a nice little WYSIWYG for text processing online. It uses iFrames and Javascript callbacks to manipulate textarea form fields. Using it with Rails can be somewhat problematic if you want to set up an observer on a field that TinyMCE is managing...
Written by Sean Behan on 06/17/2012
Validate Uniqueness on Join Tables in Rails
How to validate uniqueness in a :has_many :through relationship with Ruby on Rails. You'll need three models in this example List, Subscriber and ListSubscriber. A list has many subscribers and a subscriber has many lists. Simple enough. Running the follo...
Written by Sean Behan on 06/17/2012
upgrading to latest phusion passenger 2.1.2
super easy gem install passenger passenger-install-apache2-module will walk you through the install and remember to copy paths to your apache config file. for passenger i kept it in mods-available/passenger.conf and then linked it to mods-enabled ln -s...
Written by Sean Behan on 06/17/2012