vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Never explain yourself. Your friends don’t need it and your enemies won’t believe it."
-- Belgicia Howell

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The seven real wonders of the world:
to see
to hear
to feel
to touch
to taste
to laugh
to love

DeanMSands3 commented: Well said. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Most of us remember September 11, 2001.
Write a Python program that shows how many days ago that event was, and on what day of the week.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Love is friendship on fire.
-- The Perfect Man

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

My advice, in Python2 it is better not to use the input() function. If you don't want to type raw_input all the time start your code with something like this ...

>>> input = raw_input
>>> 
>>> name = input("Enter your name: ")
Enter your name: Clark Kent
>>> name
'Clark Kent'
>>> 

... now you are in line with Python3 syntax.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Twitter will soon reach the 500 million messages per day mark.

Reverend Jim commented: And the useful information conveyed is near zero. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

We as a global society are increasingly dependent on science, yet increasingly ignorant of it.
-- Rolf Heuer

ChrisHunter commented: TRUE THAT ! +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Line 7 needs an extra ] at the end
line 8 needs to be else:

Are you sure you want & rather than and

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"If I can get a mechanism which will make a current of electricity vary in its intensity, as the air varies in density when a sound is passing through it, I can telegraph any sound, even the sound of speech."
— Alexander Graham Bell

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You basic problem is explained here ...

alist = [[u'', u'-0', u'-3', u'-6', u'-9', u'-12', u'-15', u'-18']]

# alist is a list within a list, so use alist[0]
# the if x statement filters out the empty string u''
xval  = [int(x) for x in alist[0] if x]

print(xval)  # test

'''
[0, -3, -6, -9, -12, -15, -18]
'''

You can find a good elementary book on Python here:
http://www.swaroopch.com/notes/Python

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have the Windows OS, you can download the portable version of Python27 or Python32 from:
http://www.portablepython.com/

That comes with a very nice editor (IDE) called PyScripter.

The portable version allows you to run Python from a flashdrive, or simply pass on your code to a computer that does not have Python installed.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Actually IDLE that comes with the normal Python distribution is quite good. If you use WIndows and have Python32, you can run this little batch file to get IDLE going ...

REM a batch file to force IDLE to use Pyhon32
REM saved as IDLE32.bat
C:\Python32\pythonw.exe -u C:\Python32\Lib\idlelib\idle.pyw

There is an improved version of this program available as VIDLE for Python2:
http://vpython.org/vidle/vidle2.zip

For more info see:
http://vpython.org/vidle/index.html

It is also fun to experiment with the 3D graphics of the VPython package. Installing VPython will install VIDLE.
For Python27 download from:
http://vpython.org/contents/download/VPython-Win-Py2.7-5.41.exe

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A good teacher can keep students interested regardless what programming language they have to use.

If I would have to teach children, I would most likely use Python because that has a turtle module (LOGO like).

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example how to connect a button to a label ...

'''
run_button_label1.py

a simple loader for .ui XML files generated with PySide Designer
the Designer's XML file was saved as "button_label1.ui"

it contains a QMainWindow form with a QPushButton and a QLabel

select the QPushButton and use the Desiger's "Edit Signals/Slots" (F4) 
to connect (drag) the QPushButton signal via clicked()
to the QLabel slot via clear() 

# PySide is the official LGPL-licensed version of PyQT
tested with PySide474 and Python27/Python32
'''

from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import QUiLoader

def on_click():
    label.setText("hello")

# create the application
app = QApplication([])

# create the ui loader
loader = QUiLoader()
# and load the form's ui file
widget = loader.load("button_label1.ui")
widget.show()

# create the pushbutton and label objects
# (for correct names check the .ui file)
button = widget.findChild(QPushButton, 'pushButton')
label = widget.findChild(QLabel, 'label')

# if the button is clicked clear and change the label text
# uses newer connect style (4.7)
button.clicked.connect(on_click)

# execute the application
app.exec_()
xopenex commented: quick and direct +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I just got a robo-phonecall from Barbara Bush telling me that Mitt Romney's wife would make a fine First Lady.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Until one has loved an animal,
a part of one's soul remains unawakened.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PySide is out for Python32, here is a little test program ...

