Re: Will MySQL ever be supported for Python 3.x?

2012-04-02 Thread Jason
On Sunday, April 1, 2012 1:54:14 AM UTC-4, Tim Roberts wrote:
> John Nagle  wrote:
> 
> >On 3/30/2012 2:32 PM, Irmen de Jong wrote:
> >> Try Oursql instead  http://packages.python.org/oursql/
> >> "oursql is a new set of MySQL bindings for python 2.4+, including python 
> >> 3.x"
> >
> >Not even close to being compatible with existing code.   Every SQL
> >statement has to be rewritten, with the parameters expressed
> >differently.  It's a good approach, but very incompatible.
> 
> Those changes can be automated, given an adequate editor.  "Oursql" is a
> far better product than the primitive MySQLdb wrapper.  It is worth the
> trouble.
> -- 
> Tim Roberts, t...@probo.com
> Providenza & Boekelheide, Inc.

Is OurSQL still active? 
I had problems with it because it couldn't handle MySQL's zeroed dates, but the 
latest release seems to be patched now (applied a year after the bug was 
reported with a small patch to fix it).

-- Jason
-- 
http://mail.python.org/mailman/listinfo/python-list


specify end of line character for readline

2012-05-14 Thread Jason
Is there any way to specify the end of line character to use in file.readline() 
?

I would like to use '\r\n' as the end of line and allow either \r or \n by 
itself within the line.

Thanks,

Jason
-- 
http://mail.python.org/mailman/listinfo/python-list


multiprocessing shows no benefit

2017-10-17 Thread Jason
I've got problem that I thought would scale well across cores.

def f(t):
   return t[0]-d[ t[1] ]

d= {k: np.array(k) for k in entries_16k }
e = np.array()

pool.map(f, [(e, k) for k in d]

At the heart of it is a list of ~16k numpy arrays (32 3D points) which are 
stored in a single dict.  Using pool.map() I pass the single item of 32 3D 
Points to  be evaluated again the 16k entries. In theory, this would be a 
speedup proportional to the number of physical cores, but I see all 4 cores 
being maxed out and results in a regular map time. 

How can I use pool.map better?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing shows no benefit

2017-10-18 Thread Jason
I've read the docs several times, but I still have questions.
I've even used multiprocessing before, but not map() from it.

I am not sure if map() will let me use a common object (via a manager) and if 
so, how to set that up.





-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing shows no benefit

2017-10-18 Thread Jason
#When I change line19 to True to use the multiprocessing stuff it all slows 
down. 

from multiprocessing import Process, Manager, Pool, cpu_count
from timeit import default_timer as timer

def f(a,b):
return dict_words[a]-b

def f_unpack(args):
return f(*args)

def init():
global dict_words, dict_keys
d = {str(k):k for k in range(10)}
for k in d:
dict_words[k] = d[k]
dict_keys.append(k)

if __name__ == '__main__':
print 'CPUs:', cpu_count() # 4 on my machine
if False: # make this a zero to use PODs
'''
CPUs: 4
pool.map: 47.1494848728 100 21209.1394571
map: 49.2051260471 100 20323.0858314
'''
manager = Manager()
dict_words = manager.dict()
dict_keys = manager.list()
else:
'''
CPUs: 4
pool.map: 3.2546248436 100 307255.074872
map: 1.19043779373 100 840027.093617
'''
dict_words = {}
dict_keys = []

init()

pool = Pool(cpu_count())
z=5
funcs = {'pool.map:': pool.map, 'map': map}
for name in funcs:
start = timer()
x = funcs[name](f_unpack, [(k,z) for k in dict_keys])
duration = float(timer() -start)
print funcs[name], duration, len(x), len(x) / duration
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing shows no benefit

2017-10-18 Thread Jason
On Wednesday, October 18, 2017 at 12:14:30 PM UTC-4, Ian wrote:
> On Wed, Oct 18, 2017 at 9:46 AM, Jason  wrote:
> > #When I change line19 to True to use the multiprocessing stuff it all slows 
> > down.
> >
> > from multiprocessing import Process, Manager, Pool, cpu_count
> > from timeit import default_timer as timer
> >
> > def f(a,b):
> > return dict_words[a]-b
> 
> Since the computation is so simple my suspicion is that the run time
> is dominated by IPC, in other words the cost of sending objects back
> and forth outweighs the gains you get from parallelization.
> 
> What happens if you remove dict_words from the Manager and just pass
> dict_words[a] across instead of just a? Also, I'm not sure why
> dict_keys is a managed list to begin with since it only appears to be
> handled by the main process.

You can try that code by changing line 17 :-) It's 10 times faster.

Well given the many objects to be iterated over, I was hoping pool.map() would 
distribute them across the processors. So that each processor gets 
len(dict_words)/cpu_count() items to process. The actual computation is much 
longer than a single subtraction, currently I can process about 16k items per 
second single core.  My target is to get those 16k items processed in .25s.



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing shows no benefit

2017-10-18 Thread Jason
I refactored the map call to break dict_keys into cpu_count() chunks, (so each 
f() call gets to run continuously over n/cpu_count() items) virtually the same 
results. pool map is much slower (4x)  than regular map, and I don't know why. 


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing shows no benefit

2017-10-20 Thread Jason
Yes, it is a simplification and I am using numpy at lower layers. You correctly 
observe that it's a simple operation, but it's not a shift it's actually 
multidimensional vector algebra in numpy. So the - is more conceptual and takes 
the place of hundreds of subtractions. But the example dies demonstrate the 
complexity and how I can divide the problem up conceptually. 

-- 
https://mail.python.org/mailman/listinfo/python-list


General Purpose Pipeline library?

2017-11-20 Thread Jason
a pipeline can be described as a sequence of functions that are applied to an 
input with each subsequent function getting the output of the preceding 
function:

out = f6(f5(f4(f3(f2(f1(in))

However this isn't very readable and does not support conditionals.

Tensorflow has tensor-focused pipepines:
fc1 = layers.fully_connected(x, 256, activation_fn=tf.nn.relu, scope='fc1')
fc2 = layers.fully_connected(fc1, 256, activation_fn=tf.nn.relu, 
scope='fc2')
out = layers.fully_connected(fc2, 10, activation_fn=None, scope='out')

I have some code which allows me to mimic this, but with an implied parameter.

def executePipeline(steps, collection_funcs = [map, filter, reduce]):
results = None
for step in steps:
func = step[0]
params = step[1]
if func in collection_funcs:
print func, params[0]
results = func(functools.partial(params[0], 
*params[1:]), results)
else:
print func
if results is None:
results = func(*params)
else:
results = func(*(params+(results,)))
return results

executePipeline( [
(read_rows, (in_file,)),
(map, (lower_row, field)),
(stash_rows, ('stashed_file', )),
(map, (lemmatize_row, field)),
(vectorize_rows, (field, min_count,)),
(evaluate_rows, (weights, None)),
(recombine_rows, ('stashed_file', )),
(write_rows, (out_file,))
]
)

Which gets me close, but I can't control where rows gets passed in. In the 
above code, it is always the last parameter.

I feel like I'm reinventing a wheel here.  I was wondering if there's already 
something that exists?

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General Purpose Pipeline library? (Posting On Python-List Prohibited)

2017-11-21 Thread Jason
On Monday, November 20, 2017 at 4:02:31 PM UTC-5, Lawrence D’Oliveiro wrote:
> On Tuesday, November 21, 2017 at 4:49:01 AM UTC+13, Jason wrote:
> > a pipeline can be described as a sequence of functions that are
> > applied to an input with each subsequent function getting the output
> > of the preceding function:
> > 
> > out = f6(f5(f4(f3(f2(f1(in))
> > 
> > However this isn't very readable and does not support conditionals.
> 
> Do you want a DAG in general?

If the nodes have a __call__, yes?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: General Purpose Pipeline library?

2017-11-21 Thread Jason
On Monday, November 20, 2017 at 10:49:01 AM UTC-5, Jason wrote:
> a pipeline can be described as a sequence of functions that are applied to an 
> input with each subsequent function getting the output of the preceding 
> function:
> 
> out = f6(f5(f4(f3(f2(f1(in))
> 
> However this isn't very readable and does not support conditionals.
> 
> Tensorflow has tensor-focused pipepines:
> fc1 = layers.fully_connected(x, 256, activation_fn=tf.nn.relu, 
> scope='fc1')
> fc2 = layers.fully_connected(fc1, 256, activation_fn=tf.nn.relu, 
> scope='fc2')
> out = layers.fully_connected(fc2, 10, activation_fn=None, scope='out')
> 
> I have some code which allows me to mimic this, but with an implied parameter.
> 
> def executePipeline(steps, collection_funcs = [map, filter, reduce]):
>   results = None
>   for step in steps:
>   func = step[0]
>   params = step[1]
>   if func in collection_funcs:
>   print func, params[0]
>   results = func(functools.partial(params[0], 
> *params[1:]), results)
>   else:
>   print func
>   if results is None:
>   results = func(*params)
>   else:
>   results = func(*(params+(results,)))
>   return results
> 
> executePipeline( [
>   (read_rows, (in_file,)),
>   (map, (lower_row, field)),
>   (stash_rows, ('stashed_file', )),
>   (map, (lemmatize_row, field)),
>   (vectorize_rows, (field, min_count,)),
>   (evaluate_rows, (weights, None)),
>   (recombine_rows, ('stashed_file', )),
>   (write_rows, (out_file,))
>   ]
> )
> 
> Which gets me close, but I can't control where rows gets passed in. In the 
> above code, it is always the last parameter.
> 
> I feel like I'm reinventing a wheel here.  I was wondering if there's already 
> something that exists?

Why do I want this? Because I'm tired of writing code that is locked away in a 
bespoke function. I'd  have an army of functions all slightly different in 
functionality. I require flexibility in defining pipelines, and I don't want a 
custom pipeline to require any low-level coding. I just want to feed a sequence 
of functions to a script and have it process it. A middle ground between the 
shell | operator and bespoke python code. Sure, I could write many binaries 
bound by shell, but there are some things done far easier in python because of 
its extensive libraries and it can exist throughout the execution of the 
pipeline whereas any temporary persistence  has to be though environment 
variables or files.

Well after examining your feedback, it looks like Grapevine has 99% of the 
concepts that I wanted to invent, even if the | operator seems a bit clunky. I 
personally prefer the affluent interface convention. But this should work.

Kamaelia could also work, but it seems a little bit more grandiose. 


Thanks everyone who chimed in!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please tell me how to execute python file in Ubuntu by double clicking on file.

2017-12-05 Thread Jason
On Monday, December 4, 2017 at 4:49:11 AM UTC-5, dhananjays...@gmail.com wrote:
> Respected Sir/Mam,
> I am Dhananjay Singh,Student of IIIT Manipur. Sir/Mam when i am 
> double click in python program (Dhananjay.py),it is opening in Text Editor by 
> Default in Ubuntu.I want to run this program when i double click on it as any 
> *.Exe file executes as in Window.
> Sir please help me.



Make the first line oh the file:
#!/usr/bin/env python

Then chmod it with executable permissions:
chmod +x Dhananjay.py

Then you can double-click to run it.
-- 
https://mail.python.org/mailman/listinfo/python-list


csv.DictReader line skipping should be considered a bug?

2017-12-05 Thread Jason
I ran into this:
https://stackoverflow.com/questions/27707581/why-does-csv-dictreader-skip-empty-lines

# unlike the basic reader, we prefer not to return blanks,
# because we will typically wind up with a dict full of None
# values

while iterating over two files, which are line-by-line corresponding. The 
DictReader skipped ahead many lines breaking the line-by-line correspondence. 

And I want to argue that the difference of behavior should be considered a bug. 
It should be considered as such because:
1. I need to know what's in the file to know what class to use. The file 
content should not break at-least-1-record-per-line. There may me multiple 
lines per record in the case of embedded new lines, but it should never no 
record per line. 
2.  It's a premature optimization. If skipping blank lines is desirable, then 
have another class on top of DictReader, maybe call it 
EmptyLineSkippingDictReader. 
3. The intent of DictReader is to return a dict, nothing more, therefore the 
change of behavior isn inappropriate. 

Does anyone agree, or am I crazy?


-- 
https://mail.python.org/mailman/listinfo/python-list


Where did csv.parser() go?

2018-01-02 Thread jason
I need record the starting offsets of csv rows in a database for fast seeking 
later. 
Unfortunately, using any csv.reader() (or DictReader) tries to cache, which 
means:
example_Data = "'data
0123456789ABCDE
1123456789ABCDE
2123456789ABCDE
3123456789ABCDE
...
'''

for line in reader:
offsets[row] = f.tell() 

is not possible. With my example data , offsets are reported as [0, 260, 260, 
260...] they should be [0x00, 0x00,0x15, 0x25, ...] (sample data is 16 byte 
rows after a 5 byte header (just for now)) 

I saw in one of PEP-305's references a mention of csv.parser() which won't 
return a row until parsing is complete. This is ideal since some lines will 
have quoted text containing commas and new lines.  I don't want to re-write the 
parser, since later usage will use csvDictReader, so we need to identically 
parse rows. How can I do that with the Python 2.7 csv module?

Or how can I accomplish this task through other means?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Numpy and Terabyte data

2018-01-02 Thread jason
I'm not sure if I'll be laughed at, but a statistical sampling of a randomized 
sample should resemble the whole.

If you need min/max then min ( min(each node) )
If you need average then you need sum( sum(each node)) sum(count(each node))*

*You'll likely need to use log here, as you'll probably overflow.

It doesn't really matter what numpy can nagle you just need to collate the data 
properly, defer the actual calculation until the node calculations are 
complete. 

Also, numpy should store values more densely than python itself.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where did csv.parser() go?

2018-01-02 Thread jason
Wow, awesome!!!

Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


Defer, ensure library is loaded

2018-02-13 Thread Jason
I have a variety of scripts that import some large libraries, and rather than 
create a million little scripts with specific imports, I'd like to so something 
like

psycopg2 = ensure_imported (psycopg2)

This way, regardless of invocation I can know psycopg2 is loaded, if it hasn't 
already been loaded. If I just do a normal import 95% of the time I'll be 
waiting time with a meaningless import.


Can I do that somehow?
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting the exit code of a subprocess

2021-12-15 Thread Jason
Hello,

How can I find out the exit code of a process when using the subprocess module? 
I am passing an email message to a shell script and I need to know whether the 
shell script threw an error.

Here is my code:
p = Popen(cmd, stdout=None, stdin=PIPE, stderr=None)
p.communicate(input=msg)

I tried something like this:
e_stat = p.communicate(input=msg)

but the value of e_stat is always '(None, None)'


-- 
Thanks & best regards,
Jason Rissler
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting the exit code of a subprocess

2021-12-15 Thread Jason
On Wed, Dec 15, 2021 at 08:19:16PM -0800, Kushal Kumaran wrote:
> On Wed, Dec 15 2021 at 09:38:48 PM, Jason  wrote:
> > Hello,
> >
> > How can I find out the exit code of a process when using the
> > subprocess module? I am passing an email message to a shell script and
> > I need to know whether the shell script threw an error.
> >
> > Here is my code:
> > p = Popen(cmd, stdout=None, stdin=PIPE, stderr=None)
> > p.communicate(input=msg)
> >
> > I tried something like this:
> > e_stat = p.communicate(input=msg)
> >
> > but the value of e_stat is always '(None, None)'
> >
> 
> You want to look at p.returncode after communicate returns:
> https://docs.python.org/3/library/subprocess.html#subprocess.Popen.returncode
> 
> https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
> returns a tuple with the stdout and stderr contents.

Thank you, that is the info I needed!

-- 
Jason Rissler

-- 
https://mail.python.org/mailman/listinfo/python-list


Struggling with basics

2005-09-25 Thread Jason
A week ago I posted a simple little hi-score routine that I was using to 
learn Python.

I've only just managed to examine the code, and the responses that 
people gave, and I'm now seriously struggling to understand why things 
aren't working correctly.

At present my code is as follows...

import random
import bisect

class HiScores:
 def __init__(self,hiScores):
 self.hiScores=[entry for entry in hiScores]

 def showScores(self):
 for score,name in self.hiScores:
 score=str(score).zfill(5)
 print "%s - %s" % name,score


 def addScore(self,score,name):
 score.zfill(5)
 bisect.insort(self.hiScores,(score,name))
 if len(self.hiScores)==6:
 self.hiScores.pop()

 def lastScore(self):
 return self.hiScores[-1][0]

def main():
 
hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')]
 

 a=HiScores(hiScores)
 print "Original Scores\n---"
 a.showScores()

 while 1:
 newScore=str(random.randint(0,1))
 if newScore  > a.lastScore():
 print "Congratulations, you scored %s " % newScore
 name=raw_input("Please enter your name :")
 a.addScore(newScore,name)
 a.showScores()

if __name__=="__main__":
 main()


My first problem (lack of understanding of course) is that if I run the 
above, I get an error saying:

 print "%s - %s" % name,score
TypeError: not enough arguments for format string

Now I understand what it's saying, but I don't understand why.

If I change the code to read:

print "%s - %n" % name, score (thinking of course that ah-ha, score is 
numeric) then I get the same error.

The only way for the program to run is to simply have

print name,score (or print score,name)


The final part that's simply not working correctly is that the entire 
program isn't sorting the data.

If I run the program and get a score of, say, 6789, then when I add my 
name, nothing is entered.  I have changed the clause that deletes (pops) 
the last array if the array count is 6 and seen what figures are being 
entered into the array.

Sure enough they are going in the array, and they are being sorted, but 
they are only being sorted AFTER the 0 of the initial array creation.

I'm pretty sure it's to do with comparing a string against an integer 
but can't for the life of me see where to force the comparrison to check 
against two integers.

Apologies for going over old ground and if I'm not understanding, I'm 
getting there honest ;)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling with basics

2005-09-25 Thread Jason
Rather than reply to those individuals, just a big "thanks" to those 
that have helped.

It's definitely making sense, the fact that I need to show the 
two-element tuple to show correctly was one of those head-slapping moments.

And Dennis Lee Bieber hit the nail on the head when he mentioned that 
I'd declared the initial scores as strings, yet I was comparing them 
against integers.  I simply removed the single-quotes from the scores 
and everything slotted into place.

Again, I now have the list working, apart from the list is reversed (as 
per Dennis Lee Bieber mentioned).  I'm afraid I don't understand what 
you mean about the DIFF report but I'll investigate further and learn a 
bit more.

Again, thanks for the assistance.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling with basics

2005-09-25 Thread Jason
Reinhold Birkenfeld wrote:
> Jason wrote:
>> Rather than reply to those individuals, just a big "thanks" to those 
>> that have helped.
>>
>> It's definitely making sense, the fact that I need to show the 
>> two-element tuple to show correctly was one of those head-slapping moments.
>>
>> And Dennis Lee Bieber hit the nail on the head when he mentioned that 
>> I'd declared the initial scores as strings, yet I was comparing them 
>> against integers.  I simply removed the single-quotes from the scores 
>> and everything slotted into place.
>>
>> Again, I now have the list working, apart from the list is reversed (as 
>> per Dennis Lee Bieber mentioned).  I'm afraid I don't understand what 
>> you mean about the DIFF report but I'll investigate further and learn a 
>> bit more.
> 
> Please bear in mind: If you just remove the quotes from '00050', you will get
> a value of 40. This is because integer literals with leading zeroes are inter-
> preted as octal.
> 
> Reinhold


Doh!

Just found that out! lol.

OK I'm going to read a bit more in the manual now; I'm determined to 
crack this nut by the morning.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling with basics

2005-09-25 Thread Jason
Tom, best explanation yet!  Entertaining as well as educational.

The "%05i" trick is very neat, must remember that one!

Everything working a charm apart from the viewScores is still returning 
the results from the lowest score (at the top) to the highest score.

What I'd like to know is do you think it would be better to sort the 
list in memory, or print it out sorted?  If the latter, then naturally 
I'd need to change the showScores section to show the list in a reverse 
order.  But, would sorting the list in memory be more effective?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling with basics

2005-09-25 Thread Jason
George Sakkis wrote:
> "Jason" <[EMAIL PROTECTED]> wrote:
> 
>> What I'd like to know is do you think it would be better to sort the
>> list in memory, or print it out sorted?  If the latter, then naturally
>> I'd need to change the showScores section to show the list in a reverse
>> order.  But, would sorting the list in memory be more effective?
> 
> The list *is* sorted; the thing is that it is in ascending order (from lowest 
> to highest) but you
> would rather have it in descending. There are (at least) two alternatives:
> 
> 1. Keep the list as it is now in ascending order and print it in reverse. In 
> python 2.4, this is as
> elegant and efficient as it can, using the reversed() builtin function. Just 
> replace in showScores
> "for score,name in self.hiScores" with "for score,name in 
> reversed(self.hiScores)". reversed()
> returns an iterator over the sequence, not a new list, so the memory overhead 
> is minimal.
> 
> 2. Instead of storing (score,name) pairs, store (-score,name). When a list of 
> the latter is in
> ascending order, the former is in descending. In this case of course, you 
> have to make sure that
> showScores() and lastScore() return the actual (positive) score, not the 
> stored (negative) one.
> 
> I would go for the first alternative but YMMV.
> 
> George
> 
> 
Thanks George, I've learned a lot tonight.

-- 
http://mail.python.org/mailman/listinfo/python-list


Plotting points to screen

2005-09-26 Thread Jason
If I'm wanting to plot points to the screen (nothing fancy at all for 
the moment), would you recommend PyGame, PyOpenGL or PIL?

Like I said, it's nothing complicated, no flashing wotsits or 3d 
quad-linear vertexes with bi-linear real-time shading, just simple 
'points' a few lines or circles and nothing more.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plotting points to screen

2005-09-26 Thread Jason
jay graves wrote:
> I've used both pygame and PIL for this in the past.  (i'm plotting a
> non-standard 3d data format from a in-house app)
> Pygame was nice because I put a key handler in to reload the file and
> do a little zooming/panning and when I wanted to save a particular plot
> I would just use a screen capture program.
> Then I upgraded my harddrive and didn't re-install PyGame. The next
> time I had to plot some data, I tweaked my script to use PIL.  I ended
> up liking this solution better.  I could easily create large images
> (bigger than physical screen which was a limiting factor in PyGame) and
> used a regular image viewer to pan and shrink/zoom.  I had the drawing
> portions of my script well separated from the data parsing and
> manipulation so tweaking the script was simple.
> 
> YMMV, but PIL was the best way for me.
> 
> ...
> jay graves
> 
Thanks Jay.

One question, that's twice in as many days that someone has said "YMMV".

What's it mean!?

-- 
http://mail.python.org/mailman/listinfo/python-list


Distributing programs

2005-10-02 Thread Jason
A non-python programming friend of mine has said that any programs made 
with Python must be distributed with, or an alternative link, to the 
source of the program.

Is this true?

-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython date

2005-07-18 Thread Jason
How do I form a new wxPython date using day, month and year?

I've tried the wx.DateTimeFromDMY but it crashes in Pythonwin when I
test it out and I get all manner of complaints when I try it from the
command line.

Surely there's an equivalent to the python datetime.date(2005,07,18)

thanks,

jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython date

2005-07-18 Thread Jason
Thanks, Peter.

I must have been having a bit of the stupids, your example worked fine
for me too.

Back to the salt mines!

-- 
http://mail.python.org/mailman/listinfo/python-list


Python CGI and Firefox vs IE

2005-09-07 Thread Jason
Hey y'all, this falls under the murky realm of HTML, CGI and
Python...and IE.

Python 2.4, using CGI to process a form.

Basically I've got 3 buttons.  Here's the HTML code:


All
Servers
WKPEA1
WKNHA2



And the code that's messing things up:

fields = cgi.FieldStorage()

if fields.has_key('display'):
print fields['display']
which_server,which_display = fields['display'].value.split(',')
if which_server == 'all':
which_server = servers
else:
which_server = [which_server]


This program works fine under firefox.  If, say, you clicked on the 1st
button, All Servers, you'd get this returned in the field['display']
variable

MiniFieldStorage('display', 'all,status')



Under Internet Explorer, this is what I get in field['display']:

[MiniFieldStorage('display', 'All Servers'),
MiniFieldStorage('display', 'WKPEA1'), MiniFieldStorage('display',
'WKNHA2')]




I see what's happening, but I'm at a loss to figure out what to do
about it.  Any help would be appreciated.

thanks,

jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python CGI and Firefox vs IE

2005-09-07 Thread Jason
IE...

Have to come up with a workaround, go back to the old .  I'm
about the only one who uses firefox in our facility.

Thanks for the reply and the link.

-- 
http://mail.python.org/mailman/listinfo/python-list


Can someone explain what I've done wrong...

2005-09-17 Thread Jason
Hi,

I'm following a tutorial about classes, and have created the following 
(well, copied it from the manual buy added my own and wifes names)...

class Person:
 population=0

 def __init__(self,name):
 self.name=name
 print '(Initialising %s)' % self.name
 Person.population += 1

 def __del__(self):
 print "%s says bye." % self.name

 Person.population -= 1

 if Person.population == 0:
 print "I am the last one"
 else:
 print "There are still %d people left." % Person.population

 def sayHi(self):
 '''Greeting by the person.

 That's all it does.'''
 print "Hi, my name is %s" % self.name

 def howMany(self):
 if Person.population==1:
 print "I am on the only person here."
 else:
 print "We have %d persons here." % Person.population

Jason=Person("Jason")
Jason.sayHi()
Jason.howMany()

Sophie=Person("Sophie")
Sophie.sayHi()
Sophie.howMany()

Jason.sayHi()

The code, when run, should produce the following...

Hi, my name is Jason.
I am the only person here.
(Initializing Sophie)
Hi, my name is Sophie.
We have 2 persons here.
Hi, my name is Jason.
We have 2 persons here.
Jason says bye.
There are still 1 people left.
Sophie says bye.
I am the last one.

But what I actually get is...

(Initialising Jason)
Hi, my name is Jason
I am on the only person here.
(Initialising Sophie)
Hi, my name is Sophie
We have 2 persons here.
Hi, my name is Jason
We have 2 persons here.
Jason says bye.
There are still 1 people left.
Sophie says bye.
Exception exceptions.AttributeError: "'NoneType' object has no attribute 
'popula
tion'" in > ignored

I've looked through the code but can't find anything obvious.

I also want to apologise if this isn't the write newsgroup to post on, 
but it's the only one I know of.  IF anyone knows a good newsgroup, I'd 
appreciate it.

TIA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone explain what I've done wrong...

2005-09-17 Thread Jason
Thanks for the explanation JP Calderone.

Have to say, I was confused with the post (I received via email, can't 
see it on the newsgroup yet) from Astan Chee saying he couldn't 
understand how the Person class was destroyed.  I'm still new(ish) with 
Python but I was lead to believe the __del__ call was pretty reliable. 
Thanks for the heads up on that.

Thanks again.

-- 
http://mail.python.org/mailman/listinfo/python-list


How am I doing?

2005-09-18 Thread Jason
Please don't laugh, this is my FIRST Python script where I haven't 
looked at the manual for help...

import string
import random

class hiScores:
 
hiScores=['1Alpha','07500Beta','05000Gamma','02500Delta','0Epsilon']

 def showScores(self):
 for entry in self.hiScores:
 print entry[0:5]," - ",entry[5:]

 def addScore(self,score,name):
 newScore=string.zfill(score,5)
 self.hiScores.append(newScore+name)
 self.hiScores.sort(reverse=True)

 if len(self.hiScores)==6:
 del self.hiScores[-1]

a=hiScores()
print "Original Scores\n---"
a.showScores()

while 1:
 newScore=random.randint(0,1)
 if string.zfill(newScore,5)>a.hiScores[4][0:5]:
 print "Congratulations, you scored %d " % newScore
 name=raw_input("Please enter your name :")
 a.addScore(newScore,name)
 a.showScores()
 continue

Anything I could have done differently or any "bad-habits" you think I 
have which could lead to ultimate doom I really appreciate to know.

TIA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How am I doing?

2005-09-18 Thread Jason
George Sakkis wrote:
> "Jason" <[EMAIL PROTECTED]> wrote:
> 
>> Please don't laugh, this is my FIRST Python script where I haven't
>> looked at the manual for help...
> 
> Sooner or later you should ;)
> 
>> import string
> 
> Don't need it it modern python; use string methods instead.
> 
>> import random
>>
>> class hiScores:
> 
> The common convention is to use Capitalized words for classes, e.g.
> HiScores.
> 
>> hiScores=['1Alpha','07500Beta','05000Gamma','02500Delta','0Epsilon']
> 
> hiScores should better be given as parameter when an instance is made,
> not hardcoded as a class instance. Also, it is better to separate the
> score from the name. Then hiScores can be, say, a list of (score,name)
> tuples, e.g. [('1', 'Alpha'), ('07500', 'Beta'), ..., ('0',
> 'Epsilon')]:
> 
> def __init__(self, hiScores):
> self.hiScores = [(entry[:5], entry[5:]) for entry in hiScores]
> 
>>  def showScores(self):
>>  for entry in self.hiScores:
>>  print entry[0:5]," - ",entry[5:]
> 
> If you separate the score from the name in the constructor, you don't
> have to split the entries every time showScores is called:
> def showScores(self):
>   for score,name in self.hiScores:
>   print score, " - ", name
> 
> You can express the same more compactly using string interpolation:
> def showScores(self):
>   for entry in self.hiScores:
>   print "%s - %s" % entry
> 
>>  def addScore(self,score,name):
>>  newScore=string.zfill(score,5)
>>  self.hiScores.append(newScore+name)
>>  self.hiScores.sort(reverse=True)
> 
> If you add one entry at a time, it is more efficient to keep the list
> sorted and use the bisect.insort function instead of sorting the whole
> list:
> 
> bisect.insort(self.hiScores, (newScore,name))
> 
>>  if len(self.hiScores)==6:
> 
> With your given hiScores, this test is useless; you started with 5
> entries and added one so you know there are 6 now. In the more general
> case, sort the initial hiScores in the constructor and take the top 5
> entries.
> 
>>  del self.hiScores[-1]
> 
> You can also remove the last element of a list by self.hiScores.pop()
> 
>> a=hiScores()
>> print "Original Scores\n---"
>> a.showScores()
>>
>> while 1:
>>  newScore=random.randint(0,1)
>>  if string.zfill(newScore,5)>a.hiScores[4][0:5]:
> 
> Two things:
> - string.zfill(newScore,5) is better written as newScore.zfill(5)
> - a.hiScores[4][0:5] is cryptic; it is better to write a method to give
> you the last score so that you can spell it as a.lastScore():
> 
> def lastScore(self):
> return a.hiScores[-1][0] # assuming (score,name) entries
> 
>>  print "Congratulations, you scored %d " % newScore
>>  name=raw_input("Please enter your name :")
>>  a.addScore(newScore,name)
>>  a.showScores()
>>  continue
> 
> "continue" doesn't do anything at the line you put it. When do you want
> your program to exit ? As it is, it will loop forever.
> 
>> Anything I could have done differently or any "bad-habits" you think I
>> have which could lead to ultimate doom I really appreciate to know.
>>
>> TIA
> 
> HTH,
> George
> 
LOL - O dear!!

Well I can certainly see a lot of better methods that you've pointed out 
George.  For one thing, I was 'wanting' to go down the tuples or 
dictionary mode but was under the impression you couldn't sort them 
directly.  From what I understand, you can't, but the example you have 
shown clearly makes sense and a hell-of-alot more practical.

Never knew about the Pop command!!

Thanks again for the help though, really appreciate it.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How am I doing?

2005-09-19 Thread Jason
I've restructured my code with the assistance of George and Mike which 
is now as follows...

import random

class HiScores:
 def __init__(self,hiScores):
 self.hiScores=[(entry[:5],entry[5:]) for entry in hiScores]

 def showScores(self):
 for name,score in self.hiScores:
 print "%s - %s" % name,score

 def addScore(self,score,name):
 score.zfill(5)
 bisect.insort(self.hiScores,(score,name))
 if len(self.hiScores)==6:
 self.hiScores.pop()

 def lastScore(self):
 return self.hiScores[-1][0]

def main():
 
hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')]
 

 a=HiScores(hiScores)
 print "Original Scores\n---"
 a.showScores()

 while 1:
 newScore=random.randint(0,1)
 if newScore.zfill(5) > a.lastScore():
 print "Congratulations, you scored %d " % newScore
 name=raw_input("Please enter your name :")
 a.addScore(newScore,name)
 a.showScores()

if __name__=="__main__":
 main()


However doing like the above (which DOES make sense now) raises a few 
questions that I've been struggling to find answers for over several 
hours now.

1) The most important is that when run, the program crashes with

Traceback (most recent call last):
   File "D:\My Documents\Development\Python\highscore1.py", line 35, in 
-toplevel-
 main()
   File "D:\My Documents\Development\Python\highscore1.py", line 28, in main
 if newScore.zfill(5) > a.lastScore():
AttributeError: 'int' object has no attribute 'zfill'

I've read as many websites as I can about zfill and I can't see why on 
earth it's failing.

2) The output of the predefined hiscores is now...

1 - Alpha ()
07500 - Beta ()
05000 - Gamma ()
02500 - Delta ()
0 - Epsilon ()

Why are there the pairing parenthesis there?  George very kindly showed 
me another way which was to have...

def showScores(self):
   for entry in self.hiScores:
   print entry[0:5]," - ",entry[5:]

But using that method output the entire list in it's full format (sorry 
if that's not the correct terminology).  But give me a small plus mark 
for changing code and not simply copying George :)

3) The hardest thing to 'understand' is the line...
self.hiScores=[(entry[:5],entry[5:]) for entry in hiScores]

I 'understand' what it's doing, but I don't quite comprehend what the :5 
and 5: do.  I know that the :5 is technically saying from the start to 
position 5, and likewise the 5: would say from position 5 onwards, but I 
just can't get my head around how this works.

TIA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How am I doing?

2005-09-20 Thread Jason
Tom Anderson wrote:
> On Mon, 19 Sep 2005, Brett Hoerner wrote:
> 
>> Wouldn't the standard idiom be to actually put the code under the 
>> if-name, and not make a whole new main() function?
> 
> Yes.
> 
> The nice thing about the main() function, though, is that you can do the 
> most basic argument parsing in the if-block. Like so:
> 
> def powers(n):
>   m = 1
>   while True:
>   yield m
>   m = m * n
> 
> def main(n, limit):
>   for power in powers(n):
>   if (power > limit): break
>   print power
> 
> import sys
> 
> if (__name__ == "__main__"):
>   main(int(sys.argv[1]), int(sys.argv[2]))
> 
> That serves as a sort of documentation on the arguments to the script, and 
> also makes it easier for other scripts to reuse the main logic of the 
> program, since they don't have to package parameters up as a string array. 
> It is more verbose, though.
> 
>> I'm not sure I see the reason behind main(), couldn't that also 
>> interfere with other modules since main() seems like it might be common, 
>> not sure how it would work as I'm pretty new to Python myself.
> 
> The two mains would be in different namespaces, so they wouldn't conflict.
> 
>> from script import *
> 
> Don't do that. 'from script import x' is, IMNERHO, bad practice, and 'from 
> script import *' is exceptionally bad practice. I know a lot of people do, 
> but that doesn't make it right; namespaces are there for a reason.
> 
> tom
> 

I haven't a clue what all this means, but it looks important ! lol

Thanks for the headsup, will take note of what you've said.

Incidentally, at work my main programming platform is VisualStudio .Net, 
and I never import the children of namespaces so hopefully this practice 
I have will be carried over to Python.

-- 
http://mail.python.org/mailman/listinfo/python-list


Calling a derived class's constructor from a parent method

2015-01-14 Thread jason
If I have a class hierarchy like so:

 
class A(object):
  def __init__(self, s):
self.s = s
  def foo(self, s):
return A(s)

class B(A):
  def __init__(self, s):
A.__init__(self, s)

If I make a B:

b = B(0)

I'd like b.foo(1) to return an instance of B. Is there a way to do that besides 
implementing a construct(self, s) for each part of the hierarchy? I.e. is there 
a way for the base class to look at self and find out what type to create?

I'm using Python 2.7.5, but I'm curious what the 3.x answer is too.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Calling a derived class's constructor from a parent method

2015-01-14 Thread jason
On Wednesday, January 14, 2015 at 12:05:55 PM UTC-5, Mark Lawrence wrote:
 
> I'm confused, can you please explain what you're trying to achieve 
> rather than how you're trying to achieve it and I'm sure that others 
> will give better answers than I can :)
> 

Good call. Coming up with a minimal example make things pretty far out of 
context.

The base class represents a generic function (in formal logic) with some name 
and a list of parameters. The derived class is some sort of specialization of 
that generic class (like associative functions, etc).

It is desirable to do certain things to these functions, like perform 
substitution or canonization, that can be implemented in the basic class but 
which I'd like to return as a copy rather than modify the class. Thus, the base 
class needs to know which derived class (if any) to create.

The burden is indeed on me to keep the signature of the init() for each of 
these the same. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: do people really complain about significant whitespace?

2006-08-07 Thread Jason
infidel wrote:
> Where are they-who-hate-us-for-our-whitespace?  Are "they" really that
> stupid/petty?  Are "they" really out there at all?  "They" almost sound
> like a mythical caste of tasteless heathens that "we" have invented.
> It just sounds like so much trivial nitpickery that it's hard to
> believe it's as common as we've come to believe.

I have a coworker who dislikes Python for the whitespace.  He likes the
idea that if someone is silly enough to put a whole program on one
line, they can put it back together by following the braces.  He also
likes that the compiler can compile the program even if a normal person
can't read it.

I've pointed out that we format our code with the whitespace anyway.
He points out that if some code gets accidentally dedented, it is
difficult for another programmer to determine which lines were supposed
to be in the indented block.  I pointed out that if someone
accidentally moves a curly brace, the same problem can occur.
Anecdotally, I've never had either problem.

Sadly, people who do dislike the whitespace do exist.  I have also
talked with several other programmers who were very turned off about
the white-space thing and wouldn't give the language a chance.

Eric S. Raymond wrote enthusiastically about Python, but was initially
turned off by the whitespace rules.  (See
"http://www.python.org/about/success/esr/"; for details.)

I personally love that my logically formatted code imparts information
logically to the language.

(I haven't seen a good hate-us-for-our-whitespace thread go on for
awhile.  I do remember some good "We like Python, Now Add Our Favorite
C/C++/LISP/INTERCAL Features or We'll Leave" threads on this newsgroup.)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do people really complain about significant whitespace?

2006-08-07 Thread Jason
[EMAIL PROTECTED] wrote:
> Jason wrote:
> > He points out that if some code gets accidentally dedented, it is
> > difficult for another programmer to determine which lines were supposed
> > to be in the indented block.  I pointed out that if someone
> > accidentally moves a curly brace, the same problem can occur.
>
> I like significant whitespace, but a forum, newsgroup manager (like
> Google Groups in the beginning), email management program, blog comment
> system, etc, may strip leading whitespace, and it usually doesn't
> "move" braces. A language (like Python) doesn't exist alone in vacuum,
> it exists in an ecosystem of many other programs/systems, and if they
> don't manage leading whitespace well, such language may have some
> problems :-)
>
> Bye,
> bearophile

Certainly, you are correct.  Most of the time, I zip up any source code
for email purposes.  But newsgroup managers are certainly an issue.
For comment thingies online, the preformat tag is your friend, too.

It is annoying that certain communication channels do not respect
white-space.  I dislike using braces because I have to indicate my
intentions twice: once for the compiler and once for humans.

In the situations where I use Python, though, I haven't had a problem.
In the situations where my coworker is using Python (code updates
through CVS), he also shouldn't have a problem.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newb question: file searching

2006-08-08 Thread Jason

[EMAIL PROTECTED] wrote:
> Mike Kent wrote:
> > What you want is os.walk().
> >
> > http://www.python.org/doc/current/lib/os-file-dir.html
>
> I'm thinking os.walk() could definitely be a big part of my solution,
> but I need a little for info.  If I'm reading this correctly, os.walk()
> just goes file by file and serves it up for your script to decide what
> to do with each one.  Is that right?  So, for each file it found, I'd
> have to decide if it met the criteria of the filetype I'm searching for
> and then add that info to whatever datatype I want to make a little
> list for myself?  Am I being coherent?
>
> Something like:
>
> for files in os.walk(top, topdown=False):
> for name in files:
>  (do whatever to decide if criteria is met, etc.)
>
> Does this look correct?

Not completely.  According to the documentation, os.walk returns a
tuple:
  (directory, subdirectories, files)
So the files you want are in the third element of the tuple.

You can use the fnmatch module to find the names that match your
filename pattern.

You'll want to do something like this:

>>> for (dir, subdirs, files) in os.walk('.'):
...  for cppFile in fnmatch.filter(files, '*.cpp'):
...   print cppFile
...
ActiveX Test.cpp
ActiveX TestDoc.cpp
ActiveX TestView.cpp
MainFrm.cpp
StdAfx.cpp
>>>

Please note that your results will vary, of course.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Python-- Help

2006-08-08 Thread Jason
John & Mary Cook wrote:
> I just installed Python on Windows XP Pro.  When I enter 'python' at the >>>
> prompt in Pythonwin IDE I get the following:
>
> Traceback (most recent call last):
>File "", line 1, in ?
> Name Error: name 'python' is not defined
>
> Can anyone help?
>
> Thank you,
>
> J. T. Cook

That's because the Pythonwin IDE with the >>> prompt is already running
the Python interpreter.  The Python interpreter allows you to run
python statements and expressions with instant feedback.

Python doesn't define the 'python' name inside of itself.

I recommend that you read through the Python tutorial, and maybe do a
Google search for Python tutorials.

When you next see the >>> prompt, try typing in the following:
import this
print ' '.join( ('Python', 'rocks!') )

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] John Salerno

2006-08-12 Thread jason
John Salerno wrote:
> Alan Connor wrote:
> 
>> Almost certainly bogus. I wouldn't believe anything in this
>> fellow's headers or articles.
>>
>> TROLL.
>> I don't help trolls.
> 
> 
> Ok, I don't know how seriously to take this post, so I won't spend much 
> time addressing it. All I will say is yes, this is really me and I am 
> asking a genuine question.

Basically just killfile alan connor. It will greatly improve the signal 
to noise ratio here. He's one of usenets most pathetic and whinest trolls.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] John Salerno

2006-08-13 Thread jason
Alan Connor wrote:

> Looks like pretty much all trolls to me. 
> 
> Note: I won't be downloading any articles on this thread.
> 
> Alan
> 

Funny how you keep saying that but keep downloading and responding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble understanding inheritance...

2006-08-17 Thread Jason
KraftDiner wrote:
> c = [a, b]
> for c in [a,b]:
>c.getName()
>
> but when does baseClass ever get used?
> Why did i even have to define it?
>

One reason for using base classes are for logical reasons.  Oranges and
Apples are different, but they are both fruits.  Python has both
unicode strings and 8-bit ASCII strings.  Both are strings and share a
common base class: the 'basestring' class.

A second reason is for code sharing.  Let's say Python's string class
does everything you want already... except for one little thing.  You
want the split method to return a list with some extra information.
Why re-invent the wheel trying to implement the other string methods
when you can reuse everything that's already been done?

>>> class MyString(str):
...   def split(self):
... "Perform some extra work this version of split"
... wordList = str.split(self)  # Call the original method
... return ['Extra'] + wordList + ['Information']  # Do additional
work!
...
>>>

In Python, we often rely on duck typing.  "If it looks like a duck,
quacks like a duck, it's a duck."  If we can treat it like a string, we
can consider it a string.  If we can't treat it like a string, Python
will let us know by raising an exception.  We can catch this exception
and try something different, or let the exception stop the program and
let the user know something went wrong.

Duck typing allows us to re-use code very efficiently.  I'll
demonstrate it with a function and the class defined above.

>>> def GetWords(stringValue):
...   "Print the list of words in a string"
...   print 'Words are: %s' % stringValue.split()
...
>>> stringValue = str('Hello, world!')
>>> unicodeValue = unicode('These are different strings')
>>> myStringValue = MyString('good, hopefully useful')
>>>
>>> GetWords(stringValue)
Words are: ['Hello,', 'world!']
>>> GetWords(unicodeValue)
Words are: [u'These', u'are', u'different', u'strings']
>>> GetWords(myStringValue)
Words are: ['Extra', 'good,', 'hopefully', 'useful', 'Information']
>>>

As shown above, the GetWords() function works fine with my new string
class.  Any methods that I didn't redefine keep their old behavior.
For example, I didn't define the upper() method in MyString, but I can
still use it:

>>> stringValue.upper()
'HELLO, WORLD!'
>>> myStringValue.upper()
'GOOD, HOPEFULLY USEFUL'
>>>

While we rely on duck typing in Python, we occassionally want special
behavior for certain types of data.  Currently, you can pass anything
into the GetWords() function that has a method named 'split'.  It does
not have to be a string:

>>> class NotAString(object):
...   def split(self):
... return 'I am not a string!'
...
>>> otherDataValue = NotAString()
>>> GetWords(otherDataValue)
Words are: I am not a string!
>>>

Sometimes, we want some specialized behavior.  Lists, tuples, and
strings all act like sequences (meaning, you can get their length and
use them in for-loops).  Often, though, you'll want to treat strings
differently.  You can check the type directly, or you can check by
using the isinstance() built-in function.  isinstance() checks to see
if a variable is an instance of a class or any of its subclasses.

Remember the first reason given, of using a base class to logically
organize other classes?  This is it in practice.  I'll demonstrate
below:

>>> def CheckOnlyBuiltinStrings(stringValue):
...   "Tells us whether or not stringValue is a str or unicode string."
...   if type(stringValue) is str  or  type(stringValue) is unicode:
... print 'A built-in string type: %s' % stringValue
...   else:
... print 'Not a built-in string type: %s' % stringValue
...
>>> def CheckAllStrings(stringValue):
...   "Tells us whether or not stringValue is a string."
...   # The basestring class is a superclass for all string classes.
...   if isinstance(stringValue, basestring):
... print 'Is a string: %s' % stringValue
...   else:
... print 'Not a string: %s' % stringValue
...
>>> CheckOnlyBuiltinStrings(stringValue)
A built-in string type: Hello, world!
>>> CheckOnlyBuiltinStrings(unicodeValue)
A built-in string type: These are different strings
>>> CheckOnlyBuiltinStrings(myStringValue)
Not a built-in string type: good, hopefully useful
>>>
>>> CheckAllStrings(stringValue)
Is a string: Hello, world!
>>> CheckAllStrings(unicodeValue)
Is a string: These are different strings
>>> CheckAllStrings(myStringValue)
Is a string: good, hopefully useful
>>> CheckAllStrings(42)
Not a string: 42
>>>

How do you know when you should use type() checks, when you should use
isinstance(), and when you should just try to use the data?  That
depends, and there have been many lively debates on this subject in the
newsgroup.  I recommend that you should only use as much type checking
as needed, and the less is better.

A bit long, but I hope this helps you out.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python wrapper for C++ core

2006-10-17 Thread Jason
[EMAIL PROTECTED] wrote:
> Hi All
>
> Apologies in advance for the pretty basic question - but I can't seem
> to find an answer anywhere else.
>
> I am developing a fluid sim in C++ and have heard that many people use
> Python in conjunction with C++ for this sort of thing (especially in
> games dev).
>
> What I can't understand why you would want to do this. Obviously the
> core would be written in C++ (for my purposes anyway) so what parts
> would be written in Python? What is the benefit, in this situation, of
> using Python instead of C++?
>
> thanks for your help
>
> Holly

What would be the advantages?  Let's see if I can knock it down for
you.

You didn't give any information about your fluid simulation other than
you are developing it in C++.  Whether or not you'd want to expose your
fluid sim objects to Python depends on your purposes.  If you code the
main fluid engine in C++ and expose it in Python, you might be able to:

  1) Easily run your fluid simulation over a variety of parameters.
Vary the equation constants so you can see how the simulation works
with water, rubbing alcohol, air, and molasses.

  2) Perform statistical analysis of your results.  Use one of the
various statistical packages to examine the results.  Use the CSV
module to save out an Excel-compatible set of results, or use the Win32
modules to start up Excel and populate a spreadsheet.

  3) Use Python to set up the specific physical layout for the fluid
simulation.  For a 2D fluid simulation, you might want to set up a
specific set of walls.  You can do that automatically, or use your own
custom file format and let Python deal with parsing it.

  4) Use Python to load models from different file formats into the
simulation.  For 3D fluid simulations, you'd most likely use CAD
generated models.  Create a basic C++/Python class for models that can
load triangles into the simulation.  For each format that you support,
use or write a Python class, derived from the basic model class, that
can parse that format and put the triangles into the model using the
superclass.  If the file format is text-based, Python's excellent
string manipulation can help out here.

  5)  Use Python to allow the user to "react" to certain conditions and
