Waiting for Singularity

Thoughts on science, tech and other preoccupations

Brains in Jars!

Singularity Hub describes how scientists grew miniature, but distinctly human, brain in the lab.

Austrian researchers have used regenerative techniques to grow a miniature human brain in the lab, they reported recently in the journal Nature.

The researchers started with pluripotent human stem cells, or stem cells that are capable of developing into various kinds of specialized cell. After letting them develop, they removed proto-neural cells and placed them on a scaffold. Using a bioreactor to improve cellular growing conditions, they obtained a brain-like organ that exhibited differentiated brain regions.

The mini-brains developed into distinct regions, including a cerebral cortex, retina (pictured), meninges and choroid plexus. But they stopped growing after two months. The Austrian researchers, led by Jurgen Knoblich of the Institute of Molecular Biotechnology of the Austrian Academy of Sciences, said that in the absence of a circulation system, the core of the mini-brains probably didn’t receive adequate nutrients or oxygen to continue growing.

Rake Tasks Flashcards

A flashcard app to test your knowledge of Rake tasks.

Outputs:

    Q: What rake task does the following: Run tests quickly by merging all types and not resetting db?
    A: test:all
    Correct
    Do you want to continue? (Y/N): y

    Q: What rake task does the following: Load the seed data from db/seeds.rb?
    A: db:seed
    Correct
    Do you want to continue? (Y/N): y

    Q: What rake task does the following: Run tests quickly by merging all types and not resetting db?
    A: db:test
    Incorrect. The answer is: test:all
    Do you want to continue? (Y/N): n

Read about the humble beginnings of Rake in Rational.doc. For a good introduction to Rake, head to Jason Seifer’s blog.

    "I never intended to write this code. I‘m not convinced it is useful, and I‘m not convinced anyone would even be interested in it."
    -  Jim Weirich

Pi Approximation in Python and Ruby

In 1910, the mathematician Srinivasa Ramanujan found several rapidly converging infinite series that can be used to generate a numerical approximation of pi. His series are now the basis for the fastest algorithms currently used to calculate π.

Below are implementations of a function called estimate_pi that uses his formula to compute and return an estimate of pi (an exercise from Chapter 7 of Think Python by Allen Downey).

Solution in Python

import math

def factorial(n):
    if n == 0:
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result

def estimate_pi():
    total = 0
    k = 0
    factor = 2 * math.sqrt(2) / 9801
    keep_going = True
    while keep_going == True:
        numerator = float(factorial(4*k) * (1103 + 26390 * k))
        denominator = float(factorial(k)**4) * 396**(4*k)
        term = factor * float(numerator/denominator)
        total += term
        k += 1
        if term < 1e-15:
            keep_going == False
            print "Finished at iteration number", k
            break
    return 1 / total

print estimate_pi()

Solution in Ruby

def factorial(n)
  if n == 0
    return 1
  else
    recurse = factorial(n-1)
    result = n * recurse
  end
  return result
end

def estimate_pi
  total = 0
  k = 0
  factor = 2 * Math.sqrt(2) / 9801
  keep_going = true

  while keep_going == true
    numerator = (factorial(4*k).to_f * (1103 + 26390 * k).to_f)
    denominator = (factorial(k).to_f**4) * 396**(4*k).to_f
    term = factor.to_f * (numerator.to_f/denominator.to_f)
    total += term
    k += 1
    puts term < 1E-15

    if term < 1E-15
      keep_going == false
      puts "Finished at iteration number #{k}"
      break
    end

  end
  return 1 / total
end

puts estimate_pi()

Outputs:

Finished at iteration number 3
3.14159265359

Regular Expressions Flashcards

A flashcard app to test your knowledge of regular expressions.

Question pool based on terminologies from Ruby QuickRef from ZenSpider.com