# explore multiple QFrame() in a QGridLayout()
# also change the color of the frames
# tested with PySide 474 and Python32

from PySide.QtCore import *
from PySide.QtGui import *

class FrameTester(QWidget):
    def __init__(self, title, width, height, parent=None):
        # create the window (this will be instance self)
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, width, height)
        self.setWindowTitle(title)
        self.make_frame()
    
    def make_frame(self):
        self.frame1 = QFrame(self)
        self.frame1.setLineWidth(3)
        self.frame1.setFrameStyle(QFrame.Box|QFrame.Sunken)
        
        self.frame2 = QFrame(self)
        self.frame2.setLineWidth(3)
        self.frame2.setFrameStyle(QFrame.Box|QFrame.Sunken)        

        self.frame3 = QFrame(self)
        self.frame3.setLineWidth(3)
        self.frame3.setFrameStyle(QFrame.Box|QFrame.Sunken)
        
        grid = QGridLayout()
        grid.setSpacing(10)
        # addWidget(QWidget, row, column, rowSpan, columnSpan)
        # span 2 rows and 1 column each
        grid.addWidget(self.frame1, 1, 1, 2, 1)
        grid.addWidget(self.frame2, 1, 2, 2, 1)
        # span 1 row and 2 columns
        # note that you occupy row 3 now
        grid.addWidget(self.frame3, 3, 1, 1, 2)
       
        self.setLayout(grid)
        
        # put a button on frame1
        self.button = QPushButton("Change colors", self.frame1)
        self.button.resize(150, 30)  # alternate size
        self.button.move(20, 20)
        # bind the button click
        self.button.clicked.connect(self.changeFrameColor)
        
    def changeFrameColor(self):
        # color is a string in #RRGGBB format
        red = "#ff0000"
        blue = "#0000ff"
        yellow = "#ffff00"        
        style_str = "QFrame {background-color: %s}"            
        # use style sheet to set background colors of frames
        self.frame1.setStyleSheet(style_str % yellow)
        self.frame2.setStyleSheet(style_str % red)
        self.frame3.setStyleSheet(style_str % blue)        

# create the Qt Application
app = QApplication([])

title = "3 frames in a grid layout"
width = 800
height = 600
tester = FrameTester(title, width, height)
tester.show()

