Wednesday, December 30, 2015

Event Driven - Java

Button:
setup() {
    ...
    MapUtils.createDefaultEventDispatcher(this, map);
    ...
}

draw() {
    map.draw();
}

Add two buttons to control the background color:
Step1: Draw Buttons (using processing)
fill() rect() etc.
* Need to put into draw method because setup only execute once.

Step2: Add functionality for buttons
mousePressed(); mouseClicked(); mouseReleased();
need to check the coordinate where the mouse is released.

Listener Hierarchy:

We have introduced the class CommonMarker as the parent class of both EarthquakeMarker and CityMarker. Now CommonMarker is the class that overrides the draw() method, and it calls drawMarker() which each subclass will implement. We introduced CommonMarker because in this assignment there will be some drawing functionality that is common to all markers on our map, so we didn’t want to have to duplicate code between EarthquakeMarker and CityMarker. This process of restructuring our code is known as refactoring and it is very common in software engineering.

Implement the selectMarkerIfHover helper method in EarthquakeCityMap. This method is called in mouseMoved() method in EarthquakeCityMap, and mouseMoved() is called by the event handler when the user moves the mouse. selectMarkerIfHover should set the instance variable selected for the first Marker it finds that mouseX and mouseY is inside of.

Wednesday, December 23, 2015

Polymorphism

What:
多态

Why:
So the methods can be called based on the dynamic object type. (one of them).

Details:

Step1: Compiler interprets the code.
Step2: Runtime environment executes interpreted code.
Compile time rules:
Compiler only look at reference type. (solution: casting)
Can only look in reference type class for method.
Outputs a method signature.
Run time rules:
Follow exact runtime type of object to find method.
Must match compile time method signature
Run time type check: "instanceof"

