Dev Shed Forums - Python Programming http://forums.devshed.com/ Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language. en Sun, 17 Dec 2017 00:44:13 GMT vBulletin 60 http://forums.devshed.com/images/misc/rss.png Dev Shed Forums - Python Programming http://forums.devshed.com/ <![CDATA[[Python 3 + Tkinter] Option Menu, Error Found!]]> http://forums.devshed.com/python-programming/979655-python-3-tkinter-option-menu-error-found-new-post.html Sat, 16 Dec 2017 17:47:41 GMT Hey Python Programmers... I try to create an option menu they create diffrence buttons... but i get an problem with it... *This is an test to train my self in programming... this is my script:* Code: --------- from tkinter import * Hey Python Programmers...

I try to create an option menu they create diffrence buttons... but i get an problem with it...

This is an test to train my self in programming... this is my script:
Code:

from tkinter import *

main = Tk()

def selectOption(optionselect):

    global select

    select = optionselect

    select = 'Image'

    if select == 'Image':
        selectOption_Image()
        buttonTexture.config(text = 'Texture' % (buttonTexture, buttonTextureExt))
        buttonPreview.config(text = 'Preview' % (buttonPreview, buttonPreviewExt))
        buttonExport.config(text = 'Export' % (buttonExport, buttonExportExt))

    if select == 'Texture':
        selectOption_Texture()
        buttonImage.config(text = 'Image' % (buttonImage, buttonImageExt))
        buttonPreview.config(text = 'Preview' % (buttonPreview, buttonPreviewExt))
        buttonExport.config(text = 'Export' % (buttonExport, buttonExportExt))

    if select == 'Preview':
        selectOption_Preview()
        buttonImage.config(text = 'Image' % (buttonImage, buttonImageExt))
        buttonTexture.config(text = 'Texture' % (buttonTexture, buttonTextureExt))
        buttonExport.config(text = 'Export' % (buttonExport, buttonExportExt))


    if select == 'Export':
        selectOption_Export()
        buttonImage.config(text = 'Image' % (buttonImage, buttonImageExt))
        buttonTexture.config(text = 'Texture' % (buttonTexture, buttonTextureExt))
        buttonExport.config(text = 'Export' % (buttonExport, buttonExportExt))


    def selectOption_Image():

        def selectOption_Image_Button():

            def printImage():

                print('')
                print('Image Found!')

            buttonImageExt = Button(main, command = printImage)
            buttonImageExt.pack()
            return buttonImageExt

        buttonImage = Button(main, command = selectOption_Image_Button)
        buttonImage.pack()
        return buttonImage

    def selectOption_Texture():

        def selectOption_Texture_Button():
           
            def printTexture():

                print('')
                print('Texture Found!')

            buttonTextureExt = Button(main, command = printTexture)
            buttonTextureExt.pack()
            return buttonTextureExt

        buttonTexture = Button(main, command = selectOption_Texture_Button)
        buttonTexture.pack()
        return buttonTexture


    def selectOption_Preview():

        def selectOption_Preview_Button():

            def printPreview():

                print('')
                print('Preview Render!')

            buttonPreviewExt = Button(main, command = printPreview)
            buttonPreviewExt.pack()
            return buttonPreviewExt

        buttonPreview = Button(main, command = selectOption_Preview_Button)
        buttonPreview.pack()
        return buttonPreview

    def selectOption_Export():

        def selectOption_Export_Button():

            def printExport():

                print('')
                print('Source Exported !')

            buttonExportExt = Button(main, command = printExport)
            buttonExportExt.pack()
            return buttonExportExt

        buttonExport = Button(main, command = selectOption_Export_Button)
        buttonExport.pack()
        return buttonExport

optionlist = ('Image', 'Texture', 'Preview', 'Export')

variable = StringVar()
variable.set(optionlist[0])

optionmenu = OptionMenu(main, variable, *optionlist, command = selectOption)
optionmenu.pack()


main.mainloop()

This is an simple test to train my self in programming and write software... but if i run this script,
i get an error... for more information...

