vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I got curious, so I did a little test run ...

# use Python3's dictionary comprehension to
# speed up list searches
#
# the time it takes to create the dictionary
# will be regained after about 6 searches
# as list size increases this goes down to > 1 search
# tested with Python 3.1.1  vegaseat

import timeit

data = """\
Bill
Brutus
Daphne
Dorky
Al
Kristin
Cloe
Carlos
Pete
Pheobe
Jerry
Jack
Justin
John
Julie
Joe
Moe
Theo
Albert
Alberto
Pauline
Paula
Christopher
Gisela
Lamar
Donna
Demitrius
Frank
Heidi
Margot
Cindy
Doris
Harry
Larry
Dilbert
Mary
Robert
Sophia
Samuel
Candy
Tawny
Terry
Markus
Veronika
Norbert
Zoe
Udo"""

# create a list of names from the data
mylist = data.split('\n')

# create a dictionary with name:zero pairs from the list
mylist_d = {name:0 for name in mylist}

# search for 'Udo' is the last item in the list and dictionary
statement = "'Udo' in mylist"
setup = "from __main__ import mylist"
t = timeit.Timer(statement, setup)
# doing 1000000 passes (default) gives microseconds per pass
elapsed = t.timeit()
sf = "Code  %-20s takes %0.3f micro-seconds/pass"
print( sf % (statement, elapsed))

statement = "'Udo' in mylist_d"
setup = "from __main__ import mylist_d"
t = timeit.Timer(statement, setup)
elapsed = t.timeit()
sf = "Code  %-20s takes %0.3f micro-seconds/pass"
print( sf % (statement, elapsed))

print('-'*60)

statement = "{name:0 for name in mylist}"
setup = "from __main__ import mylist"
t = timeit.Timer(statement, setup)
elapsed = t.timeit()
sf = "Code  %-20s takes %0.3f micro-seconds/pass" …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Dictionary key searches are highly optimized, since Python itself uses dictionaries internally. There are entire articles published that recommend converting a long list into a dictionary for fast searches. Still faster than a list search even with the time it takes to convert.

I remember seeing one of these articles in:
http://code.activestate.com/recipes/langs/python/

SuperMetroid commented: Thanks for that informative answer! +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This works with Python 2.5 ...

# from http://pypi.python.org/pypi/processing installed:
# processing-0.52.win32-py2.5.exe

from processing import Process

def func(name):
    print 'hello %s' % name

if __name__ == '__main__':
    # initialize thread
    p = Process(target=func, args=('bob', ))
    # starts thread
    p.start()
    # waits until thread is done
    p.join()
Dixtosa commented: thx +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Before God we are all equally wise - and equally foolish.
-- Albert Einstein

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Okay, I got the message, I will post more stuff in the every so lively C forum!!!!

iamthwee commented: Actually this is relevant as the user asked what language might be best to achieve this and that python snippet looks short and sweet. +24
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Testing can only prove the presence of bugs, not their absence.
-- Edsger W. Dijkstra

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An example of a range generator that handles floating point numbers, appropriately called frange(). The function range() or the generator xrange() can only be used for integers. Note that xrange() now is range() in Python3.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here we use the Python Image Library (PIL) and Tkinter to display the images inside a folder as thumbnails ...

# explore Tkinter and PIL to create a list of photos
# that can be displayed as thumbnails
# tested with Python25  by  vegaseat

import Tkinter as tk
from PIL import ImageTk, Image
import glob
import random

# make sure you have a folder with some jpeg pictures
folder = "./Pics_jpg"
# create a list of .jpg images that are in this folder
pic_list = glob.glob(folder+'/*.jpg')

root = tk.Tk()
root.title(folder)

label_list = []
photo_list = []
for pathname in pic_list:
    image = Image.open(pathname)
    # create a thumbnail of each image
    # width=100  height=150
    image.thumbnail((100, 150), Image.ANTIALIAS)
    # convert to something Tkinter can handle
    photo = ImageTk.PhotoImage(image)
    # the photo list is needed for labels to retain photos!
    photo_list.append(photo)
    label_list.append(tk.Label(image=photo))

