Thursday, October 27, 2016

Open form in the UI thread from another thread

Problem
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();
            globalForm.Show();
            globalForm.Hide();

            Task t = new Task(Run);
            t.Start();

        }

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

                //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)
                {
                   test.Show();
                    test.Activate();
                 };
            };
            globalForm.Invoke(m);
        }

Tuesday, September 27, 2016

Error: Subreport could not be shown

Problem
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."

Solution
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


SERVER-SIDE - PARSE FORM DATA

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


CLIENT-SIDE - POST VIA AJAX
var something = "i'm posting via ajax";

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


Ref: http://codehandbook.org/python-flask-jquery-ajax-post/ 

Thursday, August 25, 2016

Network share is not showing new directories / files

Problem
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.

Solution
Add this registry entry:

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


Ref: https://thecitrixman.com/2013/02/11/scanned-files-not-showing-up-in-network-drives/

Tuesday, August 23, 2016

DateTime.ParseExact is throwing Format Exception when single H specified

Problem
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.


Solution

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');

            switch(input.Length)
            {
                case 2:
                    format = "HH";
                    break;
                case 4:
                    format = "HHmm";
                    break;
                case 6:
                    format = "HHmmss";
                    break;
                default:
                    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

Problem
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

Solution
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 combiner.py. 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)
os.chdir(dname)

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

outputFile = "";

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


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

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 combiner.py>
5. Save it all

6. Try editing one of the small JS files and then saving it. combiner.py 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.

Steps
1. Download Paint.Net: http://www.dotpdn.com/files/paint.net.4.0.9.install.zip

2. Download plugin pack:
Direct = http://forums.getpaint.net/index.php?app=core&module=attach&section=attach&attach_id=9798

Forum post with instructions = http://forums.getpaint.net/index.php?/topic/32048-v

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.

Code
radioGroupChangeHandler= function(e){
    switch(e.target.id)
    {
        case "radioGroupOption1":
            console.log("option 1 was selected")
            break;
        case "radioGroupOption2:            console.log("option 2 was selected")
            break;
    }
}

$("input[name='radioGroupName']").change(radioGroupChangeHandler)

Monday, June 13, 2016

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

Problem
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:
6/13/2016

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

Solution
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';
     default:
        return 'th';
   }
 }

Ref: http://stackoverflow.com/a/6003589/1538717

Friday, June 10, 2016

Dexterity - SetBooleanProperty() for FIELD_PROP_REQUIRED is not working

Problem
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.

Solution
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

Problem
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

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

Ref: https://social.msdn.microsoft.com/forums/en-US/a45a3786-5bf7-4661-91bc-587e0b43e849/reportviewer-and-enums

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">
    </div>
</div>

</form>


#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">
        </div>
    </div>
</div>

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.
Ref: http://stackoverflow.com/questions/18429121/inline-form-nested-within-horizontal-form-in-bootstrap-3 

Tuesday, April 12, 2016

Round time to the nearest 30 min #javascript

Problem
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.

Example:
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


Code
var now = new Date();
now.setSeconds(0);
now.setMilliseconds(0);
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);

Note:


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))
  ORDER BY COUNT(*) DESC

Monday, March 21, 2016

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

var obj1 = {
  subscribers:[],
  addSubscriber:function(subObj)
   {
       obj1.subscribers.push(subObj);
   },
   notifySubscribers:function()
   {
        for(var subIndex in obj1.subscribers)
        {
            obj1.subscribers[subIndex].onObj1Change();
        }
   },
   doStuff:function()
   {
       obj1.notifySubscribers();
   }
}


