Disclaimer:
These pages about different languages / apis / best practices were mostly jotted down quckily and rarely corrected afterwards.
The languages / apis / best practices may have changed over time (e.g. the facebook api being a prime example), so what was documented as a good way to do something at the time might be outdated when you read it (some pages here are over 15 years old).
Just as a reminder.

Howto for using py2app on MacOsX

Developer notes for how to use it and common installation problems

Py2app, how to use it on macosx

Installation of py2app

It already exist in Snow Leopard and later (not sure about before) , in
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/


So normally no need to install it on Macosx.

If you need to install it:

Download the latest py2app

Install it from source:
sudo python setup.py install
To use it on your python script:
py2applet --make-setup py2app_test.py
python setup.py py2app

Possible problems

AttributeError: 'NoneType' object has no attribute 'get_config_var'
Solution: ?

Cant recall the error message, but if it complains about argv emulation when trying to execute the app
Set it to false in setup.py: 'argv_emulation': False

Links to relevant websites

py2app, MacPorts, Snow Leopard, and PIL: a match made in Hell
How to make standalone OS X application bundles from PyQt apps using py2app

Usage examples of py2app

Including extra files (e.g. images)
Edit setup.py to include the extra files in DATA_FILES
DATA_FILES = ['pyhon_py2app_package_testing.png']

Alternatives to py2app

Platypus, "Platypus is a developer tool for the Mac OS X operating system. It creates native Mac OS X applications from interpreted scripts such as shell scripts or Perl, Ruby and Python programs. This is done by wrapping the script in an application bundle along with a native executable binary that runs the script."

Reload module

from importlib import reload # Python 3.4+ only. import foo foo = reload(foo)

Python general notes

#add a path so python will find modules in it from the code import sys sys.path.append("colaboratory_helpers")

installing pgdb with mac ports

Make sure you have the macports pip (and not the default one)
sudo port install py27-pip

install with pip:
pip-2.7 install PyGreSQL

If pg_config tool is not available:
Make sure the postgres bin is in the path, e.g.
export PATH=/usr/local/pgsql91/bin/:$PATH

Timeout when waiting for user input

# Expect the user to type something
# if he does not type something within 5 seconds the script complains

import sys, signal

Timeout = 'Timeout exception.' 

def timed_out(signo, frame):
    raise Timeout

signal.signal(signal.SIGALRM, timed_out)

print "write something! "

buf = ''
try:
    signal.alarm(5)
    buf = sys.stdin.readline()
    signal.alarm(0)
except Timeout:
    print "\a----Are you still there?"

if buf:
    print "Received: ", buf

Dump a dictionary

(to avoid "too many values to unpack" problem)

for field, possible_values in fields.iteritems():
    print field, possible_values

Check syntax without executing

python -m py_compile

Convert int to string and vice versa

str(42)
int('42')
Save image dlib from skimage import io io.imsave("somedir/{}_{}.jpg".format(itemid, idx), faces[0])

Save file

fh = open("/tmp/somefile.txt", "w") fh.write("stuff") fh.close()

Find methods of instance, parameters for function

import inspect inspect.getargspec(flann.nn_index) dir(flann) Find out which version of package torch.__version__

boto

Sending/Receiveing msgs to SQS automatically decode/encode base64

jupyter notebook

%matplotlib inline df.Age.plot(kind='hist')

Pandas

df = pd.read_csv(filename, header=None, names=['Objectid', 'Name']) #iterate over df for index, row in df.iterrows(): print(row['c1']) df.dtypes df.Sex.value_counts() df.Sex.describe() #number of missing values for each attribute df.isnull().sum() #Select columsn to use df1 = df[['a','d']] #Drop column inplace df.drop('Colname', axis=1, inplace=True) #Drop duplicates based on column df.drop_duplicates(subset='Columnname', keep="first", inplace=True) #Drop rows if it exist in another dataframe https://stackoverflow.com/questions/60956063/remove-a-row-from-a-dataframe-if-any-row-value-is-in-another-dataframe df21k[~df21k['word'].isin(dfToRemove['word'].values.flatten())] #Fill missing values df.fillna('', inplace=True) #Selecting df[ df['ThisIsAcolumn'] == '9' ].head(5) #Change value of a column oldval = tmpdf['label'].values dfall.loc[ dfall['objectid'] == row['objectid'], 'label' ] = oldval[0] + "," + currentlabel #Change type of columns newdf = newdf.apply(pd.to_numeric) df['B'] = pd.to_numeric(df['B']) df['points'] = df['points'].astype(str) #convert column to int df['Weight'] = df['Weight'].astype(int) #Getting values dfAUto[ dfAUto['word'] == 'car' ]['suggestion'].values[0] # See if a value exist in a frame if 0 < len(df[ df['keyword'] == 'something' ].values): # Apply function df['ratio'] = df['stuff'].apply(lambda x: x / len(df.index)) #Selecting based on the index df['itemid'].iloc[3] #Selecting with regex, all rows where the MYCOL is not digits only df[ df.MYCOL.str.contains('^[^0-9]+$', regex=True, na=False) ] #Rename columns df.rename(columns={'How Many People': 'new_col_name'}, inplace=True) #Export specific columns, leaving out index header = ["somecol", "other_col", "blabablalbal"] merged2.to_csv('/tmp/output.csv', columns = header, sep='|', index=False) #Merging on a specific column df = pd.merge(df_new, df_n, on='subject_id') #Concatting two dataframes df = pd.concat([dfa,dfb]) #After concatting, reset index df.reset_index(drop=True, inplace=True) #Randomize dataframe df = df.sample(frac=1).reset_index(drop=True) #Assign result of groupby to new column dfsnow['TaxsumTotal'] = dfsnow['Taxsum'].groupby(dfsnow['Keyword']).transform('sum') https://mycheatsheets.com/pandas http://www.swegler.com/becky/blog/2014/08/06/useful-pandas-snippets/ #Dummy frame for quick copyNpaste import pandas as pd df = pd.DataFrame({'num_legs': [2, 4, 8, 0], 'num_wings': [2, 0, 0, 0], 'num_specimen_seen': [10, 2, 1, 8]}, index=['falcon', 'dog', 'spider', 'fish']) df = pd.DataFrame({'phrase': ['dog','cat','dolphin'])

More programming related pages

Workflow: Release process
Workflow: Bug tracking
Teambox (Redbooth) - Mantis connector
Design Patterns
Git & Github
Go / Golang
CVS
CVS backup script
Distribution process
Installation script
Java Server Faces
Facelets
jibx
jBoss
jBpm
Perl tips
Perl links
PostgreSQL
Python / py2app
Shell scripts
Xslt
Node.js
Facebook / Opengraph
PHP developer notes
Redbooth API through php
Website optimization
jqTableKit demo
Javascript / html / css links