events during the simulation.  Perhaps the model changes in one
simulation at a given time (as a valve opens or closes).  Perhaps if
the model reaches a stable equilibrium, you'd like to end the
simulation so you don't need to know exactly when to end the
simulation.

  6) Give your users the ability to perform any of the above.

What Python can give you is flexibility.  Whether or not this is useful
for you depends entirely on the goals of your program, and the design
of your program.  I'm sure there are other things Python can do for
you, but you'll need to figure them out (or post more information about
your program).

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Accessing ClarifyCRM with Python

2006-10-27 Thread Jason
I need to embed the ability to create a Clarify Case in a python
program I have written.  Unfortunately my familiarity with Clarify is
very limited at this point.

Is there a module out there that makes this process semi-painless?  I
couldn't find one googling around...  Has anyone implemented something
like this?  Care to give a few pointers?

I do know that another part of the business has a perl script that can
generate a Clarify case. I'm chasing down that example as well, but I
don't have it in hand at this point.  So I know that this is
possible... I just don't know how much work it will be.

Any pointers would be greatly appreciated.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: create global variables?

2006-10-30 Thread Jason

Alistair King wrote:
> have tried:
>
> def monoVarcalc(atom):
> a = atom + 'aa'
> Xaa = a.strip('\'')
> m = atom + 'ma'
> Xma = m.strip('\'')
> global Xma
> global Xaa
> Xaa = DS1v.get(atom)
> Xma = pt.get(atom)
> print Xma
> print Xaa
>
> monoVarcalc('C')
>
> print Caa
> print Cma
> ...
>
> where global Xma & Xaa are before and after any further functions
>
> i get still get the error
>
> Traceback (most recent call last):
>   File "DS1excessH2O.py", line 54, in ?
> print Caa
> NameError: name 'Caa' is not defined