This my error (# Image Button):
Quote:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 3436, in __call__
self.__callback(self.__value, *args)
File "C:/Users/Gebruiker/Desktop/Options.py", line 14, in selectOption
selectOption_Image()
UnboundLocalError: local variable 'selectOption_Image' referenced before assignment
This is my error (#Texture Button):
Quote:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 3436, in __call__
self.__callback(self.__value, *args)
File "C:/Users/Gebruiker/Desktop/Options.py", line 14, in selectOption
selectOption_Image()
UnboundLocalError: local variable 'selectOption_Image' referenced before assignment
This my error (# Preview Button):
Quote:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 3436, in __call__
self.__callback(self.__value, *args)
File "C:/Users/Gebruiker/Desktop/Options.py", line 14, in selectOption
selectOption_Image()
UnboundLocalError: local variable 'selectOption_Image' referenced before assignment
And the error in the Export Button:
Quote:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 3436, in __call__
self.__callback(self.__value, *args)
File "C:/Users/Gebruiker/Desktop/Options.py", line 14, in selectOption
selectOption_Image()
UnboundLocalError: local variable 'selectOption_Image' referenced before assignment
Pleace... said not thad this program is boring... this only an simple test to figure out, how i can
create diffrenct menu buttons... but i need some help with tkinter...

Can you correct my code, just i can expiriment with it ?... thanks for help,
Jamie... ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-tkinter-option-menu-error-found-979655.html
<![CDATA[[Python 3 + PIL, Tkinter] Problems with filters and save export, help needed!]]> http://forums.devshed.com/python-programming/979642-python-3-pil-tkinter-filters-save-export-help-new-post.html Thu, 14 Dec 2017 21:06:05 GMT Hey Python Programmers... I try to create an image editor, to test my python knowledge.... but i get two problems: 1) The Filters in images are not showing... 2) The image (img.) you save is empty... (see def export() function)... *This is my script:* Code: Hey Python Programmers...

I try to create an image editor, to test my python knowledge.... but i get two problems:
1) The Filters in images are not showing...
2) The image (img.) you save is empty... (see def export() function)...


This is my script:
Code:

from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename, asksaveasfile
from PIL import Image, ImageTk
from PIL import ImageFilter

main = Tk()

filename_error = 'No File Imported...'


def Open():
    folder = askopenfilename(parent = main, initialdir = 'C:/', filetypes = [('PNG Files', '*.png')], title = "Open File")

    try:
        with open(folder) as filename:

            listbox.insert(END, str(filename.name))
            print(filename.name)

            img = Image.open(folder)
            showimage = ImageTk.PhotoImage(img)
            photo = Label(main, image = showimage)
            photo.image = showimage
            photo.pack(padx = 10, pady = 12, side = RIGHT)
           

            def tool_Blur():

                try:
                    blur_filter = img.filter(ImageFilter.BLUR)
                    show = ImageTk.PhotoImage(img)
                    blur = Label(main, image = show)
                    blur.image = show
                    blur.pack(padx = 10, pady = 12, side = RIGHT)
                    print('Tools/Blur: ', img.filter)

                except:
                    print('Tools/Blur: ', filename_error)

            def tool_Emboss():
   
                try:
                    emb_filter = img.filter(ImageFilter.EMBOSS)
                    show = ImageTk.PhotoImage(img)
                    emb = Label(main, image = show)
                    emb.image = show
                    emb.pack(padx = 10, pady = 12, side = RIGHT)
                    print('Tools/Emboss: ', img.filter)

                except:
                    print('Tools/Emboss: ', filename_error)

            def tool_Contour():

                try:
                    cont_filter = img.filter(ImageFilter.CONTOUR)
                    show = ImageTk.PhotoImage(img)
                    cont = Label(main, image = show)
                    cont.image = show
                    cont.pack(padx = 10, pady = 12, side = RIGHT)
                    print('Tools/Contour: ', img.filter)
       
                except:
                    print('Tools/Contour: ', filename_error)

            def Export():
                output = asksaveasfile(mode = 'w', parent = main, initialdir = 'C:/', filetypes = [('PNG Files', '*.png')], title = 'Export File')

                try:
                    print(saveimage)

                    saveimage = img.save(output, filetypes).convert('RGB')
                    saveimage.write(output)

                    with open(output, mode) as savedfile:
                        print('Saved: ', savedfile.name)

                    saveimage.close()

                       

                except:
                    print('Images not Saved...')




            exp = Menu(menu, tearoff=0)
            exp.add_command(label = 'Export', command = Export)
            menu.add_cascade(label = 'Image', menu = exp)

            tool = Menu(menu, tearoff=0)
            tool.add_command(label = 'Blur', command = tool_Blur)
            tool.add_command(label = 'Emboss', command = tool_Emboss)
            tool.add_command(label = 'Contour', command = tool_Contour)
            menu.add_cascade(label = 'Tools', menu = tool)

    except:
        print('File not Exit...')
   

def Exit():
    print("Exit...")
    exit()


Title = main.title('AVI File Loader')
label = ttk.Label(main, text = 'Load Movies')
label.pack()

menu = Menu(main)
main.geometry("150x250+300+300")

file_label = Label(main, text = 'Files')
file_label.pack()

file = Menu(menu, tearoff=0)
file.add_command(label = 'Open', command = Open)
file.add_command(label = 'Exit', command = Exit)
menu.add_cascade(label = 'File', menu = file)

main.config(menu=menu)


scrollbar = Scrollbar(main, orient = VERTICAL)
scrollbar.pack(side = LEFT)

listbox = Listbox(main, yscrollcommand = scrollbar.set)
listbox.pack(padx = 4, pady = 16, side = LEFT)
scrollbar.config(command = listbox.yview)



main.mainloop()

Can anyone correct my code, pleace... so i can expiriment with it ?...
Can you fix the two problems... just first test my program and see what the problems
are ?... to give me the just code ?... The image thad you save with my export menu tool
is just empty... it must be the edited image img. ... Can you fix the two problems ?...

Thanks for help, Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-pil-tkinter-filters-save-export-help-979642.html
<![CDATA[[Python 3 + Tkinter] Diffrence Style Colors, Error Found!]]> http://forums.devshed.com/python-programming/979641-python-3-tkinter-diffrence-style-colors-error-found-new-post.html Thu, 14 Dec 2017 16:23:17 GMT Hey Python Programmers... I try to create an menu thad can change the color of my title... *This is my code (Tkinter, Python 3):* Code: --------- from tkinter import * from tkinter import ttk Hey Python Programmers...

I try to create an menu thad can change the color of my title...

This is my code (Tkinter, Python 3):
Code:

from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename

main = Tk()
main.styles['red', 'green', 'yellow', 'blue', 'black']

def Open():
    name = askopenfilename(initialdir = 'C:/', filetypes = [('AVI Files', '*.avi')], title = "Open File")

    print(name)

    try:
        with open(name) as filename:

            listbox.insert(END, str(filename.name))
            print(filename.name)

    except:
        print("Session Failed !")


def Exit():
    print("Exit...")
    exit()


Title = main.title('AVI File Loader')
label = ttk.Label(main, text = 'Load Movies', background = defeult_style)
label.defeult_style = styles[0]
label.pack()

menu = Menu(main)
main.config(menu=menu)
main.geometry("150x250+300+300")

file_label = Label(main, text = 'Files')
file_label.pack()

file = Menu(menu)
file.add_command(label = 'Open', command = Open)
file.add_command(label = 'Exit', command = Exit)
menu.add_cascade(label = 'File', menu = file)

style = Menu(menu)
style.add_command(label = 'Red', command = label.styles[0])
style.add_command(label = 'Green', command = label.styles[1])
style.add_command(label = 'Yellow', command = label.styles[2])
style.add_command(label = 'Blue', command = label.styles[3])
style.add_command(label = 'Black', command = label.styles[4])
menu.add_cascade(label = 'Styles', menu = style)

listbox = Listbox(main)
listbox.pack(fill = BOTH, expand = 1)


main.mainloop()

I want expiriment with user preference like tools... thad can chance things like the style
of buttons, menu's, widget, etc... this is my first code thad must make my program
changeble... bit if i run my script, i get this error:

Quote:

Traceback (most recent call last):
File "C:/Users/Gebruiker/Desktop/AVILoader.py", line 6, in <module>
main.styles['red', 'green', 'yellow', 'blue', 'black']
File "C:\Users\Gebruiker\Desktop\Software\Python\Ware\lib\tkinter\__init__.py", line 2095, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'styles'
This is what i means...

Can anyone correct my code please, so i can expiriment with it...
Thanks for help, Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-tkinter-diffrence-style-colors-error-found-979641.html
<![CDATA[[Python 3 + Tkinter] File Loader can't find .avi files, help needed!]]> http://forums.devshed.com/python-programming/979637-python-3-tkinter-file-loader-cant-avi-files-help-new-post.html Thu, 14 Dec 2017 07:37:04 GMT Hey python programmers...

I am learn tkinter and i try to make an .avi file loader with an listbox of imported avi files...
But my script (or program) can't find the .avi files you will be import...

This is my code:
Code:

from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename

main = Tk()

def Open():
    name = askopenfilename(initialdir = 'C:/', filetypes = [('AVI Files', '*.avi')], title = "Open File")

    print(name)

    try:
        with open(name) as filename:

            listbox.insert(END, str(filename.name()))
            print(filename.name())

    except:
        print("Session Failed !")


def Exit():
    print("Exit...")
    exit()


Title = main.title('AVI File Loader')
label = ttk.Label(main, text = 'Load Movies')
label.pack()

menu = Menu(main)
main.config(menu=menu)
main.geometry("150x250+300+300")

file_label = Label(main, text = 'Files')
file_label.pack()

file = Menu(menu)
file.add_command(label = 'Import', command = Open)
file.add_command(label = 'Exit', command = Exit)
menu.add_cascade(label = 'File', menu = file)

listbox = Listbox(main)
listbox.pack(fill = BOTH, expand = 1)


main.mainloop()

What is the reasion thad my script can't find my .avi files... this is an test... i try to figure out,
how i can create GUI's in tkinter... now i try to make an .avi file loader, just you can see the
name of the avi files... into the listbox...

Can you give my two just codes (or reather code corrections), please ?...
- 1) To correct my code for load .avi files
- 2) To correct my code for load multiply .avi files in an directory

Thanks for help... Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-tkinter-file-loader-cant-avi-files-help-979637.html
Need some help http://forums.devshed.com/python-programming/979634-help-new-post.html Wed, 13 Dec 2017 20:09:37 GMT Code: --------- def problem3(): count = 0 for i in range(2, 10000): for n in range(2, i): if (i % n == 0): break else:
Code:

def problem3():
    count = 0
    for i in range(2, 10000):
        for n in range(2, i):
            if (i % n == 0):
                break
        else:
                count += 1
    return count

I need some help figuring out why this is not returning a number, pretty sure it has to do with range(2, i).

Anything anyone knows would be great ]]>
Python Programming CJT157 http://forums.devshed.com/python-programming-11/help-979634.html
<![CDATA[[Python 3 + Tkinter] HotKeys Events, Error Found!]]> http://forums.devshed.com/python-programming/979633-python-3-tkinter-hotkeys-events-error-found-new-post.html Wed, 13 Dec 2017 20:02:46 GMT Hey Python Programmers... I try to figure out, how i can create an GUI with python 3 and tkinter.... This is my script: Code: --------- # GUITest from tkinter import * Hey Python Programmers...