Outputs:

    *** Test your knowledge of Regular Expressions***
    Based on Ruby QuickRef from ZenSpider.com

    Q: non-word boundary
    A: \B
    Correct
    Do you want to continue? (Y/N):y

    Q: 0 or more previous regular expression (non-greedy)
    A: .
    Incorrect. The answer is: *?
    Do you want to continue? (Y/N):

    Q: 0 or more previous regular expression
    A: *
    Correct
    Do you want to continue? (Y/N):n

All the Buzz About Fizzbuzz

Do companies still use Fizzbuzz to find programmers who can code?

The test may be old news but FizzBuzz is still relevant. Some interesting observations: Global nerdy found that only 40% of the candidates he interviewed could write FizzBuzz, LosTechies believe it provides an accurate window into coding skills, while some engineers think it is plain boring.

StackExchange has suggestions on what to do after you fail the test in an interview. Resources: Project Euler 99 Prolog Puzzles TopCoder Google Code Jam

Find more programming exercises on StackExchange.

FizzBuzz test:

Write a program that prints out the numbers from 1 through 100, but…

For numbers that are multiples of 3, print “Fizz” instead of the number. For numbers that are multiples of 5, print “Buzz” instead of the number For numbers that are multiples of both 3 and 5, print “FizzBuzz” instead of the number.

Shortest Fizzbuzz Scripts

Implemented in Python

for i in range(1,101):print"FizzBuzz"[i*i%3*4:8--i**4%5]or i
for i in range(1,101):print"Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i
for x in range(100): print x%3/2*'Fizz'+x%5/4*'Buzz' or x+1

via  http://koichitamura.blogspot.com/2009/05/python-fizzbuzz.html
and tested on Python v2.7.2

Implemented in Ruby

(1..100).map{|n|puts"FizzBuzz#{n}"[n%3<1?0:n%5<1?4:8,n%15<1?8:4]}
1.upto(100){|i|p"FizzBuzz#{i}"[i%3<1?0:i%5<1?4:8,i%15<1?8:4]}
100.times{|i|p"FizzBuzz#{i}"[i%3<1?0:i%5<1?4:8,i%15<1?8:4]}

via http://golf.shinh.org/p.rb?FizzBuzz and tested on Ruby v2.0.0

Implemented in Perl

perl -le'print(($_%3?"":Fizz).($_%5?"":Buzz)or$_)for 1..100'
perl -M5.01 -e 'say+(Fizz)[$_%3].(Buzz)[$_%5]||$_,for 1..100'

via http://www.perlmonks.org/?node_id=602901 tested on v5.12.4

Implemented in PHP

while(++$i<100)echo($i%15?$i%3?$i%5?$i:Buzz:Fizz:FizzBuzz)."\n";

via http://jakespurlock.com/2012/11/php-fizzbuzz-test/ tested on PHP 5

Statistics on Shortest FizzBuzz codes

Language User Size Time Date Statistics
Ruby ksk 50 0.0162 11/02/15 0B / 25B / 24B
Perl shmem 48 0.0918 07/03/02 0B / 22B / 25B
Python Defenestrator 56 0.1151 07/04/20 0B / 35B / 20B
Clojure youz 77 2.7364 11/06/01 0B / 47B / 24B
JavaScript ozy4dm 56 0.0450 07/02/25 0B / 30B / 26B
AWK nn 57 0.0024 08/10/27 0B / 32B / 24B
Bash daishi 41 0.0152 11/02/26 0B / ?B / ?B
Scala lyrical_logical 66 7.8083 11/07/12 0B / 36B / 29B

Ruby Flashcards: Globals in Ruby

An flashcard app to test your knowledge of Ruby global variables.

Question pool based on terminologies from Ruby QuickRef from ZenSpider.com

Outputs:

*** Test your knowledge of Ruby Globals!***
Based on Ruby QuickRef from ZenSpider.com

Q: The exception object passed to #raise
A: $!
Correct
Do you want to continue? (Y/N):y