# optionally random shuffle the label_list
#random.shuffle(label_list)

# display the thumbnails in rows of pics_per_row pictures
pics_per_row = 4
row = col = 0
for label in label_list:
    label.grid(row=row, column=col)
    col += 1
    if col >= pics_per_row:
        col = 0
        row += 1

root.mainloop()

If you also have GIF images in that folder and want to display them too use:
pic_list = glob.glob(folder+'/*.jpg') + glob.glob(folder+'/*.gif')

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The best kind of learning is learning by doing, or as more educated folks have said, "the maximal level of performance for individuals in a given domain is not attained automatically as a function of extended experience, but the level of performance can be increased even by highly experienced individuals as a result of deliberate efforts to improve."

nomemory commented: Sounds like a Jedi quotation. Use the pointer Luke! +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"The lyf so short, the craft so long to lerne."
-- Chaucer (1340-1400)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A little learning is a dangerous thing
-- Alexander Pope

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

first off try using the raw_input function rather than the input function, second off pythion 3.x may never become standard, they may just skip it or drag 2.x out for a long long time, thing is no one like 3.x because they made very little changes and those changes aren't really worth porting all your old code to, so skipping back to 2.x would be the smartest choice in my opinion.

I think soulrider is the smart person here.

The code you gave works fine with Python 3.1.1 using IDLE. Which IDE are you using?

On another note, why on Earth would you use
sys.stdout.writelines(added_dirs) ???
That is what the print() function is for.

JasonHippy commented: well said sir! +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Pessimist: "The glass is half empty."
Optimist: "The glass is half full."
Engineer: "The glass is twice as big as it needs to be."

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Gribouillis commented: good link +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example how to present the elements of a list or tuple in a nice tabular format ...

# create a table string from a list

def create_table(mylist, itemsperline=5):
    """
    given a list mylist return a string containing
    itemsperline of the list items in each line
    """
    table = ""
    for ix, element in enumerate(mylist):
        # add new line character after every itemsperline elements
        if ix % itemsperline == 0 and ix != 0:
            table += '\n'
        # use string formatting (adjust to your needs)
        # if length of element varies from 1 to 10 use for instance
        # table += "%-12s" % element 
        table += "%-4s" % element
    return table


# create the test list
mylist = [x+y for x in 'abcdef' for y in '1234']

#print mylist  # test ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', ... ]

itemsperline = 4
table = create_table(mylist, itemsperline)
    
print(table)

"""my result -->
a1  a2  a3  a4  
b1  b2  b3  b4  
c1  c2  c3  c4  
d1  d2  d3  d4  
e1  e2  e3  e4  
f1  f2  f3  f4  
"""
Ene Uran commented: works well +8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A code example to show that wxPython does have a very flexible plotting widget. Here we graph the last 300 trading days (about 1 year) of a given company's closing stock values ...

# using wxPython's wx.lib.plot.PlotCanvas()
# to show a line graph of some stock values
# tested with Python25 and wxPython28
# vegaseat

import wx
import wx.lib.plot
import urllib2

class MyFrame(wx.Frame):
    def __init__(self, data_list, start_date, end_date, ticker,
        max_val, min_val):
        wx.Frame.__init__(self, parent=None, id=-1,
            title="line graph of stock values",
            size=(600, 300))

        # set up the plotting canvas
        plot_canvas = wx.lib.plot.PlotCanvas(self)
        # get client usable size of frame
        frame_size = self.GetClientSize()
        # needed for SaveFile() later
        plot_canvas.SetInitialSize(size=frame_size)
        # optional allow scrolling
        plot_canvas.SetShowScrollbars(True)
        # optional drag/draw rubberband area to zoom
        # doubleclick to return to original
        # right click to shrink
        plot_canvas.SetEnableZoom(True)
        # optional
        # set the tick and axis label font size (default is 10 point)
        plot_canvas.SetFontSizeAxis(point=8)
        # set title font size (default is 15 point)
        plot_canvas.SetFontSizeTitle(point=10)

        # connect (x, y) points in data list with a line
        val_line = wx.lib.plot.PolyLine(data_list, colour='blue',
            width=1)
        # assign lines, title and axis labels
        title = "Latest 300 trading days of %s" % ticker
        x_axis = "Starting %s up to %s" % (start_date, end_date)
        y_axis = "value at close ($)"
        gc = wx.lib.plot.PlotGraphics([val_line],
            title, x_axis, y_axis)
        # draw the plot and set x and y axis sizes
        plot_canvas.Draw(gc, xAxis=(1, 300), yAxis=(min_val, max_val))

        # optional save graph to an image file
        plot_canvas.SaveFile(fileName='stock1.jpg')