I try to figure out, how i can create an GUI with python 3 and tkinter....
This is my script:

Code:

# GUITest
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
import winsound


root = Tk()





def __import(event):
    __input = event.askopenfilename(initialdir="C:/", filetypes=[("PNG Supported","*.png")], title = "Brouse: ")

    print(__input)

    try:
        with open(__input) as fileinput:
            print(fileinput)

            for file in fileinput:
                listbox.insert(END, str(file))
           
    except:
        print('File not exit')


def __playSounds(event):

    play = Tk()

    def __playSound_Exit():
        winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

    def __playSound_Excl():
        winsound.PlaySound("SystemExclamation", winsound.SND_ALIAS)

    def __playSound_Aste():
        winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS)


    playTitle = play.title("WinPlayer")
    playlabel_main = ttk.Label(event.play, text = "Player: ", foreground="white",background="black",font=("Arial", 18))
    playlabel_main.pack()

    play.geometry("100x200+250+250")

    buttonPlayExit = ttk.Button(event.play, text = "SystemExit", command=__playSound_Exit(event))
    buttonPlayExcl = ttk.Button(event.play, text = "SystemExclamation", command=__playSound_Excl(event))
    buttonPlayAste = ttk.Button(event.play, text = "SystemAsterisk", command=__playSound_Aste(event))

    buttonPlayExit.pack()
    buttonPlayExcl.pack()
    buttonPlayAste.pack()

    play.mainloop()
   
