my net house


Category Archives: Python

Asynchronous recipes in Python

“Concurrency” is not “Parallelism” May be it’s better. If you will not work with DataScience, DataProcessing, Machine-Learning and other operations which are CPU-Intensive you probably will found that you don’t need parallelism but you need concurrency more!

  1. A Simple Example is Training a machine learning model is CPU intensive or You can use GPU.
  2. To Make various Predictions from one model based on many Different Input-Parameters to find out best result You need Concurrency!


There are so Many ways one can hack into Python stuff and do cool Stuff either it is CPU intensive or just a task to do stuff that is good/bad/Better/Best for one user to communicate. One thing you have to believe that Python Does support Multiprocessing as well as Multi-threading

but for various reasons when you are doing CPU intensive Tasks you have to Stay away from using Threading operations in Python. Use Numpy, Cython,Jython or anything you feel, Write C++ code and glue it with Python

The number of threads will usually be equivalent to the number of cores you have. If you have hyperthreading on your processor, than you will be able to double the number of threads used.

Above image is just one Example to understand what actually we are doing. We are processing Chunks and Chuncks of Data. Now the real common scenario is If you are using I/O bound tasks use Threads in Python if you are using CPU bound tasks use Processes in Python.  I have worked with various Python Projects where Performance was issue at some level so at that time I always went to other things like Numpy, Pandas, Cyhton or numba but not Plain-Python.

Let’s come to the point and Point is What are those Recipes I can use:

Using concurrent.futures(futures module is also back-ported into Python2.x):

Suppose you have to call multiple URLs at same time using same Method. That is what actually Concurrency is, Apply same method different operations, We can do it either using ThreadPool or ProcessPool.

# Using Process Pool
from concurrent.futures import ProcessPoolExecutor,as_completed
def health_check1(urls_list):
pool = ProcessPoolExecutor(len(urls_list))
futures = [pool.submit(requests.get,url,verify=False) for url in final_url]
results = [r.result() for r in as_completed(futures)] # when all operations done
return results # a Python list of all results, Here you can also use Numpy as well

Using ThreadPool it is also not different:

# Using Thread Pool
from concurrent.futures import ThreadPoolExecutor,as_completed

def just_func(urls_list):
pool = ThreadPoolExecutor(len(urls_list))
futures = [pool.submit(requests.get,url,verify=False) for url in urls_list]
results = [r.result() for r in as_completed(futures)] # when all operations done
return results # a Python list of all results, Here you can also use Numpy as well

In the above code ‘url_list’ is just list of tasks which are similar and can be processed using same kind of functions.

On the other-side using it with with as context manager is also not different. In this Example I will Use ProcessPoolexecutor’s inbuilt map function.

def just_func(url_list):
with concurrent.futures.ProcessPoolExecutor(max_workers=len(final_url)) as executor:
result =,final_url)
return [i for i in result]

Using multiprocessing: (Multiprocessing is also Python-library that can be used for Asynchronous behavior of your code.)

*in Multiprocessing the difference between map and apply_async is only that Map returns results as task list is passed to it on the other-hand apply_async returns results based on results those returned by function.

# Function that run multiple tasks
def get_response(url):
“””returns response for URL ”””
response = requests.get((url),verify=False)
return response.text

Now above function is simple enough that is getting one URL and returning response but if have to pass multiple URLs but I want that get request to each URL should be fired at same time then That would be Asynchronous process not multiprocessing because in Multiprocessing Threads/Processes needs to communicate with each other but on the other hand in case of Asynchrounous threads don’t communicate(in Python because Python uses Process based multiprocessing not Thread Based although you can do thread-based multiprocessing in Python but then you are on your OWN 😀 😛 Hail GIL (Mogambo/Hitler)).

So above function will be like this as usual:

from multiprocessing import Pool
pool = Pool(processes=20)
resp_pool =,tasks)
URL_list = []
resp_pool =,tasks)

Although This is an interesting link one can watch while going into Multiprocessing in Python using Multiprocessing: It is Process-Bases Parallelism.

Using Gevent: Gevent is a concurrency library based around libev. It provides a clean API for a variety of concurrency and network related tasks.

import gevent
import random

def task(pid):
Some non-deterministic task
print(‘Task %s done’ % pid)

def asynchronous():
threads = [gevent.spawn(task, i) for i in xrange(10)]


If you have to Call Asynchronously but want to return results in Synchronous Fashion:

import gevent.monkey

import gevent
import urllib2
import simplejson as json

def fetch(pid):
response = urllib2.urlopen(‘’)
result =
json_result = json.loads(result)
datetime = json_result[‘datetime’]

print(‘Process %s: %s’ % (pid, datetime))
return json_result[‘datetime’]

def asynchronous():
threads = []
for i in range(1,10):
threads.append(gevent.spawn(fetch, i))


Assigning Jobs in Queue:

import gevent
from gevent.queue import Queue

tasks = Queue()

def worker(n):
while not tasks.empty():
task = tasks.get()
print(‘Worker %s got task %s’ % (n, task))

print(‘Quitting time!’)

def boss():
for i in xrange(1,25):


gevent.spawn(worker, ‘steve’),
gevent.spawn(worker, ‘john’),
gevent.spawn(worker, ‘nancy’),

When you have to manage Different Groups of Asynchronous Tasks:

import gevent
from gevent.pool import Group

def talk(msg):
for i in xrange(3):

g1 = gevent.spawn(talk, ‘bar’)
g2 = gevent.spawn(talk, ‘foo’)
g3 = gevent.spawn(talk, ‘fizz’)

group = Group()


Same As multiprocessing Library you can also use Pool to map various operations:

import gevent
from gevent.pool import Pool

pool = Pool(2)

def hello_from(n):
print(‘Size of pool %s’ % len(pool)), xrange(3))

Using Asyncio:

Now let’s talk about concurrency Again! There is already lot of automation is going inside asyncio or Gevent but as programmer we have to understand how we need to break a “One large task into small chuncks of Subtasks so when we will write code we will be able to understand which tasks can work independently.

import time
import asyncio

start = time.time()

def tic():
return ‘at %1.1f seconds’ % (time.time() – start)

async def gr1():
# Busy waits for a second, but we don’t want to stick around…
print(‘gr1 started work: {}’.format(tic()))
await asyncio.sleep(2)
print(‘gr1 ended work: {}’.format(tic()))

async def gr2():
# Busy waits for a second, but we don’t want to stick around…
print(‘gr2 started work: {}’.format(tic()))
await asyncio.sleep(2)
print(‘gr2 Ended work: {}’.format(tic()))

async def gr3():
print(“Let’s do some stuff while the coroutines are blocked, {}”.format(tic()))
await asyncio.sleep(1)

ioloop = asyncio.get_event_loop()
tasks = [


Now in the above code gr1 and gr2 are somehow taking some time to return anything it could any kind of i/o operation so what we can do here is go to the gr3 in using the event_loop and event_loop will run until all three tasks are not completed.

Please have a closer look at await keyword in the above code. It is one of the most important step where you can assume interpreter is shifting from one task to another or you can call it pause for function. If you have worked with yield or yield from in Python2 and Python3 you would be able to understand that this is stateless step for the code.

There is on more library which is aiohttp that is being used to handle blocking Http requests with asyncio.

import time
import asyncio
import aiohttp

URL = ‘’

async def fetch_async(pid):
print(‘Fetch async process {} started’.format(pid))
start = time.time()
response = await aiohttp.request(‘GET’, URL)
return response

async def asynchronous():
start = time.time()
tasks = [asyncio.ensure_future(
fetch_async(i)) for i in range(1, MAX_CLIENTS + 1)]
await asyncio.wait(tasks)
print(“Process took: {:.2f} seconds”.format(time.time() – start))

ioloop = asyncio.get_event_loop()

In all the above Examples we have just Scratched the world of concurrency but in real there would be much more to look into because real world problems are more complex and intensive. There are various other options in asyncio like handling exceptions with-in futures, creating future wrappers for normal tasks,Applying timeouts if task is taking more than required time and doing something else instead.

There is lot of inspiration I got while learning about concurrent programming in Python from the following Sources:


Run Flask in Parallel using ThreadPoolExecutor

from flask import Flask
from time import sleep
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor(2)

app = Flask(__name__)

def run_jobs():
executor.submit(some_long_task2, 'hello', 123)
return 'Two jobs was launched in background!'

def some_long_task1():
print("Task #1 started!")
print("Task #1 is done!")

def some_long_task2(arg1, arg2):
print("Task #2 started with args: %s %s!" % (arg1, arg2))
print("Task #2 is done!")

if __name__ == '__main__':

Running Multiprocessing in Flask App(Let’s Spawn) Hell Yeah

Ok It was going to be long time but Finally yeah Finally Able to do Process based multiprocessing in Python and even on Flask. 🙂 oh yeah! There are various recipes for Multiprocessing in this python but here you can only Enjoy with Flask.


from multiprocessing import Pool
from flask import Flask
from flask import jsonify
import ast
import pandas as pd
import requests

app = Flask(__name__)
_pool = None

# Function that run multiple tasks
def get_response(x):
“””returns response for URL list”””
m = requests.get((x),verify=False)
return m.text

def health_check():
“””returns pandas dataframe into HTML for health-check Services”””
resp_pool =,tasks)
table_frame= pd.DataFrame([ast.literal_eval(resp) for resp in resp_pool])
return table_frame.to_html()