ticker = "MSFT"

sf = 'http://ichart.finance.yahoo.com/table.csv?s=%s' % ticker
url = urllib2.urlopen(sf) …
sneekula commented: nice code! +8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

As he walked in the woods, Bill Bryson wrote:
"It is not true that the English invented cricket as a way of making all other human endeavours look interesting and lively; that was merely an unintended side effect."

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Life isn't worth living, unless it is lived for someone else.
-- Albert Einstein

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There is the Visual Python specialized GUI toolkit, used mostly for 3D modeling. You can draw an object and then drag it in space with the cursor with the right mouse button pressed. Objects can also be animated. Here is a short sample ...

# draw cones in space
# press the right mouse button and use cursor to rotate the object
# experiments with visual Python (VPython) from: http://vpython.org/
# used VPython-Win-Py2.6-5.12.exe for Python26
# needs and comes with numpy
"""
cone(pos=(0,0,0), axis=(1,0,0), radius=1, color=(0,0,0))
color (red, green, blue) color values 0.0 to 1.0 
default is white = (1,1,1)
"""

import visual as vs

vs.scene.width = 500
vs.scene.height = 500
vs.scene.title = "draw 3 cones (drag with right mouse button)"

# avoid autoscale (autoscale default=True)
vs.scene.autoscale = False

# axis x=8 points right
cone1 = vs.cone(pos=(0,0,0), axis=(8,0,0), radius=4)
cone1.color = vs.color.green

# axis x=-8 points left
cone2 = vs.cone(pos=(0,0,0), axis=(-8,0,0), radius=4)
cone2.color = vs.color.red

# pos y=-6 is below center and axis y=2.4 points up from there
cone3 = vs.cone(pos=(0,-6,0), axis=(0,2.4,0), radius=4)
cone3.color = (0.0, 0.9, 1.0)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just an experiment to explore the use of wxPython buttons to start and stop a process ...

# explore WxPython buttons to start and stop a process
# set flag to 'stop' to allow exit

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle):
        wx.Frame.__init__(self, parent, -1, mytitle, size=(300, 200))
        self.SetBackgroundColour("yellow")
        self.start_btn = wx.Button(self, -1, label='Start')
        self.start_btn.Bind(wx.EVT_BUTTON, self.start_btnClick)
        self.stop_btn = wx.Button(self, -1, label='Stop')
        self.stop_btn.Bind(wx.EVT_BUTTON, self.stop_btnClick)
        self.label = wx.StaticText(self, -1, "-------")
        
        # layout the widgets in a vertical order
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        sizer_v.Add(self.start_btn, 0, flag=wx.ALL, border=10)
        sizer_v.Add(self.stop_btn, 0, flag=wx.ALL, border=10)
        sizer_v.Add(self.label, 0, flag=wx.ALL, border=10)
        self.SetSizer(sizer_v)        
        
        self.char = '>'
        
    def start_btnClick(self, event):
        self.flag = 'start'
        self.processing()

    def stop_btnClick(self, event):
        self.flag = 'stop'
        self.processing()
    
    def processing(self):
        self.SetTitle(self.flag)
        while True:
            if self.flag == 'stop':
                break
            if self.flag == 'start':
                self.label.SetLabel(self.char)
                # needed to keep other processes going
                wx.GetApp().Yield()   
                wx.Sleep(1)
                self.char  += '>'


app = wx.App(0)
MyFrame(None, 'start and stop').Show()
app.MainLoop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Talking about Gloria, I thought I better post that here, in case someone is looking for a Tkinter GUI toolkit progressbar ...

# explore the ttk.Progressbar of the Tkinter module ttk
# ttk is included with Python 3.1.1
# vegaseat

import tkinter as tk
from tkinter import ttk

def click(event):
    # can be a float
    increment = 3.4
    pbar.step(increment)


root = tk.Tk()
root.title('ttk.Progressbar')

pbar = ttk.Progressbar(root, length=300)
pbar.pack(padx=5, pady=5)

btn = tk.Button(root, text="Click to advance progress bar")
# bind to left mouse button click
btn.bind("<Button-1>", click)
btn.pack(pady=10)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a simple Pygame example showing an approach to a resizable window ...

# create a resizable pygame window
# tested with Python 3.1.1 and Pygame 1.9.1 
# vegaseat

import pygame as pg

def create_window(width, height):
    """create a width x height resizable window/frame"""
    win = pg.display.set_mode((width, height), pg.RESIZABLE)
    # optional fill bg red, default is black
    win.fill((255, 0, 0))
    # optional title info
    sf = "size x=%s  y=%s" % (width, height)
    pg.display.set_caption(sf)
    
    # any extra code here ...
    # draw a white circle
    white = (255, 255, 255)
    # center can be fixed or calculated for resize
    center = (150, 150)
    radius = 100
    pg.draw.circle(win, white, center, radius)
    
    pg.display.flip()
    return win


pg.init()

width = 300
height = 200
win = create_window(width, height)

# event loop and exit conditions (windows titlebar x click)
while True:
    for event in pg.event.get():
        if event.type == pg.VIDEORESIZE:
            width, height = event.size
            # redraw win in new size
            win = create_window(width, height)
            print(win.get_size())  # test
        if event.type == pg.QUIT:
            raise SystemExit
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Well, PyGame is out for Python 3.1, so I downloaded/installed the Windows installer and gave it a quick test ...

# experiments with module pygame 
# bounce a red ball whose image is stored in this code
# pygame from: http://www.pygame.org/
# win binary installed: pygame-1.9.1.win32-py3.1.msi
# tested with Python 3.1.1 and Pygame 1.9.1 
# vegaseat   14sep2009

import pygame as pg
import base64

"""
# use this Python3 program to create a base64 encoded image string
# (base64 encoding produces a readable string from a binary image)
# then copy and paste the result into your pygame program ...
import base64
gif_file = "ball_r.gif"
gif_bytes = open(gif_file, 'rb').read()
b64_bytes = base64.encodebytes(gif_bytes)
# decode <class 'bytes'> bytestring to string
b64_str = b64_bytes.decode("utf8")
print( "gif64='''\\\n" + b64_str + "'''" )
"""

gif64='''\
R0lGODlhQABAAPcAACEBAY8DA9wQILcED1ECAqMECOsaL8oKGTgBAXADA5kEBeQVJ8EIFK0EC+wg
NS8BAWUCAtMOH0gCAoQDAykBAZkEBNwSJsEGEFsCAq0ECOwdNdMMGkABAXoDA6MEBuUXLsoJFbcE
DPIgNQAAAJ0FBAAAAAAAAAAAAAAABQAAAAAAAAAAAPEGCt0FBQQAAAAAAF4CBAkAAN8FBVUCAgAA
AgAAAAAAAAAAAAEBgAAAAQUAAwIC7gAAKt0FBQUBZgAAAAAABgAAAAAAAAAAAAsAAN4FBQQAAAAA
AOgPDmoCAu8GBlUCAmoDBwgAAOsFBVUCAvIGRfIGDfMHz/IGOhgGZXUDA+sFBVUCAugMoQoCwuEH
0VYCNgACBQAAAAUAAAAAAAACAwAAAAAAAAAA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L6KSBxgxLWvco0sCAgA7
'''

# encode string to <class 'bytes'>, needed for Python3
# comment out if you are using Python2
gif64 = gif64.encode("utf8")

# convert back to a binary image to save to a file in the working directory
ball = base64.b64decode(gif64)
fout = open("ball_r.gif","wb")
fout.write(ball)
fout.close()

# initialize pygame
pg.init()