def __exit(event):
    exit()


Title = root.title("PNG2Text Converter")
label_main = ttk.Label(root, text = "PNG2Text Converter: ", foreground="white",background="black",font=("Arial",18))
label_main.pack()

menu = Menu(root)
root.config(menu=menu)
root.geometry("250x150+300+300")

label_files = ttk.Label(root, text = "Total: ", foreground="black",background="white",font=("Arial",12))
label_files.pack(fill=X, padx=10, pady=10, side=LEFT)

file = Menu(menu)
file.add_command(label = 'Import', command=__import(event), accelerator = 'ctrl+i')
file.add_command(label = 'Play', command=__playSounds(event), accelerator = 'ctrl+p')
file.add_command(label = 'Exit', command=__exit(event), accelerator = 'ctrl+e')
menu.add_cascade(label = 'File', menu = file)

root.bind_all('<Control-Key-i>', __import)
root.bind_all('<Control-Key-p>', __playSounds)
root.bind_all('<Control-Key-e>', __exit)


listbox = Listbox(root)
listbox.pack(fill=BOTH, expand=1)
   

event.root.mainloop()

I try to make hotkeys for menu tools, but if i run this script... i get this error:

Quote:

Traceback (most recent call last):
File "C:/Users/Gebruiker/Desktop/Studie/Python/Languale/GUI/GUI Project/PNG2Text.py", line 76, in <module>
file.add_command(label = 'Import', command=__import(event), accelerator = 'ctrl+i')
NameError: name 'event' is not defined
Can anyone correct my code, so i can expiriment with it... this is an test to figure out how
i can work with tkinter...

Can anyone give my the just code ?... thanks for help,
Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-tkinter-hotkeys-events-error-found-979633.html
python curses module fix http://forums.devshed.com/python-programming/979622-python-curses-module-fix-new-post.html Wed, 13 Dec 2017 02:38:59 GMT Only version 1.4 of curses compiles correctly - coding from versions after 1.4 (note there is a version 1.5; but, it's the exact same 'working' code as version 1.4 - supposedly coded or modified by tim one (36560 2004-07-18 06:16:08Z tim_one) from Python 2.4 - present or as-of Python 3.6.3 is flawed, you can copy and past the bottom half (where the def of wrapper is started or the commented area describing wrapper) of the Python 3.6.3 code (curses version 2.2) into curses version 1.4 and it will compile correctly. If you are using ASCII in your program and are on a Windows machine, you can use the Command Prompt to execute the .py file and not from IDLE (Integrated Development and Learning Environment). - example G:\Python36-32>python tclock.py - just make sure the file (the file you are trying to run - tclock.py) is in the directory of the python.exe or the directory of python is in your path.

