ZZucker 342 Practically a Master Poster

Challenge:
change the code so that only .py and .txt files of a given directory are listed.

''' filename_list_given_dir1.py
use module glob to list all the filenames of .jpg files
or any extension(s) you specify in a given directory
'''

import glob
import os

# all files (split off file names) in a given directory
directory = "C:/Temp/*.jpg"
# this would give you all files
#directory = "C:/Temp/*.*"
for path in glob.glob(directory):
    #print(path)  # test
    # separate path from filename
    dirname, filename = os.path.split(path)
    print(filename)
ZZucker 342 Practically a Master Poster

If pygame and tkinter have event loops, then you have to use threading to separate them.

ZZucker 342 Practically a Master Poster
''' filename_list_given_dir1.py
use module glob to list all the filenames of .jpg files
or any extension(s) you specify in a given directory
'''

import glob
import os

# all files (split off file names) in a given directory
directory = "C:/Temp/*.jpg"
# this would give you all files
#directory = "C:/Temp/*.*"
for path in glob.glob(directory):
    #print(path)  # test
    # separate path from filename
    dirname, filename = os.path.split(path)
    print(filename)

Challenge, how would you show all .py and .txt files in a given directory?

EnergeticJet commented: Is this the right place to be posting this? +0
ZZucker 342 Practically a Master Poster

A defaultdictionary is another possibility:

''' defaultdict-random_integers.py
shows index of random integers in the form
random_integer: list_of_indexes
'''

import random as rn
import collections as co

size = 100
low = 0
high = 100
ddict = co.defaultdict(list)
for n in range(size):
    v = rn.randint(low, high)
    ddict[v].append(n)

print(ddict)
ZZucker 342 Practically a Master Poster

Python's double-ended queue called deque in module collections has a method rotate() that is ideal for that sort of thing.

ZZucker 342 Practically a Master Poster

This might give you some important hints about GUI programming:

''' tk_Entry_input101.py
explore multiple tkinter Entry() for inputs
note:
Python2 uses Tkinter
Python3 uses tkinter
'''

# Python3
import tkinter as tk

def name_action(event):
    person = enter1.get().capitalize()
    sf = "Hello {}. How are you today?".format(person)
    result['text']  = sf
    # now move cursor to enter2
    enter2.focus_set()

def mood_action(event):
    person = enter1.get().capitalize()
    mood = enter2.get().lower()
    if mood == 'happy':
        sf = "{}, nice see you are so chipper!".format(person)
    else:
        sf = "Hopefully we can help to cheer you up {}!".format(person)
    result['text']  = sf
    # move cursor in enter3
    #enter3.focus_set()

# the root window
root = tk.Tk()
# window geometry is width x height + x_offset + y_offset
root.geometry("400x150+80+30")

# make a label to display results
result = tk.Label(root)

# first entry with label
label1 = tk.Label(root, text='Please enter your name:')
enter1 = tk.Entry(root, bg='yellow')
# bind enter1 to return key press
enter1.bind('<Return>', func=name_action)
# start cursor in enter1
enter1.focus()

# second entry with label
label2 = tk.Label(root, text='Please enter happy, sad or neither:')
enter2 = tk.Entry(root, bg='yellow')
# bind enter2 to return key press
enter2.bind('<Return>', func=mood_action)


# position the widgets in the window with grid()
label1.grid(row=1, column=0)
enter1.grid(row=1, column=1)
label2.grid(row=2, column=0)
enter2.grid(row=2, column=1)

# position result label at bottom, span over 2 columns
result.grid(row=5, column=0, columnspan=2)

# the GUI event loop
root.mainloop()
ZZucker 342 Practically a Master Poster

This simple example might give you enough hints to get going:

import random as rn
import collections as co

size = 100
low = 0
high = 100
mylist = []
for n in range(size):
    mylist.append(rn.randint(low, high))

# use collection module's Counter() to find the top most common duplicates
top = 10
most = co.Counter(mylist).most_common(top)
print("of {} random integers between {} and {}".format(size, low, high))
for rnum, count in most:
    print("{} appears {} times".format(rnum, count))

print('-'*30)

# find index in mylist of the highest count number
highest_count = most[0][0]
for ix, n in enumerate(mylist):
    if n == highest_count:
        print("{} at index {}".format(n, ix))

''' possible result ...
of 100 random integers between 0 and 100
10 appears 5 times
6 appears 4 times
99 appears 4 times
2 appears 3 times
25 appears 3 times
39 appears 3 times
71 appears 3 times
85 appears 3 times
98 appears 3 times
7 appears 2 times
------------------------------
10 at index 22
10 at index 24
10 at index 38
10 at index 61
10 at index 88
'''
ZZucker 342 Practically a Master Poster

You might have to use the setText() method like this:

                # blank out old text first
                correctMessage.setText("            ")
                correctMessage.draw(self.win) 
                correctMessage.setText("Correct!")
                correctMessage.draw(self.win) 
ZZucker 342 Practically a Master Poster

An ordered dictionary remembers its insertion order.

ZZucker 342 Practically a Master Poster

Here is a typical example:

''' tk_BGImage1.py
use a Tkinter label as a panel/frame with a background image
(note that Tkinter without PIL reads only GIF and PGM/PPM images)
modified from a vegaseat example
'''

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

root = tk.Tk()
root.title('background image')

# pick a .gif image file you have in the working directory
# or give full path
image1 = tk.PhotoImage(file="roses.gif")
w = image1.width()
h = image1.height()

root.geometry("%dx%d+0+0" % (w, h))

# tk.Frame has no image argument
# so use a label as a panel/frame
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')

button2 = tk.Button(panel1, text='button2')
button2.pack(side='top')

# save the panel's image from 'garbage collection'
panel1.image = image1

# start the event loop
root.mainloop()
ZZucker 342 Practically a Master Poster

This might help:

# use opacity alpha values from 0.0 to 1.0
# opacity/tranparency applies to image and root frame
root.wm_attributes('-alpha', 0.7)
ZZucker 342 Practically a Master Poster

destroy() is used to destroy a particular window in a multiwindow program
you have to give all the Tk windows a unique name

ZZucker 342 Practically a Master Poster

Here is a hint ...

''' filename_list_given_dir1.py
use module glob to list all the filenames of .jpg files
or any extension(s) you specify in a given directory
'''

import glob
import os

# all files (split off file names) in a given directory
directory = "C:/Temp/*.jpg"
# this would give you all files
#directory = "C:/Temp/*.*"
for path in glob.glob(directory):
    #print(path)  # test
    # separate path from filename
    dirname, filename = os.path.split(path)
    print(filename)
ZZucker 342 Practically a Master Poster

Not sure what's going on, but DaniWeb is loaded with popups today!

ZZucker 342 Practically a Master Poster

Ginger? Lucky girl.

ZZucker 342 Practically a Master Poster

Here you go:

''' wx_colourdb_show1.py
show the colours in wxPython's wx.lib.colourdb
the database has 630 named colors
use wx.lib.scrolledpanel.ScrolledPanel and wx.GridSizer
to show the colours and their names
Python 2.7.5
'''

import wx
import wx.lib.scrolledpanel
# note the goofy english spelling
import wx.lib.colourdb

class MyScrolledPanel(wx.lib.scrolledpanel.ScrolledPanel):
    def __init__(self, parent):
        # make the scrolled panel larger than its parent
        wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent, wx.ID_ANY,
            size=(600, 450), style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
        # scroll bars won't appear until required
        # default is SetupScrolling(scroll_x=True, scroll_y=True)
        self.SetupScrolling()
        self.SetBackgroundColour("white")

        wx.lib.colourdb.updateColourDB()
        # create a list of all the colours in the colour data base
        #colours = wx.lib.colourdb.getColourList()
        colours = wx.lib.colourdb.getColourInfoList()

        # main sizer
        vsizer = wx.BoxSizer(wx.VERTICAL)

        # wx.GridSizer(rows, cols, vgap, hgap)
        gsizer = wx.GridSizer(len(colours), 3, 2, 2)

        n = 1
        for line in colours:
            #print line,  # eg. line = ('SNOW', 255, 250, 250)
            hexstr = "#%02X%02X%02X" % tuple(line[1:])
            s = "%3d  %s" % (n, line[0])
            t = wx.StaticText(self, wx.ID_ANY, s)
            gsizer.Add(t, 0, wx.ALL, border=2)
            t = wx.StaticText(self, wx.ID_ANY, hexstr)
            gsizer.Add(t, 0, wx.ALL, border=2)
            p = wx.Panel(self, wx.ID_ANY)
            p.SetBackgroundColour(hexstr)
            gsizer.Add(p, 0, wx.ALL|wx.EXPAND, border=2)
            n += 1

        # now add the whole thing to the main sizer and set it
        vsizer.Add(gsizer, 0, wx.ALL|wx.EXPAND, 10)
        self.SetSizer(vsizer)


