Gribouillis 1,391 Programming Explorer Team Colleague

@vegaseat: You are very wrong. Well, I haven't timed it, but theoretically it should be. Because, with multiple separate replaces you're running through the whole text string for every key in the dictionary, whereas the OP's regex method traverses 'text' just once. For short texts this may not make much difference but for longer texts it will. Too, if one of the to-be-replaced strings (keys) is a superset of another, usually you want the longer string to be replaced first (it's more specific; eg 'theater' before 'the'). Well, the regex method, because regexes try to match the maximum length, will do this naturally. With simply traversing a dict, you take your chances as to which key gets replaced first (eg 'the' could be replaced, even in the middle of 'theater'). Thirdly (though least important), searching separately key-by-key, each key is totally separate; in the regex version, if there's any overlap, the regex compiler will use that to find a slightly more efficient way to search through all keys /at once/, at any part of the text.

edit: oh, you're the same guy. Well, have you timed it? I claim that if you have a sufficiently long 'text' the re method will be faster (not to mention correctness in the case of overlap among your keys).

Actually, on this text, the second method is 6 times faster:

from timeit import Timer
NTIMES = 100000
testlist = [multiwordReplace, multipleReplace]
for func in testlist:
    print "{n}(): {u:.2f} usecs".format(n=func.__name__, u=Timer(
        "{n}(str1, wordDic)".format(n=func.__name__),
        "from …
vegaseat commented: thanks +15
Gribouillis 1,391 Programming Explorer Team Colleague

This is what im facing when I try to run the python interactively from the command prompt:

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users\Shankaranarayanan>cd\

C:\>python
Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello"
File "<stdin>", line 1
print "hello"
^
SyntaxError: invalid syntax
>>>


is this a problem with the way environment variables are set??
IF so can someone give me the step by step method to set them as i deleted them by mistake!

In principle, you don't need to cd to python's folder to invoke the command 'python' if C:\Python32 is in your PATH variable. Also I don't understand why in first post it was C:\Python27...

Your python statement fails because the 'print' statement became a function in python 3.0. So now, you must write

print("hello")

with parenthesis. I understand that you're a python beginner, so use a tutorial for python 3.x and not python 2.x. There are not so many differences, but 'print' is one of them. Also, please use code tags when you post code in the forum. Read this http://www.daniweb.com/software-development/python/threads/366794 and this http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3

Gribouillis 1,391 Programming Explorer Team Colleague

Ah, that makes sense.

In the context of the code you just posted, what are the advantage(s) from using the update_wrapper to make temp_func look like orig_func (which is sqrt() in this example)?

Thanks again.

The first advantage is sqrt's docstring which gets copied into temp_func(). For example if you write

@is_value_pos
def sqrt(val):
    "compute the square root"
    etc

then typing >>> help(sqrt) in a python shell will still print the help despite the fact that the original sqrt() was wrapped into temp_func(). This is also useful for some automated documentation tools like pydoc. Some tracing or debugging modules may also use the function's name ( sqrt.__name__ ).
Published python decorators always include the update_wrapper() call, because update_wrapper() was precisely designed for this use case. However, your decorator would work without this call.

Gribouillis 1,391 Programming Explorer Team Colleague

The code

@is_val_pos
def sqrt(val):
	print 'Entering sqrt method'
	import math
	return math.pow(val, (1.0/2))

is equivalent to

def sqrt(val):
	print 'Entering sqrt method'
	import math
	return math.pow(val, (1.0/2))
sqrt = is_val_pos(sqrt)

This show that is_val_pos() is only called once after the definition of sqrt(), and then, sqrt() becomes the function temp_func() returned by is_val_pos(). A slight improvement is to use update_wrapper():

from functools import update_wrapper

def is_val_pos(orig_func):
	print 'Entering decorator'
	def temp_func(val):
		print 'Entering temp func'
		if val < 0:
			return 0
		else:
			return orig_func(val)
        update_wrapper(temp_func, orig_func)
	return temp_func

This makes temp_func() look more like sqrt(). For example after the definition, the value of sqrt.__name__ will be "sqrt" and not "temp_func" .

Gribouillis 1,391 Programming Explorer Team Colleague

The best way I've found to do that is to run a ssh server on the remote machine and use the paramiko module. Here is a possible client code

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("IP_ADDRESS", username="USER", password="PASSWORD", allow_agent = False)
i, o, e = ssh.exec_command("cp foo bar") # example command
s = e.read()
if s: # an error occurred
    raise RuntimeError, s
result = o.read()

In windows, I installed copssh on the remote machine (there was a missing dll cygattr1.dll which I found here http://cygwin.cybermirror.org/release/attr/libattr1/libattr1-2.4.43-1.tar.bz2 and copied to the C://program Files/ICW/Bin folder). You must also open the port 22 in the firewall of the remote machine. In linux, there should be an option in your system's control center to run an ssh server.

Paramiko can also transfer files from the client to the server and back.

Also read this post relative to copssh and batch programs http://www.itefix.no/i2/node/12147

Gribouillis 1,391 Programming Explorer Team Colleague

Hi Gribouillis and snippsat, thanks a lot for your solutions.
But I was more interested in finding the flaw in the re I have written.
Because I was able to extract first name successfully using the following -

match2 = re.search(r'(<td>)([a-zA-Z]+)',line)

Then why isn't it working in second name case as $ would look for pattern from the end.

It is not true: $ matches the end of the string. There is no way to look for a pattern from the end. In this case, you could use a devilish trick:

re.search(r">dt/<([a-zA-Z]+)", line[::-1]).group(1)[::-1]

or if there is only white space after the last </td> for example, you could use the end of the line like this

re.search(r'([a-zA-Z]+)</td>\s*$',line)
Gribouillis 1,391 Programming Explorer Team Colleague

This snippet defines a simple decorator to post-process a function's return value through a sequence of filters. As a first application, the decorator can transform a generator function into a function returning a sequence type (list, tuple, dict).

Gribouillis 1,391 Programming Explorer Team Colleague

It would be better to compute with floating numbers to avoid division issues (like 5/9 == 0)

def nearest_int(number):
    return int(number + (0.5 if number >= 0 else -0.5))

print "%d Degrees Farenheit" % nearest_int(float(fc) * 9 / 5 + 32)

Also it would be much better to use the optparse or argparse module to handle command line arguments and options. Read this tutorial http://www.alexonlinux.com/pythons-optparse-for-human-beings

Gribouillis 1,391 Programming Explorer Team Colleague

Thats work. Thank you very much

In fact the code can be simplified a little because the tab is a Button widget, and you can get the name through the button:

title = 'Pmw.NoteBook demonstration'

# Import Pmw from this directory tree.
import sys
#sys.path[:0] = ['../../..']

import Tkinter
import Pmw

class Demo:
    def __init__(self, parent):
	# Create and pack the NoteBook.
        notebook = Pmw.NoteBook(parent)
        self.notebook = notebook # <-- ADDED
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

        # Add the "Appearance" page to the notebook.
        page = self.add_page('Appearance')
        notebook.tab('Appearance').focus_set()

        # Create the "Toolbar" contents of the page.
        group = Pmw.Group(page, tag_text = 'Toolbar')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
        b1.grid(row = 0, column = 0)
        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
        b2.grid(row = 0, column = 1)

        # Create the "Startup" contents of the page.
        group = Pmw.Group(page, tag_text = 'Startup')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        home = Pmw.EntryField(group.interior(), labelpos = 'w',
            label_text = 'Home page location:')
        home.pack(fill = 'x', padx = 20, pady = 10)

        # Add two more empty pages.
        page = self.add_page('Helpers')
        page = self.add_page('Images')

        notebook.setnaturalsize()
  
    def add_page(self, pagename):
        page = self.notebook.add(pagename)
        self.notebook.component(pagename+"-tab").bind("<1>", self.showname)
        return page
        
    def showname(self, event):
        print event.widget.cget("text")

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    root.title(title)

    widget = Demo(root)
    exitButton = Tkinter.Button(root, text = 'Exit', command …
Gribouillis 1,391 Programming Explorer Team Colleague

thanks for answer.it works when i click on frame but dont works when i click "Appearance" tab text. is it possible write pagename when i clicked tab?

It was more difficult. The following code works for me

title = 'Pmw.NoteBook demonstration'

# Import Pmw from this directory tree.
import sys
#sys.path[:0] = ['../../..']

import Tkinter
import Pmw
from functools import partial

class Demo:
    def __init__(self, parent):
	# Create and pack the NoteBook.
        notebook = Pmw.NoteBook(parent)
        self.notebook = notebook # <-- ADDED
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

        # Add the "Appearance" page to the notebook.
        page = self.add_page('Appearance')
        notebook.tab('Appearance').focus_set()

        # Create the "Toolbar" contents of the page.
        group = Pmw.Group(page, tag_text = 'Toolbar')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
        b1.grid(row = 0, column = 0)
        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
        b2.grid(row = 0, column = 1)

        # Create the "Startup" contents of the page.
        group = Pmw.Group(page, tag_text = 'Startup')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        home = Pmw.EntryField(group.interior(), labelpos = 'w',
            label_text = 'Home page location:')
        home.pack(fill = 'x', padx = 20, pady = 10)

        # Add two more empty pages.
        page = self.add_page('Helpers')
        page = self.add_page('Images')

        notebook.setnaturalsize()
  
    def add_page(self, pagename):
        page = self.notebook.add(pagename)
        self.notebook.component(pagename+"-tab").bind("<1>",partial(self.showname, pagename))
        return page
        
    def showname(self, name, event):
        print name

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = …
Gribouillis 1,391 Programming Explorer Team Colleague

You can bind each page of the notebook (each page is a Frame)

title = 'Pmw.NoteBook demonstration'

# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']

import Tkinter
import Pmw

class Demo:
    def __init__(self, parent):
	# Create and pack the NoteBook.
        notebook = Pmw.NoteBook(parent)
        self.notebook = notebook # <-- ADDED
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

        # Add the "Appearance" page to the notebook.
        page = self.add_page('Appearance')
        notebook.tab('Appearance').focus_set()

        # Create the "Toolbar" contents of the page.
        group = Pmw.Group(page, tag_text = 'Toolbar')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
        b1.grid(row = 0, column = 0)
        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
        b2.grid(row = 0, column = 1)

        # Create the "Startup" contents of the page.
        group = Pmw.Group(page, tag_text = 'Startup')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        home = Pmw.EntryField(group.interior(), labelpos = 'w',
            label_text = 'Home page location:')
        home.pack(fill = 'x', padx = 20, pady = 10)

        # Add two more empty pages.
        page = self.add_page('Helpers')
        page = self.add_page('Images')

        notebook.setnaturalsize()
  
    def add_page(self, pagename):
        page = self.notebook.add(pagename)
        page.bind("<1>",self.showname)
        return page
        
    def showname(self, event):
        print self.notebook.getcurselection()

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    root.title(title)

    widget = Demo(root)
    exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
    exitButton.pack()
    root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

You can also define your own bins limits for the numpy histogram by passing a sequence, like in bins = range(1, 7) . Matplotlib's histograms also use numpy's histogram() method. Here is the same example with the plotted histogram

import matplotlib.pyplot as plt

data = '''
5.639792 1.36
4.844813 1.89
4.809105 2.33
3.954150 2.69
2.924234 3.42
1.532669 4.50
0.000000 5.63
'''
weights, pos = zip(*[map(float,d.split()) for d in data.strip().splitlines()])

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(pos, bins = range(1,7), weights = weights, facecolor = "green")
print n, bins
plt.savefig("histo.png") # save figure (optional)
plt.show() # display figure on the screen
TrustyTony commented: usufull idiom .strip().splitlines() +13
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks again.I think its working but i am getting some special characters The printed code does not look like this one..-->> "\x01\x00\x12\x59"..If the printed special chars are equivalent to binary data can i send that through socket like i have mentioned in the main post.like

from binascii import hexlify, unhexlify
import socket
s = "04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00"
ss = s.replace(" ", "")
binary = unhexlify(ss)
print binary
sock.send(binary)

To print binary strings, you should print their repr():

>>> print repr(binary)
'\x04\xf8\x00PO0\xfbG(b\xa7mP\x02\x02\x00\xd2\x7f\x00\x00'

Otherwise, yes, you can send your binary string in the socket; hexlify() and unhexlify() are robust functions.

Gribouillis 1,391 Programming Explorer Team Colleague

thanks a lot for your reply..But one thing i wanna know what abou converting "04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00" hex in a format like this "\x01\x00\x12\x59"

Remove white space and use unhexlify()

s = "04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00"
ss = s.replace(" ", "")
binary = unhexlify(ss)
debasishgang7 commented: 3 +3
Gribouillis 1,391 Programming Explorer Team Colleague

The error means that one of the records does not have length 8. The first solution is to print it to see what happens

from itertools import islice

for i, record in islice(enumerate(reader), 1, None):
    if len(record) != 8:
        raise ValueError, "Bad record at line %d : %s" % (i+1, str(record))
    else:
        date, hk, ba, bsp, hgch, v995, v996, vct = record
Gribouillis 1,391 Programming Explorer Team Colleague

A feature of the doctest module can be useful when people copy and paste their idle window in the python forum: the ability to transform an example from the python interpreter into python code without the prompts >>>, ... and the output messages. The script below permits to use this function from the command line.

TrustyTony commented: Handy +13
HiHe commented: neat +5
Gribouillis 1,391 Programming Explorer Team Colleague

why is it that when i pop a dictionary in variable b, variable a does the same? And When i print variable a, the value is [{'b':2}]. How can i retain the value of variable a?

a=[{'a':1,},{'b':2,}]
    b = a
    b.pop(0)

You must copy the list pointed to by 'a' if you want to retain it's value:

>>> a=[{'a':1,},{'b':2,}]
>>> b = list(a)
>>> b.pop(0)
{'a': 1}
>>> b
[{'b': 2}]
>>> a
[{'a': 1}, {'b': 2}]

If you write b=a , the two names a and b refer to the same instance of list.

Gribouillis 1,391 Programming Explorer Team Colleague

Oh I'm sorry, looking at it again it is a mess. Maybe this renamed version is clearer.

Basically the situation would be where I know the fixed cost (the contribution cost) lets say is $17,800. However, the other costs (the one allowed to change, it is more than one cost but since I'm using the total of those costs it is only one number) are a total of $24,420 which is 58% of the Full Total cost $42,220. I need to have the "Other Costs" be 75% of the Full Total. Since this situation sometimes comes in other forms I wanted to make a program that can deal with it.

The method I was trying to emulate was the crude method where you keep adding one to the "Other Costs" and double checking to see if it 75% of the Full Total Costs and if not, then adding one again and so forth until the "Other Costs" is 75%. I'm sure there are other methods but I chose this method because I wanted to practice looping or iterations.

Yes, you are trying to write your own 'equation solver' or 'root finding' algorithm for the equation other == proportion * (fixed + other) where the unknown is 'other'. Iterative methods to solve algebraic equations exist, but as griswolf said, this equation is elementary and can be solved immediately, so the best program would be

fixed = float(raw_input('Enter the fixed amount: $ '))
proportion = float(raw_input('Enter the proportion of variable costs: …
Gribouillis 1,391 Programming Explorer Team Colleague

Hello,
The error means that one of your files has less than 2 lines. Here is a modified version which prints those files

#! /usr/bin/env python
import sys
import glob

def doit(n):
    file_names = glob.glob('*/*.pdbqt')
    everything = []
    for file_name in file_names:
        file = open(file_name)
        lines = file.readlines()
        file.close()
        try:
            line = lines[1]
        except IndexError:
            print "file %s has only %d lines" % (file_name, len(lines))
        else:
            result = float(line.split(':')[1].split()[0])
            everything.append([result, file_name])
    everything.sort(lambda x,y: cmp(x[0], y[0]))
    part = everything[:n]
    for p in part:
        print p[1],
    print

if __name__ == '__main__':
    doit(int(sys.argv[1]))

Please use code tags to post python code, see here http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3 .

Gribouillis 1,391 Programming Explorer Team Colleague

just a question, if i want the user to choose if he can play again then i just put

print 'the number was ' + str(x)
again=raw_input("play again? ")

or do i do something else?

It's ok, but you can do a little better: offer a default option (yes), and then you must translate the answer into a boolean

again = raw_input("play again? [y] ").strip().lower()
again = (again in ('', 'y', 'yes')) # now again is True or False

strip() removes white space at both ends, in case the user enters " yes " , and lower() converts to lowercase (if the user enters "Yes").

Gribouillis 1,391 Programming Explorer Team Colleague

Hm, it could be a firewall issue. Normally, idle uses the port 8833. You may have to open this port on your firewall.

Gribouillis 1,391 Programming Explorer Team Colleague

You can loop indefinitely with while True . Here is the code

import random
import re

print 'This is a guessing game'

def game(guess):
    x=random.randint(1,100)
    while True: # loop indefinitely
        respond = int(raw_input(guess)) # better than input()
        if respond < x:
            print 'nop higher'
        elif respond > x:
            print 'wow too much'   
        else:
            assert respond == x # necessarily true. We may assert it for debugging
            print 'you got it!!'
            print 'the number was ' + str(x) # must convert to string for addition
            break # exit the loop

game("Guess a number: ")

In python 2, use raw_input(), which reads a string, and convert the string to int instead of using input(). (in python 3, input() is python 2's raw_input().)

vegaseat commented: nice help +15
Gribouillis 1,391 Programming Explorer Team Colleague

You could start by running the examples of the sticky thread above http://www.daniweb.com/software-development/python/threads/191210

vegaseat commented: agree +15
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest

entry0 = "'{e:0>7}'".format(e=entry[0])
Gribouillis 1,391 Programming Explorer Team Colleague

The above functor base class can also be used to define methods, static methods and class methods, here is an example

class A(object):
    def __init__(self):
        self.value = None
        
    class foo(functor):
        def __call__(self, this, n):
            this.value = n

    class sbar(functor):
        def __call__(self, stuff):
            print "sbar called with", repr(stuff)
    sbar = staticmethod(sbar)
    
    class cbar(functor):
        def __call__(self, cls, stuff):
            print "cbar called with", cls, repr(stuff)
    cbar = classmethod(cbar)

a = A()
a.foo("value set by the foo functor")
print a.value
a.sbar("static call with instance")
A.sbar("static call with class")
a.cbar("classmethod call")
""" my output --->
value set by the foo functor
sbar called with 'static call with instance'
sbar called with 'static call with class'
cbar called with <class '__main__.A'> 'classmethod call'
"""

Notice that the 'method functor' has 2 implicit arguments: the functor object and the A instance.

vegaseat commented: interesting indeed +15
Gribouillis 1,391 Programming Explorer Team Colleague

A functor, or function object is sometimes a convenient way to encapsulate helper functions and data needed to achieve a small task, and also to share data between calls to the same function. This snippet defines a base class [b]functor[/b] which permits an easy functor creation for python 2.

Gribouillis 1,391 Programming Explorer Team Colleague

An alternative way to explore your modules is to start a pydoc server and visit it with your web browser. Here is how it goes in linux

$ pydoc -p 9999&
[1] 7877
$ pydoc server ready at http://localhost:9999/

It shows hundreds of modules for me to explore :)

Note that pydoc has a limitation: it must import a module first to show the module's doc. This could be annoying for certain modules.

Gribouillis 1,391 Programming Explorer Team Colleague

In python 2.6, I have both

>>> import wx
>>> wx.Color
<class 'wx._gdi.Colour'>
>>> wx.Colour
<class 'wx._gdi.Colour'>

You could add a piece of code like

import wx
if hasattr(wx, "Color"):
    wx.Colour = wx.Color
else:
    wx.Color = wx.Colour
Gribouillis 1,391 Programming Explorer Team Colleague

Ok thanks for helping.It was a long discussion.
Thanks again.

last thing, you may be interested in the standard module tabnanny (see info here http://effbot.org/librarybook/tabnanny.htm) and by the pep 8 advices http://www.python.org/dev/peps/pep-0008/ . Good luck.

Edit: you don't need to install tabnanny. It comes with your python distribution.

hszforu commented: very helping. +1
vegaseat commented: thanks +15
Gribouillis 1,391 Programming Explorer Team Colleague

hey it works after i do it manually,and the script also runs correctly as expected but any ideas how should i perform the identation in future for larger programs.
Thanks again.

In the future, always use an editor where indentation is configured with 4 spaces (like your idle), and if you find a bad indentation in a forum post or in a 3rd party program, try to use "reindent" to clean the script.

Gribouillis 1,391 Programming Explorer Team Colleague

now easyInstall is also installed correctly, reindent is also working and after reindenting the prolis.py file again when i open the prolis.py file in idle and run module then i get following error:
expected an indented block.

Can you post prolis.py (between code tags) ? Also python probably tells you the error's line number.

Gribouillis 1,391 Programming Explorer Team Colleague

set up the environmental variables using following cmd:
set PYTHONPATH=%PYTHONPATH%;C:\Python32

but again it gives the same previous error after i put setup.py install in cmd

If you don't have setuptools, get it from here. If your windows is 32 bits, simply download the .exe for your version of python and run it. http://pypi.python.org/pypi/setuptools#downloads

Gribouillis 1,391 Programming Explorer Team Colleague

Don't indent python code with tab characters. Configure your editor to insert 4 spaces instead of a tab when you hit the tab key. Also reindent your code like this

def print_lol(movies):
    for each in movies:
        if isinstance(each,list):
            print_lol(each)
        else:
            print(each)

I used the "reindent" script to reindent the code from the command line http://pypi.python.org/pypi/Reindent/0.1.0

Gribouillis 1,391 Programming Explorer Team Colleague

Hi all,
Forgive my pool English first...
I'm learning Python recently. But I met with a problem yesterday and I have liitle experience in solving this kind of problems.
Here are the code in Python Shell:

>>> "HuXiaoxiang\\0Nanjing University\03 Years.".replace("\0"," ")
'HuXiaoxiang\\0Nanjing University\x03 Years.'
>>> "HuXiaoxiang \0Nanjing University\03 years.".replace("\0"," ")
'HuXiaoxiang  Nanjing University\x03 years.'
>>> "HuXiaoxiang \0Nanjing University\03 years.".replace(" ","@")
'HuXiaoxiang@\x00Nanjing@University\x03@years.'

Why the first & second didn't work as I excepted?
Thxs for anyone who will view my problem in advance~

Your problem is not with the replace() method but with the escaped characters in literal strings:

  • An escaped backslash "\\" is interpreted as a single backslash character in a literal string, so your first string contains a backslash character followed by the digit 0, and not the null character '\0'.
  • A backslash followed by 1, 2 or 3 octal digits is interpreted as the character which binary value has this number. For example, 'a' has order 97, which is written 141 in base 8, so the string "\141" is the same as "a" (an octal digit is 0, ..., 7). So in the second string, "\0" is interpreted as the null character but "\03" is the character with number 3, while "\09" would mean a null character followed by the digit 9, because 9 is not an octal digit.

Because they can have a variable number of digits, the octal escaped sequences are not very useful. The better way is to represent non …

vegaseat commented: nice explanation +15
Gribouillis 1,391 Programming Explorer Team Colleague

Oh boy, Jaro's tab indented code looks like dung on a shingle.

An old trick to reindent your code is to use Tim Peters' reindent script http://pypi.python.org/pypi/Reindent/0.1.0 .

Gribouillis 1,391 Programming Explorer Team Colleague

Using the key argument of sorted() or list.sort(), you can sort a list of items according to a score function. The score of an item could be its price, name, age, mark, length, distance to a point, etc depending on what the items are.

from functools import partial

def dist_to_target(tx, ty, item):
    name, sx, sy = item
    return sqrt((int(sx) - tx)**2 + (int(sy) - ty)**2)

score = partial(dist_to_target, targetx, targety)
# score is now a function score(item) --> distance to target

sorted_items = sorted(citiescomp, key = score)
print sorted_items
vegaseat commented: nice code +15
Gribouillis 1,391 Programming Explorer Team Colleague

What do you mean? I first find the square root and then divide by 4ac. However I will fix the negative square root.

See here http://en.wikipedia.org/wiki/Quadratic_equation#Quadratic_formula :) and compare with your code.
Numerical analysis works like mathematics: when you divide by a number, there is a risk that the number is zero, when you take a square root or a logarithm, there is a risk that the argument is negative. All these cases must be handled by tests.

Lardmeister commented: good source +10
Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you're taking the square root of a negative number ? Also your formulas are false. Why not introduce a variable delta = b * b - 4 * a * c to clean up the code ?

Gribouillis 1,391 Programming Explorer Team Colleague

I think there are many ways of saving the user settings. If your aplication is named MyGreatApp, the idea is to create a folder named MyGreatApp which contains your configuration files (in text or xml formats, or split in several files in several subdirectories). The location of the folder MyGreatApp depends on the system. In windows, you could store this folder in the user's 'Applications Data' folder, In a linux system, you could store it as a subfolder of ~/.gconf/apps (the gnome project has a system named gconf to handle applications configuration, see here http://projects.gnome.org/gconf/ ).
The older way in linux is to have a folder ~/.MyGreatApp , for example I have a ~/.VirtualBox, a ~/.wine, etc.

Gribouillis 1,391 Programming Explorer Team Colleague

Google gives many answers. See this one from Alex on linux. Alex usually writes good python articles http://www.alexonlinux.com/how-to-send-sms-message-with-python .

Gribouillis 1,391 Programming Explorer Team Colleague

Wow thank you Gribouillis, that works perfectly.

Now is there a way to force it to call private functions? Because I'm calling private function through another member function. So why self.__CMD02() works but not with getattr() function?


Thanks Again

--
Mark

I think it's because when the compiler transforms your code into bytecode, it changes self.__CMD02() into self._Test__CMD02() in a member function. This is not done in a call to getattr(). You could add the class name by hand in your getattr like in getattr(self, "_Test__CMD%s" % f) .

My advice is to avoid private methods. They are not "pythonic" and they add no value to your code. If you really need to ensure that a method is not called with a subclass' instance (which is rarely needed), you can simply add an assert statement like this

class Test(object):
    def myprivatemethod(self):
        assert type(self) is Test # or self.__class__ is Test
        ...
Gribouillis 1,391 Programming Explorer Team Colleague

The first problem is that you are using attributes starting with double underscores. Double underscores are used by the interpreter to simulate "private" attributes (which don't really exist in the language). So if you set an attribute __dic , the instance will actually have an attribute _Test__dic instead of __dic . The same applies to the member functions __CMD02 and __CMDA0. So getattr(self, "__CMD02") won't work.

The simpler solution is that you avoid private attributes and write a single underscore at the beginning of the "hidden" attributes.

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

There are 2 slightly different things that you might want to do

  • execute a script xxx.py from your main program. This can be done with exec open("xxx.py").read()
  • import xxx.py as a module, which is done with import xxx or mod = __import__("xxx")

If you import the module, the script xxx.py is only executed the first time the module is imported, and a module object is stored in sys.modules["xxx"] .
If you choose the exec solution, a good idea is to execute the script in a separate dictionary to avoid polluting your namespace, like this

mydict = dict()
exec open("xxx.py").read() in mydict
# or in python 3: exec(open("xxx.py").read(), mydict)

It is unusual to choose a module to import through interaction with the user. A more logical way is that the user chooses an action to execute and this choice results in selecting a function to call. For example

action = raw_input("what should I do ? ").strip()
if action == "go to hell":
    import xxx
    xxx.gotohell()
elif action == "quit":
    import yyy
    yyy.quit()
# etc
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a slower way to do it. Actually, there was an error in list2

>>> adict = {}
>>> list1 = range(6)
>>> list2 = range(10,16)
>>> for i, item in enumerate(list1):
...  adict[item] = list2[i]
... 
>>> adict
{0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15}
Gribouillis 1,391 Programming Explorer Team Colleague

Yes, python is extremely permissive. Any function can call any other function in any module, including the module where it is defined.

Gribouillis 1,391 Programming Explorer Team Colleague

can you be more descriptive please

Well, I mean that you could handle the server's answer like this

import json

def handle_server_answer(the_answer):
    try:
        json_data = json.loads(the_answer)
    except ValueError:
        # the answer was not in json
        other_handler(the_answer)
        return
    # do something with the json data
    print("The server sent json data %s" % repr(json_data))

def other_handler(the_answer):
    # may be try to parse with an xml parser like lxml
    pass
Gribouillis 1,391 Programming Explorer Team Colleague

you want some variation on code like this

gracefulStart() # create circle etc
while True:
    # display the circle
    # do some work; pause; etc
    if readyToStop(): 
        break
    # adjust the location of the circle
gracefulEnd()

Also possibly create a second moving circle to simulate reapearance at the other side of the canvas. Why don't you use Tkinter ? Nobody has utalcanvas.

Gribouillis 1,391 Programming Explorer Team Colleague

I went and looked up the tksnack from the website posted and the latest version is for Python 2.2. Considering Python latest is 3.1, will this library still work? I'm very interested in this for my final project and would prefer to use this or something similar / more up to date.

Thanks.

Apparently, a very small part of snack is written in python (20k) and this part contains basic interaction with tkinter, so if it does not work with python 3, it should be relatively easy to adapt it. On the snack site http://www.speech.kth.se/snack/ there is a link to another program called WaveSurfer http://www.speech.kth.se/wavesurfer/ which uses snack and which last release was 1 month ago. Wavesurfer is described in this wikipedia page http://en.wikipedia.org/wiki/WaveSurfer, and apparently wavesurfer accepts plugins (in python ? it's worth exploring this direction).
Anyway, the existence of wavesurfer proves that snack still works in 2011.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you should start with pytesser http://code.google.com/p/pytesser/ which binds python to the tesseract OCR engine. Tesseract has a good reputation (although I never used it myself).