# now you can use the gif file you just saved
image_file = "ball_r.gif"

# image moves [x, y] at a time
im_dir = [2, 1]

# pygame uses an RGB color tuple
black …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You are creating a situation where the while loop exit condition is always True. Test this ...

overwrite = None
while overwrite != 'y' or overwrite != 'n':
    overwrite = raw_input("Do you want to overwrite (Y/N)? ").lower()
    print overwrite != 'y'
    print overwrite != 'n'
    # overall condition
    print False or True

Easier to understand is this approach ...

while True:
    overwrite = raw_input("Do you want to overwrite (Y/N)? ").lower()
    if overwrite == 'y' or overwrite == 'n':
        break

... or even simpler ...

while True:
    overwrite = raw_input("Do you want to overwrite (Y/N)? ").lower()
    if overwrite in 'yn':
        break
nunos commented: thanks for such a great answer to my question! +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Every generation laughs at the old fashions, but follows the new fashions religiously.
-- Henry David Thoreau

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Want to add font and color to PyQT's label text? Here is one way to do just that ...

# adding font and color to PyQT's QLabel widget text
# vegaseat 

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 320, 100)
        self.setWindowTitle("font and color")

        text = " QLabel text with font and color "
        label = QLabel(text)

        # QFont(family, pointSize, weight, italic)
        # weight QFont.Light=25, QFont.Normal=50, QFont.Bold=75
        # pointSize=12, weight=50, italic=False by default
        font = QFont("Times", 32, QFont.Bold, True)
        label.setFont(font)

        # set the foreground and background colors of the label
        fg = "QLabel {color:red}"
        bg = "QLabel {background-color:yellow}"
        label.setStyleSheet( fg+bg )
        
        # use grid layout
        grid = QGridLayout()
        # addWidget(widget, row, column, rowSpan=1, columnSpan=1)
        grid.addWidget(label)
        self.setLayout(grid)


app =  QApplication([])
form = MyForm()
form.show()
app.exec_()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Adding an item to a PyQT list box is used to take a look at PyQT programming styles ...

# add an item to a PyQT list box with a button click
# shows newer connect style and uses no 'import sys'
# tested with PyQT 4.5.2 and Python 3.1.1

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("click button")
        self.count = 1

        layout = QVBoxLayout(self)
        self.list = QListWidget(self)
        layout.addWidget(self.list)

        s = 'add an item to the list box'
        self.button = QPushButton(s, self)
        layout.addWidget(self.button)

        # old connect style for PyQt < 4.5
        #self.connect(self.button, SIGNAL('clicked()'), self.addItem)
        # new connect style for PyQt 4.5+
        self.button.clicked.connect(self.addItem)

    def addItem(self):
        s = 'Item #%d' % self.count
        self.list.addItem(s)
        self.count += 1


app = QApplication([])
window = MyWindow()
window.show()
app.exec_()

Note:
You may want to be careful with this interim release of PyQT:
PyQt-Py3.1-gpl-4.6rc1-1.exe
It gives me a QVariant() error with some of my code.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Clearing the display screen in console mode depends on the Operating System, that and the limited usefulness is why many multiplatform computer languages do not include it.

Here is a Python version using module os ...

import os
# works on windows nt (also xp and vista) or linux
os.system(['clear','cls'][os.name == 'nt'])
Gribouillis commented: nothing for idle ? +4
Warkthogus commented: Very helpful and clear. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example how to write a program to convert between units of distance, area, volume, weight, pressure, and energy. The wxPython GUI toolkit's wx.NoteBook() widget is used to make good use of the limited frame/window space available.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A variation of the previous bouncing ball code. This time the upper left corner of the image rectangle simply follows the position of each mouse click. Use an image you have, in my case I used a small red ball in a black background. A simple code to experiment with.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The module pyglet leans on OpenGL for graphics and is used in the scientific community together with Python. This short code snippet shows you how to use it to display an animated GIF file. The download is free, so give it a try. You don't have to download OpenGL to use pyglet.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This well commented Python snippet uses wxPython's plotting widget to graph the projectile motion of two different firing angles on the same plotting canvas.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This code creates a sound file in Sun's simple AU audio format of a sine wave of given frequency, duration and volume.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sometimes you want to accomplish something with a minimum ammount of code. Here is an example of using modern Python concepts of lambda, list comprehension and all() to create an anonymous function that returns a prime list from 2 to n.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This short Python program calculates Euler's number e, the base of natural logarithms, to a precision of at least 100 digits in this case. To get the precision needed, the Python module decimal is used. The result is compared to a published result.