app = wx.App(0)
# create a frame, no parent, default ID, title, size
caption = "all the colours in wx.lib.colourdb"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(600, 450))
MyScrolledPanel(frame)
frame.Show(True)
app.MainLoop()
ZZucker 342 Practically a Master Poster

Should be:

if (temperature > 35)
{
    // do something
}
else if (temperature >= 27)
{
    // do something else
}
else
{
    // do something else
}
ZZucker 342 Practically a Master Poster

Replace
system("Pause");
with
getchar(); // wait

ZZucker 342 Practically a Master Poster

I wonder if computers need to put up with humans 1000 years from now?

ZZucker 342 Practically a Master Poster

‘Auld Lang Syne’

ZZucker 342 Practically a Master Poster

‘Auld Lang Syne’, is a Scottish song. It was written by Robert Burns in the 1700's, literally meaning "old long ago," or simply, "the good old days", to remember old and new friends as the new year starts.

ZZucker 342 Practically a Master Poster

New Year is the oldest of all holidays, as it was first observed in ancient Babylon as many as 4000 years ago.

ZZucker 342 Practically a Master Poster

The news just reported that the Porsche these dummkopfs were driving went over 100 miles/hour in a residential area.

ZZucker 342 Practically a Master Poster

Sunny and warm in the Southwest (CalNevAri).
Very cold and snowy in the Northeast.

I heard there will be a windchill of -70 degF in Minnesota! That means your spit will freeze before it hits the ground.

ZZucker 342 Practically a Master Poster

There ar three basic ways to load and display an image with Tkinter:

1) from an image file you have, GIF is native any other file format needs PIL
see tk example in:
http://www.daniweb.com/software-development/python/threads/191210/python-gui-programming#post866067

2) from a base64 encoded image string
pick an example from:
http://www.daniweb.com/software-development/python/code/440446/python2python3-base64-encoded-image

3) from a web page on the internet
example:
http://www.daniweb.com/software-development/python/code/467528/show-internet-image-with-tkinter

You seem to mix those thing up. Stick with one way or the other.

ZZucker 342 Practically a Master Poster

Is there a way to make the print any smaller so I really can't read it?

ZZucker 342 Practically a Master Poster

Study this in detail:
http://www.pygame.org/docs/tut/camera/CameraIntro.html
I think it supports only certain cameras.

ZZucker 342 Practically a Master Poster

The first line in your function is
count=0
so that is what will happen each time you call the function.
If you use it as an argument, then it is only used when the function is defined, as a default value.

A temporary test print is your friend!

ZZucker 342 Practically a Master Poster

Looks like method getenv(self, tag_str) is missing in the code.

ZZucker 342 Practically a Master Poster

This should work:

def is_string_in_list(mystring, mylist):
    for c in mystring:
        if c not in mylist:
            return False
    return True


# short test
mylist = ['a', 'b', 'c']
mystring = 'acb'
print(is_string_in_list(mystring, mylist))  # True

mystring = 'afc'
print(is_string_in_list(mystring, mylist))  # False
ZZucker 342 Practically a Master Poster

The tiny calculator is a great start of a fancier calculator. Thank you!

ZZucker 342 Practically a Master Poster

The Los Angeles schooldistrict is in the progress to give all its 680,000 students an IPad. They hope to get out of the dismal rating they have now.

ZZucker 342 Practically a Master Poster

I take my iPad with me on the train, but don't commute during typical rush hour.

ZZucker 342 Practically a Master Poster

A pretzel roll with pesto and humus, big mug of hot chocolate.

ZZucker 342 Practically a Master Poster