if __name__==’__main__’:
_pool = Pool(processes=12) # this is important part- We
# insert production server deployment code
except KeyboardInterrupt:


Python For Yankees

Before going further reading about Class Development I would like you to tell
one important thing:

Most of the uses of inheritance can be simplifi ed or replaced with composition, and multiple
inheritance should be avoided at all costs.

I am sure after this you will be able to read lots and lots of code written in
python. 🙂 If you want to do it fast, Do it well. 🙂

Python Class Development Toolkit.

def __init__():

Don’t put anything in instance that you don’t need instance for.

def i_am_class_method(self):
return ‘takes self as argument’

If you need to shared data for whole class then put it on class level,
not on instance level.

class IAm(object):


def __init__(self):
print shared_data

def fun_2(self):
print shared_data

Iron_clad_rule:- in java or C++ is–>do not expose your attributes

Subclassing is just like inhertance. Data+methods:

Class NewOne(IAm):

def fun3(self):
return IAm.fun_2(self)

Multiple/Alternative-Constructors:(When you need to change the behavior
of class’s data by just calling an intensive function):

class Circle(object):

def __init__(self,radius):

def fun_2(self):
print self.radius

@classmethod   # Alternative constructive
def from_bbd(cls,new_radius):
“””construct a circle from bounding box diagnol”””

raduis = new_radius/2.0/math.sqrt(2.0)
return Circle(radius)

Make Alternate constructor to work for Subclass as well:

class Circle(object):

def __init__(self,radius):

def fun_2(self):
print self.radius

@classmethod   # Alternative constructive
def from_bbd(cls,new_radius):
“””construct a circle from bounding box diagnol”””

raduis = new_radius/2.0/math.sqrt(2.0)
return cls(radius)

Independent methods inside class: – Why we ever need those?
Think of situation where everything in your code breaks but you just need to tell
user something and something and all you need is 🙂 Static-Method.!!

class Circle(object):

def __init__(self,radius):

def fun_2(self):
print self.radius

def just_method(just_parameter):
return ‘I am independent’

Getters and Setters in Python:(Access Data,change data on the fly)
As in the other languages there are inbuilt methods to access data from
class as well as change values of method attributes in the class.

Python uses the property decorator to perform such operations:

class Person(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

def full_name(self):
return self.first_name + ‘ ‘ + self.last_name

def full_name(self, value):
first_name, last_name = value.split(‘ ‘)
self.first_name = first_name
self.last_name = last_name

def full_name(self):
del self.first_name
del self.last_name

Slots in Pyhton:
When you have lots and lots of things to perform or do in the way that
your class instance is consuming HUGE memory then you must use SLOTS.

Earlier approach:

class MyClass(object):
def __init__(self, name, identifier): = name
self.identifier = identifier

Approach after SLOTS:

class MyClass(object):
__slots__ = ['name', 'identifier']
def __init__(self, name, identifier): = name
self.identifier = identifier

Alpha generation Quantitative

The average quantitative strategy may take from 10 weeks to seven months to develop, code, test and launch.[6] It is important to note that alpha generation platforms differ from low latency algorithmic trading systems. Alpha generation platforms focus solely on quantitative investment research rather than the rapid trading of investments. While some of these platforms do allow analysts to take their strategies to market, others focus solely on the research and development of these highly complex mathematical and statistical models.

After building Models(Paint those!)

Cross Validation: Each Sample is separated into random equal sized sub-samples, Helps to improve model performance.

Different Forms of cross Validation:

  1. Train-Test Split – low variance but more bias
  2. LOOCV(Leave one out Cross validation) – Leave one data point out and apply model on rest of the data. -low bias but high variance,

Now in the above two methods we have limitations related to Bias and variance, So what to do? Let’s fire-up ‘Cross-Validation’!

There are various other important Cross Validation Examples/Methods those are interesting like Time-series_Split, Leave_P_out(LPO), Random_permutation_Split(Shuffle and split), StarifiedKfold,:

Special Case:

Some classification problems can exhibit a large imbalance in the distribution of the target classes: for instance there could be several times more negative samples than positive samples. In such cases it is recommended to use stratified sampling as implemented in StratifiedKFold and StratifiedShuffleSplit to ensure that relative class frequencies is approximately preserved in each train and validation fold.


Python for text processing

Python is more about ‘Programming like Hacker’ while writing your code if you keep things in mind like reference counting, type-checking, data manipulation, using stacks, managing variables,eliminating usage of lists, using less and less “for” loops could really warm up your code for great looking code as well as less usage of CPU-resources with great Speed.

Slower than C:

Yes Python is slower than C but you really need to ask yourself that what is fast or what you really want to do. There are several methods to write Fibonacci in Python. Most popular is one using ‘for loop’ only because most of the programmers coming from C background uses lots and lots of for loops for iteration. Python has for loops as well but if you really can avoid for loop by using internal-loops provided by Python Data Structures and Numpy like libraries for array handling You will have Win-Win situation most of the times. 🙂

Now let’s go with some Python tricks those are Super cool if you are the one who manipulates,Filter,Extract,parse data most of the time in your job.

Python has many inbuilt methods text processing methods:

>>> m = ['i am amazing in all the ways I should have']

>>> m[0]

'i am amazing in all the ways I should have'

>>> m[0].split()

['i', 'am', 'amazing', 'in', 'all', 'the', 'ways', 'I', 'should', 'have']

>>> n = m[0].split()

>>> n[2:]

['amazing', 'in', 'all', 'the', 'ways', 'I', 'should', 'have']

>>> n[0:2]

['i', 'am']

>>> n[-2]



>>> n[:-2]

['i', 'am', 'amazing', 'in', 'all', 'the', 'ways', 'I']

>>> n[::-2]

['have', 'I', 'the', 'in', 'am']

Those are uses of lists to do string manipulation. Yeah no for loops.

Interesting portions of Collections module:

Now let’s talk about collections.

Counter is just my personal favorite.

When you have to go through ‘BIG’ lists and see what are actually occurrences:

from collections import Counter

>>> Counter(xrange(10))

Counter({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})

>>> just_list_again = Counter(xrange(10))

>>> just_list_again_is_dict = just_list_again

>>> just_list_again_is_dict[1]


>>> just_list_again_is_dict[2]


>>> just_list_again_is_dict[3]


>>> just_list_again_is_dict['3']


Some other methods using counter:


Counter({'a': 10, 'r': 2, 'b': 2, 'k': 1, 'd': 1})

>>> c1=Counter('abraakadabraaaaa')

>>> c1.most_common(4)

[('a', 10), ('r', 2), ('b', 2), ('k', 1)]

>>> c1['b']


>>> c1['b'] # work as dictionary


>>> c1['k'] # work as dictionary


>>> type(c1)

<class 'collections.Counter'>

>>> c1['b'] = 20

>>> c1.most_common(4)

[('b', 20), ('a', 10), ('r', 2), ('k', 1)]

>>> c1['b'] += 20

>>> c1.most_common(4)

[('b', 40), ('a', 10), ('r', 2), ('k', 1)]

>>> c1.most_common(4)

[('b', 20), ('a', 10), ('r', 2), ('k', 1)]

Aithematic and uniary operations:

>>> from collections import Counter

>>> c1=Counter('hello hihi hoo')

>>> +c1

Counter({'h': 4, 'o': 3, ' ': 2, 'i': 2, 'l': 2, 'e': 1})

>>> -c1


>>> c1['x']


Counter is like a dictionary but it also considers the counting important of all the content you are looking for. So you can plot the stuff on Graphs.


it makes your chunks of data into meaningful manner.

>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> new_d = OrderedDict(sorted(d.items()))
>>> new_d
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> for key in new_d:
...     print (key, new_d[key])
apple 4
banana 3
orange 2
pear 1


Think it the way you need to save each line of your CSV into list of lines but along with that you also need to take care of not just the memory but as well as You should be able to store each line as dictionary data structure so if you are fetching lines from Excel or CSV document which comes in place when you work at Data-Processing environment.

# The primitive approach
lat_lng = (37.78, -122.40)
print 'The latitude is %f' % lat_lng[0]
print 'The longitude is %f' % lat_lng[1]

# The glorious namedtuple
LatLng = namedtuple('LatLng', ['latitude', 'longitude'])
lat_lng = LatLng(37.78, -122.40)
print 'The latitude is %f' % lat_lng.latitude
print 'The longitude is %f' % lat_lng.longitude


It is Container of Containers: Yes that’s really true. 🙂

You better be above Python3.3 to try this code.

>>> from collections import ChainMap

>>> a1 = {'m':2,'n':20,'r':490}

>>> a2 = {'m':34,'n':32,'z':90}

>>> chain = ChainMap(a1,a2)

>>> chain

ChainMap({'n': 20, 'm': 2, 'r': 490}, {'n': 32, 'm': 34, 'z': 90})

>>> chain['n']


# let me make sure one thing, It does not combines the dictionaries instead chain them.

>>> new_chain = ChainMap({'a':22,'n':27},chain)

>>> new_chain['a']


>>> new_chain['n']



You can also do comprehensions with dictionaries or sets as well.

>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

>>> m

{'d': 4, 'a': 1, 'b': 2, 'c': 3}

>>> {v: k for k, v in m.items()}

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

StartsWith and EndsWith methods for String Processing:

Startswith, endswith. All things have a start and an end. Often we need to test the starts and ends of strings. We use the startswith and endswith methods.

phrase = "cat, dog and bird"

# See if the phrase starts with these strings.
if phrase.startswith("cat"):

if phrase.startswith("cat, dog"):

# It does not start with this string.
if not phrase.startswith("elephant"):



Map and IMap as inbuilt functions for iteration:

map is rebuilt in Python3 using generators expressions under the hood which helps to save lot of memory but in Python2 map uses dictionary like expressions so you can use ‘itertools’ module in python2 and in itertools the name of map function is changed to imap.(from itertools import imap)

>>>m = lambda x:x*x
>>>print m
 at 0x7f61acf9a9b0>
>>>print m(3)

# now as we understand lamda returns the values of expressions for various functions as well, one just have to look
# for various other stuff when you really takes care of other things

>>>my_sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
>>>print map(m,my_sequence)

#so square is applied on each element without using any loop or if.

For more on map,reduce and filter you can fetch following jupyter notebook from my Github:


ORMise your DB operations!

ORM stands for Object Relational Mapping.

Now what is that?

Compared to traditional techniques of exchange between an object-oriented language and a relational database, ORM often reduces the amount of code that needs to be written.

There must be some kind of downside for this approach?

Disadvantages of ORM tools generally stem from the high level of abstraction obscuring what is actually happening in the implementation code. Also, heavy reliance on ORM software has been cited as a major factor in producing poorly designed databases



Now that diagram is just pulled from Internet that one is supposed to tell us about working structure of SQLAlchemy that is our main purpose to write this blog.

Let’s start from groud:

  • We have Database. (of-course what else we should have, mangoes 😀 )
  • DBAPI. (definitely needs otherwise how else we will make calls to our database for read and write operations )
  • SQLAlchemy CORE

Before talking about SQLAlchemy CORE we should really talk about what SQLAlchemy people believe about ORMs.


SQLAlchemy’s overall approach to these problems is entirely different from that of most other SQL / ORM tools, rooted in a so-called complimentarity- oriented approach; instead of hiding away SQL and object relational details behind a wall of automation, all processes are fully exposed within a series of composable, transparent tools. The library takes on the job of automating redundant tasks while the developer remains in control of how the database is organized and how SQL is constructed.

The main goal of SQLAlchemy is to change the way you think about databases and SQL!

That is true, when you start working with it you feel like you are controlling your DB with your crazy logics not from DB quiries. (That looks like bit freedom it could crash my DB if I have no Idea what I am doing but I guess that is the beauty of it. 😉 😀 )

Core contains the methods those are integrated with DB API to create Connection with DB,handle sessions,create and delete tables-rows-columns,insertion,execution,selection,accessing values from IDs comes into place. It really feels like you are just writing your favourite language while handling DB operations in place. Moreover every operation just works on the fly unless you have really messed up your DB like breaking connection while reading/writing process,declaring wrong types,messing with fields or just dumping data without even parsing-cleaning it bit. Exception handling really comes into place when you interact with DB this way. 🙂 ❤ 🙂 [I just love programming and it's nature]

There are many things as well from SQLAlchemy core those we can talk about but I feel we should stop here otherwise I might have to shift my career from developer to writer. 😉 😀

Let's taste some code so this post will really help me in near future when I will work with much complicated DB operations those really need mind mash up. 😉

from sqlalchemy import * # don't use * in production

# if you are using Mysql look for commented code
#engine = create_engine(‘mysql+pymysql://:@localhost/mdb_final’)

engine = create_engine(‘sqlite:////home/metal-machine/Desktop/sqlalchemy_example.db’)

metadata= MetaData(engine)

# creating tables, be careful with data-types 🙂
omdb_data = Table(‘positions’, metadata,
Column(‘omdb_id’, Integer, primary_key=True),
Column(‘status’, String(200)),
Column(‘timestamp’, Float(10)),
Column(‘symbol’, String(200)),
Column(‘amount’, Float(10)),
Column(‘base’, Float(10)),
Column(‘swap’, Float(10)),
Column(‘pl’, Float(10)),)

omdb_data.create() # creating tables and values
mm = omdb_data.insert() #

So above can be considered as simplest form for understanding DB writing operations using SQLAlchemy.

Making connection and updating DBs.

# make sure this DB is already created, this time we are only creating connection to read
# or insert data if we need.

bit_fine_data = create_engine('sqlite:////home/metal-machine/Desktop/sqlalchemy_example.db')
# calling all the tables in the required DB, we just have to pass table name in
# Table Class so we will be able to access,create,insert,execute from one variable.

positions_table = Table('positons',order_data_meta, autoload=True)
balance_status_table = Table('balance_status',order_data_meta, autoload=True)
account_info_table = Table('account_info',order_data_meta, autoload=True)

# inserting values in table
m=positions_table.insert({ 'status':positions['status'],'timestamp':positions['status'],'symbol':positions['status'],'amount':positions['amount'],'base':positions['base'],'swap':positions['swap'],'pl':positions['pl']})

# executing the insert data command
print bit_fine_data.execute(m)

How to read data from rows or columns from DB:

db = create_engine('sqlite:////home/metal-machine/Desktop/order_id.db')
metadata = MetaData(db)
# creating instance for Table-'orders'
tickers = Table('orders', metadata, autoload=True)

#selecting particular column from table 'orders'
time_stamp =
# creating array from the data we get in the 'timestamp' column (creating array is optional #here)

timestamp_array = np.array([i[1] for i in time_stamp.execute()])

There are much more things left for SQLAlchemy core but I believe we should stop here and look for other things as well.

Stay tuned for SQLAlchemyORM part.

Rocks cluster for virtual containers

First of all I would like to thanks Rocks community for saving our lots of money, at initial we were thinking about buying very expensive hardware and use it as dedicated server on which we would be able to run multiple docker containers as well as multiple virtual machines. Such systems are quite  expensive: Following examples of such systems are considerable when you are really serious about some kind of computing power either for research or for server business kind of thing.

  1. (A base class example, price range is 50 K)
  2. (Other possible high availability options price range is more thank 100K)


But now we had to do setup with solution which should not be costlier more than 20-30K and we want at least 8 cores and 16 GB of RAM. Presently our requirement was not too high so rather than spending much amount on SSDs(Solid state drives) we just zeroed to normal mechanical HDs.

We used used core2duo and dual-core CPUs as slave nodes for Rocks cluster, Presently we are having i3 second generation home PC for Front-Node that we might upgrade in near future but it is really efficient and working pretty much fine on CentOS. ❤ ❤


Now when we talk about Cluster-computing only one thing comes in mind a set of connected CPUs to perform heavy operations and using all core together to run some kind of simulation and feel like a scientist at NASA. 😀

Thanks to ‘Dr. H.S. Rai’( that he introduced me Rock’s Cluster many months ago that really changed my perception about super-computers,parallel-processing and most of the stuff which I am still not able to remember. 😛

So back to clusters! There are many types of clusters it just really depends on your problem, like what kind of problem you want to  solve using such systems.

Problem: User/Client wanted a simple Machine having multiple cores and GBs of memory so he/she will be able to create new virtual container for any new user as per the requirement

This tutorial assumes that you have installed Rocks Front-node in one of the system and have lots of other hardware available to you to connect with your Front-node.

Something like this:





If you are still not getting what I am trying to say you better be first go to Rocks cluster website and look what they really are doing!Adding compute Nodes:(It is one form of cluster)


For adding virtual containers Rocks comes with XEN( roll. There are so many Rock’s roles those come as per the requirement. For example there is HPC roll that comes with OpenMPI(Open message protocol interface) that can be used if you want to execute your code more than two or three nodes using computing cores of most systems together. A generic way is something like this:

# execute_progarm compute-node-0 compute-node-1 compute-node-3

Such type of systems are used when you have lot of data to analyse or handle but even for that present industry rely on expensive stuff rather than using Rock’s implementation. 😦 ;D let’s save this for another day and concentrate only on visualization stuff.


So for implementation of vitalized containers we have to install XEN roll in Front-node, that can be installed while normal installation of Front-node if you are using Jumbo DVD(comes with all rolls ~ size of 3.SOMETHING GBs) or Rocks also provide all rolls( as different ISOs.

After successful installation of XEN roll one need to connect slave node either via direct to Ethernet card or use network-switch. (Make sure while doing all this stuff you are logged-in as root user)

Execute following command.(That’s my favourite command in the whole world, I FEEL like GOD 😀 )

#  insert-ethers

You will get screen like following or it could be different if you are using other version of Rocks but you only have to concentrate on VM-Containers. Mkae sure at this time your slave node is having PXE-boot enabled. To enable PXE boot you have to look for slvave-node BIOS.



Hit enter after choosing required option and you will look installation on slave node will be started. It could take some time so have patience. 😛

While your VM container is being installed please have a look at the stuff we are doing so you will be able to understand the architecture or our cluster.






Or you can also see our creativity as well. 😛










After successful installation of VM container you can see it will be available in your System, save your node and quit. To analyse all this process or to get idea what I am really talking about you can look for this link as well but let me clear that first we are using VM container here not compute node.(


To assign IP to your VM container run following command but make sure you have your Static IP so one will be able to access your container from public internet.

# rocks add cluster ip="your_static_IP" num-computes=<1,2,or 3>

above commands look simple just mention your static IP and number of compute nodes
you want to use. It could be 1 or 2 depending on how many nodes you have and
how many VM containers you want to create.

Now clear one thing first yet we have only created virtual cluster not Virtual machines

# rocks list cluster

Above command will give you available VM clusters present in your system.

Now before creating Virtual machines we need to create RSA key pairs so we will be able to do login from Front-node to

Virtual cluster and do required operations:

# rocks create keys key=private.key passphrase=no
setting option: passphrase=no will not ask you for password but you can skip
that if you want to use password with your security key.

Add that key to your newly created virtual cluster:

# rocks add host key frontend-0-0-0 key=public.key
Following command will start installation of VM on your Virtual cluster:

# rocks open host console frontend-0-0-0 key=private.key

After installation of VM on frontend now it depends on you how you want to add virtual nodes to your system. This time these nodes will be real virtual and you can associate your static IP with those.

Again we are back to insrt-ethers but this time we are logged-in to our Virtual frontend node that we created by combining one and more node connecting together. (this text is written in bold format because it is mind blowing concept and I have blown my mind many times while understanding this step but I really don’t want you to blow yours. :D)

AGAIN: I am shouting that we have to login to VM Front-node not real Front-node 😀

# insert-ethers

Select “Compute” as the appliance type. (This time select compute and you don’t have to worry about booting and setting up slave node because we are working Virtually!!! yeah man!  I am high I think at this point and songs are being played in my mind:D)


In another terminal session on, we’ll need to set up the environment to send commands to the Airboss on the physical frontend. We’ll do this by putting the RSA private key that we created in section Creating an RSA Key Pair (e.g., private.key) on

Prior to sending commands to the Airboss, we need to establish a ssh tunnel between the virtual frontend (e.g., vi-1) and the physical frontend (e.g., espresso, where the Airboss runs). This tunnel is used to securely pass Airboss messages. On the virtual frontend (e.g., vi-1), execute:

# ssh -f -N -L 8677:localhost:8677


Now we can securely send messages to the Airboss.

Did I tell you what is Airboss?





Now make sure you know mac address of your systems so you would be able to power them on/off using following command:

# rocks set host power <mac-address> key=private.key action=install

How to get MAC address?

# rocks list host macs <your-cluster-name> key=private.key

<your-cluster-name> is the real-font-node that you named while installing the Rocks on your system first time!

Above command will be give output like this: (yours output will be definitely different according to your compute nodes)


when you will power on your real node in VM container you will see that it is
detected by VM containers as follows:


To turn your VM off following command should be executed:

# rocks set host power compute-0-0 key=private.key action=off

It was all about setting up virtual cluster and turning on/off your nodes in-between the VM containers. Let me clear one thing that VM container is one that contains various physical nodes those we can use in combined form to create virtual machines as big or as small we want. (:P  that looks like easy definition :P)


OK now that was most difficult part and if you have reached here just give yourself a BIG SABAASH!


If you are aware of  Virt-manager provided by the RED hat you are good to have smooth ride from here otherwise defiantly take a look at  (

Now keep yourself in Real-Front-node as root user and make sure the required Virtual-clusters are running as required otherwise you will not be able to create virtual machines on Virtual containers. (I am using ‘virtual’ word so many times and  I am really not sure either I am in real world or virtual?)

As root user in Front-node run:

# virt-manager

You should be able to see your VM containers there and virtual-machines:



Now Don’t ask What to do with your Virtual Machines. 😛
Here is our setup:



A simple script to do parsing of large file and save it to Numpy array

A normal approach:

huge_file = 'huge_file_location'
import re
import numpy as np
my_regex=re.compile(r'tt\d\d\d\d\d\d\d') #using a compiled regex saves the time
a=np.array([]) # just an array to save all the files
with open(file_location,'r') as f: # almost default method to open file
m = re.findall(my_regex,
np_array = np.append(a,m)
print np_array
print np_array.size
print 'unique'
print np.unique(np_array) # removing duplicate entries from array
print np.unique(np_array).size'BIG_ARRAY_LOCATION',np.unique(np_array))

In the above code saves big chuck of string into memory that is about 8GB in present situation. let’s fire up Generators.

A bit improved version:

def read_in_chunks(file_object):
while True:
data =
if not data:
yield data
import numpy as np
import re
f = open(file_location)
for piece in read_in_chunks(f):
m = re.findall(my_regex,piece) # but still this is bottle neck
np_array = np.append(a,m)
print np_array
print np_array.size
print 'unique'
print np.unique(np_array)
print np.unique(np_array).size

A little bit faster code:

file_location = '/home/metal-machine/Desktop/nohup.out'
def read_in_chunks(file_object):
while True:
data =
if not data:
yield data

import numpy as np
import re
f = open(file_location)
def iterate_regex():
”’ trying to run iterator on matched list of strings as well”’
for piece in read_in_chunks(f):
yield re.findall(my_regex,piece)
for i in iterate_regex():
np_array = np.append(a,i)
print np_array
print np_array.size
print ‘unique’
print np.unique(np_array)
print np.unique(np_array).size

But why performance is still not taht good? Hmmm……
Have to look for more things. Please use the required indentation while testing. 😛

Look at the CPU usage running on Goole instance 8Core system.



%d bloggers like this: