Tuesday, February 21, 2017

Python One Liner Wonders!

Python:
#!/usr/bin/env python
# set, list, tuple, dict, deque, heapq, OrderedDict, defaultDict, Counter

p = (4,5) # tuple packing
x, y = p
(x, y) = p # typle unpacking
entry = [ 'name', 20, 1.1, (2017, 12, 31) ]
a,b,c,date = entry # d = (2017, 12, 31)
_, x, y, _ = entry # x = 20, y = 1.1
name, *_, (*_, date) = entry # name = 'name', date = 31


s = 'string'
a,b,c,d,e,f = s # a='s', b='t', and so on
*head, tail_one = s # head = 'strin' tail_one = 'g'


# What are these?
x = set(["Postcard", "Radio", "Telegram"])
y = {"Postcard","Radio","Telegram"}
myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
   cnt[word] += 1
print(cnt)
c = Counter(a=4, b=2, c=0, d=-2)

def drop_first_last (list):
   fst, *mdl, lst = list
   return avg(mdl)


Perl:
# To get the same results... 
#

sub pairwise_sum {
   my ($arg1, $arg2) = @_;
   my (@result) = ();
   @list1 = @$arg1;
   @list2 = @$arg2;
   $len = @list1; # same as length(@list1)
   $max_index = $#list1;
   for ($i=0; $i < length(@list1); $i++) {
      push (@result, $list1[$i] + $list2[$i]);
   }
   return (\@result);
}


JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];

// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};


C++:
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };

int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 
 
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
    for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++) {
            jimmy[n][m]=(n+1)*(m+1);
        }
}



Array Initialization - Dynamic!

Java:
// anArray = new int[10];
int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);


Python:
#!/usr/bin/env python
# set, list, tuple, dict, deque, heapq, OrderedDict, defaultDict, Counter
 
x = set(["Postcard", "Radio", "Telegram"])
print(x)
# % set(['Postcard', 'Radio', 'Telegram'])

y = {"Postcard","Radio","Telegram"}
print(y)
# %  

myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]

cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
   cnt[word] += 1
print(cnt)
# % Counter({'blue': 3, 'red': 2, 'green': 1})

c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())

# This is tuple
b = ("Bob", 19, "CS")       # tuple packing
(name, age, studies) = b    # tuple unpacking

def pairwise_sum (list1, list2):
   result = []
   for i in range (len(list1)):
      result.append(list1[i] + list2[i])
   return result


Perl:
# sum up two equal-sized lists of numbers and return the pairwise sum 
#
sub pairwise_sum {
   my ($arg1, $arg2) = @_;
   my (@result) = ();
   @list1 = @$arg1;
   @list2 = @$arg2;
   $len = @list1; # same as length(@list1)
   $max_index = $#list1;
   for ($i=0; $i < length(@list1); $i++) {
      push (@result, $list1[$i] + $list2[$i]);
   }
   return (\@result);
}


Ruby:
names = Array.new(20)
puts names.size  # This returns 20
puts names.length 

names = Array.new(4, "mac")
puts "#{names}"  # This returns "["mac", "mac", "mac", "mac"]"

nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"   # This returns "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"

nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]

digits = Array(0..9)
num = digits.at(6)


JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];

// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};


C++:
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };

int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 
 
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
    for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++) {
            jimmy[n][m]=(n+1)*(m+1);
        }
}


SystemVerilog:

  • Fixed-size (multi-dimension)
  • dynamic (single dimension)
  • queue (single dimension)
  • associative (single dimension)

typedef enum {IDLE, TEST, START} state;

Tcl/Tk:


# create array
set balloon(key) red
array set balloon {color red}
array set myArray {}
array set myArray {"name" "value"}
set myArray(name) value
array unset {this myarray}
set {this myarray(key)}
parray {this myarray}
foreach idx [array names x] {
     set x($idx) {}
}
# determine if a key exists
info exists array(key)
set value1 $myArray(name)
set value2 $myArray($idx)
eval {set ${key}($item)}
puts [set ${key}($item)]

# in a procedure, use upvar to create local reference to array
upvar $key v
puts $v($item)
set v($item) $val


# not so good
set a(key) value
value
array get a

# unset the whole array
unset myArray
# use array unset to unset a subset of keys

