vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another experiment with the Standard Template Library (STL). This time we are taking a look at map. Map is a Sorted Pair Associative Container (a mouthful). The pair is -- const Key, Data --, where Key has to be unique. It is Key that is sorted. In this code sample a simple word association is shown. The map is loaded, displayed, and searched.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using the C++ Standard Template Libraries (STL) can be easy, once you know how to do it. No need to putz around with doubly linked lists anymore! Here is code showing how a STL list allows you to add, insert, remove, sort, splice, merge, display, and clean-out-duplicate strings.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Get simple information like serial number, bytes/sector, sectors/cluster, free and total disk space of your hard drive using Windows API calls.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple way to create rainbow colored text on your web page. Just cut and paste the code into Notepad, save as Rainbow.htm and run it on your browser.

vmars commented: cool +2
LastMitch commented: Thanks for sharing! +12
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can access the sound chip to play midi voices using winmm.lib, or in case of Dev C++ the libwinmm.a library. There are 128 midi voices to pick from, anything from the Acoustic Grand Piano = 0 to the Gunshot = 127.

vb6exp32 commented: i greatly appreciate the "play a MIDI voice" snippet provided.. it worked perfect in my dev c ++ +0
Metalpeich commented: Great solution, worked perfectly +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

What "Hello World" is to the console, the "Bouncing Ball" is to the Graphical User Interface. Nothing fancy, the ball is created via a call to the API function ellipse() and then bounced within the confines of the windows form. For the DEV C++ crowd: Let me know if you find these snippets somewhat helpful in your learning process in the comments section at the end.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Convert a decimal (denary) integer to a binary string. An exercise in do ... while and while loops.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This program shows how to display a JPEG (also GIF,BMP,WMF etc.) image using some Windows Graphical User Interface C code. The program uses the uuid.lib file that comes with many C compilers.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Things don't have to be black and white all the time. Use a Windows API call to add some color to your text output.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

For those who need some hand holding with the Dev C++ IDE:
In the IDE go to FILE, then NEW, then Project, select Windows Application, give it a name (eg. Menu1) click OK A filesave dialog box comes up, create a new folder and save Menu1.dev there. The DevCpp IDE comes up with a template, select and delete that and cut and paste this code into the empty editor page. Now compile and run.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The snippet shows how to create a menu on a windows form and test it. Original code via BCX, modified to compile with Dev C++ as a Windows Application. This approach does speed up writing of GUI programs.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use a Windows API call to add some color to your text output. A rewrite of an earlier C++ snippet for the C crowd.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Looking at the First In First Out (FIFO) data situation. Just like a line at the grocery store check-out. Its counterpart FILO would be like a stack of dinner plates.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In Las Vegas random numbers move billions of Dollars in and out of gamblers' pockets. For the mildly inquisitive here is a test of three simple generators.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The continued fraction expansion gives us the answer to life's most persistent questions, like what is sin(x) or even tanh(x). This surprisingly short code allows you to estimate SIN, COS, TAN, EXP, SINH, COSH and TANH fairly accurately. Careful, this code is not for the usual TV crowd! You should at least know what trigonometry is, and have a mild interest in mathematics.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

So you want to find out which day of the week you were born. Well at least some of us do. I actually wrote this program because my whole family was born on Sundays, and my friends didn't believe it! An oldie but goodie, moved from DeSmet C to Turbo C and now to Pelles C. I just had somebody tell me that 01/01/1800 was a Wednesday, check it out with this program.

compzets commented: gud +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A little calculator written in BCX basic and then translated to C code and modified to compile with Dev C++ (GCC/G++). Once you find your way past the standard GUI gibberish you can figure it out.
For those who need some hand holding with the Dev C++ IDE:
In the IDE go to FILE, then NEW, then Project, select Windows Application, give it a name like Calc1 then click OK. A filesave dialog box comes up, create a new folder, might as well call it Calc1, open it and save Calc1.dev there. The DevCpp IDE comes up with a bare bones template, select and delete that and cut and paste this code into the empty editor page. Now compile and run.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To get your feet wet with GUI programming, I would stick with Tkinter at first, if you can handle the somewhat limited image file formats that Python31 will give you right now.

