Swap Two Files on Command Line on Mac OS X

I found a link to how to inline swap using mktemp and a shell function for Ubuntu, but Mac OS X has a slightly different version of mktemp, which requires an “template.XXXXX” to be specified, where “template.” is template text that will always be included, and XXXXX (of whatever length) will have random characters.

That makes the function (included in my .zshrc):

1
2
3
4
5
6
7
8
9
10
11
function swap()
{
  if [ $# -ne 2 ]; then
    echo "Usage: swap file1 file2"
  else
    local TMPFILE=$(mktemp a.XXXX)
    mv "$1" $TMPFILE
    mv "$2" "$1"
    mv $TMPFILE "$2"
  fi
}

And then the usage:

1
swap file1 file2
zsh

Timing Different One-line Implementations of Fibonacci

I decided to time test a few variations of Fibonacci sequence implementation found on StackOverflow. The hash implementation seems incredibly fast, but will generate a stack overflow if trying to generate a sequence member too far (10000 elements for me) from previously accessed values.

The lambda version becomes unusable at about 40 elements for me, with the run times mimicking a Fibonnaci sequence themselves.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# lambda definition
f = -> x { x < 2 ? x : f[x-1] + f[x-2] }

# f[0] takes 0.009 milliseconds, f[20] took 21 ms, f[29] took 326 ms:
20.times do |x|
  duration = time_block { f[x] }
  puts "f[#{x}] took #{duration} milliseconds"
end

# even access times, because previous loops cache the h[k-1] and h[k-2] values
hash_fib = Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }
20.times do |x|
  duration = time_block { hash_fib[x] }
  puts "hash_fib[#{x}] took #{duration} milliseconds"
end

hash_fib.clear

# first hash_fib[2000] call takes 9.368 ms, subsequent calls take hash access time (0.001 ms)
20.times do |x|
  duration = time_block { hash_fib[2000] }
  puts "hash_fib[#{2000}] took #{duration} milliseconds"
end

Methods timed with a variant of Timing ruby code

1
2
3
4
5
6
7
8
9
10
11
12
13
def time_method(method, *args)
  beginning_time = Time.now
  self.send(method, args)
  end_time = Time.now
  (end_time - beginning_time)*1000 # milliseconds
end

def time_block(&block)
  beginning_time = Time.now
  yield
  end_time = Time.now
  (end_time - beginning_time)*1000 # milliseconds
end

Vim Tricks: Append Line Above

Append line above (from command mode)

1
ddpkJ
vim

List Processes Using a Certain Port on a Mac, Open Specific Folders in Finder

Go to a specific folder from within Finder: ⇧⌘G

List all processes communicating on a certain port:

1
lsof -i :3000
mac

Test Code That Sends Rspec Into a Tailspin

I created a simple rspec test for a very basic controller that sent my rspec tests into a memory-sucking tailspin:

1
2
3
4
5
6
describe "GET 'index'" do
  it "should contain this basic text" do
    get 'index'
    response.should =~ /regex to test/
  end
end

Amazingly, this code will result in ruby consuming every byte of memory the OS will allow it to have. The code for “response.should” should be

1
response.body.should =~ /regex to test/

I verified that doing a “.should =~” on TestResponse would cause this problem via rails console. The following lines entered into rails console cause ruby to start consuming memory:

1
2
3
require 'rspec/rails'
response = ActionDispatch::TestResponse.new
response.should =~ //

When fixed, the test returns immediately:

1
2
3
require 'rspec/rails'
response = ActionDispatch::TestResponse.new
response.body.should =~ //

Xhr vs Respond_to and Div vs. Span

<span> is an inline element, valid within a <p> <div> is a block element

Block level elements normally start (and end) with a new line when displayed:

  • <h1>
  • <ul>
  • <p>
  • <table>

Inline elements are normally displayed without starting a new line.

  • <b>
  • <td>
  • <a>
  • <img>

Links I found:

Gracefully Handling Timeouts With AJAX Calls.

Environment: Rails 3, jQuery.

I have a underlying session timeout being tracked in rails and I want to make sure that the client interface doesn’t get ahead of that.

First, we create a function, set_expire, to establish when the expire timeout will occur. Then, we establish a check_timeout function to check if the expire time is passed and redirect to a login page. If set_expire is called again, the expiration time will be moved based on the current time.

These functions will be placed in the static application.js file that we be loaded on every full page load.

app/assets/application.js
1
2
3
4
5
6
7
8
9
10
11
12
var expiration = 0;
var set_expire = function(minutes) {
  expiration = new Date((new Date()).getTime() + minutes * 60000);
}

var check_timeout = function(login_page) {
  var now = new Date();

  if (now >= expiration) {
    window.location = login_page;
  }
}

Next, we initiate the loading of the timeout polling by calling set_expire on document.ready and initiating the polling interval with window.setInterval.

Finally, we create a hook for extending the timeout on ajax calls via the jQuery function .ajaxComplete

app/views/layouts/application.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
<body>
  <% if helper_function_to_check_if_user_is_signed_in %>
    <script>
      $(document).ready(function() {
        set_expire(<%= expire_time_in_minutes %>);
        window.setInterval(check_timeout, <%= timeout_polling_interval %> * 1000, '<%= force_session_timeout_url %>')
        $(document).ajaxComplete(function(evt,xhr,opt) {
          set_expire(<%= expire_time_in_minutes %>);
        });
      })
    </script>
  <% end %>

Links found:

I Botched My Markdown Links. How Do I Fix Them?

I ended up reversing the link text and the urls for markdown links in several of my posts.

Instead of:

1
[description text](http://url.to/go/to)

I had:

1
[http://url.to/go/to](description text)

… which tries to make a link to page on this blog at “go/to”

So, to fix things, I wrote this sed script on my Mac (the ‘.original’ argument is unnecessary on other *nixes).

1
sed -i '.original' 's/\[\(http.*\)\](\(.*\))/[\2](\1)/' *.markdown

If you had to include the ‘.original’ argument, then you have .original files to compare the results to (and that you have to remove).

How to Call Multiple Rake Tasks in a Single Task

I’m fairly new to Rails development in general, so this is a pretty rudimentary task, but I wanted to bundle several tasks into one to quickly prep a demo environment without much intervention (or thought).

I wanted my task to be setup:demo, so I added a setup file called in lib/tasks, called “setup.rake”. The invoke method was used to due to its honoring dependencies.

Bundling this set of tasks together is probably going to make experienced Rails developers cringe, but I’m just packaging it together because I end up running this setup independently anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  namespace :setup do
    desc "Stage the system for a demo"
    task :demo do
      steps=%w(db:drop db:create db:migrate db:seed)
      steps.each do |step|
        puts "Invoking Rake::Task[\"#{step}\"]"
        Rake::Task[step].invoke
      end

      # the following model needs to be reloaded prior to doing
      # the next two tasks
      User.reset_column_information
      Rake::Task["admin:generate"].invoke
      Rake::Task["users:generate"].invoke
    end
  end

Links I found:

Notes for December 18

Links I found:

til