ddanbe commented: Nice! +15
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another application of Python module base64, this time to embed midi music data in your program. You also need the module pygame to execute this Python code. Enjoy the music!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just bouncing a red ball within the frame of a window, the twist here is that the image is stored within the code as a base64 encoded string of the gif image. This way you only have to distribute one file. The Python code is heavily commented, so you can follow what is going on.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using count() from Python's itertools module and the Tkinter GUI toolkit's after() function, you can create a simple counter that counts up the seconds until the Stop button is pressed.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This handy little utility determines the size of a folder and it's subfolders in MBytes.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tkinter GUI toolkit's canvas object is very nice for all sorts of drawings and plotting. However, when it comes to saving the image Tkinter limits you to postscript printer files. One solution is to draw the same image in parallel on PIL's image-draw object in memory. This is made relatively simple, as the Tkinter and PIL methods function pretty much the same.

Here is a Python code snippet showing you the basics in the form of a plot of two trig functions.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a little mathematical exercise in geography, namely the use of longitude and latitiude coordinates to calculate the distance between two given cities. You can obtain the coordinates for just about any earthly city from WWW.ASTRO.COM. The coordinates are in a format like 35n13 (35 degrees, 13 minutes north). The north/south indicator makes this a latitude. This value has to be converted to radians. The southerly direction is negative.

The same goes for longitudes, which have an east/west indicator. The westerly direction is negative.

You can expand the dictionary with additional cities, just stick with the format used in the code snippet.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There are times when you have to layout widgets on a window area fairly well spaced apart. To do this with pack() or grid() will be more than frustrating, for these occasions place() with its absolute coordinates comes to the rescue. Here is some Python/Tkinter GUI code showing you how place() is used. Also thrown in is code to generate random color hex strings acceptable by Tkinter.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The wxPython GUI toolkit makes a very nice plotting component/widget available. You can select line or marker plotting, or a combination of both. All you have to supply is a list of x,y point tuples. Other features include zooming and printing.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The normal XOR crypting is used with a small base64 twist to produce printable crypted text.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Wallpaper or tile images are small images that can be spread across a background repetitively. A common practice on web pages. The surface created with wx.PaintDC() can be used for this effect and still allows other widgets to be put on top of the wallpaper. The small tile image is included in the code, in the form of a base64 encoded image string.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The surface or canvas established with wx.PaintDC() can be used to draw a number of shapes like lines, rectangles and circles. The snippet shows you how to select colors and then draw a few simple shapes. Use help(wx.PaintDC) to get information about the many things you can use this surface for.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This simple isprime(number) function checks if the given integer number is a prime number and returns True or False. The function makes sure that the number is a positive integer, and that 1 is not considered a prime number.

To find out if an integer n is odd one can use n & 1, to check for even one can then use not n & 1 or the more traditional n % 2 == 0 which is about 30% slower.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This little program uses Python and it's module pygame to do some sprite type animation. The rectangle that contains the image is moved and bounced within the window's frame. Pretty crude, since the whole screen frame is erased for each move. Actually it works smooth enough, and is relatively flicker free. You could improve the code by keeping track of the image's rectangle, refreshing and updating just it.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The assumption is, that the typical workweek starts with Monday and ends with Friday. This is something the average working bloke has to live with (unless you work for a bank or the government). This little code will spit out a listing of all the workdays of a given month. It does not consider special holidays during the week. Anyway, the module calendar that comes with Python does a swell job.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Python module 'tarfile' is more flexible then it's counterpart 'zipfile'. It allows you to simply archive files without compression, or use the gzip format of compression, or the super compression format bzip2. Here is code to show you the use of the module.

fchevitarese commented: Good script ;) +0