proc incrArrayElement {var key {incr 1}} {
    upvar $var a 
    if {[info exists a($key)]} {
        incr a($key) $incr
    } else {
        set a($key) $incr
    } 
}

array set data {
    foo,x ecks    foo,y why    foo,z zed
    bar,x ECKS    bar,y WHY    bar,z ZED
}
set data(foo)(x) ecks; set data(foo)(y) why; set data(foo)(z) zed
set data(bar)(x) ECKS; set data(bar)(y) WHY; set data(bar)(z) ZED
# join [array names data] \n


#
set a(1,1) 0 ;# set element 1,1 to 0
set a([list $i1 $i2 $i3]) 0; # set element (i1,i2,i3) of array a to 0
set a([list 1 2 3]) 0
# above i equivalent to the following
set {a(1 2 3)} 0

# multi-dimention
array set data [list                                         \
    [list foo x] ecks    [list foo y] why    [list foo z] zed\
    [list bar x] ECKS    [list bar y] WHY    [list bar z] ZED\
]
proc array_dimnames {array_var dim_index} {
    upvar 1 $array_var array
    set result [list]
    foreach name [lsort -unique -index $dim_index [array names array]] {
        lappend result [lindex $name $dim_index]
    }
    return $result
}

% array_dimnames data 0
bar foo
% array_dimnames data 1
x y z

proc declare_array arrayName {
    upvar 1 $arrayName array
    catch {unset array}
    array set array {}
} 

# array sort
proc array_sort {index val _foreach_sorting_array_ref foreachsorting_command} {
    # _foreach_sorting_array_ref is a reference this mean equivalent to &array in C
    upvar $_foreach_sorting_array_ref arrref
    upvar $index i
    upvar $val v
        
    set x [list]
    foreach {k vl} [array get arrref] {
        lappend x [list $k $vl]
    }
        
        foreach e [lsort -integer -decreasing -index 1 $x] {
        #puts "$i,$v"
                set i [lindex $e 0]
                set v [lindex $e 1]
                # ------- FOREACH BODY ------------<
        uplevel $foreachsorting_command
        # ------END FOREACH BODY----------->
        }  
}

set name(first) "Mary"
set name(last)  "Poppins"

puts "Full name: $name(first) $name(last)"
parray name

array set array1 [list {123} {Abigail Aardvark} \
                       {234} {Bob Baboon} \
                       {345} {Cathy Coyote} \
                       {456} {Daniel Dog} ]

if {[array exist array1]} {
    puts "array1 is an array"
} else {
    puts "array1 is not an array"
}

proc existence {variable} {
    upvar $variable testVar
    if { [info exists testVar] } {
 puts "$variable Exists"
    } else {
 puts "$variable Does Not Exist"
    }
}

# Create an array
for {set i 0} {$i < 5} {incr i} { set a($i) test }
existence a(0)

set mylist {}
lappend mylist a
lappend mylist b
lappend mylist c
lappend mylist d
foreach elem $mylist {
    puts $elem
}
// or if you really want to use for
for {set i 0} {$i < [length $mylist]} {incr i} {
    puts "${i}=[lindex $mylist $i]"
}

set myarr(chicken) animal
set myarr(cows) animal
set myarr(rock) mineral
set myarr(pea) vegetable

foreach key [array names myarr] {
    puts "${key}=$myarr($key)"
}

foreach {index content} [array get date] {
    put $index: $content
}

# use $array($key) or $array("abc") to access
# multi dimension, use
# set a(1,1) 0
# set a(1,2) 1



Thursday, February 2, 2017

Circuit Playground Sites.



Web Services/Application History.

Java Servlets in early days:
  • Advantages:
    • Much better than CGI, ISAPI, lighter plumbing.
    • Allowed for scalable, robust web development.
  • Disadvantages
    • Hard to incorporate sophisticated HTML.
    • Harder to update HTML design, which could be designed in Dream Weaver.
    • Too much dependency on HTML embedded in Java code.
Then comes JSP:
  • Advantages: 
    • Closer to HTML.
    • Same as servlets with improvement in manipulation of display characteristics.
  • Disadvantages:
    • developers must deal more directly with the view of the application.
    • Syntax quickly becomes cryptic because of the mixing of code and display
    • Too much dependency on JAVA embedded in HTML.
Meet Model-View-Controller:
  • SmallTalk Language creator in 1980's came up with MVC. 
  • Gang of Four wrote "Design Patterns" in 1994 (Wiki).
  • Model represents the data that application is about. (eg. a list of numbers)
  • View is the visual representation of the model (eg. a spreadsheet/graph/chart)
  • Controller is how they interact (eg. keyboard changes cell value, mouse changes graph size)
MVC applications in Java web development (Model 2):
  • The model is represented by Java Beans (or Enterprise Java Beans)
    • Java Beans - a method to encapsulate information.
  • The view uses JSP.
  • The controller is a servlet that drives the process.
  • How it works:
    • The user requests a servlet via a URL or a link.
    • The servlet instantiates one or more Java Beans and calls methods on them.
    • The beans with displayable fields are added to one of the standards collections (eg.request or sessions)
    • Control is forwarded to a JSP to display the results.
Stay tuned...


Tuesday, December 20, 2016

SOAP and REST.

Web Services
  • Transport Protocols : SOAP, REST
  • Respective registries to shared data.
  • Message integrity and non-repudiation
  • Reliable messaging
  • Business process flow
  • Protocol negotiation
  • Security
  • Transactions and process flow
  • Data independence for programming languages, middle-ware systems and DBMS
    • typing
    • structure
    • semantic information associated with data (mapping, transformation, creation)

Components for Web Services
  • XML: Extensible Markup Language
  • WSDL : fundamental abstraction of Web services as interface to underlying software
  • SOAP/REST : communication protocol over internet and networks
  • UDDI : Providing registry and repository services for storing and retrieving Web services interfaces

WSDL : Web Services Description Language
  • A mechanism to describe Web Services
    • data types
    • data structures
    • define interfaces
    • associate services with underlying implementations in each interface
      • how to map the types and structures into the messages to be exchanged
      • how to tie the messages to underlying implementations
  • A definition of service to map to communication protocols and transports such as SOAP messages.
    • both parties interact by sharing a common WSDL file.
    • sender uses the WSDL file to generate the messages.
    • receiver uses the WSDL file to parse the message and map it to underlying program.
  • The goal is that the parts can be developed separately and integrated as a comprehensive WSDL file.

UDDI : Universal Description, Discovery, and Integration

SOAP : Simple object Access Protocol

  • Understanding SOAP from IBM
  • Defines a common format for XML messages over HTTP and other protocols.
  • SOAP is designed so that it can be extended to additional features and functions.
  • SOAP is a one-way asynchronous messaging technology.
  • SOAP can be used in various messaging styles, from RPC (remote procedure calls) to document oriented publishing and subscription.
  • Minimum criterion for a Web service must support SOAP.

Example of Simple SOAP Envelope
<?xml version='1.0' ?>
<env:envelope xmlns:env="http://www.w3.org/2003/05/SOAP-envelope"> 
  <env:header>
  </env:header>
  <env:body>
  </env:body>
</env:Envelope>
Example of SOAP Header with Routing Information
<?xml version='1.0' ?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/SOAP-envelope"> 
  <env:header>
    <wsa:ReplyTo xmlns:wsa=
        "http://schemas.xmlSOAP.org/ws/2004/08/addressing">
      <wsa:Address>
         http://schemas.xmlSOAP.org/ws/2004/08/addressing/role/anonymous
      </wsa:Address>
    </wsa:ReplyTo>
  </env:header>
  <env:body>
  </env:body>
</env:Envelope>

REST, RESTlet, RESTful : REpresentation State Transfer



Wednesday, December 7, 2016

Software Terms.

Framework and Software Testing
  • A framework is a semi-complete application that provides a reusable and common structure to share among developers who can incorporate it into their own application and extend it to their specific needs. 
  • A framework has a more coherent structure than a toolkits with a set of utility classes.
  • For example, JUnit (www.junit.org) is a framework created by Erich Gamma and Kent Beck in 1997, following an earlier work called SUnit.
  • Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides wrote the classic "Design Patterns : Elements of Reusable Object-Oriented Software" book in 1995 and the four authors are often referred to as the Gang of Four (GoF).
  • Kent Beck's software discipline: Extreme Programming

