Sound Alarm When Program Execution Completes in Python

Often one faces a situation where your code takes extremely long to run and you don’t want to be staring at it all the time but want to know when it is done.

In engineering analysis, simulation take a long time to run and the python driver program take a long time to finish and I face this problem a lot.

A simple solution is adding a beep at the end, here’s how to do it in python.

def beep():
    print "\a"

beep()

works on windows/ linux/mac without any modification.

via here

Simple numpy trick to check if vector is increasing

Problem:

How to check if a 1d vector is increasing…….

Solution:

np.all(np.diff(xp) > 0)

where xp is a vector of numbers.

I love numpy. When is it going to a be standard module in python?

Shelve it with python

One of the little gems hidden in python standard library is shelve.

The shelve module can be used as a simple persistent storage option for Python objects when a relational database is overkill. The shelf is accessed by keys, just as with a dictionary. The values are pickled and written to a database created and managed by dbm.

import shelve

with shelve.open('test_shelf.db') as s:
    s['key1'] = {
        'int': 310,
        'float': 3.14.5,
        'string': 'Sample string data',
	'array': [[1,2,3],[4,5,6]],
    }

I mostly work with large simulation data and run simulation from python and these simulations take time to run sometimes days, so a simple persistent storage option provided by shelve is an intuitive way to restore my work.

An advantage of is we do not have to remember the order in which the objects are pickled, since shelve gives a dictionary-like object.

Here’s a sample code I use to store my long running results and latter to restore those values at a later time.

filename=r"flake_results.out"

my_shelf = shelve.open(filename, "n")

for key in ["stress", "strain", "plas", "creep","temp"]:
	try:	
		my_shelf[key]=globals()[key]
	except Exception:
		print ("Error shelving: {}".format(key))

my_shelf.close()

To restore

my_shelf = shelve.open(filename)
for key in my_shelf:
    globals()[key]=my_shelf[key]

my_shelf.close()

for more info: Visit This

Participate in the 2018 Python Developer Survey

If you use python in your work or hobby projects, please consider participating in the 2018 python developer survey.

Reposting a PSF-Community email as a PSA

Excerpt from an email to the psf-community@python.org and psf-members-announce@python.org mailing lists:

As some of you may have seen, the 2018 Python Developer Survey is available. If you haven’t taken the survey yet, please do so soon! Additionally, we’d appreciate any assistance you all can provide with sharing the survey with your local Python groups, schools, work colleagues, etc. We will keep the survey open through October 26th, 2018.

Python Developers Survey 2018

We’re counting on your help to better understand how different Python developers use Python and related frameworks, tools, and technologies. We also hope you’ll enjoy going through the questions.

The survey is organized in partnership between the Python Software Foundation and JetBrains. Together we will publish the aggregated results. We will randomly choose and announce 100 winners to receive a Python Surprise Gift Pack (must complete the full survey to qualify).

Outlook Calendar Entries for a Day with Python

For me it is not the mobile. It is the email, which is the most distraction application in office.

The variable reward system has become a habit. I tried closing it but then I keep missing meetings etc.

So had to keep it open just so the reminders for meetings show up.

Only reason I need the outlook is to have a day view why not print it. Bad option, see the already printed stack on my desk. Why not get all the events out for a day and use a text file on the desktop.

Therefore, that is what I did.

Here’s the python function to get the appointments of the day from outlook calendar.

import win32com.client, datetime

def getCalendarEntries(days=1):
    """
    Returns calender entries for days default is 1
    """
    Outlook = win32com.client.Dispatch("Outlook.Application")
    ns = Outlook.GetNamespace("MAPI")
    appointments = ns.GetDefaultFolder(9).Items
    appointments.Sort("[Start]")
    appointments.IncludeRecurrences = "True"
    today = datetime.datetime.today()
    begin = today.date().strftime("%m/%d/%Y")
    tomorrow= datetime.timedelta(days=days)+today
    end = tomorrow.date().strftime("%m/%d/%Y")
    appointments = appointments.Restrict("[Start] >= '" +begin+ "' AND [END] <= '" +end+ "'")
    events={'Start':[],'Subject':[],'Duration':[]}
    for a in appointments:
        adate=datetime.datetime.fromtimestamp(int(a.Start))
        #print a.Start, a.Subject,a.Duration
        events['Start'].append(adate)
        events['Subject'].append(a.Subject)
        events['Duration'].append(a.Duration)
    return events

The functions spits out a dict and can be easily converted used in any way one wants.

Sweet! Let's see if am able to kill outlook now.

Mosaic Plot in Python

I am sure everyone one of us has seen charts like this.

Any management training you attend, a version of this chart is bound to sneak up in the presentation, often in lecture notes or hands on activity.

These charts are a good representation of categorical entries. A mosaic plot allows visualizing multivariate categorical data in a rigorous and informative way. Click here to read A Brief History of the Mosaic Display [PDF]

Here’s a quick example how to plot mosaic in python

from statsmodels.graphics.mosaicplot import mosaic
import matplotlib.pyplot as plt
import pandas

gender = ['male', 'male', 'male', 'female', 'female', 'female']
pet = ['cat', 'dog', 'dog', 'cat', 'dog', 'cat']
data = pandas.DataFrame({'gender': gender, 'pet': pet})
mosaic(data, ['pet', 'gender'])
plt.show()

 

Here’s another example from the tips dataset.


from statsmodels.graphics.mosaicplot import mosaic
import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
mosaic(tips, ['sex','smoker','time'])
plt.show()

 

Timeline in Python with Matplotlib

Was documenting a series of events and after the list was complete, thought of showing them on a timeline.

After an hour two, fiddling with python standard libraries this is what I had.

Format of the data


from theflile import GenerateTimeLine
import pandas as pd
data = pd.read_csv(r'events.txt', parse_dates=True, index_col=0)
ax = GenerateTimeLine(data)
plt.show()

The code as always available at this GitHub