Thursday, October 27, 2016

Open form in the UI thread from another thread

I have a thread that wakes up and processes stuff based on a schedule and it needs to show progress in a window. This is so that if any user happens to be using the system when this pops up, they can cancel it / see what's going on.

Solution - create a dummy form to Invoke()
        public static Form globalForm;
        private void btnStart_Click(object sender, EventArgs e)
            globalForm = new Form();

            Task t = new Task(Run);


        Test test; //this is the form i want to show when this job is running
        public void Run()
            test = new Test();
            while (true)

                //do stuff

                //update status on the window

        private void ShowTestForm()
             /* Note: I prefer this wrapped version over calling globalForm.Invoke(...) from the Run() method. I believe this is cleaner code.  */

            MethodInvoker m = () =>
                if (!test.Visible)

Tuesday, September 27, 2016

Error: Subreport could not be shown

I have a report that has a table with a subreport for each record. When I try to run the report it spins for awhile and then says, "Error: Subreport could not be shown."

1. Open the parent report's .rdl so that you can see the report XML, not the design surface
2. Search for <Subreport
3. In <ReportName> put .rdl at the end of the subreport's name
4. Upload the parent report to SSRS

Troubleshooting notes
What threw me off here was the fact that it was working inconsistently. I would use the Browse... button in the designer and point to this report. It would pull back the report name without .rdl at the end. This somehow worked. Manually typing in the name in the designer and adding .rdl to the name did not work. I had to open the report in a text editor and edited the name in there.

Friday, September 2, 2016

Posting form data via AJAX to Flask route


@app.route('/something', methods=['POST'])
def post_something():
    something=  request.form['something'];
    return json.dumps({'status':'OK','something':something});
def unittest_post_something(self):
    form = dict(something="hey, i'm unit testing you");
    response ="/something", data = form)
    self.assertEqual(response.status_code, 200)

var something = "i'm posting via ajax";

 url: '/something',
 data: $('form').serialize(),
 type: 'POST',
 success: function(response) {
 error: function(error) {


Thursday, August 25, 2016

Network share is not showing new directories / files

I have a network share that's not updating. I added a new directory and put some files. When I login to another server I cannot see that new directory.

Add this registry entry:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters] “DirectoryCacheLifetime”=dword:00000000


Tuesday, August 23, 2016

DateTime.ParseExact is throwing Format Exception when single H specified

DateTime.ParseExact("9", "H", CultureInfo.InvariantCulture) throws a FormatException.

It also throws the exception for the following cases:
1. "925", "Hmm"
2. "92525", "Hmmss"

Why? Because with a single "H", it tries to grab 1-2 characters. In the case of "925" it tries to grab "92" for the hour.


Let's say we want to allow the user to enter time in the following formats:

  • H
  • HH
  • Hmm
  • HHmm
  • Hmmss
  • HHmmss

What we can do is pad the string with a 0 to the left if the string length is odd. That is, if the time is in the formats H, Hmm, Hmmss, then we stick a 0 at the beginning and can simply use HH, HHmm, HHmmss.

For example

            string input = "925";
            string format = "";
            if (input.Length % 2 != 0)
                input = input.PadLeft(input.Length + 1, '0');

                case 2:
                    format = "HH";
                case 4:
                    format = "HHmm";
                case 6:
                    format = "HHmmss";
                    throw new ArgumentException("Time isn't within the expected lengths of 1-6");

            DateTime dt = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);

            //do stuff with dt

Friday, August 19, 2016

Combining multiple #javascript files into one in #PyCharm using File Watcher + #Python script

I'm working on a website and currently have one large javascript file with several classes in it, which makes the code overall less readable / harder to maintain. But I also want to only include one script file in the HTML doc, and also only make the browser download one script instead of several.

Note: I am using PyCharm

There are plenty of third party tools that you can use to do this. However, I attempted to use one, and it didn't work. So instead of wasting more time, I decided to keep it simple and write my own tool that does it.

Here's the steps I did:
1. Split the big JS file into several small ones and put them in a subdirectory

2. Delete the big JS file

3. Add a Python file called This simply takes the list of files, reads them, and then outputs them into another file
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)

files = ["smallfile1.js", "smallfile2.js", "smallfile3.js"]

outputFile = "";

for file in files:
    with open(file, 'r') as f:
        outputFile += " " +

with open("../bigfile.js", 'w+') as output:

4. Configure the File Watcher in PyCharm so that it calls this script whenever I save one of the subfiles

  • File > Settings > File Watcher
  • Add new
  • Scope = point to the subdirectory containing the small JS files and click Include Recursively
  • Program = C:\Python27\python.exe
  • Arguments = <path to>
5. Save it all

6. Try editing one of the small JS files and then saving it. should run and you should now see the combined big JS file sitting in the correct spot.

Note: This does not minimize the JS file. Remember that optimizations are a waste of time until you can prove that you have a performance problem to solve. In my case, applying a minimizer to bigfile.js barely saves any space, so I'm not going to waste my time attempting to automate the minimization process UNTIL a performance problem arises where the time spent solving the problems has quantifiable benefits.

Tuesday, June 28, 2016

Change transparency of an image

I have an upcoming demo with a customer where I need to show them a SQL Reporting Services report. On the mock they have their logo watermarked on the report. I have their logo, and in order to get it to appear as a watermark I want to just make the image more transparent.

1. Download Paint.Net:

2. Download plugin pack:
Direct =

Forum post with instructions =

3. Open the image in Paint.Net

4. Click Adjustments > Transparency

5. Now just slide the image until it's more transparent.

Wednesday, June 15, 2016

Handle radio group change event #javascript #jquery

If you need to handle the event where the user selects a different radio group option, then here's the code to do that.

radioGroupChangeHandler= function(e){
        case "radioGroupOption1":
            console.log("option 1 was selected")
        case "radioGroupOption2:            console.log("option 2 was selected")


Monday, June 13, 2016

Get "rd" "th" "rd" from datepicker date #javascript

I'm using a jquery datepicker and when the user picks a date i want to show in another textbox the "rd" "th" "rd" day of the month.

For example:

I want to show in another textbox "13th" of the month.

Found a solution on SO. This saved me quite a bit of typing :)

 function get_nth_suffix(date) {
   switch (date) {
     case 1:
     case 21:
     case 31:
        return 'st';
     case 2:
     case 22:
        return 'nd';
     case 3:
     case 23:
        return 'rd';
        return 'th';


Friday, June 10, 2016

Dexterity - SetBooleanProperty() for FIELD_PROP_REQUIRED is not working

I have a field that i need to be ignored when required() is called in certain situations. So I tried to use SetBooleanProperty(fieldName, FIELD_PROP_REQUIRED, false) on the field, then setting it to true after the situation.

For some reason this did not change the property, and I have no clue why. It's probably undocumented Dex behavior.

Lock and unlock the field instead of using SetBooleanProperty(). Lock it before required() is used, and unlock it after.

Ref: From the Dex manual it says required() ignores fields that are locked, disabled, or hidden.

Thursday, June 9, 2016

ReportViewer RDLC - show enum's string representation

I have a report that has a data source set to a collection of business objects. One of the fields shown on the report is called "Batch Status." This is an enum. On the report though, it's appearing as the integer value of the enum instead of the string representation.

For example:
BatchStatus.Available is appearing as 1 instead of Available

In the field express put just put
=System.Enum.GetName(First(Fields!BatchStatus.Value).GetType(), Fields!BatchStatus.Value)


Friday, May 27, 2016

#HTML day of month select

This took me about 10 minutes to type out, so maybe putting this here will save someone time.

<select id="day-of-month">
    <option value="1">1st</option>
    <option value="2">2nd</option>
    <option value="3">3rd</option>
    <option value="4">4th</option>
    <option value="5">5th</option>
    <option value="6">6th</option>
    <option value="7">7th</option>
    <option value="8">8th</option>
    <option value="9">9th</option>
    <option value="10">10th</option>
    <option value="11">11th</option>
    <option value="12">12th</option>
    <option value="13">13th</option>
    <option value="14">14th</option>
    <option value="15">15th</option>
    <option value="16">16th</option>
    <option value="17">17th</option>
    <option value="18">18th</option>
    <option value="19">19th</option>
    <option value="20">20th</option>
    <option value="21">21st</option>
    <option value="22">22nd</option>
    <option value="23">23rd</option>
    <option value="24">24th</option>
    <option value="25">25th</option>
    <option value="26">26th</option>
    <option value="27">27th</option>
    <option value="28">28th</option>
    <option value="29">29th</option>
    <option value="30">30th</option>
    <option value="31">31st</option>
</select>of the month

Friday, May 20, 2016

#Bootstrap form with horizontal labels

To get a form that has horizontal labels in Bootstrap like this:

Do this

<form class="form-horizontal" method="POST" action="">
<div class="form-group ">
    <label class="col-md-2 control-label" for="eventTitle">Event</label>
    <div class="col-md-10">
      <input class="form-control" id="eventTitle" type="text">


#Bootstrap form with side-by-side controls

I have a form that has some controls that need to be side-by-side. All you need to do is wrap the controls in a div with class form-inline. This needs to go after the div with the column width class. Example:
<div class="form-group">
    <label class="col-md-2 control-label" for="">Start</label>
    <div class="col-md-10">
        <div class="form-inline">
            <input class="form-control"  type="text" id="eventStartDate">  <input class="form-control" type="text" id="eventStartTime">

Note: I highlighted the gap between to the side-by-side controls. That's because that space is actually rendered. I put one or two spaces, and you can notice the small gap on the image between the two controls. So watch out for that, because obviously space is not normally rendered like that.

Tuesday, April 12, 2016

Round time to the nearest 30 min #javascript

I want to initialize the start date + time to the next 30 minute interval. I then want to set the end time to 1 hour after that time.

Right now is 4/12/16 8:45 am
I want Start DateTime = 4/12/16 9:00 am and End DateTime = 4/12/16 10:00 am

var now = new Date();
var minutes = now.getMinutes();
var minutesToAdd = 0;
if (minutes >= 0 && minutes <= 29)
    minutesToAdd = 30 - minutes;
else if (minutes >= 31 && minutes <= 59)
    minutesToAdd = 60 - minutes;
var MIN_IN_MS = 60000;
var HALF_HOUR_IN_MS = 3600000;

minutesToAdd = minutesToAdd * MIN_IN_MS;
var startDateTime = new Date(now.getTime() + minutesToAdd);
var endDateTime = new Date(startDateTime.getTime() + HALF_HOUR_IN_MS);

alert("Start Date  = " + startDateTime + " End Time =" + endDateTime);


Friday, March 25, 2016

Get all unique email domain names from Microsoft Dynamics CRM database

SELECT  COUNT(*), MIN(ISNULL([ParentCustomerIdName], '')),
SUBSTRING(EmailAddress1, CHARINDEX('@', EmailAddress1) + 1, LEN(EmailAddress1) - CHARINDEX('@', EMailAddress1))
  FROM [YourCRMDatabase].[dbo].[Contact]
  WHERE EmailAddress1 IS NOT NULL
  GROUP BY SUBSTRING(EmailAddress1, CHARINDEX('@', EmailAddress1) + 1, LEN(EmailAddress1) - CHARINDEX('@', EMailAddress1))

Monday, March 21, 2016

#javascript observer pattern - using object literal notation - very simple

var obj1 = {
        for(var subIndex in obj1.subscribers)

var obj2 = {
      console.log("Obj1 changed and I was notified. I'm gonna do stuff now");


Saturday, March 19, 2016

FullCalendar remove scroll bar's header border

FullCalendar adds the following when a scroller appears:
<div class="fc-row fc-widget-header" style="border-right-width: 1px; margin-right: 16px;">

This results in a border appearing on the rightside of the header.

There's two ways to remove this inline style:
1. jQuery -  $(".fc-row.fc-widget-header").css("border-right-width", "")

2. CSS style to override
  border-right-width:0px !important;

The !important is important! That allows the CSS to override the inline style, which would otherwise take precedence.

I prefer #2, because I prefer to deal with style in CSS when possible.

Monday, March 7, 2016

Access violation exception when using dereferencing a pointer in Dex

I have a pointer point to a temp table. When I try to dereference the pointer, Dynamics GP crashes with the error: "An unhandled exception of type 'System.AccessViolationException' occurred in Dynamics.exe"

Because I was initializing the pointer in a form procedure, it was pointing to the procedure's local table buffer. When the procedure was finished, the local table buffer's memory was deallocated (). So when I dereferenced the pointer, it was pointing at nothing, hence the memory error.

Leaky abstraction
This exposes a leaky abstraction. The table buffers and memory management are abstracted away. It's not explicit that the table buffer in a procedure is different than the containing form's table buffer. Furthermore, the memory management doesn't care that there's a pointer pointing to a location in memory, it deallocates anyway. That tells me the pointers aren't really managed.

Hidden form temp table reference pattern
Instead of running into this problem again in the future, i'm going to write down the pattern for making sure this works, so i don't have to spend hours upon hours troubleshooting a leaky abstraction problem.

"Class"-like form:
1. Has one internal window called State. This window has a hidden reference field on it.
2. Form pre: set State's ref field to the table buffer
3. Init: open form if it's not opened, use the dereferenced table buffer

Thursday, March 3, 2016

Visual Studio Ctrl-F stopped finding things

Ctrl-F > typed in "thing" and Visual Studio did not find any matching values in the entire solution. I can see that there is a "thing" in the current document.

Window Menu > click Reset Window Layout

Thanks to this post from 2008! 

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