Types of Testing
  • Programmer Test or customer test
  • Unit test: confirms the method (or a unit of work) accepts the expected range of input and returns the expected output value for each input.
    • API contract provides a view of expected behavior by method signature.
    • Notion of API contract
    • An exception should be thrown if the method cannot fulfill the contract.
  • Integration tests
  • Acceptance tests
  • Functional tests / Behavioral tests
    • web page links
    • database connection
    • forms
    • cookies
  • Usability tests
    • efficiency
    • navigation
    • UI
    • content checking
    • visual style
  • Compatibility tests
    • browser compatibility
    • OS
    • mobile browser
    • printing options
  • Performance tests
    • traffic
    • loads
    • stress testing
  • Security tests
    • authentication and authorization
    • session management
    • cryptography and SSL
    • data validation
    • denial of service
    • risky activities



Tuesday, December 6, 2016

Java Interface and Exception.

Understanding Interfaces and Abstract Methods
  • To define what a class must do but not how to do it until later in specific application.
    • An abstract class define its signature and return types, namely, its interface for multiple processes or methods without implementations.
  • How? Specify methods with no body ({}).
  • Actions are defined in a class that implements the interface.
  • One interface, multiple methods is the essence of polymorphism.
  • Prior to JDK 8, interfaces could not define any implementation whatsoever. JDK 8 changes the rule so that default implementation to an interface method is allowed.
  • The original intent behind interface/abstract class remains. and default implementation in essence is a special use feature.
  • JDK 8 also added the ability to define static methods in interfaces.
    • Same as static methods in a class, static methods in interfaces can be called independently of any object created from it.
    • Yes, no implementation or instance of the interface is required to call a static method.
    • To call, specify the interface name, a period and the method name.
    • Static interface methods are not inherited by implementing class or a sub-interface extended from the parent interface.

Using Interface References
  • You can create an interface reference variable and use it to refer to any object that implements its interface. 
  • When you call a method on an object through an interface reference, you are calling the version of the method implemented by the object that is executed at runtime. 
  • This is similar as using a superclass reference to access a child class's methods on its objects. 

Using Interface to Share Constants
  • Though controversial, one usage of interface is to share constants among multiple classes.
  • Variables in interfaces are implicitly public, static and final and these are the characteristics of constants.
  • Examples of applications includes array size, various limits, special values and the like.

Extending Interface
  • An interface can inherit another interface by extending. 
  • When a class implements the derived interface, it must implement all methods in the inheritance chain.
interface X {
   void method1 ();
   void method2 ();
}

interface Y extends X {
   void method3 ();
}

class Z implements Y {
   public void method1 () {
      // do something...
   }
   public void method2 () {
      // do something...
   }
   public void method3 () {
      // do something...
   }
}

class Z2 implements Y {
   // implements all three methods
}

// Using Interface References
class Demo {
   public static void main (String args[]) {
   Z  obz  = new Z();
   Z2 obz2 = new Z2();
   X  obx  = new X();
   obx = obz;
   System.out.println ("Class z attribute is " + obx.getAttribute());
   obx = obz2;
   System.out.println ("Class z2 attribute is " + obx.getAttribute());
}


Exceptions
  • All exceptions are represented by classes.
  • All exceptions are derived from "Throwable" class.
  • When an exception occurs, an object of some exception class is generated.
  • Two direct subclasses of Throwable: Exception and Error.
    • Class Error exceptions are those occur in JVM, not in the program.
    • Class Error exceptions are usually beyond programmer's control.
    • Class Exception exceptions are those from program activity, such as divide-by-zero, array out-of-boundary and file-not-found errors. These are called standard exceptions.
    • Class Exception exceptions should be handled in the program.
      • RuntimeException is an important subclass of Exception class and is used to represent various common types of runt-time errors.
  • Another type of exceptions are those thrown manually by using throw statement.

Exceptions Handling
  • try
    • If an exception occurs within the try block, it is thrown.
  • catch
    • If an exception is thrown by try block, it will be handled here in a predictable way.
  • throw
    • Use throw to manually throw an exception.
  • throws
    • Use throws clause in the declaration of a method to specify an exception could be thrown out of a method.
  • finally
    • Use finally block to specify any activity that must be executed upon exiting from a try block.