How to Use the Ls Command on Linux or Mac OS X to Sort Files based on Second in the Timestamp
Here is the one liner.
ls -lhtTr
It will output something like
total 24152
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:42 2019 4c2caf52cb084ea39a6a65a0e68ee382
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:44 2019 76eeeea5d...
Written by Sean Behan on 05/04/2019
How to Use the Ls Command on Linux or Mac OS X to Sort Files based on Second in the Timestamp
Here is the one liner.
ls -lhtTr
It will output something like
total 24152
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:42 2019 4c2caf52cb084ea39a6a65a0e68ee382
-rw-rw-r-- 1 sean staff 1.0M May 4 14:31:44 2019 76eeeea5d...
Written by Sean Behan on 05/04/2019
Super Simple Router for React Without Any Dependencies
Here is some very simple code to render React components dynamically without using a framework or routing library.
It doesn't cover pushState and URL parsing, so in that sense it isn't a routing library. But it does let you render components from othe...
Written by Sean Behan on 11/16/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 Use Python Shutil Make_Archive to Zip Up a Directory Recursively including The Root Folder
The documentation for Python's shutil.make_archive is very confusing. Considering that the arguments to this function only need to be source and destination, makes it even more frustrating to try and reason about.
Here are the relevant docs from the p...
Written by Sean Behan on 05/16/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
How to Emulate Double Tap for Progressive Web Apps (PWA) iOS and Android
The double tap event isn't supported in libraries like jQuery Mobile (out of date anyway). But coding up your own function is very easy.
We will compare time in milliseconds between tap or click, events. The reason for both tap and click events is due ...
Written by Sean Behan on 04/08/2018
How to Filter or Search HTML with Vanilla Javascript - No JQuery Required
The basic approach is to use the `document.querySelectorAll` to match certain elements, then manually set the display property to 'none' or 'block' (or 'inline-block') to hide or show it. Using the `match` method allows us to detect whether or not the sea...
Written by Sean Behan on 01/30/2018
How to Parse Query Strings in PHP
Here is a quick snippet for parsing query strings in PHP. You can use the `parse_url` and `parse_str` methods. `parse_str` will create a variable for you populated with results.
$url = "http://www.seanbehan.com/path/?param=key";
parse_str(parse_url...
Written by Sean Behan on 12/04/2017
Simple Way to Calculate the Odds of Something Happening
Here is a quick way to express a chance of something happening.
This is an example in JavaScript that gives you a 1 in 3 chance of being true.
[true, false, false].sort(function(){ return Math.random() >= 0.5 ? 1 : -1 })[0]
Basically, we popu...
Written by Sean Behan on 11/27/2017
How to Use Named Variables with Postgres and PHP PDO Driver
You can write reusable scripts with Postgres by taking advantage of named variables.
A named variable starts with a `:` in your sql script. Here is an example
select :a_number
You can then use this statement with `psql` and the `--variable` fl...
Written by Sean Behan on 11/11/2017
How to Slugify a String in PHP
Here is a snippet for generating a URL friendly slug in PHP
function slugify($string){
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}
And you can use it in your code like so
...
Written by Sean Behan on 10/26/2017
Apache Rewrite Rule for Mapping to index.php in Sub Folders
Below is an example URL structure with rewrite rules using an Apache .htaccess file.
GET /a/ => a/index.php
GET /a/b/ => a/b/index.php
GET /a/b/c/ => a/b/index.php
This URL mapping will give you pretty URLs in PHP without needing t...
Written by Sean Behan on 10/20/2017
How to Read Response Body HTML with Javascript Fetch Method with React Native
In React Native you see a lot of tutorials and articles using the `fetch` method when interacting with `JSON` APIs. It's great for this and the the pattern looks like this
fetch(url).then((resp)=>{ return resp.json() }).then((json)=>{ console.log(json...
Written by Sean Behan on 07/17/2017
Simple SQL for Counting New Signups
Here is a little snippet that will return new signups (or new records) for today
select id, email, created_at::date date from signups
where email not in (select distinct email from signups where created_at < current_date)
Written by Sean Behan on 07/13/2017
Active Admin Rails 5 undefined method per_page_kaminari
If you run into this error in development, using Rails 5 and Active Admin
NoMethodError - undefined method `per_page_kaminari'
Try the following.
First, make sure you have an initializer in your application.
# in config/initializers/kamina...
Written by Sean Behan on 04/27/2017
Matching email addresses in Javascript
Matching email addresses in Javascript
regex = /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/img
"hello sean@example.com how are you? do you know bob@example.com?".match(regex)
// => ["sean@example.com", "bob@example.com"]
Written by Sean Behan on 03/24/2017
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
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
Turn Off SSL Verification In Ruby
The following code will disable SSL verification when using Open SSL.
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
It is probably not a good idea to do this in production. But if you are just testing on your development
machine it might...
Written by Sean Behan on 03/02/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
How to Fix Line Wrap Bug in iPython Terminal on OS X Mavericks
There is annoying line wrap issue present after installing iPython on OS X Mavericks for the first time. The issue has to do with readline being missing. To fix the problem uninstall iPython, install readline and then install iPython.
pip uninstall ip...
Written by Sean Behan on 10/26/2013
How To Pipe To A Ruby Command Line Application
You need to read from STDIN rather than parse command line arguments.
while $stdin.gets
puts $_
end
Written by Sean Behan on 10/17/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 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
My First Ruby Gem: Hashed_Attributes
I just wrote and released my first Ruby Gem, Hashed Attributes https://rubygems.org/gems/hashed_attributes. It is a very simple ActiveRecord extension for saving variables through a serialized hash. The Gem will let you declare getter and setter methods t...
Written by Sean Behan on 06/17/2012
Backup and Rotate MySQL Databases Simple Bash Script
Make a directory ( it can anywhere ) called baks/mysql
mkdir -p /baks/mysql
Create a file (it can be anywhere) called /root/mysql_backups.sh and put this script in it
#!/bin/bash
# modify the following to suit your environment
export DB...
Written by Sean Behan on 05/16/2017
Link to jQuery Source from Google's CDN
https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js
That is the link to the jQuery source hosted by Google on their CDN. It's probably already cached on client machines so it should be as fast as is possible! You can read more/use other Java...
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
Rails 3 disable_with Does Not Work with Ajax Remote Form_for
It appears that the :disable_with option on the submit_tag form helper method does not behave as expected with remote forms. I'm not sure if this is a bug or not. But the fix is pretty straight forward, but perhaps a little difficult to trouble shoot. Usi...
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
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
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
Yield a Block within Rails Helper Method with Multiple Content_tags Using Concat
To clean up some repetitive html coding in views, pass a block of text to a helper function which will wrap it for you the same way, each and every time. For example, I have a 'help' link which will toggle the display of a block of text if a link is click...
Written by Sean Behan on 06/17/2012
Carrier Email Addresses for Sending SMS over Email
Just for reference, here are the carrier email addresses for sending email as an SMS. Look up the carrier for the phone in question, then send an email in this format [telephonenumber]@[carrier-name.com]
Carrier Email to SMS Gateway
Alltel [10-digit p...
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
Adding Public/Private Key Pairs on Mac OS X and Ubuntu for Passwordless Remote SSH Sessions
On your local machine cd into the .ssh directory in your home "~/" directory. If it doesn't exist you can create it with "mkdir ~/.ssh". Next generate your public/private keys and copy the public key to the remote server.
cd ~/.ssh
ssh-keygen ...
Written by Sean Behan on 06/17/2012
Onchange Event Fired from Select Field in Rails Form
In the view there is a regular Rails form and a javascript function that will be triggered when the country select field is changed. The javascript function will make an ajax request to the country_select url with the country code passed as the id variabl...
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
PHP Paypal IPN Script
Simple script for posting a valid response back to Paypal service after a sale is completed using the Paypal Instant Checkout payment method.
<?php
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $k...
Written by Sean Behan on 06/17/2012
Listing Files and Directories with PHP
Listing all files and directories using PHP 5.
<?php
$files = array(); $dir = dir(".");
while(false!==($file=$dir->read())):
if(($file{0}!=".") && ($file{0}!="~") && (substr($file, -3)!="LCK")
&& ($file!=basename($_SERVER["PHP_SELF"]))):
...
Written by Sean Behan on 06/17/2012
Placing an Authenticity Token in a Rails Form
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Written by Sean Behan on 06/17/2012
Managing Timestamps in MySQL with a Trigger
MySQL doesn't support having two columns with time stamping on both initialization and/or on updating at the same time. It would be nice to be able to do *this* where the created_at column gets the current_timestamp on initialization and the updated_at ge...
Written by Sean Behan on 06/17/2012
Mod_Python and Web.py on Ubuntu
Download
First install mod_python for Apache and then restart/reload the server.
apt-get install libapache2-mod-python
/etc/init.d/apache2 force-reload
apache2ctl restart
Next grab the web.py framework from webpy.org. You can grab the tar or use easy_in...
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
How to Install a Ruby Package without Ri or RDoc
gem install --no-rdoc --no-ri rails
Written by Sean Behan on 06/17/2012
TinyMCE Rich Text Editor: HELLO EDITOR Plugin Tutorial and Example
I wanted to create a button for the TinyMCE Rich Text Editor for Wordpress. It was tough to find good docs on the subject. There are a couple of useful posts out there but in general I found them lacking.
http://codex.wordpress.org/TinyMCE_Custom_Buttons...
Written by Sean Behan on 06/17/2012
Double Click Event Using Prototype Javascript Framework
Super simple to get double click "desktop" like functionality out of Prototype! For some reason, googling it doesn't yield many useful results. http://www.google.com/#hl=en&q=double+click+in+prototype+javascript&aq=f&oq=&aqi=&fp=peEfEjG9pWY :(
Anyway, he...
Written by Sean Behan on 06/17/2012
Change default ssh port number on Ubuntu
Login as the root user or as a user that can execute sudo commands.
#open this file for editing...
vim /etc/ssh/sshd_config
Find the line that reads
Port 22
Change this to an different and an available port number...
Port 8000
Next reload ssh
/etc/...
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
How to Get Your User's SHELL and PATH Information
How to find your user SHELL and PATH on Linux
echo $PATH
echo $SHELL
Which will print the paths to the screen
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
/bin/bash
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
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
Using Prototype to Access Form Data
Prototype has a powerful API for accessing and manipulating the Document Object Model, A.K.A the DOM. The following code will let you interact with a simple web form.
Suppose we have a form that contains hidden/or locked inputs and they need to be update...
Written by Sean Behan on 06/17/2012
Parse for Links with Prototype JS
Parsing for links with the Prototype javascript library is easy. Here is the pattern for finding links
/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^
=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
And to implement it you can loop through your con...
Written by Sean Behan on 06/17/2012
mysql on rails 2.3.2
mysql driver is no longer bundled w/ rails. you'll need to install it yourself w/
sudo gem install mysql
however, on ubuntu (heron) this won't work. issue these commands first
sudo apt-get install libmysql-ruby libmysqlclient-dev
if libmysqlclient-dev...
Written by Sean Behan on 06/17/2012
Rails, SSL, Ubuntu, Apache2 with Phusion on Ubuntu
Here are all the commands for setting up your Rails application to server requests over SSL -on Ubuntu, of course.
There are great resources and tutorials at these websites.
http://www.tc.umn.edu/~brams006/selfsign.html
http://www.tc.umn.edu/~brams006/se...
Written by Sean Behan on 06/17/2012