PyQT is more powerful, but has its own learning curve. Certain things will be similar to Tkinter, so switching later will be made easier if you have Tkinter knowledge.

The PyQT installation comes with a GUI designer that goes through XML code, some folks like those, others don't.

Lingson commented: Thanks for the advice! +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Procrastinate Now

nav33n commented: Good one! +11
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I prefer to know where functions came from, so I would use the namespace alternative ...

import math

y = math.sin(1) + math.cos(1)

If you use ...

from math import sin, cos

y = sin(1) + cos(1)

... in the hope that only sin and cos are imported, you are wrong. The whole math module is imported, the only efficiency is that you don't have to type the name space ("math."), but you lose the safety of the name space, as there will be conflicts with equally named functions or variables.

If your module name gets longer, you can use this import statement ...

import numpy as np

y = np.sin(1) + np.cos(1)

This would be the worst case ...

from math import *
from numpy import *

y = sin(1) + cos(1)

From which module will Python pick sin() and cos()? Let's say one module is more accurate than the other.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This small code shows how to change the Tkinter button color when the button is pressed ...

# change Tkinter button color when pressed

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def show_pressed(btn): 
    btn.config(activebackground='red') 

  
root = tk.Tk()
# optional color for the root window
root.config(bg='beige')
 
btn1 = tk.Button(root, text='Button1', bg='yellow') 

# change button color when pressed, procedure 1
btn1.bind('<ButtonPress-1>', lambda event: show_pressed(btn1))
btn1.pack(side='left', padx=10, pady=5) 

# change button color when pressed, procedure 2 (simpler)
btn2 = tk.Button(root, text='Button2', activebackground='cyan',
        bg='green') 
btn2.pack(padx=10, pady=5) 

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

"640K ought to be enough for anybody."
– Bill Gates, 1981

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Obstacles are those frightful things you see when you take your eyes off your goal.
-- Henry Ford

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

As Scru mentioned, let's hope the authors of the website were good guys and included the type of encoding. You can modify Henri's code ...

# get the code of a given URL as html text string
# Python3 uses urllib.request.urlopen()
# get the encoding used first
# tested with Python 3.1 with the Editra IDE

import urllib.request

def extract(text, sub1, sub2):
    """
    extract a substring from text between first
    occurances of substrings sub1 and sub2
    """
    return text.split(sub1, 1)[-1].split(sub2, 1)[0]


fp = urllib.request.urlopen("http://www.python.org")

mybytes = fp.read()

encoding = extract(str(mybytes).lower(), 'charset=', '"')
print('-'*50)
print( "Encoding type = %s" % encoding )
print('-'*50)

if encoding:
    # note that Python3 does not read the html code as string
    # but as html code bytearray, convert to string with
    mystr = mybytes.decode(encoding)
    print(mystr)
else:
    print("Encoding type not found!")


fp.close()
Nick Evan commented: excellent +25
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

No, the line numbers are not part of the code. They are added by DaniWeb for your convenience. Click on (Toggle Plain Text), if you want to see the code without them, or you want to copy and paste code into your editor (in your case the IDLE editor). If IDLE shows >>> prompts, you are not in the editor part.

stvrich commented: tanx 4 lking in as I struggled to get it "going" +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe a little example will help ...

import sys

args = sys.argv

print(args)
print( "Source  file: %s" % args[0] )
# use any of these arguments in your code
print( "Argument one: %s" % args[1] )
print( "Argument two: %s" % args[2] )


"""
my output after saving this code as sysargs1.py and 
entering a few arguments on the command line -->
['D:/Python25/Bull/sysargs1.py', 'myarg1', 'myarg2']
Source  file: D:/Python25/Bull/sysargs1.py
Argument one: myarg1
Argument two: myarg2
"""
mahela007 commented: A short ,clear post. .I deal for forums +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just another look at the PyQT canvas, this time we fill it with a colorful radial gradient ...

# pqt_canvasgradient2.py
# use PyQT's paintEvent to create a full frame canvas
# with a radial color gradient, works best with a square
# tested with Python 3.1 and PyQT 4.5  by  vegaseat

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

class MyFrame(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 350, 350)
        self.setWindowTitle("paintEvent creates a canvas")

        # color tuple (red, green, blue), values are 0 to 255
        self.red = QColor(255, 0, 0)
        self.blue = QColor(0, 0, 255)

    def paintEvent(self, event):
        """auto-create the painting canvas"""
        # needed by QRadialGradient widget
        outer = self.width()//2
        self.set_gradient(outer)

        painter = QPainter()
        painter.begin(self)
        # use the brush for background
        painter.setBrush(QBrush(self.gradient))
        painter.drawRect(event.rect())
        painter.end()

    def set_gradient(self, outer):
        """gradient radiates from center point on out"""
        center = QPointF(outer, outer)
        # (QPointF center, float radius, QPointF focalPoint)
        self.gradient = QRadialGradient(center, outer, center)
        # (float pos, QColor color), pos min 0.0 to max 1.0
        self.gradient.setColorAt(0.2, self.red)
        self.gradient.setColorAt(1.0, self.blue)


app =  QApplication(sys.argv)
frame = MyFrame()
frame.show()
app.exec_()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Inspired by Sneekula's exploration of the Python module frog, I came up with this little frog code (actually frog uses Tkinter under the hood, or should I say under that green skin) ...

# according to Snee get frog-1.0.1.zip from:
# http://www.zahlenfreund.de/python/frog.html
# unzip and copy frog.py into the Python lib folder
# or use it in the working folder
# tested with Python 3.1 on a Windows XP computer

import frog

canvas = frog.Pool()
canvas.title = "module frog draws 2 circles"
canvas.setbgcolor("yellow")
# use the default triangle shape
pen = frog.Frog(canvas)
pen.color = "blue"
# pen normally starts in the canvas center facing right
# pen draws a circle of radius 50 going counterclockwise 
pen.circle(50)

# do some text, something scientific like
# giving the circumference of the blue circle drawn
s = "the blue pen has moved %0.3f pixels" % pen.way
pen.jumpto(-170, 110)
pen.font = "Arial",8,"bold"
pen.write(s)
# jump back to center position
pen.jumpto(0, 0)

pen.color = "red"
# fill this lower circle with green
pen.fillcolor = "green"
pen.fill = True
# this circle goes into the opposite direction
# or clockwise
pen.circle(-50)

# make the pen wait for 1000 milliseconds = 1 second
pen.wait(1000)
pen.shape = "frog"

for k in range(3):
    # use a wave sound file you have
    pen.sing("boing.wav")
    pen.wait(200)

canvas.ready()

I have to admit, frog is a very capable fun module for any age!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The answers to life's problems aren't at the bottom of a bottle, they're on TV!
-- Homer Simpson

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Vision without action is a daydream. Action without vision is a nightmare.
-- Isoto Numaro

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Somewhere, something incredible is waiting to be known.
-- Carl Sagan

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tkinter version that comes with the Python 3.1 installation includes expansion module ttk. This module includes a couple of widgets missing from Tkinter, like a tabbed notebook. As usual, actual examples are totally missing from the Python manual, so I give you at least a hint of its use ...

# ttk_notebook1.py
# exploring the Tkinter expansion module ttk notebook
# tested with Python 3.1 and Tkinter 8.5   by  vegaseat

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (300, 200, 100, 50))
root.title('test the ttk.Notebook')

nb = ttk.Notebook(root)
nb.pack(fill='both', expand='yes')

# create a child wdget for each page
f1 = tk.Frame(bg='red')
f2 = tk.Frame(bg='blue')
f3 = tk.Frame(bg='green')

# create the pages
nb.add(f1, text='page1')
nb.add(f2, text='page2')
nb.add(f3, text='page3')

# put a button widget on child f1
btn1 = tk.Button(f1, text='button1')
btn1.pack(side='left', anchor='nw', padx=3, pady=5)

root.mainloop()

And here is the combobox, a combination of drop down listbox and entrybox ...

# ttk_combobox2.py
# exploring the Tkinter expansion module ttk combobox
# tested with Python 3.1 and Tkinter 8.5   by  vegaseat

import tkinter as tk
import tkinter.ttk as ttk

def action(event):
    """
    a combo box item has been selected, do some action
    """
    label['bg'] = combo.get()


root = tk.Tk()

# create a label
label = tk.Label(text='select a color', bg='white')

# create the combo box
combo = ttk.Combobox()
combo.bind('<<ComboboxSelected>>', action)

colors = ['red', 'green', 'magenta', 'yellow']
# load the combo box with the colors list …
sneekula commented: finally an actual example +8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Power does not corrupt. It is the fear of loss of power that corrupts.
'John Steinbeck'

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

When all think alike, no one is thinking.
-- Walter Lippman

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Coffee is a person who has been coughed upon.

The winner of the rat race is still a rat.

Veni, Vidi, Velcro. I came, I saw, I stuck around.

Nebraska: At least the cows are sane.

Taxation WITH representation isn't so hot, either!

Stable relationships are for horses.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I love flying. I've been to almost as many places as my luggage has.
-- Bob Hope,

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I got inspired by Henri's nice PyQT studies, so here is my small contribution, an "almost IDE" ...

# pqt_RunPyFile2.pyw
# run a given Python script file with a given version of Python
# show the script and the result
# use with Python3 or change line 82 and 83
# tested with Python31 and PyQT45  by  vegaseat   05aug2009

import subprocess
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self, python_path, initial_dir, *args):
        QWidget.__init__(self, *args)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(300, 200, 640, 400)
        s = "Run a Python script file with %s" % python_path
        self.setWindowTitle(s)
        self.python_path = python_path
        self.initial_dir = initial_dir

        self.show_fname = QLineEdit()
        self.show_fname.setToolTip("press enter key")
        self.show_script = QTextEdit()
        self.show_result = QTextEdit()

        # use a vertical boc layout
        layout = QVBoxLayout(self)
        layout.addWidget(self.show_fname)
        layout.addWidget(self.show_script)
        layout.addWidget(self.show_result)
        self.setLayout(layout)

        self.file_dialog()
        self.load_script()

        # press return key in show_fname to start run_command()
        # allows you to add commandline args
        self.connect(self.show_fname, SIGNAL("returnPressed(void)"),
                     self.run_command)

    def run_command(self):
        """use subprocess.Popen to run the command line"""
        py_file = str(self.show_fname.text())
        self.setWindowTitle(py_file)
        py_exe = self.python_path
        option = "-u"
        py_script = py_file
        p = subprocess.Popen([py_exe, option, py_script], 
            bufsize=2048, shell=True, stdin=subprocess.PIPE, 
            stdout=subprocess.PIPE, close_fds=False)
        # write additional args to the external program
        #p.stdin.write("args")
        # allow external program to work
        p.wait()
        result_str = p.stdout.read()
        # the result is a bytearray in Python3
        if type(result_str) != str:
            # decode <class 'bytes'> to string
            result_str = result_str.decode("utf8")
        s = "my result -->\n%s" % result_str
        self.show_result.setText(s)

    def file_dialog(self):
        """get the Python script file's mname"""
        #getOpenFileName (parent, caption, dir, filter, 
        #    selectedFilter, options) …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In C we had to code our own bugs. In C++ we can inherit them.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I never think of the future. It comes soon enough.
-- Albert Einstein

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Python functions xrange() and range() only take integer values. For floating point values you have to roll your own function. I called mine frange() ...

def frange(start=0, stop=0, step=1.0):
    """similar to xrange, but handles floating point numbers"""
    if step <= 0:
        while start > stop:
            yield start
            start += step
    else:
        while start < stop:
            yield start
            start += step

# testing ...
for x in frange(1.5, 4.7):
    print(x)

print("-"*20)

#testing count down ...
for x in frange(11.2, -4, -2.9):
    print(x)

"""
my result -->
1.5
2.5
3.5
4.5
--------------------
11.2
8.3
5.4
2.5
-0.4
-3.3
"""

