Posts

Showing posts with the label python

Python Ipdb Cheatsheet

Command CheatSheet h(elp) : Without argument, print the list of available commands. With a command name as argument, print help about that command. w(here) : Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. d(own) : Move the current frame one level down in the stack trace (to a newer frame). u(p) : Move the current frame one level up in the stack trace (to an older frame). b(reak) : [ ([filename:]lineno | function) [, condition] ] With a filename:line number argument, set a break there. If filename is omitted, use the current file. With a function name, set a break at the first executable line of that function. Without argument, list all breaks. Each breakpoint is assigned a number to which all the other breakpoint commands refer. The condition argument, if present, is a string which must evaluate to true in order for the breakpoint to be honored. tbreak : [ ([filenam...

Converting unicode date to datetime object.

In a django template i had something like: value="{{ query_date|date:'%d/%m/%Y' }}" And in my view i wanted a date not an unicoded date. So i did this in a view to parse the unicode and convert it to datetime object.  from datetime import datetime query_date_obj = datetime.strptime( query_date, "%d/%m/%Y") Ciao!

Sql statement for a query with the Django ORM?

from django.db import connection sql_statement = connection.queries.pop() print sql_statement['sql']

Matplotlibs colors

Here is a list of some weirds colors you can use to change the always classic colors. For example:     ax.scatter(band1, band2, s=size_point, color='tomato') cnames = { 'aliceblue' : '#F0F8FF' , 'antiquewhite' : '#FAEBD7' , 'aqua' : '#00FFFF' , 'aquamarine' : '#7FFFD4' , 'azure' : '#F0FFFF' , 'beige' : '#F5F5DC' , 'bisque' : '#FFE4C4' , 'black' : '#000000' , 'blanchedalmond' : '#FFEBCD' , 'blue' : '#0000FF' , 'blueviolet' : '#8A2BE2' , 'brown' : '#A52A2A' , 'burlywood' : '#DEB887' , 'cadetblue' : '#5F9...

Installing matplotlib under Mountain Lion

Follow this steps in order: [carpincho@MacBook-2]$ pip install numpy [carpincho@MacBook-2]$ pip install -e git+https://github.com/scipy/scipy#egg=scipy-dev [carpincho@MacBook-2]$ pip install git+https://github.com/matplotlib/matplotlib.git#egg=matplotlib-dev source and a link to an explanation why numpy and matplotlib can't be installed using pip straightforward

Kivy, an open source library for rapid app develop

Image
Kivy is an open source software library for rapid development of applications equipped with novel user interfaces, such as multi-touch apps. Cross Platform: Runs on Linux, Windows, MacOSX, Android and IOS. It can use natively most inputs protocols and devices like WM_Touch, WM_Pen, Mac OS X Trackpad and Magic Mouse, Mtdev, Linux Kernel HID, TUIO. A multi-touch mouse simulator is included. Business Friendly: It is 100% free to use, under LGPL 3 licence. The framework is stable and has a documented API, plus a programming guide to help for in the first step Gpu Accelerated: The graphics engine is built over OpenGL ES 2. The toolkit is coming with more than 20 widgets designed to be extensible. Many parts are written in C using Cython, tested with regression tests. Homepage: Kivy.org   Images and info from kivy official site

Swig compiling issues Mac Os Lion

One problem that happened to me, was the fact that working under a virtualenv with an specific python version as one can expect, works with ONLY that python version. So if you try to import a module compiled with one version different with the one you are running, will no work. The exception message: Fatal Python error: Interpreter not initialized (version mismatch?) Abort trap: 6 How we can solve this issue? First, knowing which python version are we running and of course, compile the module to THAT version. Below are some examples of how to compile a module to 2.6 or 2.7 (which is Mac Os Lion python default version) To use python default version just type the following: $ swig -python example.i $ cc -c `python-config --cflags` example.c example_wrap.c $ cc -bundle `python-config --ldflags` example.o example_wrap.o -o _example.so If you run: $ python-config --ldflags the output is: -L/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config -ldl -framework...

Swig Tutorial example Mac Os Lion

This tutorial is based on Leopard Tutorial but still works, thou some warnings. First, we create an example.c file with this content: /* File : example.c */ #include <time.h> double My_variable = 10.0; int fact(int n) { if (n Second, we create the interface between C and Python with the following file: /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); Now that we have all the source files we need, we compile them in this way: $ swig -python example.i $ cc -c `python-config --cflags` example.c example_wrap.c $ cc -bundle `python-config --ldflags` example.o example_wrap.o -o _example.so if you have problems with this step check this other post So, everything looks nice, but how do we use ...

timeit example

An example of how to time a statement >>> import numpy as np >>> arr1 = np.random.randint(0,1600,(3000,3000)) >>> timeit arr1.argmin() 10 loops, best of 3: 34.2 ms per loop Tested under Mac Lion Os proc i7 and Python 2.7.1 r271:86832

Escaping Charecters in python

Just an example commonly used Escaping the "\" with another "\" >>> with open('C:\\Folder1\\Folder2\\file') as file_handler: Or just add an "r" before the path (this stands for "raw"). >>> with open(r'C:\Folder1\Folder2\file') as file_handler:

Show all values in Numpy array

If an array is too large to be printed, (Scipy)NumPy automatically skips the central part of the array and only prints the corners: >>> print arange(10000) [ 0 1 2 ..., 9997 9998 9999] >>> >>> print arange(10000).reshape(100,100) [[ 0 1 2 ..., 97 98 99] [ 100 101 102 ..., 197 198 199] [ 200 201 202 ..., 297 298 299] ..., [9700 9701 9702 ..., 9797 9798 9799] [9800 9801 9802 ..., 9897 9898 9899] [9900 9901 9902 ..., 9997 9998 9999]] To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions . >>> set_printoptions(threshold='nan') from Numpy Tutorial

xrange with float steps - Python

The great thing about this code, is that the definition its a generator. (You can easily identify the keyword yield) def drange(start, stop, step): r = start while r >>>i0=drange(0.0, 1.0, 0.1) >>>["%g" % x for x in i0] ['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1'] >>> source

Timeit function

Here i present a little function (with an example below) to time some bunch of code using timeit. # -*- coding: utf-8 *-* import timeit class Chronoit(): """ A little class to handle timeit output. The output is in seconds. """ def __init__(self, main_statement, setup_statement, total_iterations): self.main_stmt = main_statement self.setup_stmt = setup_statement self.total_iter = total_iterations t = timeit.Timer(self.main_stmt, self.setup_stmt) self.show_results(t.timeit(number=self.total_iter)) def show_results(self, time_elapsed): time_per_pass = time_elapsed / self.total_iter if time_per_pass > 60.0: minutes_per_pass = time_per_pass / 60.0 secs_per_pass = time_per_pass % 60.0 print "#" * 50 print "Timing" print "setup stmt: \"" + self.setup_stmt.split("\n")[1] + ...

New Ninja-IDE scheme color - focojoaco version 2

{ "keyword": "#228b22", "operator": "#242424", "brace": "#228b22", "definition": "#6495ed", "string": "#ff8c00", "string2": "#838b83", "comment": "#8b8878", "properObject": "#8b0a50", "numbers": "#ff4500", "spaces": "#000000", "extras": "#A37A00", "editor-background": "#eeeee0", "editor-selection-color": "#ebc79e", "editor-selection-background": "#8b8878", "editor-text": "#242424", "current-line": "#6ca6Cf", "selected-word": "#a2cd5a", "fold-area": "white", "fold-arrow": "darkGray" } Ninja IDE Website

Removing white spaces in Python

Using split() in = " something with multiple white spaces " parsed = in.split() output = ' '.join(in) Using regular expresions import re in = " something with multiple white spaces " output = re.sub("\s+" , " ", in)

How to enable pdb autocomplete?

In a pdb session, just type: import rlcompleter pdb.Pdb.complete=rlcompleter.Completer(locals()).complete But if you use, ipdb, you dont need to import rlcompleter. Thanks to scooby that pointed this out

My own scheme color for ninja ide! :)

{     "keyword": "#228b22",     "operator": "#242424",     "brace": "#228b22",     "definition": "#6495ed",     "string": "#ff8c00",     "string2": "#838b83",     "comment": "#8b8878",     "properObject": "#8b0a50",     "numbers": "#ff4500",     "spaces": "#000000",     "extras": "#ffff00",     "editor-background": "#eeeee0",     "editor-selection-color": "#ebc79e",     "editor-selection-background": "#8b8878",     "editor-text": "#242424",     "current-line": "#6ca6Cf",     "selected-word": "#a2cd5a",     "fold-area": "white",     "fold-arrow": "darkGray" } Ninja-Ide Homepage!

Dictionary of Methods/Functions (Python)

Construct a dictionary with String (or other) keys and unbound methods or functions as values. During execution, use the string keys to select which method or function to execute. Can be used for simple parsing of tokens from a file thru a kind of object-oriented case statement. import string def function1(): print "called function 1" def function2(): print "called function 2" def function3(): print "called function 3" tokenDict = {"cat":function1, "dog":function2, "bear":function3} # simulate, say, lines read from a file lines = ["cat","bear","cat","dog"] for line in lines: # lookup the function to call for each line functionToCall = tokenDict[line] # and call it functionToCall() It's embarrasingly simple really, but I use it a whole lot. Instead of functions, methods might also be used (self.method1), remember to follow the binding rules if you use methods d...

gmapcatcher, an offline map viewer

Image
Overview GMapCatcher is an offline maps viewer. It downloads tiles automatically from many providers such as: CloudMade , OpenStreetMap , Yahoo Maps , Google Map . It displays them using a custom GUI. User can view the maps while offline. GMapCatcher doesn't depend on google-map's java scripts so it should work even if google changes them. It also provides a downloading tool. GMapCatcher is written in Python 2.6, can run on Linux, Windows and Mac OSX. You can find a list of improvements and latest features in the Changelog Download http://gmapcatcher.googlecode.com/files/GMapCatcher-0.7.2.0.tar.gz or $ svn checkout http : //gmapcatcher.googlecode.com/svn/trunk gmapcatcher For Windows users, get the latest Windows installer Usage maps.py is a gui program used to browse google map. With the offline toggle button unchecked, it can download google map tiles automatically. Once the file downloaded, it will reside on user's hard disk and needn't to be downloa...