dideler
3/26/2013 - 12:41 AM

Various snippets of code. Enjoy!

Various snippets of code. Enjoy!

#!/usr/bin/env bash

# The cd ensures this script is executed from the project's root
# directory, regardless of where this script is called!
#
# Source: https://github.com/github/scripts-to-rule-them-all

cd "$(dirname "$0")/.."

script/bootstrap
script/test
# Retrieves the current (Eastern) time from the US Naval Observatory Master Clock.

url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl'

import urllib2
for line in urllib2.urlopen(url):
  if 'EST' in line or 'EDT' in line:
	  print line

import requests
for line in requests.get(url).text.split('\n'):
  if 'EST' in line or 'EDT' in line:
    print line
// Examples of how you can time your benchmarks.

#include <ctime> // time_t, time, difftime, ctime
#include <chrono> // C++11
#include <iostream>
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::time_point;
using std::chrono::steady_clock; // Suitable for measuring intervals.
using std::chrono::system_clock;
using std::cout;
using std::endl;

int main
{
  // Human-readable time and date.
  time_t start_time = system_clock::to_time_t(system_clock::now());
  cout << "Started at " << ctime(&start_time) << endl; // e.g. Sat Jun 16 20:42:57 2013
  
  // Measure an interval in whole seconds.
  time_t start, stop;
  time(&start);
  doProcessing();
  time(&stop);
  cout << difftime(stop, start) << endl; // e.g. 5
  
  // Measure an interval in milliseconds (converted to seconds by dividing by 1000.0).
  time_point<steady_clock> start, stop;
  start = steady_clock::now();
  doProcessing();
  stop = steady_clock::now();
  cout << duration_cast<milliseconds>(stop-start).count() << endl; // e.g. 5312
}
--title Example Title
--author Your Name <email@example.com>
--date today
--## or put a static date (this is a comment BTW).

--horline

--withborder

--fgcolor black
--bgcolor white

--## You can "pause" with ---
---

--## colors: red, white, green, blue, cyan, magenta, yellow, black, ...
--## the set color will continue to be used on following slides unless changed

--boldon
--color red
--center Give a man a fish and you feed him for a day
--center Teach a man to fish and you feed him for a lifetime
--boldoff

--color magenta



                                                                      ___
                                                        ___======____=---=)
                                                      /T            \_--===)
                                                      L \ (@)   \~    \_-==)
                                                      \      / )J~~    \-=)
                                                        \\___/  )JJ~~    \)
                                                        \_____/JJJ~~      \
                                                        / \  , \J~~~~      \
                                                        (-\)\=|  \~~~        L__
                                                        (\\)  ( -\)_            ==__
                                                        \V    \-\) ===_____  J\   \\
                                                                \V)     \_) \   JJ J\)
                                                                            /J JT\JJJJ)
                                                                            (JJJ| \UUU)
                                                                            (UU)

--color black

--newpage page name is optional
--heading heading is the same as title

* 1 (numbered list)
* 2
  * 3 (nested list)
  * 4
    * 5
    * 6

--##huge shows huge text, requires FIGlet
--##sethugefont mini (you can change FIGlet fonts)

--center this text is centred

--right   ___======____=-
--right /T            \_-
--right L \ (@)   \~    \
--right  \      / )J~~   
--right   \\___/  )JJ~~  
--right    \_____/JJJ~~  
--right    / \  , \J~~~~ 
--right   (-\)\=|  \~~~  
--right   (\\)  ( -\)_   
--right    \V    \-\) ===
--right           \V)     

--## left justified is default, there is no --left

a paragraph of text
  whitespace   is   preserved

--newpage
--heading yet another page

--beginslideleft
 - this is not a real list, but close enough
--endslideleft

--beginslidetop
look out below!
--endslidetop

--beginslideright
i'm coming from the right
--endslideright

--beginslidebottom
who's up there?
--endslidebottom

--newpage
--beginshelloutput
$ any line beginning with $ in shell output is typed
this line will not be typed
---
$ this line will be typed after a pause
the end
--endshelloutput

--beginoutput
like shelloutput, this is enclosed in a "terminal"
but unlike shelloutput, it's not "typed"
--endoutput

--newpage text_formatting
--revon
this should have the bg and fg colours reversed
--revoff

--ulon
this should be underlined
--uloff

--##exec echo "this is exec output" -- doesn't work
--##exec fbi ~/Pictures/csc-mascot.png

--newpage
--footer a buggy footer, doesn't go away on new slides!

--center Fish is fast, the auto-completion is amazingly helpful, and it's intuitive to use without too much configuration. Give it a try
# A simple way to estimate a square root (if you cannot use a sqrt function).
#
# Example usage (prompts for the number if none passed as argument):
#   $ python sqrt.py 12313
#   estimated = 110.963958113, actual = 110.963958113

from __future__ import division
import math
from sys import argv

def newtons_method(num):
    """Newton's Method for finding a square root.
    http://www.quora.com/Mathematics/How-can-I-find-the-square-root-of-22-without-a-calculator
    """
    guess = num / 10 # An arbitrary guess, we need to start somewhere.
    for _ in xrange(10):
        guess = 0.5 * (guess + (num / guess)) # Improve the guess.
    print 'estimated = {}, actual = {}'.format(guess, math.sqrt(num))

try:
    num = int(argv[1])
except:
    num = input('Enter a number: ')
newtons_method(num)
# Open a file in its default application.

import os, subprocess

def openfile(filepath):
  if sys.platform.startswith('darwin'):
    subprocess.call(('open', filepath))
  elif os.name == 'nt':
    os.startfile(filepath)
  elif os.name == 'posix':
    subprocess.call(('xdg-open', filepath))
#!/usr/bin/env python
#
# Naive recursive search for path traversal in a simple maze.
#
# Usage:
#
# $ python maze.py 
#   S # # # # #
#   . . . . . #
#   # . # # # #
#   # . # # # #
#   . . . # . G
#   # # . . . #
#
#   S # # # # #
#   o o . . . #
#   # o # # # #
#   # o # # # #
#   x o o # o G
#   # # o o o #

maze = [['S','#','#','#','#','#'],
        ['.','.','.','.','.','#'],
        ['#','.','#','#','#','#'],
        ['#','.','#','#','#','#'],
        ['.','.','.','#','.','G'],
        ['#','#','.','.','.','#']]

def find_path(x, y):
    """ Finds a path through our character-based maze (stored in a 2D list).

    Uses recursion. See www.cs.bu.edu/teaching/alg/maze for more details.
    """

    if x < 0 or y < 0 or x > 5 or y > 5: return False  # If outside maze.
    if maze[x][y] == 'G': return True  # If found goal.
    if maze[x][y] == '#' or maze[x][y] == 'o': return False  # If position not open.

    maze[x][y] = 'o'  # Mark (x,y) as part of solution path.
    
    if find_path(x, y-1): return True  # Search north.
    if find_path(x+1, y): return True  # Search east.
    if find_path(x, y+1): return True  # Search south.
    if find_path(x-1, y): return True  # Search west.

    maze[x][y] = 'x'  # Unmark (x,y) as part of solution, was a dead-end.

    return False

def print_maze_raw():
    for char in maze:
        print char
    print

def print_maze():
    for i in range(len(maze)):
        for j in range(len(maze[0])):
            print(maze[i][j]),
        print
    print

if __name__ == '__main__':
    print_maze()  # Before.
    find_path(0,0)  # Starting position is (0,0).
    maze[0][0] = 'S'  # Remark our starting position (got lost during path traversal).
    print_maze()  # After.
# Have a function that returns more arguments than you need? Here are some options.

def foo():
    return 1, 2, 3

a, b, _ = foo()
a, b = foo()[:2]
import os

try:
    print os.environ['FOO']
except KeyError:
    print 'Please set the environment variable FOO'

if 'FOO' in os.environ:
    print os.environ['FOO']

print os.environ.get('FOO')  # Returns None if not found.
print os.environ.get('FOO', 'BAR')  # Returns 'BAR' if not found.

print os.getenv('FOO')  # Returns None if not found.
print os.getenv('FOO', 'BAR')  # Returns 'BAR' if not found.
# As seen on SO:
# http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python


class Enum(set):
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError

Commands = Enum(['Start', 'Stop', 'Pause'])
print Commands.Start, Commands.Stop, Commands.Pause
#!/usr/bin/env ruby

# Used to extract photos laid out in a grid inside one big photo.
# Several such big photos exist, so repeat the process for each.

# apt-get install libdevil-dev
# gem install devil
require 'devil'

xoffs = [5, 961]
yoffs = [116, 941, 1766]
width = 946
height = 631
counter = 1
exclude_files = %w(2 3 10 12).map { |file| sprintf("%03d", file) << ".jpg" }

Dir.mkdir("crops") unless Dir.exists?("crops")

Dir.glob("*.jpg") do |jpg|
  next if exclude_files.include? jpg
  Devil.load_image(jpg) do |img|
    xoffs.each do |xoff|
      yoffs.each do |yoff|
        tmp_img = img.clone
        tmp_img.crop(xoff, yoff, width, height)
        tmp_img.save("crops/#{counter}.jpg")
        puts "Saved #{counter}.jpg"
        tmp_img.free
        counter += 1
      end
    end
  end
end
# Quick and dirty ways to convert chars to their integer or ascii value.
# E.g. '1' -> 1, 'a' -> 97

#include <iostream>
using namespace std;

#define char2int(c)  c-'0'
#define char2ascii(c)  int(c)

int main()
{
  char c;
  while (cin >> c)
  {
    int value = char2int(c);
    if (value >= 0 && value <= 9)
      cout << c << " is a digit; converted to an int"  << endl;
    else
      cout << c << " is not a digit; its ascii value is " << char2ascii(c) << endl;
  }
}
from subprocess import call
from time import sleep

tabs = ""
for _ in xrange(9):
    call(["clear"])
    print """
    {0}  0
    {0} \|/
    {0}  |
    {0} / \\""".format(tabs)
    tabs += "\t"
    sleep(0.5)
    call(["clear"])
    print """
    {0}  0
    {0} -|-
    {0}  |
    {0} / \\""".format(tabs)
    tabs += "\t"
    sleep(0.5)
    call(["clear"])

tabs = ""
for _ in xrange(15):
    call(["clear"])
    print """
    {0}   __
    {0} _| =\__
    {0}/o____o_\\""".format(tabs)
    tabs += "\t"
    sleep(0.4)
# Collect command-line options in a dictionary.
#
# Do not use this for any production code! Use a dedicated module instead.
# See my gist for more info: https://gist.github.com/dideler/2395703
#
# Usage:
# $ python main.py -i input.txt -o output.txt
# input file is input.txt
# {'-o': 'output.txt', '-i': 'input.txt'}

def getopts(argv):
    opts = {}
    while argv:
        if argv[0][0] == '-':
            opts[argv[0]] = argv[1]
        argv = argv[1:]
    return opts

if __name__ == '__main__':
    from sys import argv
    myargs = getopts(argv)
    if '-i' in myargs:  # Example usage.
        print 'input file is', myargs['-i']
    print myargs

Snippets of code that I've played around with, which could be useful to others.
Nothing impressive, but you may learn a thing or two.