How to set the path and environment variables in Windows
https://www.computerhope.com/issues/ch000549.htm

IDLE is Python’s Integrated Development and Learning Environment.
https://docs.python.org/3/library/idle.html


Code:

from _curses import *
import os as _os
import sys as _sys

#######can not find a use for this########################
    # we call setupterm() here because it raises an error
    # instead of calling exit() in error cases.
#    setupterm(term=_os.environ.get("TERM", "unknown"),
#            fd=_sys.__stdout__.fileno())
#######can not find a use for this########################


# copy and pasted below from version curses version 1.4 from Python 2.3 to 3.6.3 by by Koten - 2017/12/12

# Some constants, most notably the ACS_* ones, are only added to the C
# _curses module's dictionary after initscr() is called.  (Some
# versions of SGI's curses don't define values for those constants
# until initscr() has been called.)  This wrapper function calls the
# underlying C initscr(), and then copies the constants from the
# _curses module to the curses package's dictionary.  Don't do 'from
# curses import *' if you'll be needing the ACS_* constants.

def initscr():
    import _curses, curses
    stdscr = _curses.initscr()
    for key, value in _curses.__dict__.items():
        if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
            setattr(curses, key, value)
   
    return stdscr

# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
 
def start_color():
    import _curses, curses
    retval = _curses.start_color()
    if hasattr(_curses, 'COLORS'):
        curses.COLORS = _curses.COLORS
    if hasattr(_curses, 'COLOR_PAIRS'):
        curses.COLOR_PAIRS = _curses.COLOR_PAIRS
    return retval

# Import Python has_key() implementation if _curses doesn't contain has_key()

try:
    has_key
except NameError:
    from has_key import has_key
# ^^copy and pasted above from curses version 1.4 from Python 2.3 to 3.6.3 by Koten - 2017/12/12 ^^ - End-Of-Line - EOL

   
   
# Wrapper for the entire curses-based application.  Runs a function which
# should be the rest of your curses-based application.  If the application
# raises an exception, wrapper() will restore the terminal to a sane state so
# you can read the resulting traceback.

def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        noecho()
        cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
   
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            echo()
            nocbreak()
            endwin()

]]>
Python Programming koten http://forums.devshed.com/python-programming-11/python-curses-module-fix-979622.html
Python/Numpy have I already written the swiftest code for large array? http://forums.devshed.com/python-programming/979620-python-numpy-written-swiftest-code-array-new-post.html Tue, 12 Dec 2017 19:14:12 GMT ***GOAL:*** I would like to get my script total execution time down from 4 minutes to less than 30 secs. I have a large 1d array (3000000+) of distances with many duplicate distances. I am trying to write the swiftest function that returns all distances that appear n times in the array. I have written a function in numpy but there is a bottleneck at one line in the code. Swift performance is an... **GOAL:**
I would like to get my script total execution time down from 4 minutes to less than 30 secs. I have a large 1d array (3000000+) of distances with many duplicate distances. I am trying to write the swiftest function that returns all distances that appear n times in the array. I have written a function in numpy but there is a bottleneck at one line in the code. Swift performance is an issue because the calculations are done in a for loop for 2400 different large distance arrays. 

Quote:

import numpy as np
for t in range(0, 2400):
a=np.random.randint(1000000000, 5000000000, 3000000)
b=np.bincount(a,minlength=np.size(a))
c=np.where(b == 3)[0] #SLOW STATEMENT/BOTTLENECK
return c
**EXPECTED RESULTS:**
Given a 1d array of distances [2000000000,3005670000,2000000000,12345667,4000789000,12345687,12345667,2000000000,12345667]
I would expect back an array of [2000000000,12345667] when queried to return an array of all distances that appear 3 times in the main array.

What should I do? ]]>
Python Programming justforkicks1 http://forums.devshed.com/python-programming-11/python-numpy-written-swiftest-code-array-979620.html
Lifetime Checker Script, Error Found ! http://forums.devshed.com/python-programming/979613-lifetime-checker-script-error-found-new-post.html Tue, 12 Dec 2017 07:26:40 GMT Hey Python Users... I try to create an script, to check your lifetime... with the datetime modulle... This is my script: Code: --------- from datetime import datetime Hey Python Users...

I try to create an script, to check your lifetime... with the datetime modulle...
This is my script:

Code:

from datetime import datetime

now = datetime.now()

birtday = int(input("Your Birthday: "))
lifetime = now.year - birthday


print(lifetime)




If i run this script, i get this error:
Quote:

Traceback (most recent call last):
File "C:/Users/Gebruiker/Desktop/YearChacker.py", line 6, in <module>
lifetime = [now.year - birthday]
NameError: name 'birthday' is not defined
Can enyone correct my code pleace... so i can expiriment with it ?...
Thanks, Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/lifetime-checker-script-error-found-979613.html
<![CDATA[[Python 3 + FNMatch] PNG Searcher not working... help needed!]]> http://forums.devshed.com/python-programming/979611-python-3-fnmatch-png-searcher-help-new-post.html Mon, 11 Dec 2017 16:32:46 GMT Hey Python Programmers... I try to create an script as an test, thad must be find PNG Files by name... This is my script... Code: --------- # Import fnmatch and os import fnmatch Hey Python Programmers...

I try to create an script as an test, thad must be find PNG Files by name...
This is my script...

Code:

# Import fnmatch and os
import fnmatch
import os

# Search PNG-File by Name:
filesearch = input('Search File: ')
for file in os.walk(filesearch):
    if fnmatch.filter(file, '*.png'):
        print(file)

If i call in the name of any PNG Files, this script doesn't works...
No PNG file found wich starts with the first letter you call, they i get on my
computer (laptop)..... I use python 3....

I try to make an PNG-Searcher (or specific file-searcher), they must be find
PNG Files by name (or the png-files they get the same letters)...

If i run my script, no files found with the begin-letters or same names...
I get realy png-files where i get testing it... to look of my script works...

Can anyone give my the just code, so i can expiriment with it...
I am in the learn fase of python (or programming)...

Thanks for my code correction...
Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-fnmatch-png-searcher-help-979611.html
<![CDATA[[Python 3 + Tkinter] Buttons not Showing, help needed!]]> http://forums.devshed.com/python-programming/979604-python-3-tkinter-buttons-help-new-post.html Sun, 10 Dec 2017 19:43:42 GMT Hey Python Programmers... I try to create an GUI they get two or more pages... this is an training... I try to create working with menus and buttons in one script... *This is my script:* Code: --------- # Import Tkinter Hey Python Programmers...

I try to create an GUI they get two or more pages... this is an training...
I try to create working with menus and buttons in one script...

This is my script:
Code:

# Import Tkinter
from tkinter import *

# Write my first page
class Window(Frame):

    # Define an __init__
    def __init__(self, master=None):
       
        # Parameters:
        Frame.__init__(self, master) 

        # Make Master               
        self.master = master

        # Window
        self.init_window()

    # Create the init_window
    def init_window(self):

        # Changing the Title of my first page
        self.master.title("GUI")

        # The Widget
        self.pack(fill=BOTH, expand=1)

        # Create an Menu
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # Create an File Object, called File
        file = Menu(menu)
        file.add_command(label="Win Sound", command=self.client_winsound)
        file.add_command(label="Exit", command=self.client_exit)
        menu.add_cascade(label="File", menu=file)

        # Create an File Object, called Edit
        edit = Menu(menu)

        # The Command of Undo in the Edit Tab
        edit.add_command(label="Undo")

        # Edit Cascade
        menu.add_cascade(label="Edit", menu=edit)

    # Define the WinSound Window
    def client_winsound(self):

        # Make the WinSound Window
        class WinSound(Frame):

            # Define the WinSound Init
            def __init_winsound(self, master=None):

                # Called by Frame
                Frame.__init__winsound(self, master)

                # Create it as Master
                self.master = master

                # Called by init_soundplay
                self.init__soundplay()

            # Define the init_soundplay
            def init_soundplay(self):

                # Change the Title of My Seccond Page
                self.master.title("WinSound")

                # Set it as Pack
                self.pack(fill=BOTH, expand=1)

                # Make Button
                self.master.butExit = Button(self, text="WinExit", command=self.__playSystemExit)
                self.master.butExit.pack()

            # Define the playSystem button in Working
            def __playSystemExit(self):
                winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

        # Make App-Page2 (My seccond page)
        root1 = Tk()
        root1.geometry("400x300")
        app1 = WinSound(root1)
        root1.mainloop()
               
    # Define the Exit
    def client_exit(self):
        exit()

       
# Make App-Page Defeult... my first page
rootMain = Tk()
rootMain.geometry("640x480")
appMain = Window(rootMain)
rootMain.mainloop()


This is my script... i try to create an app with python and tkinter... This App must be get an
two or more pages... one with an menu, an the seccond page with buttons for play diffrence
WinSounds, this is only an training to get knowledge with python tkinter.... i try to learn this...

But my problem is, thad if you start my seccond page, the play sound button(s) are not showed...
Can anyone correct my code, just it works and the buttons are showed - even they are
working.... If you don't know what my problem is... copy, past and run my script... test my
App and you can see what the problem is... the problem sit in my "WinSound" button in the
File Menu Part in my first page...

This is an test only... not an real app... only i try to learn tkinter.... just i get help needed...

Python Version: Python v3.... Tkinter + WinSound Module...