# run the main Qt event loop
app.exec_()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example of a PySide program using the drag-drop Designer that comes with it (similar to ene's example) ...

'''
run_combobox2.py

a simple loader for .ui XML files generated with PySide Designer
the Designer's XML file was saved as "combobox2.ui"

contains a QMainWindow form with a QComboBox and a QLabel
select the QComboBox and use the Desiger's "Edit Signals/Slots" (F4) 
to connect the QComboBox signal via currentIndexChanged(QString)
to the QLabel slot via setText(QString) 

tested with PySide474 and Python32
'''

from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import QUiLoader

# create the application
app = QApplication([])

# create the ui loader
loader = QUiLoader()
# and load the form's ui file
widget = loader.load("combobox2.ui")
widget.show()

# create the combo and label objects
# (for correct names check the .ui file)
combo = widget.findChild(QComboBox, 'comboBox')
label = widget.findChild(QLabel, 'label')

# load the combo box with some string items
pasta_list = ['Spaghetti', 'Fettuccine', 'Ziti', 'Penne', 'Lasagne']
for pasta in pasta_list:
    combo.addItem(pasta)

# execute the application
app.exec_()

... and here is the combobox2.ui XML file the Designer created ...

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>150</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QComboBox" name="comboBox">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>20</y>
      <width>69</width>
      <height>22</height>
     </rect>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>120</x>
      <y>20</y>
      <width>46</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>TextLabel</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>21</height> …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can expand that with slicing ...

# using del and slicing on a list

ar = range(7)

print ar  # [0, 1, 2, 3, 4, 5, 6]

# delete element 1 and 2
del ar[1:3]

print ar  # [0, 3, 4, 5, 6]

ar = range(7)

# delete every second element
del ar[::2]

print ar  # [1, 3, 5]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example how to access one frame from the other via the instance ...

# create two frames with wxFrame
# access one frame from the other

import wx
import random

class Frame1(wx.Frame):
    def __init__(self, parent):
        # self will be the Frame1 instance
        wx.Frame.__init__(self, parent, wx.ID_ANY, title='Frame1', pos=(50, 50))
        self.SetBackgroundColour("green")
        # create a Frame2 instance, pass Frame1 instance self to Frame2
        self.frame2 = Frame2(None, self)
        # show Frame2
        self.frame2.Show()

        # create a button
        self.button1 = wx.Button(self, wx.ID_ANY, label='change Frame2 color')
        # bind mouse event to an action
        self.button1.Bind(wx.EVT_BUTTON, self.button1Click)

        # use a box sizer to lay out widgets
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        sizer_v.Add(self.button1, 0, flag=wx.ALL, border=10)
        self.SetSizer(sizer_v)

    def button1Click(self, event):
        """
        button1 has been left clicked, do something
        """
        color_list = ['red', 'blue', 'white', 'yellow', 'magenta', 'black']
        # pick a color from the color_list at random
        color = random.choice(color_list)
        print(color)  # test
        # change color of Frame2 via instance self.frame2
        self.frame2.SetBackgroundColour(color)
        # now clear old colour, set to new colour
        self.frame2.ClearBackground()        


class Frame2(wx.Frame):
    # notice how the Frame1 instance is passed
    def __init__(self, parent, frame1):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title='Frame2', pos=(450, 150))
        self.SetBackgroundColour("brown")
        # in case you have to use the Frame1 instance within Frame2 methods
        self.frame1 = frame1


app = wx.App(0)
# create a Frame1 instance and show the frame
frame1 = Frame1(None)
frame1.Show()
app.MainLoop()
david.franco.94064 commented: this may be what I need to my problem +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Christmas is a time when kids tell Santa what they want and adults pay for it. Deficits are when adults tell the government what they want and their kids pay for it.
-- Richard Lamm

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This guy walks into a bar down in Texas and orders a white wine.
Surprised, the bartender looks around and says "You ain't from
around here where you from, boy?"

The guy says, "I'm from Pennsylvania."

The bartender asks, "What do you do up in Pennsylvania?"

The guy responds, "I'm a taxidermist."

The bartender asks, "A taxidermist ... what the hell is a taxidermist?"

The guy says "I mount dead animals."

The bartender smiles and shouts to the whole bar, "It's OK boys, he's one of us!"

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Tkinter's Entry widget allows the user to input a string. In your case this string has to be converted to a number for calculations.

Another option for user input is to use Tkinter's pop-up dialogs that give you some control over what the user enters. Here is an example ...

# use Tkinter's simple pop-up dialogs to ask for input
# askfloat() for floating point numbers
# askinteger() for whole numbers
# askstring() for strings

try:
    # for Python2
    import Tkinter as tk
    import tkSimpleDialog as tksd
except ImportError:
    # for Python3
    import tkinter as tk
    import tkinter.simpledialog as tksd

root = tk.Tk()
# show input dialogs without the Tkinter window
root.withdraw()

# for numeric input use askfloat or askinteger
# widgets will prompt again if wrong value is entered
# minvalue and maxvalue are optional
price = tksd.askfloat("Price", "Enter the price of the item:")
print(price)

quantity = tksd.askinteger("Quantity", "Number of items needed:",
    minvalue=1, maxvalue=1000)
print(quantity)

result = "Total cost is %0.2f" % (price * quantity)
print(result)

# you could use askstring to display the result
sf = "%0.2f" % (price * quantity)
tksd.askstring("Result", "Total cost is:", initialvalue=sf)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Today's mighty oak is just yesterday's nut that held its ground.

codeorder commented: .not a deep as a root, though "deep".:) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It might be safer to extract the numeric value ...

list1= ['NNW 30', 'SE 15', 'SSW 60', 'NNE 70', 'N 10']

