First you need to install python .
Second you need to install pyopengl module.
This is easy if we use some linux distributions.
On Fedora we can use command yum.
On Debian and Ubuntu we can use apt-get.
At last we need some basicaly examples.
We can get some examples from:PyOpenGL-Demo
But this is not all we will need more.
To go on next step we will need to read OpenGL specifications.
Try to use search on internet to see more about OpenGL.
Is a blog about python programming language. You can see my work with python programming language, tutorials and news.
Monday, March 1, 2010
Tuesday, February 23, 2010
How to display the "%" in python ?
I saw something interesting on the internet.
How to display the "%" in python.
I found so far two methods:
How to display the "%" in python.
I found so far two methods:
>>> print "See %d%%" % (0.77 * 100)
See 77%
>>> print "See {0:.0%}".format(0.77)
See 77%
>>>
Friday, February 12, 2010
Where is Santa Claus?
I wrote a python module. I called it "geo" because it is a geographic module.
The funny stuff is when i use it with "Santa Claus".
So where is Santa Claus ?!
Google Maps API should be prepared to respond.
Tomorrow a child will know how to use the Python language.
Who knows ...
The funny stuff is when i use it with "Santa Claus".
>>> import geo
>>> geo.adress("Santa Claus")
{'status': '200', 'latitude': '32.1715776', 'longitude': '-82.3315138', 'accuracy': '4'}
So where is Santa Claus ?!
Google Maps API should be prepared to respond.
Tomorrow a child will know how to use the Python language.
Who knows ...
Thursday, February 4, 2010
Parsing feeds - part 1
From time to time I used conky. Is good for me, because i have all i need on my desktop.
How helped me python in this case?
For example i use one script to parse a feed from this url:
"http://www.bnro.ro/nbrfxrates.xml"
The example is simple to understand :
The result is parsing with functions from "dom" package.
I used this functions "parseString" and "getElementsByTagName".
More about this functions you will see on:
http://docs.python.org/library/xml.dom.minidom.html
This is all.
How helped me python in this case?
For example i use one script to parse a feed from this url:
"http://www.bnro.ro/nbrfxrates.xml"
The example is simple to understand :
from xml.dom import minidom as dom import urllib def fetchPage(url): a = urllib.urlopen(url) return ''.join(a.readlines()) def extract(webpage): a = dom.parseString(webpage) item2 = a.getElementsByTagName('SendingDate')[0].firstChild.wholeText print "DATA ",item2 item = a.getElementsByTagName('Cube') for i in item: if i.hasChildNodes() == True: eur = i.getElementsByTagName('Rate')[10].firstChild.wholeText dol = i.getElementsByTagName('Rate')[26].firstChild.wholeText print "EURO ",eur print "DOLAR ",dol if __name__=='__main__': webpage = fetchPage("http://www.bnro.ro/nbrfxrates.xml") extract(webpage)The result is:
$python xmlparse.py DATA 2010-02-04 EURO 4.1214 DOLAR 2.9749With "urllib" package I read the url.
The result is parsing with functions from "dom" package.
I used this functions "parseString" and "getElementsByTagName".
More about this functions you will see on:
http://docs.python.org/library/xml.dom.minidom.html
This is all.
Saturday, January 30, 2010
How to resize images .
Sometimes it is necessary to resize the images. The PIL module is used for image processing.The glob module takes a wildcard and returns the full path of all files and directories matching the wildcard.
Here are two scripts that I made.
The first is a simple example using a resize after some dimensions.
In this case we used size 300x300.
In the second case I tried to do a resize with proportion preservation.
In both cases we use a renaming of files by adding the name of "thumb_".
Ambele scripturi pot fi modificate asa cum vreti.
Aceste scripturi demonstreaza cum sa folosim celor doua module "PIL" si "globe".
Here are two scripts that I made.
The first is a simple example using a resize after some dimensions.
In this case we used size 300x300.
from PIL import Image
import glob, os
size_file = 300,300
for f in glob.glob("*.png"):
file, ext = os.path.splitext(f)
img = Image.open(f)
img.thumbnail(size_file, Image.ANTIALIAS)
img.save("thumb_" + file, "JPEG")
In the second case I tried to do a resize with proportion preservation.
import glob
import PIL
from PIL import Image
for f in glob.glob("*.jpg"):
img = Image.open(f)
dim_percent=(100/float(img.size[0]))
dim_size=int((float(img.size[1])*float(dim_percent)))
img = img.resize((100,dim_size),PIL.Image.ANTIALIAS)
if f[0:2] != "trumb_":
img.save("thumb_" + f, "JPEG")
In both cases we use a renaming of files by adding the name of "thumb_".
Ambele scripturi pot fi modificate asa cum vreti.
Aceste scripturi demonstreaza cum sa folosim celor doua module "PIL" si "globe".
Tuesday, December 29, 2009
New book for kids with Python 3
Few days ago i found a new site about python .
I saw on this site the a new book about python for kids .
This is the link "Snake Wrangling for Kids".
The author says:
I saw on this site the a new book about python for kids .
This is the link "Snake Wrangling for Kids".
The author says:
- “Snake Wrangling for Kids” is a printable electronic book, for children 8 years and older, who would like to learn computer programming. It covers the very basics of programming, and uses the Python 3
Friday, November 13, 2009
GTK - get display resolution
Sometime is need to get the display resolution.
This python code show how to do it:
Quite simply ...
This python code show how to do it:
>>> import gtk >>> dgd=gtk.gdk.display_get_default() >>> gsd=dgd.get_default_screen() >>> height=gsd.get_height() >>> width=gsd.get_width() >>> print "height=",height,"width=",width height= 1024 width= 1280
Quite simply ...
Wednesday, October 21, 2009
MD5 - password generator
Why do we need this script?
Internet is full of generating MD5.
The Internet has and dictionaries for decrypting md5.
So safe is our script.
You must use the code line:
otherwise if you use:
you get the following error:
pass is a python keyword.
You'll need a different name for the variable.
And now to see the code:
This is all you need.
Internet is full of generating MD5.
The Internet has and dictionaries for decrypting md5.
So safe is our script.
You must use the code line:
p = md5.new ()
otherwise if you use:
pass = md5.new ()
you get the following error:
>>> pass = md5.new() File "", line 1 pass = md5.new() ^ SyntaxError: invalid syntax
pass is a python keyword.
You'll need a different name for the variable.
And now to see the code:
import md5 p = md5.new() p.update("password") p.hexdigest() '5f4dcc3b5aa765d61d8327deb882cf99'
This is all you need.
Wednesday, October 7, 2009
Pyglet - simple example
First i wanted to make a simple example. Then I saw George Oliver googlegrups question. This made me change my little script.Official Site address is: www.pyglet.org.
Documentation of this module is to: www.pyglet.org/documentation.html.
There is also a Google group for this mode where you can ask questions.
My example does nothing more than:
- Create a fereasta;
- To put a background color;
- Displaying an image.
Image i use it, name it "20000.jpg" is this:
Put in folder with your script.
In the future I will come with more complex examples.
Change the following sequence of lines of code example:
You will see that the order matters for pyglet.
Who studied OpenGL knows why.
If you use the code line:
you see:
If you use the code line:
you see:
Documentation of this module is to: www.pyglet.org/documentation.html.
There is also a Google group for this mode where you can ask questions.
My example does nothing more than:
- Create a fereasta;
- To put a background color;
- Displaying an image.
Image i use it, name it "20000.jpg" is this:
Put in folder with your script.
In the future I will come with more complex examples.
Change the following sequence of lines of code example:
win.clear ()
img1.blit (5, 5)
You will see that the order matters for pyglet.
Who studied OpenGL knows why.
import pyglet
from pyglet.gl import *
#set colors with red,green,blue,alpha values
colors = {
'playfield' : (255, 255, 255, 255),
'red' : (255, 0, 0, 255,0),
'sub_red' : (255, 50, 20, 255),
'green' : (0, 255, 0, 255),
'sub_green' : (20, 255, 50, 255),
'blue' : (0, 0, 255, 255),
'sub_blue' : (20, 50, 255, 255)}
#give img1 the place of image
img1= pyglet.image.load('20000.jpg')
#w , h the size of image
w = img1.width+15
h = img1.height+10
# create the 640x480 window size
win = pyglet.window.Window(640, 480, resizable=True, visible=True)
#or use next line to see with size of image
#win=pyglet.window.Window(width=w, height=h)
# set caption of window
win.set_caption("TEST")
#use * to unpack tuple and set background color
pyglet.gl.glClearColor(*colors['red'])
@win.event
def on_draw():
win.clear()
img1.blit(5, 5)
# to run application
pyglet.app.run()
If you use the code line:
win = pyglet.window.Window(640, 480, resizable=True, visible=True)
you see:
If you use the code line:
win=pyglet.window.Window(width=w, height=h)
you see:
Thursday, September 17, 2009
Random words from lists and text
Sometimes it is necessary to choose random words from lists or texts.
Example below illustrates this:
We have two variables "list_input" and "text_input" containing a list of words separated by newline char and a simple string ending in newline char.
Its separation is made with function ".strip ()" .
This function separates the items in the list after this particular bracket expression. The result of the expression in brackets vanishes from the list.
The result of scripts is :
Example below illustrates this:
import random
list_input = """ Apple
Crabapple
Hawthorn
Pear
Apricot
""".strip().split("\n")
text_input = "This is a text without newline char".split()
print "List is =", list_input
print "---------------------------------------"
list_result = random.choice(list_input)
print "Random list result is =", list_result
print "---------------------------------------"
print "Text is =", text_input
print "---------------------------------------"
text_result = random.choice(text_input)
print "Random word result is =", text_result
We have two variables "list_input" and "text_input" containing a list of words separated by newline char and a simple string ending in newline char.
Its separation is made with function ".strip ()" .
This function separates the items in the list after this particular bracket expression. The result of the expression in brackets vanishes from the list.
The result of scripts is :
List is = ['Apple', ' Crabapple', ' Hawthorn', ' Pear', ' Apricot']
---------------------------------------
Random list result is = Pear
---------------------------------------
Text is = ['This', 'is', 'a', 'text', 'without', 'newline', 'char']
---------------------------------------
Random word result is = is
Friday, September 11, 2009
How to use "try" ... "except"
Any program will be given over to error checking.
Python provides an exception handling capability.
There are two parts : "error checking" "catching exceptions".
Now let's try a simple example:
The code :
The code readed input will be convert in integer .
If types a value that's not an integer, the exception is caught.
In this case will print " This is not a number ".
This is very important because it generates more errors while running a program.
So, simply try to perform you action, and define what's to be done.
On except block if the action you want can't be completed.
Python provides an exception handling capability.
There are two parts : "error checking" "catching exceptions".
Now let's try a simple example:
>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string 12
>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string aaa
This is not a number
The code :
input_str = int(input ("string "))
The code readed input will be convert in integer .
If types a value that's not an integer, the exception is caught.
In this case will print " This is not a number ".
This is very important because it generates more errors while running a program.
So, simply try to perform you action, and define what's to be done.
On except block if the action you want can't be completed.
Saturday, August 8, 2009
Permutation of chars with python
It is a simple example of using python language to permutation of chars.
It uses a list generator and "yield":
Example can be modified so output will be a file.
It uses a list generator and "yield":
#!/usr/bin/env python
def permut(lst):
remove = lambda lst0, index: lst0[:index] + lst0[index+1:]
if lst:
for index, x in enumerate(lst):
for y in permut(remove(lst, index)):
yield (x,)+y
print y
else: yield ()
lst='catalin'
for p in permut(['c','a','t','a','l','i','n']):
print p
Example can be modified so output will be a file.
Saturday, August 1, 2009
Google and Python Stuff
I want share this scripts.
Is just two scripts and i think is beautifull.
First is a youtube script :
Second is a picassa script :
I hope you like this little scripts.
Is just two scripts and i think is beautifull.
First is a youtube script :
import gdata.youtube import gdata.youtube.service client_yt = gdata.youtube.service.YouTubeService() query = gdata.youtube.service.YouTubeVideoQuery() query.vs = "%s" % ('News') feed = client_yt.YouTubeQuery(query) for entry in feed.entry: print entry.title.text for link in entry.link: if link.rel == 'alternate': print link.href
Second is a picassa script :
import gdata.photos import gdata.photos.service import urllib p_client = gdata.photos.service.PhotosService() query_parameters = map(urllib.quote, ['Sexy','Bucharest']); feed = p_client.GetFeed("/data/feed/api/all?q=%s%s&max-results=10" % ('Sexy','Girl')) for entry in feed.entry: print entry.title.text for link in entry.link: if link.rel == 'alternate': print link.href
I hope you like this little scripts.
Subscribe to:
Posts (Atom)