All those people trying to cover up their wrinkles. I would start sellling cosmetics!

ZZucker 342 Practically a Master Poster

You have to consider that a good chunk of the $634 million contract price goes back to the polititians that made it possible that you got the contract. Not sure what the going cut in Washington is these days.

ZZucker 342 Practically a Master Poster

Looks like your teacher wants a more complex input in function main() like this:

# endless loop with exit condition
while True:
    print("Enter tution rate, current year, target year")
    print("in the form nnnnn.nn xxxx yyyy")
    data = raw_input("? ")
    current, thisYear, targetYear = data.split()
    current = float(current)
    thisYear = int(thisYear)
    targetYear = int(targetYear)
    # exit condition
    if current==0 or thisYear==0 or targetYear==0:
        break
    # now call your function and get result
    #newTuition = tuition(current, thisYear, targetYear)
ZZucker 342 Practically a Master Poster

This basic class example should send you on your Python way:

class Rectangle:
    # class constructor
    # supply it with initial length and width values
    # self refers to the instance
    def __init__(self, length, width):
        self.width = width
        self.length = length

    def setLength(self, length):
        self.length = length

    def show(self):
        print("rectangle has length = {}".format(self.length))
        print("rectangle has width = {}".format(self.width))


length = 10
width = 5
# create a class instance
rect = Rectangle(length, width)

# show initial setting
rect.show()

''' result >>
rectangle has length = 10
rectangle has width = 5
'''

print('-'*40)  # a line of  dashes
# now set length to another value
rect.setLength(17)

# show new setting
rect.show()

''' result >>
rectangle has length = 17
rectangle has width = 5
'''
ZZucker 342 Practically a Master Poster
ZZucker 342 Practically a Master Poster

Since you are already using Python3, This would simplify it somewhat:

def get_int(prompt="Enter an integer: "):
    """this function will loop until an integer is entered"""
    while True:
        try:
            # return breaks out of the endless while loop
            return int(input(prompt))
        except ValueError:
            print("Try again, value entered was not an integer.")

width = get_int("Please enter the width of your garden in meters ")
length = get_int("Please enter the length of your garden in meters ")

# test
print(width, length)
ZZucker 342 Practically a Master Poster

I read somewhere that Google gets 15 thousand job applications a week. So good luck!

ZZucker 342 Practically a Master Poster

A Fatburger with curly fries and a lemonade.

ZZucker 342 Practically a Master Poster

Syria was a French colony for 20 years and the occupation was brutal. Strange that these are the only folks who want to join us in bombing the place.

ZZucker 342 Practically a Master Poster

More modern:

''' tk_button_toggle6.py
using itertools.cycle() to create a Tkinter toggle button
'''

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


def toggle(icycle=itertools.cycle([False, True])):
    state = next(icycle)
    t_btn['text'] = str(state)

root = tk.Tk()

t_btn = tk.Button(text="True", width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()
ZZucker 342 Practically a Master Poster

Working with dictionaries:

''' dict_month1.py
sorting output by value of a dictionary items tuple
'''

months = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
     'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}

# month shows up in dictionary hash order
for key, val in months.items():
    print("{} {}".format(key, val))

print('-'*12)

# sort by value not key, value is at index 1 of tuple
for key, val in sorted(months.items(),key=lambda tup: tup[1]):
    print("{} {}".format(key, val))

''' result -->
Feb 2
Aug 8
Jan 1
Dec 12
Oct 10
Mar 3
Sep 9
May 5
Jun 6
Jul 7
Apr 4
Nov 11
------------
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
'''
ZZucker 342 Practically a Master Poster

There are a lot more Java jobs since it takes more person hours to develop programs with Java.

As I understand it, most apps are written with Java. However, there is a lot of garbage out there.

ZZucker 342 Practically a Master Poster

"My karma ran over your dogma."
-- Tasso Apfelstein

ZZucker 342 Practically a Master Poster

Watched "Dan in Real Life" and "Crazy, Stupid, Love" on DVD at a friend's house. Kind of romantic and funny. Will not drink cocktails with a straw after that.

ZZucker 342 Practically a Master Poster

You might want to use a drone to crash other drones that pester you.

ZZucker 342 Practically a Master Poster

Blueberries and cream