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 Mon, 11 Dec 2017 09:23:15 GMT vBulletin 60 http://forums.devshed.com/images/misc/rss.png Dev Shed Forums - Python Programming http://forums.devshed.com/ <![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