list2 = []
for item in list1:
    s = ""
    for c in item:
        # extract numeric value
        if c in '1234567890.-':
            s += c
    if item[0] == 'N':
        s = '+' + s
    if item[0] == 'S':
        s = '-' + s
    list2.append(s)

print(list2)  # ['+30', '-15', '-60', '+70', '+10']
valorien commented: elegant solution. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A wife won't say what she wants, but she reserves the right to be pissed off if she doesn't get it.

wenbnet commented: hmmm, very true +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Some people won't easily fit in because they were born to stand out.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To avoid suffering, one must not love; but then one suffers from not loving.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Destiny is something we’ve invented because we can’t stand the idea that everything that happens is accidental.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I only take Viagra when I'm with more than one woman.
-- Jack Nicholson

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The best way to guarantee a loss is to quit.
-- Morgan Freeman

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

History is the sum total of things that could have been avoided.
-- Konrad Adenauer

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"The nicest thing for me is sleep, then at least I can dream."
-- Marilyn Monroe

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Leading a large country like the US is a thankless task at best. So, whoever manages to buy his or her way into the presidency will be an idiot to some, a savior to others, and hopefully a decent person to most of us.

Unfortunately in the US news casts have turned into entertainment, no facts, just opinions at the moron level. I would say that the internet is probably the best source of information. Check the US press and the foreign press.

Salem commented: The popular press has always been trashy +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Cinnamon rolls and a strong cup of coffee.

I think you are are a couch potato only if you eat your chips on a couch. You might be a mouse potato if you eat your chips in front of the computer. Just reading the calories on a bag of potato chips is enough to scare the hell out of me!

jingda commented: You really are strict about the food labels +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PyQt, or in this case PySide, allows you to look at a given web page via PySide.QtWebKit.QWebView() ...

# PySide is the official LGPL-licensed version of PyQT
# You can download and use the Windows self-extracting installer
# PySide-1.0.0qt472.win32-py2.7.exe
# from: http://developer.qt.nokia.com/wiki/PySide_Binaries_Windows
# modified example from:
# http://www.pyside.org/docs/pyside/PySide/QtWebKit/
# tested with pyside472 and Python27
 
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
 
# create a Qt application
app = QApplication([])

# create a PySide.QtWebKit.QWebView() to display a web page
# (your computer needs to be connected to the internet)
view = QWebView()
url = "http://qt.nokia.com/"
view.load(QUrl(url))
view.show()

# run the application event loop
app.exec_()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Binary Block

Unhnd_Exception commented: :) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use one of the Python GUI toolkits to display an image of a person. Define hot-spots (regions) on the person so when you click on them it will tell you which part of the body has been clicked on.

bumsfeld commented: fine project +11
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Why are things as they are and not otherwise?
__ Johannes Kepler

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In Science the credit goes to the man who convinces the world, not to the man to whom the idea first occurred.
>> Sir William Osler

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In essence, science is a perpetual search for an intelligent and integrated comprehension of the world we live in.
== Cornelius Bernardus Van Neil

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Science is what you know. Philosophy is what you don't know.
-- Bertrand Russell

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PIL will be your answer. Here is an example ...

# load, resize and save image with Python Imaging Library (PIL)
# optionally display images using Tkinter
# PIL from: http://www.pythonware.com/products/pil/
# or
# http://www.lfd.uci.edu/~gohlke/pythonlibs/

from PIL import Image

# pick an image file you have .bmp  .jpg  .gif.  .png
# (if not in the working directory, give full path)
file_in = 'Roses.jpg'
pil_image = Image.open(file_in)
# retrieve some information
print("image.size   = (%d, %d)" % pil_image.size)
print("image.format = %s" % pil_image.format)  # 'JPEG'
# common modes are 
# "L" (luminance) for greyscale images,
# "RGB" for true color images, 
# "CMYK" for pre-press images
print("image.mode   = %s" % pil_image.mode)    # 'RGB'

# change to a 200x100 size image using best downsize filter
image200x100 = pil_image.resize((200, 100), Image.ANTIALIAS)