Mr King, please look at the documentation for the global keyword.  You
can either see it at "http://docs.python.org/ref/global.html#l2h-564";.
You can also access information about it using Python's help function
(use "help('global')" to see its help).

The global statement makes the names that follow available globally.
It does *not* evaluate the name in any way.  If you have "global Xma"
in your code as above, the name Xma becomes a global name.  That name
happens to contain the string value "Caa" in it.  The local name "Caa"
is not placed into the global name-space because you didn't put it into
the global statement.

Heck, I don't see that you have a local variable with the name "Caa".
You have three local variables and two global variables in the
monoVarcalc function:
  -- "atom" is the name of the parameter to the function.  The name is
only local to the function.
  -- "a" and "m" are local variables in the function.  They are the
result of adding strings to atom.
  -- "Xaa" and "Xma" are global names.  They are assigned values from
the local variables "m" and "a".  You then overwrite their values with
the global object DSv1's and pt's get methods.

As others have shown, you can use the dictionary-like object returned
by the globals() function to place arbitrary names into the global
namespace.

However, I highly recommend that you review your algorithms.  I
generally find that programs designed with many globals is a sign that
the program is badly designed.  I also recommend that you resolve any
syntax warnings that your program may be generating (hint: relocate
your global statement to the top of your function).

Your program could probably benefit from a number of things that Python
does well:

  -- Python has very efficient dictionaries.  Dictionaries allow you to
easily pass around things like your values in the above program.

  -- Python makes it trivial to return multiple values.  If you simply
need to return more than one value from the function, just return a
tuple.

  -- Python's object-oriented programming model and nested name-spaces
are pretty easy to use.  If you are unfamiliar with object-oriented
programming, there are a number of tutorials out there that can help.
You don't need to use objects with Python, but there are many cases
where they will "obviously" work far better than ugly procedural-level
hacks.  (By obviously, I mean that it will be pretty easy to understand
exactly what you did later on.)