Can anyone helpme ?...
Thanks, Jamie. ]]>
Python Programming JamieVanCadsand http://forums.devshed.com/python-programming-11/python-3-tkinter-buttons-help-979604.html
PNP server code http://forums.devshed.com/python-programming/979569-pnp-server-code-new-post.html Fri, 01 Dec 2017 16:35:17 GMT I am in need of a python script to run and send responses to a network broadcast on 224.0.1.75:5060. The purpose is to send a url in a sip message to tell a IP phone where the phone's server is located at.

I found the following code for Snom phones. I would prefer that the response would be to ALL subscribe requests using this address/port.

Code:

#! /usr/bin/python
#
# snom multicast telephone discovery
#
#
# Author: Filip Polsakiewicz <filip.polsakiewicz@snom.de>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import socket
import struct
import sys
import re

from optparse import OptionParser

class snom_phone(object):
    """Basic representation of a snom phone."""

    def __init__(self, mac=None, ip=None, mod=None, fw=None, subs=None):
        """Default constructor."""
        self.mac_addr = mac
        self.ip_addr = ip
        self.sip_port = 5060
        self.model = mod
        self.fw_version = fw
        self.subscribe = subs

    def __repr__(self):
        """Gets a string representation of the phone"""
        return "%s (MAC: %s) running Firmware %s found at IP %s" % (self.model, self.__macrepr(self.mac_addr), self.fw_version, self.ip_addr)

    def __macrepr(self, m):
        """ Normalize a MAC address to lower case unix style """ 
        m = re.sub("[.:-]", "", m)
        m = m.lower()
        n =  "%s:%s:%s:%s:%s:%s" % (m[0:2], m[2:4], m[4:6], m[6:8], m[8:10], m[10:])
        return n

def parse(text):
    """Parses the incoming SUBSCRIBE."""
    try:
        lines = text.split('\r\n')
   
        # Line 1 conatains the SUBSCRIBE and our MAC
        new_phone = atcomtec(subs=text)
        new_phone.mac_addr = lines[0][80:82]
       
        # We can read the IP address from line 2
        new_phone.ip_addr = lines[1][17:].split(';')[0].split(':')[0]
        new_phone.sip_port = lines[1][17:].split(';')[0].split(':')[1]
       
        # The other interesting information can be found in line 7
        model_info = lines[6]
        l_model_info = model_info.split(';')
        new_phone.model = l_model_info[3].split('=')[1][1:-1]
        new_phone.fw_version = l_model_info[4].split('=')[1][1:-1]
        print new_phone
           
        return new_phone
    except:
        # Parsing failed. Probably not a SUBSCRIBE
        return None


def get_sip_info(text):
    """Get some relevant SIP information which we need in order to generate the responses."""
   
    lines = text.split('\r\n')
    # Some SIP info we need
    call_id = lines[4][9:]
    cseq = lines[5][6]
    via_header = lines[1]
    from_header = lines[2]
    to_header = lines[3]
   
    if options.verbose: print "CallId: " + call_id + "; CSeq: " + cseq + "\r\n";   
    return (call_id, cseq, via_header, from_header, to_header)

def get_ip_address():
        # This is a simple hack to find our IP address
        # AFAIK this is the only platform-independent way to obtain the address

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('snom.com', 0))
            return s.getsockname()[0]

prov_uri = None
parser = OptionParser()
parser.add_option('-u', '--url', action="store", dest="prov_uri", help="URI of the provisioning server")
parser.add_option('-l', '--local-ip', action="store", dest="local_ip", help="Local IP address")
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=False,
                  help="make lots of noise")

(options, args) = parser.parse_args()



print "Nimbus PnP Provisioning Server\n"