var obj2 = {
   init:function(){
       obj1.addSubscriber(obj2);
   },
   
   onObj1Change:function()
   {
      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
.fc-row.fc-widget-header{
  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

Problem
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"

Solution
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

Problem
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.

Solution
Window Menu > click Reset Window Layout


Ref
Thanks to this post from 2008! http://forums.asp.net/t/1103223.aspx?Find+also+find+and+replace+not+working+in+Visual+Studio 

Sunday, February 28, 2016

Word frequency counter in #javascript

var model = {
    init:function()
    {
        model.words = []
        model.wordCounts =[]

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

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>",
    resetOutput:function(){
        $("#output").text('')
    },
    writeOutput:function(outputArray){$("#output").append(outputArray.join("<br>"))}
}

var controller = {
    inputArea:$("#divInput"),
    init:function(){
       controller.inputArea.append(view.input)
        $("#do").click(controller.doClickHandler)

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


$(controller.init)

Saturday, February 27, 2016

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

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

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

Solution

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)
    })



References
1. http://stackoverflow.com/a/494046/1538717 

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.
*/


HTML

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

</div>
<div id="output">

</div>


Javascript

var model = {
    data:[],
    init:function()
    {
        model.data =[
        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,
            "last":last,
            "position":position,
            "leftdate":leftdate

        }
    }
}

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

var controller = {
    inputArea:$("#divInput"),
    outputArea:$("#output"),
    contains:function(target, search)
    {
        return target.indexOf(search) != -1    },
    init:function(){
       model.init()
        controller.inputArea.append(view.searchForm)
        $("#btnSearch").click(controller.search)

    },
    search:function(){
        var searchWords = $("#search").val()
        controller.outputArea.html('')
        model.data.filter(function(employee)
        {
            return controller.contains(employee.first + " " + employee.last, searchWords)
        }).forEach(function(employee)
        {
            controller.outputArea.append(JSON.stringify(employee)+ "<br>")
        }

        )
    }
}


$(controller.init)

Wednesday, February 24, 2016

#javascript "Unexpected token :"

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

function buildObj(a, b){

return{ 
    "a":a,
    "b":b

}
}

Solution

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

function buildObj(a, b){

return { 
    "a":a,
    "b":b

}
}

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++)
    {
        arr.push(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.


Basics

IDE

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. http://ironpython.codeplex.com/ 
  2. NetBeans. Haven't tried this yet. http://plugins.netbeans.org/plugin/56795/python4netbeans802   
  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: https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows . I want a powerful Python w/ web development IDE. I really like this one!

Indenting

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

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


Importing

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
sys.exit()

Comments

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

Conditionals

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"

Output:
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: http://www.pydanny.com/why-doesnt-python-have-switch-case.html 

Conversions

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

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

Output:
Decimal 1.25  Integer 1

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

Try ... catch


try:
     statements
except (optional Exception type here):
     handle error

example

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

output:
could not convert string to float: haha

functions

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

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

ex
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")

Assertions

assert booleanStatement
example
assert name=="Mak"

Loops


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

Slicing


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


Examples

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])

#reversed
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]



Strings


Formatting

1.
input = raw_input("What's the word? ")
length = len(input);
 #named arguments
print "{input} has {length} chars".format(input=input, length=length)
 #positions
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()

Parsing

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




Classes


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
    @staticmethod
     def BuildMyClass():
         return MyClass()

You'd use it like MyClass.BuildMyClass()

3. Constructor = def __init__():

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

EXAMPLE
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

IO

create directory
import os
os.makedirs("folder1/subfolder1")

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
3. UPDATE:
arr.append("Mac")
4.DELETE:
arr.remove(key)
arr.pop()

5. Checking if a key exists
-arr.__contains__(key)
-key in arr

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


Associative array

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

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

#updating
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")

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



Output
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 = datetime.datetime.now()
print "The year is {0}".format(now.year)
print "20 years from now is {0}".format(now.year + 20)   

output
The year is 2016
20 years from now is 2036


Specific tasks

Opening a URL

response = urllib2.urlopen("http://api.open-notify.org/astros.json")

Getting and parsing JSON

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

response = urllib2.urlopen("http://api.open-notify.org/astros.json")
data = json.loads(response.read())

#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: http://stackoverflow.com/a/8959399/1538717

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("https://api.flickr.com/services/feeds/photos_public.gne?tags=dogs")
    images = []
    for entry in feed["entries"]:
        for link in entry["links"]:
            if (link["type"] == "image/jpeg"):
                images.append(link["href"])
    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 https://pypi.python.org/pypi/bcrypt/2.0.0#downloads 

Website directory
  1. https://docs.python.org/2/library/ 
  2. Twilio - Phone voice and SMS API - https://www.twilio.com/docs/python/install  
  3. Learn Python the Hard way: http://learnpythonthehardway.org/book/index.html 
  4. Hosting: PythonAnywhere.com 
  5. Google Python Style Guide https://google.github.io/styleguide/pyguide.html 
There was an error in this gadget