Multiprocessing – Python

Operating Systems handle and provide mechanisms for multiprocessing. Developers can spawn new processes using the multiprocessing package library in python.

Signature of Process class.
Process class takes the group, target, name, args and kwargs as parameters.

Process(group=None, target=None, name=None, args=(), kwargs={})

Here we’ll see how to to declare processes and execute it.

from multiprocessing import Process
import os


class Loop:
	def __init__(self, num):
		self.num = num
		self.loop = lambda n: [y for y in n]
		print(self.loop(self.num))

if __name__ == "__main__":
	[Process(target=Loop, args=(10,)) for x in range(0, 10)]

Output :

25200
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25201
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25202
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25203
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25204
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25205
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25206
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25207
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25208
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25209
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

A class Loop is defined. We create 10 processes. These processes are iteratively ( a typical for loop )created.

[Process(target=Loop, args(10,)) for x in rage(0, 10)]

A new process is created using the imported Process class with the passing the class name that has been defined to create an object in the process. Seconds parameter consists of parameters to be given to the class.

Process(target=Loop, args=(10,))

For lambda functions in the program visit :Lambda Operator in Python

Static Variables : Java

Declaring a variable static renders the compiler to create only one storage location. Whenever the variable is referred operations are done on that location alone. No other copy of the variable is made. Multiple threads share the same memory location for a particular variable.

Static Variable:

public class Threads extends Thread{
	static int num ;
	Threads(){
		num = 0; 
	}
	public void run(){
		System.out.println("num : "+(num+=1)) ;
	}
	public static void main(String args[]){
		Threads threads1 = new Threads();
		Threads threads2 = new Threads();
		Threads threads3 = new Threads();
		threads1.run();
		threads2.run();
		threads3.run();
	}
}

Output:

Num:1
Num:2
Num:3

Non Static Variables:

class Threads extends Thread{
	int num ;
	Threads(){
		num = 0;
	}
	public void run(){
		System.out.println("Num:"+(num+=1));
	}
	public static void main(String args[]){
		Threads threads1 = new Threads();
		Threads threads2 = new Threads();
		Threads threads3 = new Threads();
		threads1.run();
		threads2.run();
		threads3.run();
	}
}

Output:

Num:1
Num:1
Num:1

Comparing the about outputs we can see the value of num change when the variable is declared static. Unlike the case where a non static variable creates a new storage location for every thread. The memory is not shared in case of a non-static variable. That is why we see the value one repeated in every thread.

Remote Method Invocation

An important topic in this world of ubiquitous computing Remote Method Invocation (RMI). Accessing methods or rendering procedure calls from a remote system subtly connected client server model that reduces the overload on the client by simply transporting the objects from server to client when required. This article focuses on implementation of RMI in java only.
Note: Works with localhost and this post is for beginners.

Server Side

RMI required an interface that the server implements. These methods can be invoked remotely.

  • The interface extends Remote class.
  • All methods throw RemoteException.
import java.rmi.Remote;
import java.rmi.RemoteException;

interface ServerInterface extends Remote{
	int port = 1099 ;
	String stub = "Stub" ;
	void printString(String data) throws RemoteException;
}

Server class implements the remote method interfaces.


import java.rmi.AlreadyBoundException ;
import java.rmi.RemoteException ;
import java.rmi.registry.LocateRegistry ;
import java.rmi.server.UnicastRemoteObjcet ;

class Server implements ServerInterface{
	ServerInterface serverInterface ;
	Registry registry ;
	Server(){
		try{
			serverInterface = (ServerInterface) UnicastRemoteObject.exportObject(this, port) ;
			registry = LocateRegistry.createRegistry(port) ;
			registry.bind(stub, serverInterface) ;
		}catch(RemoteException | AlreadyBoundException e){
			System.err.println(e.getMessage()) ;
		}
	}
	void printString(String string){
		System.out.println(string) ;
	}
}

serverInterface = (ServerInterface) UnicastRemoteObject.exportObject(this, port) ;

The serverInterface (this class object is type casted to it’s interface) object is exported to port 1099 (default port number can be change when desired).

registry = LocateRegistry.createRegistry(port) ;

The object is then registered in the server registry. On the client side we then lookup the registry using it’s stub name.

registry.bind(stub, serverInterface)

Binding the interface object to the stub name. When the registry is looked up with the stub name the server responds with the correct interface.

RemoteException must be caught.

Client Side

Client that requests the remote procedure calls.