Q: The status of the last executed child process. Read only. Thread local.
A: $.
Incorrect. The answer is: $?
Do you want to continue? (Y/N):y

Q: The current standard input.
A: $stdin
Correct
Do you want to continue? (Y/N):n

Chess Quote Bot

A quote bot app developed using Python, Flask and Twilio API.

Quotes from Chess Grandmasters

Text 1-617-9936601 for an inspirational chess quote

The beauty of a move lies not in its appearance but in the thought behind it.
-  Aaron Nimzowitsch

ROT13 Encryption in Python and Ruby

A program to encrypt a message in ROT13 by shifting a letter through the alphabet (an exercise from Chapter 8 of Think Python by Allen Downey)

ASCII numbers ord(‘a’) => 97 ord(‘z’) => 122 ord(‘A’) = > 65 ord(‘Z’) = > 90 chr(97) => ‘a’

Key is the number of places the letters of the message should be moved during encryption

Solution in Python

def rotate_word(message, key):
    new_message = ''
    s = message.lower()
    for letter in s:
        new_ord = key + ord(letter)
        if new_ord > 122:
            new_ord = new_ord - 26
            new_letter = chr(new_ord)
        else:
            new_letter = chr(new_ord)

        new_message = new_message + new_letter
    return new_message.lower()

words = ['abc', 'python', 'ruby', 'unladen swallow']

print "*** Messages encrypted in ROT13 ***"
for word in words:
    print "%s: %s" % (word, rotate_word(word, 13))

Solution in Ruby

def rotate_word(message, key)
  new_message = ''
  message.downcase!
  message_array = message.split('')
  message_array.each do |m|
    new_ord = key + m[0].ord
    if new_ord > 122
      new_ord = new_ord - 26
      new_letter = new_ord.chr
    else
      new_letter = new_ord.chr
    end
    new_message = new_message + new_letter
  end
  return new_message.downcase
end

words = ['abc', 'python', 'ruby', 'unladen swallow']

puts "*** Messages encrypted in ROT13 ***"
words.each do |word|
    puts "#{word}: #{rotate_word(word, 13)}"
end

Outputs:

*** Messages encrypted in ROT13 ***
abc: nop
python: clguba
ruby: ehol
unladen swallow: haynqra-fjnyybj

Sublime Text 2 Pro Tip: Multiple Cursors

This Sublime Text 2 feature is a real-time saver: Place your cursor within the word and press Ctrl+Cmd+G. This selects every occurrence of that word and creates multiple cursors. Edit the word and watch the multiple cursors do the same.

Learn about Multiple Cursors and other pro tips from the article 10 Must-know Sublime Text 2 tips.

Palindrome Checker in Python and Ruby

Write a function that takes a string argument and returns True if it is a palindrome and False otherwise (an exercise from Chapter 6 of Think Python by Allen Downey).

Solution in Python

def first(word):
    return word[0]

def last(word):
    return word[-1]

def middle(word):
    return word[1:-1]

def is_palindrome(word):
    if len(word) <=1:
        return True
    if first(word) != last(word):
        return False
    return is_palindrome(middle(word))

words = ['cat', 'noon', 'radar', 'swallows', 'racecar']

for word in words:
  print '%s: %s' % (word, is_palindrome(word))

Solution in Ruby

def first_letter(word)
  word[0]
end

def last_letter(word)
  word[-1]
end

def middle(word)
  word.byteslice(1..-2)
end

def is_palindrome?(word)
  if word.length <= 1
    return 'True'
  elsif first_letter(word) != last_letter(word)
    return 'False'
  else
    return is_palindrome?(middle(word))
  end
end

puts "Palindrome Detector"

array = %w[cat noon radar swallows racecar]
array.each do |word|
  puts "#{word}: #{is_palindrome?(word)}"
end

Outputs:

Palindrome Detector
cat: False
noon: True
radar: True
swallows: False
racecar: True