Sunday, February 28, 2016

Word frequency counter in #javascript

var model = {
        model.words = []
        model.wordCounts =[]

        var index = $.inArray(word, model.words)
        if (index == -1) {
            index = model.words.push(word) - 1            model.wordCounts.push({word:word, count:0})

var view = {
    input:"<textarea style='width:500px; height:500px' id='words' placeholder='paste words here to count'></textarea><br>"    + "<button id='do'>Count words</button>",

var controller = {

        var input = $("#words").val()
        input.split(" ").forEach(function(word){
        var output = []
        $.each(model.wordCounts, function(key, obj){
            output.push(obj.word + " count: " + obj.count)


Saturday, February 27, 2016

How to replace all occurences of a string using a variable in regex in #javascript

I want to replace all occurrences of words in a substitution dictionary

My small substitution dictionary is a javascript object like this {"utilize":"use"}


1. Loop through the substitution dictionary using jQuery.each
2. we have to use the javascript string function .replace with regex. 
3. You might typically hardcode the pattern like this .replace(/replaceThis/g, "withThis"). Instead we want to use the substitution value from the dictionary. In order to do this we need to use a RegEx object. Instead of /replaceThis/g we use new RegEx(patternVariable, "g")

Example code
var targetText = $("#targetText")

    $.each(wordSubsfunction(key, value){

        targetText targetText .replace(new RegExp(key, "g"), value)


Thursday, February 25, 2016

Simple #javascript search form using #MVC pattern

Lesson 40 in 57 exercises for programmers is to implement simple search functionality. The employee data is from the book

I am learning javascript. Please leave constructive criticism on any aspect of this code if you wish; I would love to get some feedback.


index.html has two divs
<div id="divInput">

<div id="output">



var model = {
    { =[
        model. buildEmpObj("John", "Johnson", "Manager", "2016-12-31"),
        model.buildEmpObj("Tou", "Xiong", "Software Engineer", "2016-10-05"),
        model.buildEmpObj("Michaela", "Michaelson", "District Manager", "2015-12-19"),
        model.buildEmpObj("Jake", "Jacobson", "Programmer", ""),
        model.buildEmpObj("Jacquelyn", "Jackson", "DBA", ""),
        model.buildEmpObj("Sally", "Weber", "Web Developer", "2015-12-18")
    buildEmpObj:function(first, last, position, leftdate) {
        return { //Javascript "unexpected token :" if the { is on a new line            "first":first,


var view = {
    searchForm:"<input type='text' id='search'><br>"    + "<button id='btnSearch'>Search</button> "}

var controller = {
    contains:function(target, search)
        return target.indexOf(search) != -1    },

        var searchWords = $("#search").val()
            return controller.contains(employee.first + " " + employee.last, searchWords)
            controller.outputArea.append(JSON.stringify(employee)+ "<br>")



Wednesday, February 24, 2016

#javascript "Unexpected token :"

This is giving me the error "Unexpected token :", and all the : in the {} have a red sqiggly line

function buildObj(a, b){




Just move the { to the same line as return. For some reason this matters.

function buildObj(a, b){

return { 


Tuesday, February 23, 2016

#javascript generating ASCII char code arrays for various ranges

var numArr = []
var specialArr = []
var charArr = []

putRange = function(startChar, endChar)
    var arr = []
    for(var i = startChar.charCodeAt(0); i < endChar.charCodeAt(0); i++)
    return arr}

numArr = putRange('0', '9')
specialArr = putRange('!', '/')
charArr = putRange('a', 'z').concat(putRange('A', 'Z'))

This generates the following

charArr [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89]

specialArr [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46]

numArr [48, 49, 50, 51, 52, 53, 54, 55, 56]

Wednesday, February 10, 2016

Regex for turning a Dex profile text file into CSV

Text format
Type     Name                      Count   Time in  +Children  Minimum  
P Do Stuff script                  29513     25.15     25.42      0.00  

P Do other stuff script        288      7.94     22.78      0.00      0.31

CSV format
P Do Stuff script,29513,25.15,25.42,0.00  
P Do other stuff script,288,7.94,22.78,0.00,0.31

Regex to do this
0. Manually remove the header row

1. This puts a comma between the Type Name and Count columns
Replace ([\D\S])\s+([0-9]+) with \1,\2

2. This puts commas between all the numeric columns
Replace ([0-9]+)\s+([0-9]) with \1,\2

Wednesday, February 3, 2016

My #python reference

What is this? I read a book called 57 Exercises for Programmers and used the exercises to learn Python. I took notes as I went along. Here they are.



I tried a few different IDEs and a text editor. I liked PyCharm the best.
  1. Visual Studio has Python support. Need to install Python Tools for Visual Studio. I also installed IronPython. 
  2. NetBeans. Haven't tried this yet.   
  3. IDLE. It's installed when you install Python. Just open it and create a new file. I like it because it works quickly without hassle.
  4. Trying PyCharm: . I want a powerful Python w/ web development IDE. I really like this one!


In C# you have { } to indicate blocks. In Python, you have indents, which you must use for everything.

def MyFunction():
<indent>print "Hello World"


C# "using" equivalent = import. ex: import sys

  1. import decimal
  2. from decimal import Decimal
  3. Alias like this: from decimal import Decimal as D
    1. instead of Decimal("1.25") you can use D("1.25"). This is useful when there are very long names to type 

In this case "decimal" is a module (a .py file) that contains a class called Decimal. 

Exiting a script

import sys


single line = #this is a comment
multiple = """this
is a 
multiple line 


dogName = "Scruffy"
if dogName == "Scruffy":
    print "Woof woof"elif dogName == "Rex":
    print "Bark bark"else:
    print "I have no idea what sound that dog makes"

spoon = Noneif not spoon:
    print "There is no spoon"
catName = ""
if not catName:
    print "You didn't name the cat"

Woof woof
There is no spoon
You didn't name the cat

Notice how the "not" operator worked on both a null object (None) and an empty string? Yeah, that's pretty sweet

Switch/case: Python doesn't have these. Use a dictionary instead. See here: 


from decimal import Decimal
myString = "1.25"myDecimal = Decimal(myString)
myInt = int(myDecimal)

print "Decimal {0}  Integer {1}".format(myDecimal, myInt)

Decimal 1.25  Integer 1

A reusable function checking if a thing is a float
def isfloat(value):
    return True
    return False

Try ... catch

except (optional Exception type here):
     handle error


    first = float("haha")
except ValueError as ex:
    print ex.message

could not convert string to float: haha


def functionName(params):
     string for documentation -- this shows up when you're calling the function
     return something

optional parameters like: def function(name="")

def askName()
     "Prompts the user for their name, then returns the name"
     return raw_input("What's your name? ")

command line inout

print raw_input("Print this")


assert booleanStatement
assert name=="Mak"


1. while loop syntax

input = getInput()
while input.upper() != DONE:
    #parse input
    #do stuff with it
    input = getInput()

Note the colon + indenting of the body of the loop. 

2. For loop syntax

Items = []
Items.append(Item("Computer", 1, 1000.55))

for item in Items:
     print item; 

3. Counting to 10 with a for loop
for i in range(1, 11):
     print i


This is pretty strange if you're coming from a language that doesn't have slicing. After seeing the examples, I'm sure you'll understand how awesome this language feature is. Try writing code in another language and producing the exact the same output, and comparing it to this (including checking boundaries)

The format

a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step


hello = "Hello World"
print "hello[:] prints [{0}]".format(hello[:])

#This won't throw an 'index out of range' exception

print "hello[500:] prints [{0}]".format(hello[500:])

#Neither will this
print "hello[0:500] prints [{0}]".format(hello[0:500])

#from 0 to 5
print "hello[:5] prints [{0}]".format(hello[:5])

#every other character
print "hello[::2] prints [{0}]".format(hello[::2])

print "hello[::-1] prints [{0}]".format( hello[::-1])

This produces
hello[:] prints [Hello World]
hello[500:] prints []
hello[0:500] prints [Hello World]
hello[:5] prints [Hello]
hello[::2] prints [HloWrd]
hello[::-1] prints [dlroW olleH]



input = raw_input("What's the word? ")
length = len(input);
 #named arguments
print "{input} has {length} chars".format(input=input, length=length)
print "{0} has {1} chars".format(input, length)
 #using function pointer
output = "{0} has {1} chars".format
print output(input, length)

2. Uppercasing: stringObject.upper()


1. Split string 
input = "1.00:2.00"
QTY, Price = input.split(":", 1) # : is my delimiter in this particular example


1. Creating a class
Pretty much the same syntax as a function. Need the colon after the class name. Class variables and functions need be indented.

class MyClass:
    "I'm a doc string. Use print ClassName.__doc__"
  def __init__(self):
       self.InstanceVariable = "I'm a class variable"

     def ClassFunction(self):
          "I'm a class function"
           print self.InstanceVariable 

2. Static method

class MyClass
     def BuildMyClass():
         return MyClass()

You'd use it like MyClass.BuildMyClass()

3. Constructor = def __init__():

4. Inheritance
class Parent():
class Child(Parent):

class Parent():
def __init__(self, eyecolor, haircolor):
print "parent cstr called"
self.eyecolor = eyecolor
self.haircolor = haircolor

class Child(Parent):
def __init__(self, eyecolor, haircolor, numberoftoys):
print "child cstr called"
Parent.__init__(self, eyecolor, haircolor)
self.numberoftoys = numberoftoys

Method Overriding - just name the function in the child class


create directory
import os

create file + write to it
with open("folder1/dummy.txt", 'a+') as f:
    f.writelines("One should never utilize the word 'utilize' in writing. Use 'use' instead")

read file
with open(oldFileName, 'r') as f:
    for line in f.readlines():
              print line

Data Structures

Array / List

Arrays and lists are the same thing in python. 
Example: arr = ["Yasmin"]
1. CREATE: arr = ["Yasmin"]
2. READ: 
for a in arr:
    print a

5. Checking if a key exists
-key in arr

6. Operations on all elements in a list: use map()

Associative array

addresses = {
    'Mac':"Mac's house",
    "Bob Saget": 'Full House in SF'}

addresses["Obama"] = "The White House"

addresses["Mac"] = "Mac's new house"

#checking for a value
if addresses.has_key("Bob Saget"):
    print "Evicting Bob Saget"    #deleting    addresses.pop("Bob Saget")

for name in addresses:
    print "{0} lives at {1}".format(name, addresses[name])

Evicting Bob Saget
Mac lives at Mac's new house
Obama lives at The White House

Date & Time

Getting the current date + adding to it 
import datetime
now =
print "The year is {0}".format(now.year)
print "20 years from now is {0}".format(now.year + 20)   

The year is 2016
20 years from now is 2036

Specific tasks

Opening a URL

response = urllib2.urlopen("")

Getting and parsing JSON

import urllib2
import json
import pprint #this stands for Pretty Print

response = urllib2.urlopen("")
data = json.loads(

#pretty printer
pprint.pprint( data)

This outputs
{u'message': u'success',
 u'number': 6,
 u'people': [{u'craft': u'ISS', u'name': u'Mikhail Kornienko'},
             {u'craft': u'ISS', u'name': u'Scott Kelly'},
             {u'craft': u'ISS', u'name': u'Sergey Volkov'},
             {u'craft': u'ISS', u'name': u'Yuri Malenchenko'},
             {u'craft': u'ISS', u'name': u'Timothy Kopra'},
             {u'craft': u'ISS', u'name': u'Timothy Peake'}]}

#parsing into a nice table
def p(name, craft, filler=' '):
    formatString = "{0}|{1}"    print formatString.format(name.ljust(20, filler), craft.ljust(10,filler))

p("Name", "Craft")
p('','', '-')
for line in data["people"]:
    p(line["name"], line["craft"])

This outputs
Name |Craft
Mikhail Kornienko |ISS
Scott Kelly |ISS
Sergey Volkov |ISS
Yuri Malenchenko |ISS
Timothy Kopra |ISS
Timothy Peake |ISS 

Getting and parsing an RSS feed

to install feedparser just do "pip install feedparser".
see here:

This example pulls in the flickr feed, searching for public photos with the tag of "dog"
and then loops through the results and gets all the URLs to the photos
import feedparser

def getImages():
    feed = feedparser.parse("")
    images = []
    for entry in feed["entries"]:
        for link in entry["links"]:
            if (link["type"] == "image/jpeg"):
    return images

Encryption using bcrypt

  1. Install bcrypt using pip by executing the following in the command prompt C:\Program Files\Python2.7\Scripts> pip install bcrypt
  2. use bcrypt - see here 

Website directory
  2. Twilio - Phone voice and SMS API -  
  3. Learn Python the Hard way: 
  4. Hosting: 
  5. Google Python Style Guide