class Process{
	final static int port = 1099;
	final static stub = "Stub" ;
	ServerInterface server ;
	Registry registry ;
	Process(){
		try{
			registry = LocateRegistry.getRegistry(port) ;
			server = (serverInterface)registry.lookup(stub) ;
		}catch(RemoteException | NotBoundException e){
			System.err.println(e.getMessage()) ;
	}
	public static void main(String args[]){
		final Process process = new Process ;
		server.printString("Hello world") ;
	}
}

output: Hello world

registry = Locate.getRegistry(port);
server=(serverInterface)registry.lookup(stub);

Create a registry object to locate the desired interface methods in the remote registry. Using the object ServerInterface the client can request all the methods from the remote object.

Continue reading

Storing Object in Text File : Java

Java an object oriented programming language provides mechanism to read and write object from a text file. It is common to see developers storing string or integers in a text file. But usage of files can go beyond those capabilities. Java allows developers to store objects in a text and retrieve them when required. This post covers the details on how to store an object in a text file.

Program.java

import java.io.* ;

class Program{
	private static ObjectOutputStream objectOutputStream ;
	private static ObjectInputStream objectInputStream ;
	private Program(){
		File file = new File("objects.txt") ;
		if( !file.exists() )
			file.createNewFile() ;
		FileInputStream inputStream = new FileInputStream(file) ;
		FileOutputStream outputStream = new FileOutputStream(file) ;
		objectInputStream = new ObjectInputStream(inputStream) ;
		try{
			objectOutputStream = new ObjectOutputStream(outputStream) ;
		}catch(EOFException e){e.getMessage();}
	}
	public static void main(String args[]){
		new Program();
		Student student1 = new Student("name1", "0001") ;
		Student student2 = new Student("name2", "0002") ;
		objectOutputStream.writeObject(student1) ;
		objectOutputStream.writeObject(student2) ;
		Student stu1 = (Student)objectInputStream.readObject() ;
		Student stu2 = (Student)objectInputStream.readObject() ;
		System.out.println("Object1:\nName:"+stu1.name+"\tRegistration:"+stu1.reg) ;
		System.out.println("Object2:\nName:"+stu2.name+"\tRegistration:"+stu2.reg) ;
	}
}

Input/output File streams:
FileInputStream and FileOutputStream opens a byte stream channel between the program and the file. The objects need to be serialized before writing to the file.

Serializing an object means to convert the object to a byte stream.

Object Input/Output Streams:
ObjectInputStream and ObjectOutputStream provides the application with persistent storage for graph of object.
ObjectInputStream throws EOFException when all the objects are read.

Student.java

Class of the objects that needs to be written to the file need to be serialized. This can be done by implementing Serializable interface over the class.

import java.io.Serializable ;

class Student implements Serializable{
	String name, reg ;
	Student(String name, String reg){
		this.name = name ;
		this.reg = reg ;
	} 
}

Output :

Object 1 :
Name : name1 Registration : 0001
Object 2 :
Name: name2 Registration : 0002

Continue reading

Will JavaScript dominate web technology?

Something interesting crept up a while ago. A friend of mine was curious if JavaScript would dominate the web world, as of recent times, he’s been using more of those. In a sense he’d be right or maybe had just become a better developer. Either way it got me thinking, and the answer, not much of a surprise, was yes! Its dominance is already being resonated through what we do.

Today’s client programming requirements, consists of HTML, CSS and JavaScript. HTML is used for constructing the pages, CSS is used to stylize and beautify the page. JavaScript is equally significant to HTML and more significant to CSS. JavaScript is the tool via which we can render a page responsive. Traversing of elements is easy today because of jQuery. Imagine what would AJAX be if there was no JavaScript? No dynamic content on web pages.

In addition to the above, both google and Mozilla, (dominating players with respect to the development of browsers), are key players in the setting the environment for development of JavaScript. Mozilla on one hand provides official documentation and google developed the V8 engine.

Node.js, a gift for JavaScript developers as it allows developers to choose JavaScript as the scripting language on the server. It uses JavaScript as a primary option for full-stack development. Database management systems such as MongoDB has made itself to be very compatible with JavaScript due to its use of JSON as a querying structure and output. For years JavaScript was limited to front-end web development until Node.js was introduced.

A new development environment and language known as web assembly is on its way. I still am a novice in that environment though. As far as I have worked and heard about the language people say it is used to fill the gaps that has been left by JavaScript. Parallel processing, building games, Virtual Reality and Augmented Reality are some of the limitations of JavaScript. For this reason, wasm has been introduces and obviously for better performance. Wasm will be used like how C is being used today, for computation intensive applications and JavaScript will be used like JAVA or Python. But Wasm is no replacement for JavaScript.

Taking into consideration the community that supports it, and the development and advancement of the language, it’s obvious that JavaScript will reside and grow in the near future, i.e, for another decade.

 

Array filter in JavaScript

For years developers have been writting loops to traverse an array and remove undesired elements from it. Now, JavaScript provides its developers with a simple prototype known as filters to this task.

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by provided function.

I don’t remember writing loops to iterate through an array to remove elements that doesn’t satisfy a given condition.

var newarray = arr.filter(callback[, thisArg]) ;

A program to filter out all the odd values and return only even values:

a = [1, 2, 3, 4, 5, 6, 7, 8] ;
a.filter( n => n%2==false) ;
Output: [2, 4, 6, 8]

Values are returned to the new array only if the input value satisfies the above condition.

filter() method takes in three parameters:

  • element – current element that is being processed in the array.
  • index – index of the element.
  • array – array object that is being traversed.

Bubble Sort

Bubble sort also referred to as Sinking sort. Bubble sort is one of the simplest sorting algorithms. It simply compares the adjacent elements and swaps them based on the given condition.

Time complexity : O(n2)

Bubble sort is not an optimal solution when n is large.

import java.util.Arrays ;
public class BubbleSort{
	static int[] list = {10, 12, 1, 15, 16, 13, 18, 9 ,15} ;
	static int count = 0 ;
	public static void main(String... args){
		do{
			for( int  i=0, j=0; j < list[j] ){
					int temp = list[i] ;
					list[i] = list[j] ;
					list[j] = temp ;
				}
			}
			count++ ;
		}while( count < list.length ) ;
		Arrays.stream(list).forEach(System.out::println) ;
	}
}
Output: 1 9 10 12 13 15 16 18

Donald Knuth in his book the Art of Computer Programming has concluded that:

the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems.

Bubble sort and insertion sort have similar running time.

I contemplate, this is called bubble sort because with lesser number of values, i.e. N, the process is light and arises as a bubble in the water which rises up to the surface of the water. On the other hand, when N is large, the process becomes heavier and sinks to the bottom.

Anonymous function in javascript

Javascript is a programming language that improves every year. ECMAScript 2016 has been released with a new feature known are anonymous function. As it can be inferred from the it’s name, a function that not have a name. These functions are declared at runtime. Furthermore, there are instance where the keyword function is not required. In most scenarios you can get rid of the function keyword where callback is required.

An anonymous function is a function that does have a name.

var square = (num)=> num*num ;
square(10) ;

Can be written as:

function square(num){
	return num*num ;
}
square(10) ;
Output: 100

Anonymous functions help reduce the number of lines of code written. Usage in map() built-in function. Map is attached to an array or an iterable object. It take a function as its parameter. This function is anonymous.

var a = [10, 20, 30, 40] ;
a.map( param => param*2 ) ;

Can be written as:

var a = [10, 20, 30, 40] ;
a.map( function(param){
	return param*2 ;
});
Output: [20, 40, 60, 80]
  • If the body of an anonymous function has only a single return statement, then the keyword return is not required.
  • If an anonymous function has only a single statement in it body then {} is not requried.

Anonymous function cannot be used in place where the parameter requires the context. If the parameter has this being passed, it cannot be used. For example, the below code will not work. this refers to global window.

var value = $('input').focusout( this => this.val()) ;
Output: Undefined

It should be written with the function keyword.

var value = $('input').focusout( function(this){
	return this.val() ;
}); 

These anonymous function can be very useful in rendering your promise handler look more simple. An exmple using firebase google sign-in.

firebase.auth().signInWithPopup(provider)
	.then( result => console.log(result) )
	.catch( error => console.log(error) ) ;

It can be written as:

firebase.auth().signInWithPopup(provider)
	.then( function(result) {
		console.log(result) ;
	}).catch( function(error){
		console.log(error);
});

Finally, anonymous function helps developers in reducing the number of lines of code and make the large programs more fathomable to readers.

AngularJS file input

AngularJs a ui framework by Google. It has pretty much dealt with many features that is in HTML. One particular function is lacking, i.e, there is no model to handle files to upload them to a server.

This topic covers the portion on how to receive the name of the file that has been uploaded by the user. If a file name can be obtained it is implied that the developer can handle the file.

below is the HTML code.

<input type="file" file-model="imgURL" ng-click="upload()">

angular.module("myApp", [])
	.controller('ctrl', function($scope){
		$scope.upload = function(){
			console.log($scope.imgURL.name) ;
		}
	})
	.directive('fileModel', ['$parse', function($parse){
		return{
			restrict: 'A',
			link: function(scope, element, attrs){
				var model = $parse(attrs.fileModel) ;
				var modelSetter = model.assign ;
				element.bind('change', function(){
					$scope.apply(function(){
						modelSetter(scope, element[0].files[0]) ;
					}) ;
				}) ;
			}
		}
	}]) ;

We create a new directive since a directive to handle files is not pre-defined unlike other input elements. The file value can be obtained in the controller of the app.

Enhanced For Statement In Java

Java has an enhanced for statement, commonly known as, For-each statememt. These statements are used to iterate through array and collections, such as, ArrayList, String, HashMap and Set.

Below is a demo of a for-each loop through an integer array.

public class ForEachDemo{
	static int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9} ;
	public static void main(String... args){
		for(int num: numbers){
			System.out.prin(num+"\t") ;
		}
	}
}

Output:

1 2 3 4 5 6 7 8 9

Unlike primitive for loop, enhanced for loop has two parts:

  1. Intialize a temporary variable to collect the value in each iteration.
  2. Give the reference of the collection or array to be iterated through.

Signature of enhanced for loop :

for( intialization : collection )

Explanation of the above program:

  • int num is the temporary variable that stores the value at each iteration.
  • numbers is the array that contains the integer values that needs to be iterated.

The above arrays can be iterated through streams also.