The module numpy has an arange() function ...

# module numpy (numeric python extensions, high speed)
# free from: http://sourceforge.net/projects/numpy

import numpy as np

for x in np.arange(11.2, -4, -2.9):
    print x

"""
my result -->
11.2
8.3
5.4
2.5
-0.4
-3.3
"""
scru commented: Nice use of generators +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This an example showing the use of ttk that comes with the Python 3.1 installation as part of tkinter ...

'''
Python31 includes the Tkinter Tile extension Ttk.

Ttk comes with 17 widgets, 11 of which already exist in Tkinter: 
Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, 
PanedWindow, Radiobutton, Scale and Scrollbar 

The 6 new widget classes are: 
Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview

For additional info see the Python27 or Python31 manual:
http://gpolo.ath.cx:81/pydoc/library/ttk.html

Here the TreeView widget is configured as a multi-column listbox
with adjustable column width and column-header-click sorting.

Tested with Python3.1 and Tkinter8.5  by  vegaseat  17jul2009
modified to work with Python273 and Python31+
'''

try:
    # Python 2.7.3
    import Tkinter as tk
    import tkFont
    import ttk
except ImportError:
    # Python 3.1 or higher
    import tkinter as tk
    import tkinter.font as tkFont
    import tkinter.ttk as ttk

class McListBox(object):
    """use a ttk.TreeView as a multicolumn ListBox"""
    def __init__(self):
        self.tree = None
        self._setup_widgets()
        self._build_tree()

    def _setup_widgets(self):
        s = """\
click on header to sort by that column
to change width of column drag boundary
        """
        msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
            padding=(10, 2, 10, 6), text=s)
        msg.pack(fill='x')

        container = ttk.Frame()
        container.pack(fill='both', expand=True)

        # create a treeview with dual scrollbars
        self.tree = ttk.Treeview(columns=element_header, show="headings")
        vsb = ttk.Scrollbar(orient="vertical", command=self.tree.yview)
        hsb = ttk.Scrollbar(orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)

        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)

    def _build_tree(self):
        for col in element_header:
            self.tree.heading(col, text=col.title(),
                command=lambda c=col: sortby(self.tree, c, 0))
            # adjust the column's width …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To be or not to be, that is the question.
-- William Shakespear

(To do or not to do, that is my question.)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Do be do be do.
-- Frank Sinatra

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To be is to do.
-- Voltaire

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To do is to be.
-- Descartes

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The whole is more than the sum of its parts.
-- Aristotle

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Nothing astonishes men so much as common sense and plain dealing.
-- Ralph Waldo Emerson

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The nice part about being a pessimist is that you are constantly being either proven right or pleasantly surprised.
-- George F. Will

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PyGame is a GUI based module used mostly for game programming with Python. It comes with colorful graphics, sprites for animation, sound and responds to the mouse and keyboard ...

# a simple pygame example
# module pygame free from: http://www.pygame.org
# creates nested circles on a yellow background
# vegaseat

import pygame

pygame.init()

# create a 300 x 300 pixel display window
# the default background is black
win = pygame.display.set_mode((300, 300))
# add nice title
pygame.display.set_caption("Bull's Eye!")

# pygame uses (r, g, b) color tuples
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)

# create a canvas (in memory) to draw on
canvas = pygame.Surface(win.get_size())
# fill surface
canvas.fill(yellow)

center = (150, 150)
# draw a black border circle
radius = 92
pygame.draw.circle(canvas, black, center, radius)

# draw a white circle
radius = 90
pygame.draw.circle(canvas, white, center, radius)

# draw a red circle that fits into the white one
radius = 80
pygame.draw.circle(canvas, red, center, radius)

# finally the black bull's eye
radius = 10
pygame.draw.circle(canvas, black, center, radius)

# transfer canvas to display window at ulc (x=0, y=0)
win.blit(canvas, (0, 0))

# update/flip to show on the computer display
pygame.display.flip()

# event loop and exit conditions (windows titlebar x click)
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise SystemExit
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The symptom of an approaching nervous breakdown is the belief that one's work is terribly important.
-- Bertrand Russell