# save the resized image as .jpg file to working directory
# (you could save it as .bmp, .gif, .png  too)
file_out = 'Roses200x100.jpg'
image200x100.save(file_out)

print("File saved as %s" % file_out)

# optional show image using Tkinter ...
# for Python3 use tkinter
import Tkinter as tk
from PIL import ImageTk

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

# convert PIL image objects to Tkinter PhotoImage objects
tk_image1 = ImageTk.PhotoImage(pil_image)
tk_image2 = ImageTk.PhotoImage(image200x100)

# display the images on labels
label1 = tk.Label(root,image=tk_image1)
label1.pack(padx=5, pady=5)
label2 = tk.Label(root,image=tk_image2)
label2.pack(padx=5, pady=5)

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

Mildly more complex, but very practical ...

s = "threestoryhomesdrainpipes"
size = 5
print([s[k:k+size] for k in range(0, len(s), size)])
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python27 is simply a more advanced Python26 with a fair number of Python3 features thrown in to help the user in the transition to Python3.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hmm ...

a = list(range(10))
print a[::-----1]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

After looking for it all those many years, I just found out the money does not grow on trees.

~s.o.s~ commented: Nice one :-) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use
import wx.lib.newevent

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The nice thing about using a list of (char_frequency, char) tuples is that they also sort the characters that have matching frequencies ...

# create a list of (char_frequency, char) tuples

import pprint

text = "supercalifragilisticexpialidocious"

# create a character list of the text
ch_list = list(text)

# create a list of (letter_freq, letter) tuples
# set(ch_list) creates a set of unique characters
# c.isalpha() is True for letters only
ltc = [(ch_list.count(c), c) for c in set(ch_list) if c.isalpha()]

# sort by increasing frequency
# also sorts the letters with matching frequencies
ltc.sort()

# pretty print the result
pprint.pprint(ltc)

''' my result ...
[(1, 'd'),
 (1, 'f'),
 (1, 'g'),
 (1, 't'),
 (1, 'x'),
 (2, 'e'),
 (2, 'o'),
 (2, 'p'),
 (2, 'r'),
 (2, 'u'),
 (3, 'a'),
 (3, 'c'),
 (3, 'l'),
 (3, 's'),
 (7, 'i')]
'''
vlady commented: difficult one! :-) +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The named tuple is a versatile container similar to a tuple but with named indexes replacing the numeric ones ...

# named tuples have named indexes that behave similar to class 
# instances but require no more memory than regular tuples
# tested with Python27 and Python32  by  vegaseat

import collections as co
import pprint

def create_nt_dict(data_list, Person):
    """
    load the named tuple with the data list and
    create a dictionary of the named tuple
    where the instance name is the key
    """
    nt_dict = {}
    for name, age, weight in data_list:
        # use lower first name + initial letter of last name
        # as key to avoid name collisions
        first, last = name.split()
        instance_name = first.lower() + last[0] 
        nt_dict[instance_name] = Person(name, age, weight)       
    return nt_dict   

# a test list of (name, age, weight) tuples
data_list = [
('Sarah Gellar', 26, 121),
('Alec Baldwin', 47, 214),
('Mandy Moore', 22, 135),
('Matthew Goode', 29, 167),
('Amanda Bynes', 19, 112),
('James Kirk', 24, 175)
]

# create the named tuple
# does behave like a Python class so use name 'Person'
Person = co.namedtuple('movie_star', 'name, age, weight')

# load the named tuple and get a dictionary of instances
nt_dict = create_nt_dict(data_list, Person)
# add nt_dict to dictionary local to __main__
locals().update(nt_dict)

# test_prints only ...
pprint.pprint(nt_dict)
print('<>'*35)
pprint.pprint(locals())
print('<>'*35)

# work with the named tuple ...
print("names of instances =\n%s" % sorted(nt_dict.keys()))

'''
names of instances =
['alecB', 'amandaB', 'jamesK', 'mandyM', 'matthewG', 'sarahG']
'''

# pick one instance ...
print(mandyM.name)   # …
Ene Uran commented: great help +13