Abstract classes and Interface:
  Abstract:
    - Can make any class abstract with keyword:
      public abstract class Person {
    - Class must be abstract if any methods are:
      public abstract void monthlyStatement() { (concrete subclass must override this method)

Implementation vs. Interface:
Implementation: instance variables and methods which define common behavior
Interface: method signatures which define required behaviors
Abstract class can do both.
If only interface needed, use Interface.

  Interfaces:
    - Interfaces only define required methods
    - Classes can inherit from multiple Interfaces

If you just want to define a required method: Interface
If you want to define potentially required methods AND common behavior: Abstract class




Tuesday, December 22, 2015

Inheritance

What:
继承,子类继承父类。

Why:
Good for complex, large projects.
1. Keep common behavior in one class.
2. Split different behavior in separate classes.
3. Keep all of the objects in a single data structure.

How:
Use "extends"

Details:
What is inherited?
1. Public instance variables.
2. Public methods.
3. Private instance variables (can only be accessed via public methods eg. getter and setter).

Person p = new Student(); //correct, a student is a person

// Following is fine
Person[] p = new Person[3];
p[0] = new Person();
p[1] = new Student();
p[2] = new Faculty();
public class Person {
    private String name;
    public String getName() { return name; }
}

public class Student extends Person {
    private int id;
    public int getId() { return id; }
}

public class Faculty extends Person {
    private String id;
    public String getId() { return id; }
}

//In main method somewhere
Student s = new Student();
Person p = new Person();
Person q = new Person();
Faculty f = new Faculty();
Object o = new Faculty();

String n = s.getName(); // fine
p = s; // fine, all student is a person
int m = p.getId(); // bad, because compiler does not know that p is a student, you need to cast it as below
int m = ((Student)p).getId();
f = q; // bad, not all person is a faculty
o = s; //fine, anything is a object

Modifiers:
public: can access from any class
protected: can access from: same class, same package, any subclass
package: can access from: same class, same package
private: can only access from same class
一般来说,只用public和private

Revisit Constructor:
Student s = new Student();
new - allocates space
Student() is passed to constructor
From inside out:
Student() -> Person() -> Object()
Object() will initialize variables then Person(), then Student().

Compiler Rules:
1. No super class: then insert "extends Object"
2. No constructor: give one for you
2. In the constructor, the first line must be:
    this(args_optional);
  or super(args_optional);
  If none, then compiler inserts "super();"

Method Overriding:
Override: Subclass has same method name with the same parameters as the superclass
Overload: Same class has same method name with different parameters.




Thursday, December 17, 2015

Database - Python

dir() - list capabilities of a class 
type() - type of a variable/object (will show "instance" only)

Inheritance class PartyAnimal:
class FootballFan(PartyAnimal):

CRUD SQL:
CREATE TABLE Users(name VARCHAR(128), email VARCHAR(128))
INSERT INTO Users(name, email) VALUES ('testname', 'testname@test.it')
DELETE FROM Users WHERE email='testname@test.it'
UPDATE Users SET name='realname' WHERE email='realname@test.it'
SELECT * FROM Users
SELECT * FROM Users WHERE email='realname@test.it'
SELECT * FROM Users ORDER BY email

Counting Email from org:
import sqlite3

conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()

cur.execute('''
DROP TABLE IF EXISTS Counts''')

cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')

fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: ') : continue
    pieces = line.split()
    email = pieces[1]
    emailpcs = email.split('@')
    org = emailpcs[1]
    print org
    cur.execute('SELECT count FROM Counts WHERE org = ? ', (org, ))
    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (org, count)
                VALUES ( ?, 1 )''', ( org, ) )
    else : 
        cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?',
            (org, ))
    # This statement commits outstanding changes to disk each 
    # time through the loop - the program can be made faster 
    # by moving the commit so it runs only after the loop completes
    conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'

print
print "Counts:"
for row in cur.execute(sqlstr) :
    print str(row[0]), row[1]

cur.close()

Database Design:
Step1:
Think about the central attribute of the application: Track in Music db.

Step2:
Create the table from the most non-central attribute: Start from the end of the arrows.

Step3:
Insert data.

Join:
select Album.title, Artist.name from Album join Artist on Album.artist_id = Artist.id

If no "on", then do full outer join.

Many-to-many relationship
We need to add a "connection" table with two foreign keys. (Usually no primary key).
Table 1: Course (id, title)
Table 2: User(id, name, email)
Add table:
Member(course_id, user_id)

SELECT User.name, Member.role, Course.title
FROM User JOIN Member JOIN Course
ON Member.user_id = User.id AND Member.course_id = Course.id
ORDER BY Course.title, Member.role DESC, User.name


Tuesday, December 8, 2015

Linked List

Nodes.
Each node has a value and a link to next node. (singly)

基本操作:
1. Create a Linked List
class Node {
 Node next = null;
 int data;
 public Node(int d) {
  data = d;
 }
 
 void appendToTail(int d) {
  Node end = new Node(d);
  Node n = this;
  while (n.next != null) { n = n.next; }
  n.next = end;
 }
}

2. Deleting a Node from Singly Linked List
    1) Delete a node, given head node and the value of the node to be deleted. (singly)
   
Node deleteNode(Node head, int d) {
  Node n = head;
  if (n.data == d) {
   return head.next;
  }
  while (n.next != null) {
   if (n.next.data == d) {
    n.next = n.next.next;
    return head; //head not change
   }
   n = n.next;
  }
  return head; //return head if d is not in the list
 }

    2) Delete a node from the middle, only access to that node. (Leetcode)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        if (node == null || node.next == null) return;
        node.val = node.next.val;
        node.next = node.next.next;
        node = node.next;
    }
}

3. Reverse a singly linked list
    1) Recursive

public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode second = head.next;
        head.next = null;
        ListNode node = reverseList(second);
        second.next = head;
        return node;
    }
}
    2) Iterative
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        return prev;
    }
}

实际应用:

Thursday, November 12, 2015

Files - Python

Files - Python

Open a file:
open(): return a handle to operate the file
syntax:
handle = open(filename, mode)
fhandle = open('mbox.txt', 'r')
handle is not the actual data from the file, it is a "connection".


The newline character:
\n
it is one character.

Can treat a file handle as a sequence: (a sequence is an ordered set)
xhandle = open('mbox.txt')
for cheese in xhandle:
    print cheese

Read the Whole file (into a single string inlucding the newlines):
inp = xhandle.read()

Searching through the file:
for and if
line.startwith('xxx')
line.rstrip() #strip the white space(s) at the right of the line

Skipping with continue:
use continue in for and if

'xxx' in line
not 'xxx' in line

Prompt for the file name:
fname = raw_input('Enter the file name: ')

Try to open a file:
fname = raw_input...
try:
    fhand = open(fname)
except:
    print "Cannot open the file: ", fname
    exit()

Python Data Structures

<String>
### String Processing

# String literals
s1 = "Rixner's funny"
s2 = 'Warren wears nice ties!'
s3 = " t-shirts!"
#print s1, s2
#print s3

# Combining strings
a = ' and '
s4 = "Warren" + a + "Rixner" + ' are nuts!'
print s4

# Characters and slices
print s1[3]
print len(s1)
print s1[0:6] + s2[6:]
print s2[:13] + s1[9:] + s3

# Converting strings
s5 = str(375)
print s5[1:]
i1 = int(s5[1:])
print i1 + 38

Another example:
# Handle single quantity
def convert_units(val, name):
    result = str(val) + " " + name
    if val > 1:
        result = result + "s"
    return result
        
# convert xx.yy to xx dollars and yy cents
def convert(val):
    # Split into dollars and cents
    dollars = int(val)
    cents = int(round(100 * (val - dollars)))

    # Convert to strings
    dollars_string = convert_units(dollars, "dollar")
    cents_string = convert_units(cents, "cent")

    # return composite string
    if dollars == 0 and cents == 0:
        return "Broke!"
    elif dollars == 0:
        return cents_string
    elif cents == 0:
        return dollars_string
    else:
        return dollars_string + " and " + cents_string
    
    
# Tests
print convert(11.23)
print convert(11.20) 
print convert(1.12)
print convert(12.01)
print convert(1.01)
print convert(0.01)
print convert(1.00)
print convert(0)

dir function: return the available built-in functions of a type.

<Sets>

Sets: Keep track of a collection of objects.

List - ordered sequence
Dictionary - Key-Value Mapping
Sets - unordered collection of data with no duplicates

list:
[1, 2, 2, 3, 1]

set:
set([1, 2, 3])

set1.add()
set2.remove()
set3.difference_update(set2)

<List>

List
a = [1, 2, 3]
b = a  #b point to where a is pointing
c = list(a) #c point to a new list copied from a
list is mutable

list can be empty
list can contain different of types

list is a ordered sequence
lis1.sort()

Tuple
a = (1, 2, 3)

tuple is immutable (a[1] = 4, throws an type error)

Methods:
lst = [1, 82, -6, 4,  3, 8]

len(lst) give the number of elements in list
sum(lst)
max(lst)
min(lst)
avg = sum(lst)/len(lst)

range(n) returns a list [0, ..., n-1] //usually used to construct a loop

82 in list => T/F
if 4 in list:
    print "4 is there"

lst.index(8) => 5

lst.append(632) => [1, 82, -6, 4, 3, 8, 632]

lst.pop() => [1, 82, -6, 4, 3, 8]

lst.pop(4) => [1, 82, -6, 4, 8]

lst.remove(82) => [1, -6, 4, 8]

list1 + list2 to concatenate two lists.

use ":" to slice lists
list1[:]
list1[1:3]

split() split a string into a word list.
or split(";")

<Dictionary>

Dictionary
compare to List:
List - a linear collection of values that stays in order / use index (position) to lookup element
Dictionary - A bag (unordered) of values, each with its own label / use key (label) to lookup values

Properties or Map or HashMap in Java
Associate Arrays Perl/PHP
Property Bag C#/.net

Mapping
    Key -> Values

d = {1:2, 3:4}
d[1] -> 2

d = dict()
d = {} # empty dictionary
d = {"abc":1, "cd":2}
d["abc"] = 1
d["abc"] = d["abc"]+1
d = {"abc":2, "cd":2}

if reference a key which is not in the dict, trace error.
to check, use:
"key" in dict1 (True or False)

Methods:
get
dict1.get(key, default): return the value for key, if key does not exist, then return the default value.

list(dict1) list all the keys
dict1.keys() list all the keys
dict1.values() list all the values
dict1.items() list of (key, value) tuples.

Two iteration variables:
for aaa.bbb in dict1.items():

Typical application:
1) Most common names (many counters)
use name as key, go through all the names, and for each "name", do dict["name"]+1

2) most common word and the number of appearances
same as above
bigcount = None
bignumber = None
for word.count in dict1.items():
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count

<Tuples>
Tuples are like list. Use index to lookup, and ordered.
x = ('Glenn', 'Jen', 'Steve')
x[2] -> Steve
max(x)
for i in x

Tuple is immutable. So cannot do: sort(), append(), reverse()
use dir(tuple1) to check what methods are available.
count() and index()

Tuples are more efficient. (faster since do have to save space for modification)

Can put tuple on the LHS of assignment:
(a, b) = ('jack', 'Annie')
(x, y) = (1, 2)
a, b = ('jack', 'Annie')
a -> 'jack'

Dictionary items() return list of tuples

for (k, v) in dict1.items():

tups = dict1.items()

tuples are comparable (compare one by one)
(0, 1, 20000) < (0, 2, 3) -> True
so use dict1.items() and sort, we can sort by keys (since only look at the first one)
or use t = sorted(dict1.items())
if want to sort by value,
tmp = [] (or list())
then for k, v in dict1.items():
            tmp.append((v,k))
        tmp.sort(reverse=True)

applications:
top 10 common used words
print sorted([(v,k) for k, v in dict1.items()] )