print "Provisioning URI is %s\n" % options.prov_uri

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('224.0.1.75', 5060))
mreq = struct.pack('4sl', socket.inet_aton('224.0.1.75'), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
if not options.local_ip:
    ip_adr = get_ip_address()
else:
    ip_adr = options.local_ip
   
print "Local IP Address is :: %s" % ip_adr
print "=" * 80

while True:
    subs = sock.recv(10240)
   
    if options.verbose: print subs
   
    phone = parse(subs)
    (call_id, cseq, via_header, from_header, to_header) = get_sip_info(subs)
   
    if phone:
        # Create a socket to send data
        sendsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sendsock.bind(('%s' % ip_adr, 1036))

            # If a phone has been recognized first send 200 OK
        ok_response = "SIP/2.0 200 OK\r\n"
        ok_response += via_header + "\r\n"
        ok_response += "Contact: <sip:" + phone.ip_addr + ":" + phone.sip_port + ";transport=tcp;handler=dum>\r\n"
        ok_response += to_header + "\r\n"
        ok_response += from_header + "\r\n"
        ok_response += "Call-ID: %s\r\n" % call_id
        ok_response += "CSeq: %s SUBSCRIBE\r\nExpires: 0\r\nContent-Length: 0\r\n" % cseq
       
        sendsock.sendto(ok_response, ("%s" % phone.ip_addr, int(phone.sip_port)))

        # Now send a NOTIFY with the configuration URL
       
        if not options.prov_uri:
            prov_uri = "192.168.0.20"
        else:
            prov_uri = options.prov_uri
            prov_uri = "%s/%s.htm" % (prov_uri,phone.model)

        notify = "NOTIFY sip:%s:%s SIP/2.0\r\n" % (phone.ip_addr, phone.sip_port)
        notify += via_header + "\r\n"
        notify += "Max-Forwards: 20\r\n"
        notify += "Contact: <sip:%s:1036;transport=TCP;handler=dum>\r\n" % ip_adr
        notify += to_header + "\r\n"
        notify += from_header + "\r\n"
        notify += "Call-ID: %s\r\n" % call_id
        notify += "CSeq: 3 NOTIFY\r\n"
        notify += "Content-Type: application/url\r\n"
        notify += "Subscription-State: terminated;reason=timeout\r\n"
        notify += "Event: ua-profile;profile-type=\"device\";vendor=\"OEM\";model=\"OEM\";version=\"7.1.19\"\r\n"
        notify += "Content-Length: %i\r\n" % (len(prov_uri))
        notify += "\r\n%s" % prov_uri

        print "Sending NOTIFY with URI :: %s\n" % prov_uri
        if options.verbose: print notify
        sendsock.sendto(notify, ("%s" % phone.ip_addr, int(phone.sip_port)))

The prov_rui needs to be the local ip of the system the script is running on.

Thanks for any ideas / help anyone can help with. ]]>
Python Programming Edlentz http://forums.devshed.com/python-programming-11/pnp-server-code-979569.html
<![CDATA[NameError: name '__file__' is not defined]]> http://forums.devshed.com/python-programming/979550-nameerror-name-__file__-defined-new-post.html Tue, 28 Nov 2017 18:47:26 GMT in () 466 467 if __name__ == '__main__': --> 468 test_SdA()]]> HI

I'm getting this error after I run stacked denoising autoencoder code http://deeplearning.net/tutorial/code/SdA.py code , how this error can be fixed ?


NameError Traceback (most recent call last)
<ipython-input-9-94013ff577e5> in <module>()
466
467 if __name__ == '__main__':
--> 468 test_SdA()

<ipython-input-9-94013ff577e5> in test_SdA(finetune_lr, pretraining_epochs, pretrain_lr, training_epochs, dataset, batch_size)
375
376 print(('The pretraining code for file ' +
--> 377 os.path.split(__file__)[1] +
378 ' ran for %.2fm' % ((end_time - start_time) / 60.)), file=sys.stderr)
379 # end-snippet-4

NameError: name '__file__' is not defined


could you please help me ]]>
Python Programming tohi http://forums.devshed.com/python-programming-11/nameerror-name-__file__-defined-979550.html
Finding the term frequency in a list (new to programming) http://forums.devshed.com/python-programming/979524-finding-term-frequency-list-programming-new-post.html Fri, 24 Nov 2017 14:51:48 GMT Hi guys

I’m making a ‘term frequency’ program which counts the strings in a list and then gives the number of times the strings have been repeated, for example…

[‘a’,‘horse’,‘a’,‘fast’,‘horse’,‘jumps’,‘over’,‘the’,‘smart’,‘duck’]

({‘a’: 2, ‘horse’: 2, ‘over’: 1, ‘fast’: 1, ‘duck’: 1, ‘the’: 1, ‘jumps’: 1, ‘smart’: 1})

Here is the code I need to build a function for, the Bag() is an ADT to help the program run.

Code:

from Bag import *
terms = ['the','fox','the','quick','fox','jumps','over','the','lazy','dog']
document = Bag()
for term in terms:
    document.add(term)
def tf(term, document):
   
print(tf('the', document))

This is what I have as the body at the moment, but I can only get it to count the number of string… How do I divide the string counts by the length of the list to get term frequency?

Code:

from collections import Counter
terms=['the','fox','the','quick','fox','jumps','over','the','lazy','dog']
counts = Counter(terms)
print(counts)
Counter({})

Any help is appreciated ]]>
Python Programming Os9008 http://forums.devshed.com/python-programming-11/finding-term-frequency-list-programming-979524.html
Please help! http://forums.devshed.com/python-programming/979516-please-help-new-post.html Thu, 23 Nov 2017 15:21:21 GMT I want to write this small program in Python:
Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
I tried this:

index = 0
fruit="banana"
while index < len(fruit):
letter = fruit[index-1]
print(letter)
index = index-1

it works but with an error:

a
n
a
n
a
b
Traceback (most recent call last):
File "/Users/bicharaetienne/Desktop/while.py", line 6, in <module>
letter = fruit[index-1]
IndexError: string index out of range

How can I make it work perfectly?

Thanks! ]]>
Python Programming Bichalways http://forums.devshed.com/python-programming-11/please-help-979516.html