Python's website has a tutorial section
(http://www.python.org/doc/Intros.html) and many people recommend the
"Dive Into Python" tutorial series (http://www.diveintopython.org/).
Do a google search for "Python tutorials" for more information.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Singleton Class Exception

2006-11-13 Thread Jason
dischdennis wrote:
> Hello List,
>
> I would like to make a singleton class in python 2.4.3, I found this
> pattern in the web:
>
> class Singleton:
> __single = None
> def __init__( self ):
> if Singleton.__single:
> raise Singleton.__single
> Singleton.__single = self
>
>
> the line "raise Singleton.__single" invokes in my class the following
> error:
>
> exceptions must be classes, instances, or strings (deprecated), not
> PurchaseRequisitionController
>
>
>
> Greetings, Dennis

The problem is that you yoinked a bad example of a singleton.  The
error is correct, only exceptions derived from the Exception class and
strings are supported.  (Strings are supported for historical usage,
and a deprecated.)

Why exactly do you need a singleton?  Do you want only one instance of
a class?  Often, you really want something that shares state: all are
one.  This pattern is known as a borg.  Please see
"http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531"; to see
how the Borg Pattern works.

If you absolutely gotta have a singleton, there are other ways of
implementing it.  I can think of only one reason: You want the
singleton's destructor to be called only if there are no remaining
instances in existance.  (For the Borg pattern, the deconstructor can
be called once per instance created.)

The problem with this reason is that Python doesn't guarantee when the
destructors will be called for instances (and some instances will never
have their destructors called).  Although C-Python implements usually
destroys an instance when its ref-count drops to 0, IronPython and
Jython may do things very differently.  (I have no experience with
either of those, so I cannot tell you how they differ.)

Still, if you're dead set on a Singleton class, I'll post one in a
little bit.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Singleton Class Exception

2006-11-13 Thread Jason
I threw together two different singleton classes.  They both ensure
that the initializers and destructors can be called at most once.  (The
ImmortalSingleton won't ever have its destructor called unless the
programmer manually forces things.)

I haven't extensively tested these things, so handle this code like a
rabid wildebeest.  Observe that Python may not call your destructors
when you expect.  IAnd again, you probably want the Borg pattern.

Still, this was an interesting exercise to do.

--- Code Starts ---
class MortalSingleton(object):
"""This class implements a 'mortal' singleton pattern.  Classes
derived
from this class cannot be directly instantiated or take arguments in
their
initializers.

The GetSingleton() class method returns a reference to a single
instance,
or creates a single instance as needed.

This class only keeps a weak reference to the single instance.  This
means
that, if all hard references are destroyed, the instance can be
destroyed
by Python (and the __del__ method *could* be called, depending on
implementation).  Thus, the single-ton is mortal.

This could be used as a mix-in class, assuming that the other classes
do not over-ride the __new__() method (which prevents willy-nilly
instantiation).

Note that if you need all instances to share state, you probably want
to use the Borg pattern.

Comments on this travesty are appreciated.  *grin*
"""
def __new__(cls, *args, **keyargs):
# Raise a run-time error preventing direct instantiation
raise RuntimeError(
'Do not instantiate %s directly.  Use the
%s.GetSingleton()'
'class method.' % (cls.__name__, cls.__name__)
)

@classmethod
def GetSingleton(cls):
from weakref import ref

retObject = getattr(cls, '_instance', lambda : None)()
if retObject is None:
# Create a new object with the given class
retObject = object.__new__(cls)

# The initializer must be manually called in this case
retObject.__init__()
cls._instance = ref(retObject)
return retObject

class ImmortalSingleton(object):
"""This class implements a classic 'immortal' singleton pattern.
Classes derived from this class will allow only one instance to exist.

Since the class caches a hard reference to the single pattern, it
doesn't die unless the programmer gets rid of all references and
manually
deletes the cache reference.

Note that you probably want to use a variant of the Borg class rather
than
this."""
def __new__(cls, *args, **keyargs):
# Raise a run-time error preventing direct instantiation

raise RuntimeError(
'Do not instantiate %s directly.  Use the
%s.GetSingleton()'
'class method.' % (cls.__name__, cls.__name__)
)

@classmethod
def GetSingleton(cls):
retObject = getattr(cls, '_instance', lambda : None)()
if retObject is None:
# Create a new object with the given class
retObject = object.__new__(cls)

# The initializer must be manually called in this case
retObject.__init__()
cls._instance = retObject
return retObject

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what are you using python language for?

2006-06-07 Thread Jason
I've been working on an RPG character generator for consistent (yet
varied) set of role-playing systems.  Nothing like a pen-and-pencil RPG
to throw in tons of special cases and strange rulesets.

Python's turned out to be very useful for this project:

1. Fast prototyping and testing.  I'm not starting the GUI until after
I get all the quirks of the rule-set down first.  Naturally, I've got a
python script which sets up a subset of the rules, then a series of
unit tests which operate on the partially constructed RPG.

2. Dynamic typing.  The cost object for a Character Gift can vary
dramatically in behavior.  Being able to dynamically re-assign the
current cost object to a different cost type is very nice.  (The cost
types are pretty much similar in data, but their methods act
differently.)

3. Joyous object serialization via the pickle protocol.  While I'm
using the Gnosis XML pickler, there's always the default picklers, too.

While not part of Python, the platform-agnostic ruleset should be a
bonus.  If someone doesn't like my wxPython front-end, then they can go
through the trouble of re-implementing it in their favorite system, be
it .NET and IronPython or Python/TK.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python with Eclipse

2006-06-20 Thread Jason
PyDev Eclipse keeps around the python interpreter unless it gets
removed.  I think part of the point is to keep around failed runs so
the user can investigate the stack.  Eclipse doesn't keep this around
if you Run you script, but it will keep the interpreter alive if you
Debug your script, regardless of how it exits.  (It may dispose of the
interpreter if your program exits with a normal error code.)

Anyway, in the Debug View, you can see a list of all the python
interpreters that PyDev and Eclipse are keeping alive.  There's a set
of debugging-related buttons just above: step into, step over, step
return, continue, and others.

One of the buttons there looks like a couple of "X" symbols.  This
button officially shuts down a python interpreter.  (Be careful and
don't actually click the "X" symbol that closes the debug area!)

  --Jason

Stan Cook wrote:
> I've been trying to use Eclipse with Python on Linux for a
> while and have noticed something odd.  After running the
> code or debugging a few times, its responsiveness gets
> really bad.  Upon checking the equivalent of the task
> manager, I find several instances of Python running.  When I
> kill these instances, the responsiveness comes back.  I'm
> not sure if there is a better place to post this, but it is
> Python related.  Is this just an issue with Eclipse or is
> there something else I should inspect?
> 
> Any help would be appreciated.
> 
> Regards,
> 
> S Cook

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error with string (beginner)

2006-06-25 Thread Jason
I believe what you are trying to do is something like the following.

[code]
def isIntLike(x):
try:int(x)
except: return False
else:   return True

something = raw_input("Enter something and I will tell you the type: ")

if isIntLike(something):print "I am an int"
elif isinstance(something, type('')):   print "I am a string"
else:   print "I am an impostor!"
[/code]

Note that you should be using raw_input() rather than input().  The
former always returns a string.  The latter tries to execute the input,
hence your error message.

Also note that everything input on the command line is a string,
regardless of what you type.  If you want type checking, use C++ or
java.  If you want to check for anything more than IntLike strings, you
should consider using regular expressions through the 're' package.
For user-defined types, use 'isinstance(something, class object)' to
check for a type.

Lastly, you may be interested in the 'getopt' module, which handles
command line arguments (as opposed to prompting user for input)
automatically.   See here:
http://python.active-venture.com/lib/module-getopt.html

Check out the Python Cookbook for lots of good examples:
http://aspn.activestate.com/ASPN/Cookbook/Python

HTH,

Jay



Alex Pavluck wrote:
> Hello. I get the following error with the following code.  Is there
> something wrong with my Python installation?
>
> code:
> import types
> something = input("Enter something and I will tell you the type: ")
>
> if type(something) is types.IntType:
> print "you entered an integer"
> elif type(something) is types.StringType:
> print "you entered a string"
> 
> error:
> String: Source for exec/eval is unavailable

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that modifies a string

2006-07-09 Thread Jason
greenflame wrote:
> I want to make a function that does the following. I will call it
> thefunc for short.
>
> >>> s = "Char"
> >>> thefunc(s)
> >>> s
> '||Char>>'
>
> I tried the following
>
> def thefunc(s):
> s = "||" + s + ">>"
>
> The problem is that if I look at the string after I apply the function
> to it, it is not modified. I realized that I am having issues with the
> scope of the variables. The string in the function, s, is local to the
> function and thus I am not changing the string that was inputed, but a
> copy. I cannot seem to figure out how to get what I want done. Thank
> you for your time.

You cannot do what you are trying to do directly.  Strings are
immutable objects.  Once a string is created, that string cannot be
modified.  When you operate on a string, you produce a different
string.  Functions which operate on a string should return their value:

>>> def thefunc(s):
... return '||' + s + '>>'
...
>>> s = 'Char'
>>> s = thefunc(s)
>>> s
'||Char>>'

There /are/ a few hacks which will do what you want.  However, if you
really need it, then you probably need to rethink your program design.
Remember, you can't change a string since a string is immutable!  You
can change a variable to bind to another string.  In the following
example, s gets rebound to the new string while t keeps the original
string value:

>>> def changeString(varName):
... globalDict = globals()
... globalDict[varName] = '||' + globalDict[varName] + '>>'
... return
...
>>> s = 'Char'
>>> t = s
>>> changeString('s')
>>> s
'||Char>>'
>>> t
'Char'

Further note that this only affects variables in the global scope.  I
hope this helps!

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that modifies a string

2006-07-10 Thread Jason
Simon Forman wrote:
> greenflame wrote:
> > Jason wrote:
> > >
> > > There /are/ a few hacks which will do what you want.  However, if you
> > > really need it, then you probably need to rethink your program design.
> > > Remember, you can't change a string since a string is immutable!  You
> > > can change a variable to bind to another string.  In the following
> > > example, s gets rebound to the new string while t keeps the original
> > > string value:
> > >
> > > >>> def changeString(varName):
> > > ... globalDict = globals()
> > > ... globalDict[varName] = '||' + globalDict[varName] + '>>'
> > > ... return
> > > ...
> > > >>> s = 'Char'
> > > >>> t = s
> > > >>> changeString('s')
> > > >>> s
> > > '||Char>>'
> > > >>> t
> > > 'Char'
> > >
> > > Further note that this only affects variables in the global scope.  I
> > > hope this helps!
> > >
> > > --Jason
> >
> > Ok so let me see if I understand. The globalDict is just a dictionary
> > containing the name of the global variables as the keys and their
> > values as the values of the dictionary? Thus the inputed variable is
> > treated like a global variable?
>
> The answer to your first question is yup!  You've got it.  That's what
> the globals() function returns.  (There is also a function locals()
> that returns a similar dict but for locals.)
>
> The answer to your second question is no.  The inputed *name* (the
> changeString() function must be passed a string, not a variable) must
> be the name of an object in the global scope for the function to work.
>
> You almost certainly want to use a function like the thefunc() function
> that Jason posted.
>
> One other thing, you could define it like so:
>
> def thefunc(s):
> return '||%s>>' % s
>
>
> Peace,
> ~Simon

Certainly.  I do want to add a warning: do not modify the dictionary
returned from locals(). Please note the warning given at
"http://docs.python.org/lib/built-in-funcs.html#l2h-45";.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessors in Python (getters and setters)

2006-07-10 Thread Jason

mystilleef wrote:
> I decided to change the name of an attribute. Problem is I've used the
> attribute in several places spanning thousands of lines of code. If I
> had encapsulated the attribute via an accessor, I wouldn't need to do
> an unreliable and tedious search and replace accross several source
> code files to achieve my goal. I could simply change the name of the
> attribute and move on. Well, I'm glad python has properties. It's a
> feature that should be advertised more, especially for large scale
> python development.
>
> Diez B. Roggisch wrote:
> > mystilleef wrote:
> >
> > > Hello,
> > >
> > > What is the Pythonic way of implementing getters and setters. I've
> > > heard
> > > people say the use of accessors is not Pythonic. But why? And what is
> > > the alternative? I refrain from using them because they smell
> > > "Javaish."
> > > But now my code base is expanding and I'm beginning to appreciate the
> > > wisdom behind them. I welcome example code and illustrations.
> >
> > Which wisdom do you mean? The wisdom that a language that has no property
> > mechanism and thus can't intercept setting and getting of instance members
> > needs a bulky convention called JAVA Beans, so that _all_ uses of
> > properties are tunneled through some code, even if only a few percent of
> > these actually need that?
> >
> > Or the wisdom that strangling developers by putting access modifiers with
> > approx. a dozen different rules in place is an annoyance to adult
> > developers to say the least?
> >
> > These are the reasons they are not pythonic. We can intercept property
> > access (see the property descriptor, http://pyref.infogami.com/property),
> > and we trust in developers being able to judge form themselves if messing
> > with internals of code is a good idea or not.
> >
> > Regards,
> >
> > Diez

The property() mechanism gets rid of the need for getters and setters,
as you can invisibly change a member variable into a getter/setter as
needed.  Nothing else needs to know that its using a property and not a
getter/setter.

Nothing like being forced to write getters and setters in C++/Java
before you feel like shooting your source code.  Please don't bring
this code-rage into Python.

To refactor a name in your code, take a look at Bicycle Repair Man
[http://bicyclerepair.sourceforge.net/].  It integrates into Eclipse
via PyDev, and allows you to refactor variable names, class names, and
method names fairly easily.

Good luck!

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: refering to base classes

2006-08-29 Thread Jason
Chaz Ginger wrote:
> Chaz Ginger wrote:
> > glenn wrote:
> >> hi - Im quite new to python, wondering if anyone can help me understand
> >> something about inheritance here. In this trivial example, how could I
> >> modify the voice method of 'dog' to  call the base class 'creatures'
> >> voice method from with in it?
> >>
> >> class creature:
> >> def __init__(self):
> >> self.noise=""
> >> def voice(self):
> >> return "voice:" + self.noise
> >>
> >> class dog(creature):
> >> def __init__(self):
> >> self.noise="bark"
> >>
> >> def voice(self):
> >> print "brace your self:"
>
> I did forget to mention that in 'dog"s' __init__ you had better call
> creature's __init__. You might make it look like this:
>
> def __init__(self):
>   self.noise = 'bark'
>   creature.__init__(self)
>

There's a problem with Chaz's __init__() method.  Notice that the
creature class's __init__ sets self.noise to the empty string.  In this
case, the superclass's __init__() method should be called first:

class dog(creature):
def __init__(self):
creature.__init__(self)
self.noise = "bark"
def voice(self):
print "brace your self:"
creature.voice(self)

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run Python file?

2006-09-02 Thread Jason
mistral wrote:
> I have installed ActivePython
> http://www.activestate.com/Products/ActivePython/
> How I can run Python file, test.py?

You can open up the folder containing the "test.py" file, then
double-click on the file to run it.  A command-line window should pop
up, and your program will run in it.  Once the Python program is done
running, the command window will probably close immediately.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data structure

2006-09-03 Thread Jason
noro wrote:
> Hello again.
>
> I have a task i need to do and i can't seem to find an elegent
> solution.
> i need to make a tree like data structure (not necessry a binary tree).
>
>
> i would like each node to access his sons in a dicionary kind of why,
> for example: if  ROOT node has the name 'A' and 'AA', 'AB' are his
> sons, and 'ABA' is 'AB son etc' (in this name scheme the letters from
> left to right shows the route from the root to the node) then
> ROOT['AB'] will point to 'AB' node and ROOT['AB'][ABA'] will point to
> 'ABA' node.
>
> the tree does not have to be symmarical and every node link to
> different number of nodes. two nodes can have the same name if they are
> in a different location in the tree. so ROOT['factory1]['manager'] and
> ROOT['factory2']['manager'] can be in the same tree and point to
> different objects.
>
> all up to now i can manage.
> -
> my problem is this: i would like to find a way to easly construct the
> tree by giving some simple template, somthing similer to:
> "
> ROOT={'factory1':FACTORY,'facory2':FACTORY,'linux':OS,'windows':OS}
> FACTORY={'manager':EMPLOEY,'worker':EMPLOEY,'office':BUILDING,'..}
> OS={'ver':VERSION,'problems':LIST,}
> "
> i started bulding the class NODE as an extention of  "dict" with the
> keys are the childern names and the items are the next node reference.
> the proablem was that as you can see from the above example 'factory1'
> and 'factory2' point to the same object. i would like to have 2
> different objects of FACTORY. making FACTORY a template and not an
> object.
>
> i'll appreciate any comment
> amit

You can make a shallow copy of a dictionary using the dictionary's copy
method.  To make a completely new copy, use the deepcopy function in
the copy module.  Please see the copy module's documentation on the
limits and differences between deep copies and shallow copies.
(http://docs.python.org/lib/module-copy.html)

 --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie with a problem writing files

2006-09-04 Thread Jason
limodou wrote:
> > Code:
> >
> > import feedparser
> > from xml.sax import saxutils
> >
> > feed_number=200
> >
> > feed_list = open("feed_listing.conf","r")
> > for each_feed in feed_list:
> > data=feedparser.parse(each_feed)
> > feed_title=data.entries[0].title
> > xml_output=open("xml_data\\feed" + str(feed_number) + ".xml", "w")
>
> Maybe there is a extra '=', if it should be:
>
> xml_output.write(feed_title)
>
> ?
>

It took me a few moments to parse what limodou wrote here, but he's
absolutely correct.  Your problem is that you are trying to reassign
the write method in your file.  File objects are built-in types, and do
not allow their methods to be calvaliery replaced.

Here's an example on the correct way (and your way) of writing to a
file:
>>> f = open('spam.xml', 'w')
>>> f.write( 'This data is written to the file' )
>>> f.write = ("This is not a valid Python syntax")
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'file' object attribute 'write' is read-only
>>>

You'll notice that the AttributeError describes exactly what's wrong in
this case.  The write method on your file attribute is read-only.  It
doesn't say anything about whether your file is read-only.

If you really, really want to change the write method into a string,
you can subclass from the file class:

>>> class MyFileType(file):
... pass
...
>>> myfile = MyFileType('spam_and_eggs.xml', 'w')
>>> myfile.write

>>> myfile.write = "Gonna replace write method with this string!"
>>> myfile.write
'Gonna replace write method with this string!'
>>>

Of course, you can no longer easily access the original write method
after re-assigning it like that.

(limodou, I thought this might need a little bit of extra explanation
for the original poster.  I apologize if I seem rude here.)

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python vs java

2006-09-06 Thread Jason
Bruno Desthuilliers wrote:
> With a GUI ? If so, you probably want to check out wxPython or PyGTK
> (wxPython will also buy you MacOS X IIRC, and wil perhaps be easier to
> install on Windows).

Just a warning: wxPython does operate slightly differently between Mac
OS X, Linux, and Windows.  The differences are usually minor and easy
to clean up in a cross-platform manner, but be aware that you need to
test on all platforms that you're going to release on.

For example, MDI apps are anthema to Linux's GTK, so wxGTK uses a
tabbed dialog to approximate the same thing.  While Mac OS X can
associate a Python object (in my case, None) with a hidden top-level
tree control node, Windows will throw a C++ assertion.

If you are used to using MFC, wxWidgets (which wxPython uses) provides
a very MFC'ish programming experience.  It's pretty decent, and the
wxPython demo provides lots of neat interactive examples.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to build extensions on Windows?

2006-09-07 Thread Jason
Kevin D. Smith wrote:
> I've written a simple Python extension for UNIX, but I need to get it
> working on Windows now.  I'm having some difficulties figuring out how
> to do this.  I've seen web pages that say that MS Visual Studio is
> required, and other that say that's not true, that MinGW will work.
> Then there is Mike Fletcher's web page
> (http://www.vrplumber.com/programming/mstoolkit/) that describes in
> detail how to build extensions, but most of the links to external
> software are no longer valid.  I think it's safe to say that I am
> completely lost, as there appears to be no authoritative, up-to-date
> description on how to make this work.
>
> --
> Kevin D. Smith

I don't know about MinGW, but you can get the Microsoft compilers by
installing Visual C++ 2005 Express.  I'm guessing the old toolkit is
deprecated.  While you must register each Visual Studio Express module
that you download, I don't think the actual command-line tools are
encumbered.

Why not try it out and let us know how it goes?

(Visual Studio 2005 Express:
http://msdn.microsoft.com/vstudio/express/)

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python vs java

2006-09-07 Thread Jason
Felipe Almeida Lessa wrote:
> 2006/9/7, Bruno Desthuilliers <[EMAIL PROTECTED]>:
> > I don't think one could pretend writing a cross-platform application
> > without testing it on all targeted platforms.
>
> E.g: while creating a free software, you may not have an Apple
> computer but you may want to be *possible* to run your program there.
> You don't test it, but you *think* it runs there. Not everybody has a
> spare MacOS X to test apps.

Ah, but those with the Intel Apples can run Linux, Windows, and Mac OS
X at the same time!  *grin*

Actually, that's how I'm working on my wx/Python application.  I write
it under Mac OS X and occasionally pull it into my Windows and Ubuntu
virtual machines for further testing.

> Of course, if your software *needs* to run in some particular OS then
> you have to test on it.

Certainly.  And this point should be emphasized for any cross-platform
language, especially for folk who may not have done such development
before.  The "write once, run everywhere" phrase does have a footnote.
Python's documentation is very good at pointing out what is platform
independent and what isn't, but other packages are not as thorough.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Method resolution for super(Class, obj).

2006-09-07 Thread Jason

ddtl wrote:
> Hello everybody.
>
> Consider the following code:
>
>
> class A(object):
> def met(self):
> print 'A.met'
> class B(A):
> def met(self):
> print 'B.met'
> super(B,self).met()
> class C(A):
> def met(self):
> print 'C.met'
> super(C,self).met()
> class D(B,C):
> def met(self):
> print 'D.met'
> super(D,self).met()
> d = D()
> d.met()
>
>
> When executed, it prints:
>
> D.met
> B.met
> C.met
> A.met
>
> The book (Python in a nutshell, 2nd edition) explains:
>
> "The solution is to use built-in type super. super(aclass, obj),
> which returns a special superobject of object obj. When we look
> up an attribute (e.g., a method) in this superobject, the lookup
> begins after class aclass in obj's MRO."
>
> But I don't understand - MRO means that when attribute is found
> somewhere in hierarchy, the search for it stops, that is: when
> d.met() is executed, it is supposed to print 'D met', call
> super(D,self).met() which should resolve met() to be B's attribute,
> and after B's met() is executed, we should be done. Why does the
> lookup proceeds from B to C as though met() wasn't found in B?
> Indeed, lookup order (according to a new-style MRO) is B, then C
> and at last A (because of a diamond inheritance), but only when
> attribute is not found in B it is looked up in C, and only if it
> is not found neither in B nor in C it is looked up in A...
>
> What is different here?

Let's examine what the mro order is for class D:
>>> D.mro()
[, , ,
, ]

When you call d.met(), the call dispatches to the D.met() method.
After printing out 'D.met', you use super() to get the next class in
the mro order, and call that class's met method.

As shown with the mro(), the class after D is B.  So B.met() is called.
 Normally, we would be done.  But take a look at B's method!

> class B(A):
> def met(self):
> print 'B.met'
> super(B,self).met()

B.met calls super, and invokes the next met method!  So, the code does
exactly what you've asked it to do, and searches for the next class
after B in the mro list: class C.  You are then invoking met method of
that class.  So, class B is calling class C's met method.

Class C also uses super, and calls the resulting met method on the
result as well.  This finds class A as the next class in the mro list,
and invokes the met method on it as well.

When you get to A's met method, you aren't calling another met method,
so the print statements end.

If you want the dispatch to end at B's method, comment out the
'super(B,self).met()' line:
>>> class B2(A):
... def met(self):
... print 'B2.met'

Alternatively, you could do away with using super entirely, and
actively call the superclass method that you want:
>>> class D2(B2, C):
... def met(self):
... print 'D2.met'
... B2.met(self)  # Invoke B2's method directly
...
>>> d2 = D2()
>>> d2.met()
D2.met
B2.met

You don't need super() to call a superclass method.  It can help with
complex class heirarchies, but most single-descendent class structures
don't need it.  Either way, when designing a class heirarchy, you
should either always use super() or never use super().  Mixing
non-super-using and super-using can give you problems.

(Rhetorical Q: Does this make me more or less super?)

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super and __init__

2006-09-08 Thread Jason
Noah wrote:
> Am I the only one that finds the super function to be confusing?
>
> I have a base class that inherits from object.
> In other words new style class:
>
> class foo (object):
> def __init__ (self, arg_A, arg_B):
> self.a = arg_A
> self.b = arg_B
> #   Do I need to call __init__ on "object" base class?
>
> class bar (foo):
> def __init__ (self, arg_Z):
> self.z = "Z" + arg_Z
> foo.__init__(self, 'A', arg_Z)#  this is the old-style
> class way
> def __str__ (self):
> return self.a + self.b + self.z
>
> I don't know how people will use the "bar" class
> in terms of inheritance. I don't want to lock anyone
> out of multiple inheritance, but I'd like to  have to
> worry about it as little as possible. From what I've
> read using  the  old style of calling the
> base class __init__ can cause conflicts
> if the class is later part of a diamond relationship.
>
> I just want "bar" to initialize the properties that it add
> to the base class and to have it tell the base class to
> initialize the inherited properties. The old way seemed
> clear enough; although, a bit ugly. The super function
> seems like it would make this more clear, but
> it doesn't (to me).
>
> Is there a "just do this" answer for 90% of the use cases?
>
> Yours,
> Noah

As far as I can tell, the best way to use super() with an __init__
function is to stick to a rigid function signiture.  This means, all
__init__'s must either have the same functions, accept parameters in
the same order (and handle excess parameters through the *args
mechanism), or use keyword arguments (using the **keyargs mechanism).

So, use one of the following for all your classes in the hierarchy:
def __init__(self, arg1, arg2):  # No subclass can add or remove
arguments
  pass

def __init__(self, arg1, arg2, *args):
# Subclasses can add arguments, but cannot remove or have a
different
# argument order.  The instances must be created with all possible
parameters.
pass

def __init__(self, arg1, arg2, **keyargs):
# Subclasses can add or remove arguments, and order doesn't matter.
# The instances must be created with all possible keyword
parameters.
pass

Unfortunately, I don't see a way of avoiding this problem with super().
 Any such super command resolves in the mro order.  Since the mro order
invoked at a certain class can change depending on its subclasses,
there's no way for the class to predict at design time what super() is
going to return.  You can predict what will be returned with your class
hierarchy, but another programmer can create a multiple-inheritence
class that will change the result.

Explicitly calling the base class is much easier, but a given class
method can be called multiple times in that case.

I do wish there was a way to kinda combine the two methods: Explicitly
call the super-classes, but do so that each super-method can get called
one or no times.  Unfortunately, I haven't (yet) found a way to do so
that can resolve things right.

That's not to say that there isn't a better way.  I'm sure that the
Python developers had a devil of a time working on this thing.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


newbie: datastructure `dictionary' question

2006-09-09 Thread jason
Hello,

I am completely new to python and I have question that I unfortunately
could not find in the various documentation online. My best guess is
that the answer should be quitte easy but I have just enterd the learning
phase so that means a hightend chance for stupidity and mistakes on my
part.

I am trying to fill a nested dictionary from parsing a logfile. However
each time there is only one key entry created and that's it. Just
one entry, while the keys are different. That's 100% sure. I think
therefore that it is an assignment error in my part. [there we have it...]

To give an static example of the datastructure that I am using to clear
any confusion on the datastructure part:

records = { 'fam/jason-a' : {
'date': 'Fri Sep  8 16:45:55 2006',
'from': 'jason',
'subject' : 'Re: Oh my goes.',
'msize'   : '237284' },
'university/solar-system' : {
'date': 'Fri Sep  8 16:45:46 2006',
'from': 'jd',
'subject' : 'Vacancies for students',
'msize'   : '9387' }
}

Looping over this datastructure is no problem.
rkeys = ['date', 'from', 'subject', 'msize']
for folder in records.keys():
print '--'
print folder
for key in rkeys:
print records[folder][key]

Now for the actual program/dynamic part - assignment in the loop I use the
following function. Note `datum' is not a date object, just a string.

def parselog(data):
other = 0
records = {}

for line in string.split(data, '\n'):
str = line.strip()
if str[:4] == 'From':
mfrom, datum = extrfrom(str), extrdate(str)
print datum, mfrom
elif str[:4] == 'Fold':
folder = extrfolder(str[8:])
records = {folder : { 'date' : datum, 'mesgbytes' : 
extrmsize(str[8:]), 'mesgcount' : 1}}
else:
other += 1

displrec(records)

Note, this is not ment as a collision type datastructure, all initial data
entries are unique. My question: Where is my assignment e.g. records =
{folder wrong ?

Thankx in advance for any tips, hints and answers.

Cheers,

Jason.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: datastructure `dictionary' question

2006-09-09 Thread jason
On Sat, 09 Sep 2006 09:00:35 -0700, John Machin wrote:
 
> jason wrote:
>> Hello,
>>
>> I am completely new to python and I have question that I unfortunately
>> could not find in the various documentation online. My best guess is
>> that the answer should be quitte easy but I have just enterd the
>> learning phase so that means a hightend chance for stupidity and
>> mistakes on my part.
>>


...


Owww.. Of course... ! Thankx for the answer and the suggestion. It really
helped me a lot. I defintely going to take the OO approach later on. 

thankx again for the quick reply.

Jason.

> You are *assigning* records = blahblah each time around. "records" will
> end up being bound to the blahblah related to the *last* record that you
> read.
> 
> You can do it item by item:
> records[folder]['date'] = datum
> etc
> or as a oneliner:
> records[folder] = {'date' : datum, 'mesgbytes' :
> extrmsize(str[8:]), 'mesgcount' : 1}
> 
> When you find yourself using a dictionary with constant keys like
> 'date', it's time to start thinking OO.
> 
> class LogMessage(object):
>def __init__(self, date, .)
> self.date = date
> etc
> 
> then later:
> 
> records[folder] = LogMessage(
>   date=datum,
>   mesgbytes= extrmsize(str[8:]),
>   mesgcount=1,
>   )
> 
> 
> [snip]
> 
> HTH,
> John

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running python from a usb drive

2006-09-11 Thread Jason
cjl wrote:
> Hey all:
>
> It seems no matter what I do the %1 gets replaced by paramaters sent to
> the batch file...there must be some way of "escaping" this, but I can't
> find the answer (yet) with google. Anyone?
>
> -CJL

Use two percents in a row turn into a single percentage sign.  So you'd
want "%%1".

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running python from a usb drive

2006-09-13 Thread Jason
cjl wrote:
> Thorsten:
>
> Thank you for your reply.
>
> > Setting environment variables has only effect on the process itself
> > and the subprocesses. This has nothing to do with Windows, it's the
> > same with Linux.
>
> True, and the changes to path and pythonpath are gone after I close the
> console window, but the results of the assoc and ftype commands are
> changes to the registry that linger. If I run my setup on a computer
> that has python installed, I will overwrite the pre-existing registry
> settings. I can restore them with a script, but I can't guarantee that
> my restore script will run.
>
> I'm still looking for a way to modify these temporarily, but it looks
> like I might be "up the creek" on this one. Oh well.
>
> Thanks again,
> CJL

I notice that you've already got the environmental variables set up to
run your Temp-Python.  You can retrieve the current associations (if
any) by using the assoc and ftype commands:

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python24\python.exe" "%1" %*

C:\>assoc .NotAnExtension
File association not found for extension .NotAnExtension

C:\>

Using this information, you could write a little python script with
your distribution which records the current file associations and
settings.  Then, when you're ready to revert, you run another little
python script which restores the associations.

These associations are also stored in the registry.  You could back up
the registry keys which you know will be modified, make the registry
changes yourself, and restore the registry settings at finish.  It
would require Python's win32 extension modules, though.

I don't know how you could do it without using a
backup/run-stuff/restore sequence.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how are dictionary literals handled by the interpreter?

2006-09-13 Thread Jason
[EMAIL PROTECTED] wrote:
> I wrote up a quick little set of tests, I was acutally comparing ways
> of doing "case" behavior just to get some performance information.  Now
> two of my test cases had almost identical results which was not at all
> what I expected.  Ultimately I realized I don't really know how
> literals are treated within the interpreter.
>
> The two implementations I was looking at were:
>
> class caseFunction(object):
> def __init__(self):
> self.caseDict = {'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}
>
> def doIt(self,a):
> exec(self.caseDict.get(a))
> return retval
>
>
>
> def caseFunc3(a):
> exec(  {'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}.get(a))
> return retval
>
>
> I had expected caseFunc3 to be slower.  I had thought the interpreter
> would be recreating the dictionary each time, but that doesn't seem to
> be the case since performance of the class version and the function
> version are nearly identical on most runs.  If i rewrite caseFunc3 as:
>
> def caseFunc4(a):
> exec(  dict({'a':"retval = 'a'",
> 'b':"retval='b'","c":"retval='c'","d":"retval='d'",
>
> "e":"retval='e'","f":"retval='f'","g":"retval='g'","h":"retval='h'",
>  "i":"retval='i'"}).get(a))
> return retval
>
> now with the explicit use of dict, i see the performace of the
> functional version decline as I initially expected.
>
> So what is happeneing in caseFunc3.  It seems as though the literal is
> "cached".  The other hypothesis I came up with is the name lookup for
> self.caseDict takes the same amount of time as creating the dictionary
> literal - but that doesn't make sense to me.
>
> Thanks

Why not check to see what the interpreter is doing?  Rather than
dealing with your overly complicated dictionaries, I've made a simple,
one case dictionary.  I've also done a similar bit to replicate your
doIt method.

>>> def case3(a):
... exec( {'a': "retval = 'a'"}.get(a) )
... return retval
...
>>> case3('a')
'a'
>>> def case4(a):
... exec( dict({'a': "retval = 'a'"}).get(a) )
... return retval
...
>>> case4('a')
'a'
>>> class caseFunction(object):
... def doIt(self, a):
... exec(self.caseDict.get(a))
... return retval
...

Then, use the dis module to disassemble the function objects:
>>> import dis
>>> dis.dis(case3)
  2   0 BUILD_MAP0
  3 DUP_TOP
  4 LOAD_CONST   1 ('a')
  7 LOAD_CONST   2 ("retval = 'a'")
 10 ROT_THREE
 11 STORE_SUBSCR
 12 LOAD_ATTR0 (get)
 15 LOAD_FAST0 (a)
 18 CALL_FUNCTION1
 21 LOAD_CONST   0 (None)
 24 DUP_TOP
 25 EXEC_STMT

  3  26 LOAD_NAME2 (retval)
 29 RETURN_VALUE
>>> dis.dis(case4)
  2   0 LOAD_NAME0 (dict)
  3 BUILD_MAP0
  6 DUP_TOP
  7 LOAD_CONST   1 ('a')
 10 LOAD_CONST   2 ("retval = 'a'")
 13 ROT_THREE
 14 STORE_SUBSCR
 15 CALL_FUNCTION1
 18 LOAD_ATTR1 (get)
 21 LOAD_FAST0 (a)
 24 CALL_FUNCTION1
 27 LOAD_CONST   0 (None)
 30 DUP_TOP
 31 EXEC_STMT

  3  32 LOAD_NAME3 (retval)
 35 RETURN_VALUE
>>> dis.dis(caseFunction.doIt)
  3   0 LOAD_FAST0 (self)
  3 LOAD_ATTR1 (caseDict)
  6 LOAD_ATTR2 (get)
  9 LOAD_FAST1 (a)
 12 CALL_FUNCTION1
 15 LOAD_CONST   0 (None)
 18 DUP_TOP
 19 EXEC_STMT

  4  20 LOAD_NAME4 (retval)
 23 RETURN_VALUE
>>>

Take a look at what happens before the 'get' attribute is loaded in
each case.  In case 3, you've simply created a dictionary literal,
which is a very fast operation under Python.  In case 4, you've created
a dictionary literal, then you call the dict() function.  The dict
function will create a dictionary from the supplied dictionary, and
return the shallow copy.

Case 3 is slower, but the Python developers have worked to make
dictionary creation and look-up very fast.  Did you use the timeit
module to test your functions?

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are Python's reserved words reserved in places they dont need tobe?

2006-09-14 Thread Jason
Antoon Pardon wrote:
> On 2006-09-14, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> > On Wed, 13 Sep 2006 07:45:02 +, Antoon Pardon wrote:
> >
> >>>> This is just an idea of mine, nothing I expect python to adapt.
> >>>> But just suppose the language allowed for words in bold. A word
> >>>> in bold would be considered a reserved word, a word in non bold
> >>>> would be an identifier.
> >
> > But surely all you are doing is changing the reserved word from (say)
> > "return" to "\x0breturn". Once you do that, you can bet that people will
> > complain that they want to have identifiers in bold too, why can't they
> > create a name "\x0breturn", and somebody will come up with an even more
> > complicated scheme for accommodating them... wash, rinse, repeat.
>
> Do you really think this is a serious possibility? As far as I can see,
> that \x0b that will be prepended to differentiate keywords from
> identifiers is a technique called stropping, that has been used with
> some algol languages. Have you any knowledge of people programming algol
> who asked for the use of stropped identifiers?
>
> I think I really would be amazed to find out there were such people,
> but then I have been amazed before. So I really would like to know.

Don't restrict yourself to something like that!  Use HTML to indicate
purpose of your python programs!  So, your identifiers must be between
 and  tags.  You strings will have to sit inside of a CDATA
section to work right, and you get all sorts of entity substitutions
for free!

"My program doesn't work anymore."
"Are your function names between h3 tags?"

(Secretly repulsed, yet fascinated)
--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: add without carry

2006-09-15 Thread Jason
Jon Ribbens wrote:
> In article <[EMAIL PROTECTED]>, Bruno Desthuilliers wrote:
> >
> > No need to think too long to come up with the most possibly Q&D solution:
> >
> > res = int(str(5 + 7)[-1])
>
> Am I missing something subtle in the question or is there some reason
> that nobody has posted the correct solution:
>
>   (a + b) % 10
>
> ?

You're not missing anything.  That's the obvious solution.  We're just
celebrating our non-Dutchness at the moment.

>>> def bound(value, maxBound):
... while value > maxBound:
... value -= maxBound
... return value
...
>>> bound(5 + 6, 10)
1
>>> bound(8 + 7, 10)
5

See?  I'm definitely not Dutch.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Builder Pattern

2006-01-28 Thread Jason
Hi

I really need an example of a builder pattern in python, the closest I
could find to something resembling builder was on this thread...
http://groups.google.co.uk/group/it.comp.lang.python/browse_thread/thread/44f79c1def2583ca/200adefeefa5f3fa?lnk=st&q=design+pattern+builder+python+-build&rnum=25#200adefeefa5f3fa

Unfortunately I can't read the discussion it's possibly in Spanish.

Does anyone know of a builder example for python? Thanking you in
advance for your help.

Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Builder Pattern

2006-02-02 Thread Jason
I have converted another example of strategy which I prefer to the 2
described earlier, here it is:

class FindMinima:
def algorithm(self):raise NotImplementedError


class LeastSquares (FindMinima):
def algorithm(self,line):
return (1.1,2.2)


class NewtonsMethod (FindMinima):
def algorithm(self,line):
return (3.3,4.4)

class Bisection (FindMinima):
def algorithm(self,line):
return (5.5,6.6)

class ConjugateGradient (FindMinima):
def algorithm(self,line):
return (3.3,4.4)



class MinimaSolver: # context class
strategy=''
def __init__ (self,strategy):
self.strategy=strategy

def minima(self,line):
return self.strategy.algorithm(line)

def changeAlgorithm(self,newAlgorithm):
self.strategy = newAlgorithm

def test():
solver=MinimaSolver(LeastSquares())
print solver.minima((5.5,5.5))
solver.changeAlgorithm(Bisection())
print solver.minima((5.5,5.5))
test()

-- 
http://mail.python.org/mailman/listinfo/python-list


NumPy error

2006-02-05 Thread jason
Hello:

I am using the following versions of Python and packages on Windows XP 
(SP2):

Python 2.4.2
NumPy  0.9.4.win32-py2.4
SciPy 0.4.4 for Python 2.4 and Pentium 4/SSE2

In the Python Shell I am running the following:

>>> from scipy.optimize import fmin
>>> def rosen(x):
  return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)

>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> xopt = fmin(rosen, x0)

I get the following error:

Traceback (most recent call last):
  File "", line 1, in -toplevel-
xopt = fmin(rosen, x0)
  File "C:\Python24\Lib\site-packages\scipy\optimize\optimize.py", line 191, 
in fmin
sim = Num.zeros((N+1,N),x0.dtypechar)
AttributeError: 'numpy.ndarray' object has no attribute 'dtypechar'

Any idea what the problem might be?

Thanks.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NumPy error

2006-02-05 Thread jason
Thanks.

After executing the first line, I now get:

>>> from scipy.optimize import fmin
Overwriting fft= from scipy.fftpack.basic (was 
 from numpy.dft.fftpack)
Overwriting ifft= from scipy.fftpack.basic (was 
 from numpy.dft.fftpack)

And then I get the following result:

>>> xopt = fmin(rosen, x0)
Optimization terminated successfully.
 Current function value: 0.66
 Iterations: 141
 Function evaluations: 243

>>> print xopt
[ 0.99910115  0.99820923  0.99646346  0.99297555  0.98600385]

Two questions:
1. does the "overwriting..." message make sense?
I uninstalled scipy and numpy and re-installed them.

2. has the algorithm (accuracy level) changed? the result seems different 
from that reported in
http://www.scipy.org/Wiki/Documentation?action=AttachFile&do=get&target=scipy_tutorial.pdf
on page 12.

Thanks again.

"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> jason wrote:
>
>> Hello:
>>
>> I am using the following versions of Python and packages on Windows XP
>> (SP2):
>>
>> Python 2.4.2
>> NumPy  0.9.4.win32-py2.4
>> SciPy 0.4.4 for Python 2.4 and Pentium 4/SSE2
>
> I fell for that yesterday. Cost me two hours. You have to install NumPy
> 0.9.2. Make sure you cleaned up the site-packages, and if you build stuff
> yourself, a clean rebuild is necessary.
>
> Regards,
>
> Diez 


-- 
http://mail.python.org/mailman/listinfo/python-list


RPy / R

2006-02-06 Thread jason
Hello:

I installed the following:

python-2.4.2.msi
pywin32-207.win32-py2.4.exe
R-2.2.1-win32.exe
rpy-0.4.6-R-2.0.0-to-2.2.1-py24.win32.exe

on a Windows XP (SP2) box.

When I try to run the following (source: 
http://rpy.sourceforge.net/plotting-with-RPy.html) in IDLE
>>> from rpy import *
>>> x = range(0, 10)
>>> y = [ 2*i for i in x ]
>>> r.plot_default(x, y)

I get a window entitled "pythonw.exe" which says: pythonw.exe has 
encountered a problem and needs to close. We are sorry for the 
inconvenience.

And then in IDLE
>>>  RESTART 
>>> 

When try the following test (from 
http://rpy.sourceforge.net/rpy/doc/manual.pdf page 5),

from rpy import *
r.wilcox_test
r.wilcox_test([1,2,3], [4,5,6])

I get for the second line:
 
And then for the third line I get the same error.

Is this a setup issue? Thanks for your help.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RPy / R

2006-02-08 Thread jason
Thanks for your response. I'll try to install all the same versions that you 
have.

I have removed my version of Python and installed ActivePython 
(ActivePython-2.4.2.10-win32-x86.msi).

Could you please tell me which versions of the following you have installed:
NumPy
SciPy
RPy
R

I have not installed Numeric. Is that different from NumPy? If so, which 
version do you have?

Thanks.

"Eddie" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi Jason
>
> I had more success, being able to run a few test programs.
> Not sure why yours would be crashing - I have a similar setup (Win XP SP2 
> with all updates) - my version of Python is the Activestate download 
> (ActivePython-2.4.2.10-win32-x86.msi). Have you installed Numeric?
> If all else fails might be worth trying to unistall Python and installing 
> the Activestate version (which includes the Win32 extensions).
>
> Good luck
>
> Eddie
>
> jason wrote:
>> Hello:
>>
>> I installed the following:
>>
>> python-2.4.2.msi
>> pywin32-207.win32-py2.4.exe
>> R-2.2.1-win32.exe
>> rpy-0.4.6-R-2.0.0-to-2.2.1-py24.win32.exe
>>
>> on a Windows XP (SP2) box.
>>
>> [SNIP]
>>
>> Is this a setup issue? Thanks for your help.
>> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help a C++ escapee!

2007-06-07 Thread Jason
On Jun 7, 1:59 am, "Simon Pickles" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Can someone help me leave the murky c++ world and enter shiny pythonland?
>
> I have a problem with importing and global variables, here's my code:
[snip!]
> When run, I come unstuck here:
>
> self.clientSocket, self.clientAddress = network.accept()
>
> I get a nameError on 'network', yet it is one in the global namespace,
> defined in server.py before CServerThread.Listen() is called.
>
> In c++, I understood how to declare variables, here I have a problem. Its
> like I need an extern statement from c++.
>
> Can anyone clarify this for me?

The others have covered your problem.  I'd just like to add a little
detail.

As the others have mentioned, global variables reside in their module
namespace.  There is no truly "global" namespace, and that hasn't
really shown up as a problem in Python.  There are two tricks to this:

  1)  Modules are only executed once, at the first import.  Every
additional import merely gets the module object, but does not execute
the code again.  Try adding a print statement outside all class and
function statements in a module, then import it multiple times.
You'll only see the results of the print statement once.

You can also start up python with the "-v" flag.  Python will then
tell you whenever it executes a module.

This means that you can have a "global" module.  Create a Python
module with all the variables that you want, and just import that
module in all places that need those variables.  If you find yourself
stuffing a huge number of variables into your global module, you
probably need to rethink your program design.

Otherwise, put the global data in the various modules that create and
update it.  Usually, your other code will only need to access that
data under more rare conditions.

If you absolutely need a module to be re-executed, the "reload"
function will do what you want.

  2)  Modules do not have to be imported at the start of the file.  A
module import statement can occur any time code is executed.  By
convention, we place the import statement at the beginning of the
block where we use it.

Remember that Python isn't C++.  If you place an import statement in a
function, Python doesn't try to import that statement until the
function is called.  This is very different from C/C++'s #include
preprocessor statements.

If you're having problems with circular references, the import
statement can usually
be moved inside of functions or methods that need them, or the files
can be refactored to  get rid of the circular reference.

Here's something that shows both points.  I started python by typing
in "python -v".  There's a large number of imported modules that
Python automatically loads.  After that finishes:
>>> def spam(x):
... x = 5 * x
... import math   # Math won't be imported until this function is
called
... return math.pow(x, 2)
...
>>> spam(1) # This should import the math module, executing its contents
import math # builtin
25.0
>>> spam(2) # spam() will now use the previously import math module.  (This is 
>>> fast)
100.0

Hope this helps!

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best platform and editor for Python

2007-07-05 Thread Jason
On Jul 1, 1:10 pm, kimiraikkonen <[EMAIL PROTECTED]> wrote:
> Hi,
> For experienced with Pyhton users, which developing software and
> enviroment would you suggest for Pyhton programming? Compiler+Editor
> +Debugger.

That would depend on what platform(s) you would be developing on, what
development environments you were used to, and so forth.  I personally
enjoy working in Eclipse with the PyDev plugin.  Other people love
Emacs.  I know folk who you'll only pry their vim editors from their
cold, dead fingers.

For people dipping their toes into the Python pool, I recommend using
Idle.  It comes with Python itself, and has a built-in debugger (see
the Debug menu), syntax highlighting, and other goodies.  It's
certainly enough to write your programs in.

Quite frankly, you can use Windows Notepad to write your Python
programs.  Python itself is just a language.  There is no single
environment that Python ties to itself tightly.  The basic debugger,
PDB, is built in as a Python module, so you can use Python to debug
itself.  Most of the IDE's that provide debuggers are merely placing a
nice wrapper over the python debugger.

To develop very short programs, I often start Python on my command
line and fiddle away.

> Also what are your suggestions for beginners of Pyhton programming?

Don't worry about making GUI programs at first.  GUIs are present in
every operating system, but they are an additional level of
complexity.  Get the language down, first, then head into the world of
graphical user interfaces.

Start programming.  See "Dive Into Python"[1].  Check out the
Beginner's section of the Python Wiki[2].  The hardest part about
learning to programming is learning to structure your thoughts into a
coherent series of logical units.  The rest is just code, and code is
easy.  It's the damn thinking that's so hard.

Get familiar with the Python documentation.  If you are under Windows,
the Python docs are installed with Python in Microsoft's Compiled Help
format, so you can browse them via the contents, look things up in the
index, and search via the search tab.  Remember that the built-in
stuff, like lists and dictionaries, are documented in the Python
Library Reference [3], while most of the modules are documented in the
Global Modules [4] document.  It's huge, but if you want to know what
Python has, it's almost always in there.

If you have a question, look for the solution by Googling this
newsgroup or the web in general.  If you still can't find a solution,
ask around in here.  Give plenty of detail, such the exact error
messages if one occurred, and the minimum amount of working code that
causes or demonstrates the problem.

You may get twenty different answers sometimes (like for your question
here), but that's twenty answers or perspectives that you may not have
known before you asked.

  --Jason

[1] http://www.diveintopython.org/
[2] http://wiki.python.org/moin/BeginnersGuide
[3] http://docs.python.org/lib/lib.html
[4] http://docs.python.org/modindex.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Copy List

2007-07-19 Thread Jason
On Jul 19, 10:21 am, Falcolas <[EMAIL PROTECTED]> wrote:
> On Jul 18, 6:56 am, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
>
> > This is shallow copy
> > If you want deep copy then
> > from copy import deepcopy
>
> What will a "deep copy" of a list give you that using the slice
> notation will not?

With a shallow copy, you end up with a new list object, but the items
contained within the new list object are the same as in the original
list object.  This makes no real difference if the original list only
contains immutable values (such as strings, integers, or floats), but
it can make a big difference if the values are mutable.

>>> originalList = [1, 2, [3, 4]]
>>> shallowCopy = originalList[:]
>>> shallowCopy.append(5)
>>> print str(originalList), '\n', str(shallowCopy)
[1, 2, [3, 4]]
[1, 2, [3, 4], 5]
>>> originalList[2].append(100) # Mutate the list inside this list
>>> print str(originalList), '\n', str(shallowCopy)
[1, 2, [3, 4, 100]]
[1, 2, [3, 4, 100], 5]
>>>

As you can see in the above code snipped, the original list contains a
list at index 2.  The slice copy is a different list, so appending a 5
to it doesn't modify the original list.  However, the result of
appending 100 to the object at index 2 can be seen in both lists.  A
deep copy creates a new object for ever item in the list, and all
items in those items, and so forth, so the lists guaranteed to be
truly disconnected:

>>> from copy import deepcopy
>>> originalList = [1, [2, [3, 4]]]
>>> fullCopy = deepcopy(originalList)
>>> originalList[1][1].append(100)
>>> print originalList, '\n', fullCopy
[1, [2, [3, 4, 100]]]
[1, [2, [3, 4]]]
>>>


  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: preferred windows text editor?

2007-05-09 Thread Jason
On May 9, 12:06 pm, "T. Crane" <[EMAIL PROTECTED]> wrote:
> Right now I'm using Notepad++.  What are other people using?
>
> trevis

IDLE for short scripts, PyDev under Eclipse for big Python projects,
and the Python shell for basic one-offs.

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance problem

2007-05-09 Thread Jason
On May 9, 12:09 pm, [EMAIL PROTECTED] wrote:
> I'm trying to solve a problem using inheritance and polymorphism in
> python 2.4.2
>
> I think it's easier to explain the problem using simple example:
>
> class shortList:
>
> def __init__(self):
>
> self.setList()
>
> def setList(self):
>
> a = [1,2,3]
>
> print a
>
> class longList(shortList):
>
> def __init__(self):
>
> shortList.setList()
>
> self.setList()
>
> def setList(self):
>
> a.extend([4,5,6])
>
> print a
>
> def main():
>
> a = raw_input('Do you want short or long list? (s/l)')
>
> if a.upper() == 'S':
>
> lst = shortList()
>
> else:
>
> lst = longList()
>
> lst.setList()
>
> if __name__ == '__main__':
>
> main()
>
> After that I'm getting a message:
>
> TypeError: unbound method setList() must be called with shortList
> instance as first argument (got nothing instead)
>
> Where is the problem?
>
> Thanks in advance...

As Neil indicated, you use the self object to access the current
object's class members.  The first parameter to a Python method is the
object that the method is operating on.  For a silly example:

>>> class SayHi(object):
... def __init__(self, name):
... self.name = name  # Save the name for later
... def Talk(self):
... print "Hi,", self.name
...
>>> helloWorld = SayHi("World")
>>> helloWorld.Talk()
Hi, World
>>>

As you can see, the __init__ special method saves the name by
"self.name = name".  Similarly, the name is accessed in the Talk
method via "self.name".

Please note that the first parameter is called "self" by convention.
Python doesn't care what you call the first parameter to a method.
However, most of the Python world uses "self", so it is highly
recommended to follow this convention.

Now for the problem specific to the error message that you're getting:

As above, the first parameter to a Python method is the object being
operated on.  Python uses a little bit of "syntactic sugar" to make
calling methods easier.  You can explicitly call a class method
directly and pass the object in as the first parameter yourself.

>>> helloWorld.Talk()   # This is the normal way of calling Talk
Hi, World
>>> SayHi.Talk(helloWorld)  # This works, too!
Hi, World

To easily call a superclass method, you can explicitly use the
baseclass.  You're attempting to do so, but you forgot one important
ingrediant: the object being operated on!  In C++, the object is
implicit.  In Python, you must explicitly send it to the superclass:

>>> class SayHello(SayHi):
... def __init__(self, name):
... SayHi.__init__(self, name)  # Call the superclass's init
... def Talk(self):
... print "Hello,", self.name
...
>>> moreTalk = SayHello("World")
>>> moreTalk.Talk()
Hello, World

Basically, you need to:
  1.  Assign your lists in setList to "self.a" instead of the local
variable "a".
  2.  Pass the object to the superclass method in setList
("shortList.setList(self)")

There are other things that may be improved with your design.  Keep
plugging at it!

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File writing success

2007-05-11 Thread Jason
On May 11, 12:21 pm, HMS Surprise <[EMAIL PROTECTED]> wrote:
> If file writing has no return value (http://docs.python.org/lib/bltin-
> file-objects.html), how do you know if the write was successful?
> Should one assume that if the open was successful then write are also?
>
> Thanks,
>
> jvh

In Python, errors are not usually indicated by a return code.
Instead, an exception should be raised for error conditions.  The
Python file semantics follows this.  If the function returns instead
of raising an exception, you may assume that the write completed
successfully.  Please note that the file objects may use buffers, so a
call to the flush method may be needed to ensure that everything is on
disk.

K:\temp>dir
 Volume in drive K is LEXAR MEDIA
 Volume Serial Number is -

 Directory of K:\temp

05/11/2007  01:14 PM  .
05/11/2007  01:14 PM  ..
   0 File(s)  0 bytes
   2 Dir(s)  75,071,488 bytes free

K:\temp>python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> out = file("test.txt", "wb")
>>> out.write( "Hi!" * 8000 )
Traceback (most recent call last):
  File "", line 1, in 
IOError: [Errno 28] No space left on device
>>>

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anyone else has seen "forrtl: error (200) ..."

2007-05-30 Thread Jason
On May 30, 9:33 am, Alexander Eisenhuth <[EMAIL PROTECTED]>
wrote:
> Hello,
>
> Ctrl+C is not passed to the interpreter (i guess it) while I'm executing a
> script. Instead i get:
> forrtl: error (200): program aborting due to control-C event
>
> If I start python in interactive mode Ctrl+C is passed:
>
> bash-3.2$ python
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on 
> win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> raw_input()
> Traceback (most recent call last):
>File "", line 1, in 
> KeyboardInterrupt
>  >>>
>
> Any idea ?
>
> Thanks
> Alexander

Forrtl indicates that your script is running a Fortran library or
program.  Remember that Python exceptions only apply during Python.
If a Fortran DLL performs a divide-by-zero error, or accesses invalid
memory, it will kill the interpreter instead of throwing a Python
exception.  With Compaq Visual Fortran, the Fortran library calls can
kill your entire program if a function receives an invalid value.
(Try raising a negative real number to a fractional exponent, for
example.)

I'd guess that the Fortran code is intercepting the CTRL-C signal and
killing the running script.

Without knowing anything about your script and the library calls it
makes, I can't give you much advice.  There may be little that you can
do, especially if you don't have the Fortran source code in question
and/or can't recompile it.  Maybe someone with some Fortran/Python
experience can assist you.

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators tutorials

2007-07-23 Thread Jason
r, and keyargs has the keyword arguments.
try:
# The name "func" comes from the outer scope,
WrapWithHelpDebug
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, error:
from logging import DEBUG, log
from sys import exc_info
import pdb

log(DEBUG, "Caught Exception: %s", error)
# Start the debugger at the place where the
# exception occurred
pdb.post_mortem(exc_info()[2])
return  # Nothing to return when an exception occurred

# Back in the WrapWithHelpDebug scope.
# HelpDebug is now a function objected defined in this scope.

def DivXY(x, y):
"Divides X by Y"
return x / y

DebugDivXY = WrapWithHelpDebug(DivXY)

# Debug the following calls
DivXY(5.0, 2.1)  # This will succeed
DebugDivXY(10.0, 0.0) # Causes a ZeroDivisionError exception

Wow, that's pretty easy, isn't it!  But, it's not as easy as it could
be.  Let's say that DivXY is used a lot, and you want to debug all
calls to it.  Rather than change the calls to "DivXY" to "DebugDivXY"
everywhere, we can simply assign the wrapped function object to the
DivXY name.
Instead of:
  DebugDivXY = WrapWithHelpDebug(DivXY)
We use:
  DivXY = WrapWithHelpDebug(DivXY)

Now, all calls to DivXY call the HelpDebug object that uses our
original DivXY function!  This is *exactly* what a decorator does.
Instead of writing:

def DivXY(x, y):
"Divides X by Y"
return x / y
DivXY = WrapWithHelpDebug(DivXY)

You write:

@WrapWithHelpDebug
def DivXY(x, y):
"Divides X by Y"
return x / y

To turn off the help-debug behavior, simply comment out the decorator.

This has turned out to be a bit long, so I'll finish up in the next
post

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators tutorials

2007-07-23 Thread Jason
On Jul 23, 11:25 am, Jason <[EMAIL PROTECTED]> wrote:
> On Jul 23, 2:13 am, james_027 <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > I am learning python by learning django, and I stumble upon decorator
> > which is very cool, any beginners resources for python decorators,
> > although I can google it, I just want to get a good tutorial for this
> > topic.
>
> > Thanks
> > james

With apologies, there is an error in my previous WrapWithHelpDebug.
The last part of the function should read:
# Back in the WrapWithHelpDebug scope.
# HelpDebug is now a function objected defined in this scope.
return HelpDebug  # This line was missing


Now, my prior post shows how decorators work.  Functions are objects
created by Python's def statement.  They have access to the names in
all their enclosing scopes: the module's global scope and any
functions that they are nested in.

The WrapWithHelpDebug decorator wraps a function so uncaught
exceptions get caught, logged, and the Python debugger is started.
You won't notice much output from the logger usually, because the
default log level is set to "DEBUG".  That might be fine, but maybe
you want to pass the debugging level as a parameter.

import logging

def WrapWithHelpDebug(func, logLevel):
"""Returns a function object that transparently wraps the
parameter
with the HelpDebug function"""

# The def statement actually defines a function object and binds
# it to a name.  Since it is nested in this function, the def
# statement isn't evaluated until
def HelpDebug(*args, **keyargs):
"Assist with debugging a function."
# The func argument is a Pythong function object
# arg is the positional arguments that follow the
# first parameter, and keyargs has the keyword arguments.
try:
# The name "func" comes from the outer scope,
WrapWithHelpDebug
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, error:
from logging import log
from sys import exc_info
import pdb

log(logLevel, "Caught Exception: %s", error)
# Start the debugger at the place where the
# exception occurred
pdb.post_mortem(exc_info()[2])
return  # Nothing to return when an exception occurred

# Back in the WrapWithHelpDebug scope.
# HelpDebug is now a function objected defined in this scope.
return HelpDebug

def DivXY(x, y):
"Divides X by Y"
return x / y
DivXY = WrapWithHelpDebug(DivXY, logging.DEBUG)

# Debug the following calls
DivXY(5.0, 2.1)  # This will succeed
DivXY(10.0, 0.0) # Causes a ZeroDivisionError exception

So, if we just need to add a new parameter, how do we do that with a
decorator?  Could we use "@WrapWithHelpDebug(logging.DEBUG)"?

No.  Remember, the decorator symbol is just a bit of syntactic sugar.
It turns:
@WrapWithHelpDebug(logging.DEBUG)
def DivXY(x, y):
"Divides X by Y"
return x / y

Into:
def DivXY(x, y):
"Divides X by Y"
return x / y
DivXY = WrapWithHelpDebug(logging.DEBUG)(DivXY)

Oops!  That implies that we're calling "WrapWithHelpDebug" with our
logging parameter.  To accommodate the extra parameter, we're going to
need to use Python's nested scopes again.  Here's a final version that
does everything we want:

import logging

def HelpDebugDecorator(logLevel):
"Returns a function object that will properly decorate a
function."

# Note that logLevel used in the nested function HelpDebug
# comes from this scope.

def WrapWithHelpDebug(func):
"""Returns a function object that transparently wraps the
parameter
with the HelpDebug function"""

# The def statement actually defines a function object and
binds
# it to a name.  Since it is nested in this function, the def
# statement isn't evaluated until
def HelpDebug(*args, **keyargs):
"Assist with debugging a function."
# The func argument is a Pythong function object
# arg is the positional arguments that follow the
# first parameter, and keyargs has the keyword arguments.
try:
# The name "func" comes from the outer scope,
WrapWithHelpDebug
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, error:
from logging import log
from sys import exc_info
import pdb

   

Re: Closures / Blocks in Python

2007-07-24 Thread Jason
On Jul 24, 8:58 am, treble54 <[EMAIL PROTECTED]> wrote:
> Does anyone know a way to use closures or blocks in python like those
> used in Ruby? Particularly those used in the { } braces.

Python isn't Ruby.  Python has a lambda function for creating
anonymous functions, but many of the common use cases expired with the
introduction of iterators and comprehensions.  Python's functions are
first class objects, and can be passed around, bound to names, and
used like any other object.  (I don't know whether Ruby's functions
are first class objects.)  Python's function objects are callable, but
so are classes (calling them creates a class instance) and some
instances (those that define the __call__ special method).

If you can't find a way of doing what you want with iterators,
comprehensions, or lambda, consider writing a little function.  Heck,
you can even nest functions in Python or pass a function as a
parameter.

For example, removing all names that start with a 'J' from a list of
names:
newListOfNames = [ name  for name in nameList  if not
name.startswith('J') ]  # List comprehension
newListOfNames = filter(lambda name: not name.startswith('J'),
nameList)  # Filter with lambda

# Explicit for-loop
newListOfNames = []
for name in nameList:
if not name.startswith('J'):  newListOfNames.append(name)


Take a look at "http://ivan.truemesh.com/archives/000392.html"; for a
comparison between some simple Ruby code and Python.  Hope this helps.

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython - How to add sorting to a ListCtrl?

2007-07-24 Thread Jason
On Jul 24, 10:21 am, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have 3 columns in my list control, each with a different "type" of
> data (for example, one column has names, the other has dates, etc).
> Can anyone reference a tutorial for solving this issue? I've done my
> share of googling to no avail. I need the user to be able to click any
> of the column headers and sort the rows of data by that column in
> ascending or descending order.
>
> Thanks for your time.

You probably want to post these questions to the wxPython forums.
Still, take a look at the wxPython demo [1].  Under the "Core Windows/
Controls" category, the ListCtrl demo does exactly what you describe.
They have code and comments built into the demo itself.

[1] http://www.wxpython.org/download.php

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'Advanced' list comprehension? query

2007-08-08 Thread Jason
On Aug 8, 10:00 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> I'm playing around with list comprehension, and I'm trying to find the
> most aesthetic way to do the following:
>
> I have two lists:
>
> noShowList = ['one', 'two', 'three']
>
> myList = ['item one', 'item four', 'three item']
>
> I want to show all the items from 'myList' that do not contain any of
> the strings in 'noShowList'.
>
> i.e. 'item four'
>
> I can do it like this:
>
> def inItem(noShowList, listitem):
> return [x for x in noShowList if x in listitem]
>
> print [x for x in myList if not inItem(noShowList, x)]
>
> and I can do it (horribly) with:
>
> print [x for x in myList if not (lambda y, z:[i for i in y if i in z])
> (noShowList, x)]
>
> I can also print out the items that DO contain the 'noShowList'
> strings with:
>
> print [x for x in myList for y in noShowList if y in x]
>
> but I can't get the 'not' bit to work in the above line.
>
> Any ideas?
> Thanks!

Here's how I would do it:

>>> noShowList
['one', 'two', 'four']
>>> myList
['item one', 'item two', 'item three', 'item four', 'item five']
>>> [x  for x in myList  if not any(y in x  for y in noShowList)]
['item three', 'item five']
>>>

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tests

2007-08-09 Thread Jason
On Aug 9, 8:46 am, "special_dragonfly" <[EMAIL PROTECTED]>
wrote:
> <[EMAIL PROTECTED]> wrote in message
> >http://docs.python.org/lib/module-filecmp.html
>
> My understanding of reading that is that it only looks at the file names
> themselves and not their contents. So whether filename1=filename2 and in the
> case of the function below it, whether one directory has files which are in
> the other.
> Correct me if I'm wrong.
> Dom
>
> P.S. md5 or sha hash is what I'd go for, short of doing:
>
> MyFirstFile=file("file1.xls")
> MySecondFile=file("file2.xls")
> If MyFirstFile==MySecondFile:
> print "True"
>
> although this won't tell you where they're different, just that they are...

You're incorrect.  If the shallow flag is not given or is true, the
results of os.stat are used to compare the two files, so if they have
the same size, change times, etc, they're considered the same.

If the shallow flag is given and is false, their contents are
compared.  In either case, the results are cached for efficiency's
sake.

  --Jason


The documentation for filecmp.cmp is:
  cmp(  f1, f2[, shallow])
  Compare the files named f1 and f2, returning True if they seem
equal, False otherwise.

  Unless shallow is given and is false, files with identical
os.stat() signatures are taken to be equal.

  Files that were compared using this function will not be
compared again unless their os.stat() signature changes.

  Note that no external programs are called from this function,
giving it portability and efficiency.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Icons for GUI development

2007-08-14 Thread Jason
On Aug 13, 8:22 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> I'm developing a mail client. Since GUI are usually improved with some
> icons, I'm looking for some. Because I'm not a very gifted artist I'm
> searching for a library of GPL or public domain icons. Any suggestions?

Try out the Silk icon set, too.
http://www.famfamfam.com/lab/icons/silk/

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to setup pyOpenGL3.0.a6 for window xp?

2007-08-19 Thread Jason
On Aug 17, 6:42 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> Windows comes with OpenGL libraries.  However, before you can use
> OpenGL you'll need a package that can provide an OpenGL context, which
> PyOpenGL doesn't do (easily).
>
> PyGame is the typical choice for most uses.  If all you need is a
> simple window to draw on, this is the package you want.
>
> However, it doesn't (easily) work with common GUIs like GTK and Wx.
> If you want to use use OpenGL in a GUI app, then you'll want to find
> an "OpenGL canvas widget" for that GUI.
>
> Carl Banks

Sorry Carl, but I'm a bit confused with your third paragraph.  Do you
mean that PyGame doesn't work easily with Wx/GTK, or that OpenGL
doesn't work easily with Wx/GTK?

If it's the second, then I must disagree.  wxPython comes with an
OpenGL widget in the "wx.glcanvas" module.  The widget only requires
PyOpenGL.  The wxPython Demo shows how to set up and program the
widget quite easily.  Another example is at: "http://
aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325392".

Unfortunately, I don't have much experience with PyGTK.  Their FAQ
does indicate that you need an extension to add OpenGL support.

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I Need help from all the group participants

2007-08-20 Thread Jason
On Aug 20, 1:14 pm, Boris Ozegovic <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I would be happy to help but I don't have a clear understand of what
> > the poster needs.
>
> Suppose you want to find out what is someone's pulse/heart rate, you can
> ask question in many ways, syntaxically, but with same semantic.  One way
> to find out someone's pulse is to ask: "What is John's pulse", other is
> "Please, tell me, what is Jonh's pulse", or "Send me John's pulse
> immediatelly!", etc.  So, if you can write some other question to find out
> someone's pulse, please do, but, it would be great if your question would
> have different pattern, e.g. "Please, tell me John's pulse immediatelly"
> and "Tell me John's pulse right now" have the same pattern, because they
> are syntaxically very alike.
>
> --
> Ne dajte da nas la¾ljivac Bandiæ 
> truje:http://cnn.blog.hr/arhiva-2007-06.html#1622776372

I wonder what John's pulse is?  Display John's pulse.  I need to know
John's pulse.  How many beats per minute is John's heart going?
What's John's pulse rate?  How fast is John's heart rate?  How fast is
John's blood pumping?  What is the rate of John's heart?  What is the
rate of John's pulse?  How fast is John's heart beating?  What is the
frequency of John's heart pulses?  What is the frequency of John's
cardiac cycle?  How fast is John's cardiac cycle?  What is the rate of
John's pulse?  I want the result of John's auscultation.  Give me
John's heart beats, or give John death!

Okay, probably not the last one.

If you're trying to do some natural language processing, you should
take a look at the Natural Language Tool Kit (NLTK) [1].  The NLTK is
written in Python, and also has a book to help you out (available free
online or as a physical book for price).

In any case, English is a terribly difficult language to parse, and
can have many ambiguities that can only be resolved through knowledge
of the subjects and verbs involved.  Good luck on your project.  Just
remember: Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo
buffalo [2].

[1] The NLTK website is at "http://nltk.sourceforge.net/index.php/
Main_Page"
[2] That's actually valid English.  See "http://en.wikipedia.org/wiki/
Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo"

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check for dict key existence, and modify it in one step.

2007-08-28 Thread Jason
On Aug 28, 8:36 am, rodrigo <[EMAIL PROTECTED]> wrote:
> Im using this construct a lot:
>
> if dict.has_key(whatever):
> dict[whatever] += delta
> else:
> dict[whatever] = 1
>
> sometimes even nested:
>
> if dict.has_key(whatever):
> if dict[whatever].has_key(someother):
> dict[whatever][someother] += delta
> else:
> dict[whatever][someother] = 1
> else:
> dict[whatever]={}
> dict[whatever][someother] = 1
>
> there must be a more compact, readable and less redundant way to do
> this, no?
>
> Thanks,
>
> Rodrigo

As Bruno said, don't shadow the built-in objects.  When things
inevitably go south because the dict class has been replaced by your
dictionary, it will be difficult for you to find out what went wrong.

Under Python 2.5, you have the defaultdict class in the collections
module [1].  (This class is trivial to implement in prior versions of
Python, too.)

>>> from collections import defaultdict
>>> myDict = defaultdict(lambda: 1)
>>> myDict['spam'] = 5
>>> myDict['spam'] += 10
>>> myDict['vikings'] += 20
>>> myDict
defaultdict( at 0x00AAC970>, {'vikings': 21, 'spam':
15})
>>>

  --Jason

[1] The module documentation is at "http://docs.python.org/lib/module-
collections.html"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-03 Thread Jason
On Aug 30, 1:27 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
> > [EMAIL PROTECTED] writes:
>
> >> What's with the index() function of lists throwing an exception on not
> >> found?
>
> > It's letting you know that the item isn't in the list. There's no
> > sensible return value from an "index" function in that condition.
>
> What about -1?  C programmers do this all the time.  :-)
>
> Ciao,
> Marc 'BlackJack' Rintsch

As other people pointed out, C doesn't have exceptions, so a C
programmer must make an in/out parameter to indicate an error, or have
a special return value.  In Python, you're most often searching the
list for an object which is in the list, so the lack of the object is
an exceptional condition.  You can certain check with the "in"
operator beforehand to avoid the exception.  You may also subclass a
list and override the index method, or write a standalone function to
catch the exception and change its value.

The reason why the exception is more Pythonic is that the return value
is always a guaranteed good index into the list.  Any errors
(including calling .index() on a non-list instance that doesn't have
a .index method) are exceptional, and should probably follow a very
different code path.

Returning -1 is not a good return value to indicate an error.  After
all, -1 is a valid index in most Python lists.  (Negative numbers
index from the tail of the list.)

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python syntax wart

2007-09-10 Thread Jason
On Sep 8, 11:16 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> The one thing I don't like about Python syntax is using backslashes to
> continue lines. Yes, you can avoid them if you can include parentheses
> somehow, but this isn't always possible.
>
> Possible:
>
> if (
> quitting
> and
> len(client["to_write"]) == 0
> and
> len(client["read"]) + client["to_read"] == 0
> ) :
> close_client(client, "shutting down")
> #end if
>
> Not possible:
>
> for \
> Link \
> in \
> GetEachRecord \
>   (
> "links",
> ("from_episode",),
> "to_episode = %s",
> [EpisodeID],
> "order by when_created"
>   ) \
> :
> out.write \
>   (
> "Back to episode %d\n"
> %
> (
> LinkToMe({"ep" : Link["from_episode"]}),
> Link["from_episode"]
> )
>   )
> #end for

Python doesn't prevent you from writing ugly code, using poor variable
names, or doing other silly things.  The rules on indention require
that you are at least consistent on a given line.  That said, the
backslash simply continues the line, and I don't see why your (ugly,
IMO) code is impossible.  Here's some similarly schizophrenically
formatted code that I just tried:

>>> for \
... l\
... in \
... (\
... 1,
... 2,
... 3
... )\
... :
... print\
... "This is "\
... "poorly "\
... "formatted!",\
... l
...
This is poorly formatted! 1
This is poorly formatted! 2
This is poorly formatted! 3
>>>

Looks like it runs to me.  In general, I'd recommend that you avoid
such nonsense spacing and alignment, and use wrappers, generators, and
other Python constructs to help write more sensible code.

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?)

2007-03-21 Thread Jason
On Mar 21, 8:38 am, "dmitrey" <[EMAIL PROTECTED]> wrote:
> Hi all,
> I looked to the PEPs & didn't find a proposition to remove brackets &
> commas for to make Python func call syntax caml- or tcl- like: instead
> of
> result = myfun(param1, myfun2(param5, param8), param3)
> just make possible using
> result =  myfun param1 (myfun2 param5 param8) param3
>
> it would reduce length of code lines and make them more readable, + no
> needs to write annoing charecters.
> Maybe it will require more work than I suppose, for example handling
> of things like
> result = myfun(param1, myfun2(param5, param8), param3=15, param4=200)
> to
> result =  myfun param1 (myfun2 param5 param8) param3=15 param4=200 #so
> it needs some more efforts to decode by compiler
>
> but anyway I think it worth.
> + it will not yield incompabilities with previous Python versions.
>
> WBR, D.

In my opinion, it is much less readable.  That may be due to my
experiences with TCL, BASH-scripting, with C, C++, and Python.  The
parenthesis make it very obvious that a function call is going on, and
mirrors the mathematical notations that denote using a function.

With touch-typing on an American keyboard, the ()'s are not really any
more annoying than any of the various top-row digits.  I personally
find the backslash character (\) to be far more annoying, as it can
have one of several locations depending on the keyboard style.  (Most
sanely put it above the "Enter" key.)

As others have pointed out, the code that you presented really isn't
all that much shorter.  Short code isn't really what Python's about.
Perl has many ways to write very short, incomprehensible code.

A further ambiguity to consider:

result = func1

Is the name "result" bound to the function func1?  Or is func1 called,
and its result is bound to the name "result"?

Good luck with your PEP.

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: yield, curry, mix-in, new.function, global, closure, .... what will work?

2007-04-16 Thread Jason
On Apr 16, 7:28 am, [EMAIL PROTECTED] wrote:
> On Apr 16, 3:05 am, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
>
> > [EMAIL PROTECTED] writes:
>
> > > Please, can you elaborate further, I'm not sure if I understood.
> > > Should I lock global variables i, j during the execution of run()? In
> > > that case I have to apologize, I showed rather simplified version of
> > > the actual problem I have - in fact changer() and run() will be a bit
> > > more complex thus executing a bit longer and perhaps causing a dead-lock.
>
> > Put both variables into one shared object with a lock (see the docs for
> > threading.RLock()).  Acquire the lock before modifying or reading the
> > variables, and release it afterwards.  That is the traditional way.
>
> Thanks for the reply! And at the same time, please bear with me.
>
> If I understand correctly: when one thread acquires the lock, every
> other thread has to wait. If so, this is not exacly what I would like
> to have since the thread might take a bit longer to finish.
>
> The reason why I try so hard to use local variables is that they are
> inherently thread-safe. So I don't even mind to copy changer() every
> time run() is called - run() has it's own local variables i, j, no one
> has to touch them except it's ("local") function changer(). But the
> problem is, I don't know how to propagate run()'s variables into
> changer() without declarating them as changer()'s arguments (it would
> be ok to append the declaration during run-time, though, if I only
> knew how).

In Python, names are bound to objects.  The parameter names passed to
a function *are not inherently thread safe*!  Python parameters are
not passed-by-value.  To show you what I mean:

>>> spam = ["delicious"]
>>> def test(meal):
...  global spam
...  if spam is meal:
...print "Spam is the same object as meal"
...
>>> test(spam)
Spam is the same object as meal

(While the "global spam" statement is optional in this case, I wanted
to make it painfully obvious where the "spam" name in function test is
coming from.)

It is thread-safe to rebind the name "meal" in the function test (ie,
meal = "Green eggs").   It is not thread-safe to mutate or modify the
object that meal is bound to.  In the example given above, appending
data to the list, removing data, changing elements, and other
operations will cause potential race conditions across multiple
threads.

Follow Paul's advice and get acquainted with the issues of concurrent
and threaded programming.  Judicious locking will help avoid most race
conditions.  If you don't want to keep other threads waiting, make a
copy of your data then release the data lock.

Depending on the data, you can usually have multiple threads "reading"
the data, as long as no other threads write to the data while there
are any readers.  A writer can be allowed to change the data, but only
if there are no readers and no other writers.  (This is commonly known
as a read/write lock.)  I didn't see a read/write lock in the Python
documentation with some casual browsing, but one can be implemented
from the existing thread locking mechanisms.

Your description of what you want to do is rather vague, so I can't
get too specific.  You've described how you want to do things, but I
don't know what you're trying to accomplish.  Where possible, simplify
your design.

--Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >