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

实际应用: